Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

chore(server): session uploader names for the capture code

Samrat Talukdarc38d32917a80
diff --git a/apps/server/src/capture-client.test.ts b/apps/server/src/capture-client.test.ts
index 099016c9..d168d35f 100644
--- a/apps/server/src/capture-client.test.ts
+++ b/apps/server/src/capture-client.test.ts
@@ -12,7 +12,7 @@ import { FakeArchiveServer, slowPartTwo } from "./session-archive/fake-archive-s
import { openArchive } from "./session-archive/test-helpers.js";
/**
- * The capture worker: the collector's and the archiver's work runs off the
+ * The capture worker: the session uploader's and the archiver's work runs off the
* main event loop, a resumed session starts with the whole workspace, and
* shutdown with work in flight settles in bounded time with archive uploads
* aborted first.
@@ -80,7 +80,7 @@ function uploadSink() {
};
}
-function service(options: Partial<CaptureServiceOptions> & Pick<CaptureServiceOptions, "stateDir" | "collector">): CaptureService {
+function service(options: Partial<CaptureServiceOptions> & Pick<CaptureServiceOptions, "stateDir" | "sessionUploader">): CaptureService {
const capture = startCaptureService({
appVersion: "0.0.0-test",
engineVersion: "0.0.0-test",
@@ -120,7 +120,7 @@ describe("capture worker", () => {
test("a 6,000-file start snapshot is read, scrubbed, compressed and uploaded without a main-loop stall over 100 ms", async () => {
const root = await syntheticWorkspace(6_000);
const sink = uploadSink();
- const capture = service({ stateDir: await tempDir("state"), collector: { upload: sink.upload } });
+ const capture = service({ stateDir: await tempDir("state"), sessionUploader: { upload: sink.upload } });
const monitor = loopMonitor();
const started = performance.now();
capture.startSession("session-offload-0001", "workspace-offload", root);
@@ -149,14 +149,14 @@ describe("capture worker", () => {
const stateDir = await tempDir("state");
const sessionId = "session-resume-0001";
const firstSink = uploadSink();
- const first = service({ stateDir, collector: { upload: firstSink.upload } });
+ const first = service({ stateDir, sessionUploader: { upload: firstSink.upload } });
first.startSession(sessionId, "workspace-resume", root);
await first.stop();
expect(firstSink.envelopes().map((item) => [item.snapshot_type, item.files_scope])).toEqual([["start", "full"], ["end", "changed"]]);
await writeFile(join(root, "src", "m7", "file7.ts"), "export const edited = true;\n");
const secondSink = uploadSink();
- const second = service({ stateDir, collector: { upload: secondSink.upload } });
+ const second = service({ stateDir, sessionUploader: { upload: secondSink.upload } });
second.startSession(sessionId, "workspace-resume", root);
await second.idle();
const [resumed] = secondSink.envelopes();
@@ -172,7 +172,7 @@ describe("capture worker", () => {
test("stopping with a start snapshot in flight finishes it and the session's end snapshot, then ends the worker", async () => {
const root = await syntheticWorkspace(3_000);
const sink = uploadSink();
- const capture = service({ stateDir: await tempDir("state"), collector: { upload: sink.upload } });
+ const capture = service({ stateDir: await tempDir("state"), sessionUploader: { upload: sink.upload } });
capture.startSession("session-stop-00001", "workspace-stop", root);
await capture.diagnostics();
const stopping = performance.now();
@@ -203,7 +203,7 @@ describe("capture worker", () => {
const sink = uploadSink();
const capture = service({
stateDir: await tempDir("state"),
- collector: { upload: sink.upload },
+ sessionUploader: { upload: sink.upload },
archive: {
enabled: true,
excludedDirs: [],
@@ -225,11 +225,11 @@ describe("capture worker", () => {
await capture.stop();
expect(slow.puts).toEqual([{ part: 2, bytes: 256, abortedAfterMs: expect.any(Number), completed: false }]);
expect(slow.puts[0]!.abortedAfterMs!).toBeLessThan(1_000);
- // The collector still delivered the session's end snapshot on the way out.
+ // The session uploader still delivered the session's end snapshot on the way out.
expect(sink.envelopes().map((item) => item.snapshot_type)).toContain("end");
}, 60_000);
- test("a stop that runs out of time aborts the collector upload this thread still serves for the worker, and does not wait for it", async () => {
+ test("a stop that runs out of time aborts the session upload this thread still serves for the worker, and does not wait for it", async () => {
const root = await syntheticWorkspace(5);
const signals: AbortSignal[] = [];
let started!: () => void;
@@ -237,7 +237,7 @@ describe("capture worker", () => {
const capture = service({
stateDir: await tempDir("state"),
stopTimeoutMs: 300,
- collector: {
+ sessionUploader: {
// The gateway never answers and this hook ignores its signal, as a stalled upload on the main thread would.
upload: (_sessionId, _bytes, signal) => {
signals.push(signal!);
@@ -268,7 +268,7 @@ describe("capture worker", () => {
stateDir,
worker: false,
stopTimeoutMs: 300,
- collector: {
+ sessionUploader: {
upload: (_sessionId, _bytes, signal) => {
signals.push(signal!);
started();
@@ -283,7 +283,7 @@ describe("capture worker", () => {
expect(performance.now() - stopping).toBeLessThan(5_000);
expect(signals[0]!.aborted).toBe(true);
// The start snapshot and the session's end snapshot wait in the spool, the end one never sent.
- const spoolDir = join(stateDir, "omnirush-collector-spool");
+ const spoolDir = join(stateDir, "omnirush-upload-spool");
const spooledTypes = async () => (await Promise.all((await readdir(spoolDir).catch(() => [] as string[]))
.filter((name) => name.endsWith(".json"))
.map(async (name) => (JSON.parse(await readFile(join(spoolDir, name), "utf8")) as { snapshot_type: string }).snapshot_type))).sort();
@@ -310,7 +310,7 @@ describe("capture worker", () => {
const stateDir = await tempDir("state");
const capture = service({
stateDir,
- collector: { upload: uploadSink().upload },
+ sessionUploader: { upload: uploadSink().upload },
archive: {
enabled: true,
excludedDirs: [],
@@ -354,7 +354,7 @@ describe("capture worker", () => {
const refreshFlags: unknown[] = [];
const capture = service({
stateDir: await tempDir("state"),
- collector: { upload: uploadSink().upload },
+ sessionUploader: { upload: uploadSink().upload },
archive: {
enabled: true,
excludedDirs: [],
@@ -389,7 +389,7 @@ describe("capture worker", () => {
}
}, 60_000);
- test("on the worker, the paths the collector sees a session touch reach the touched-files archive: a folder without .git gets only those files", async () => {
+ test("on the worker, the paths the session uploader sees a session touch reach the touched-files archive: a folder without .git gets only those files", async () => {
const sessionId = "ses_touched_0001";
const engine = Bun.serve({
hostname: "127.0.0.1",
@@ -408,7 +408,7 @@ describe("capture worker", () => {
const stateDir = await tempDir("state");
const capture = service({
stateDir,
- collector: { upload: uploadSink().upload },
+ sessionUploader: { upload: uploadSink().upload },
archive: {
enabled: true,
excludedDirs: [],
@@ -449,7 +449,7 @@ describe("capture worker", () => {
const results: Array<Array<[string, string, number]>> = [];
for (const worker of [true, false]) {
const sink = uploadSink();
- const capture = service({ stateDir: await tempDir("state"), collector: { upload: sink.upload }, worker });
+ const capture = service({ stateDir: await tempDir("state"), sessionUploader: { upload: sink.upload }, worker });
expect(capture.mode()).toBe(worker ? "starting" : "local");
capture.startSession("session-modes-0001", "workspace-modes", root);
expect(capture.hasSession("session-modes-0001")).toBe(true);
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 087b6978..b168cc8a 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -1,5 +1,5 @@
/**
- * The server's handle on session capture (the workspace collector, the
+ * The server's handle on session capture (the session uploader, the
* project archive and the turn observers, see capture-host.ts). By default
* the capture runs on a worker thread (capture-worker.ts): the main event
* loop, which serves the app (in the desktop app, the Electron main process),
@@ -26,7 +26,7 @@ import {
type ToWorker,
} from "./capture-protocol.js";
import { externalFetch } from "./server-fetch.js";
-import { isCollectableWebUrl, workspaceCollectorEnabled, type CollectorWebVisit } from "./workspace-collector.js";
+import { isUploadableWebUrl, sessionUploaderEnabled, type UploadWebVisit } from "./session-uploader.js";
/** A prompt body larger than this is not traced, so it is not copied to the worker either. */
const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
@@ -46,19 +46,19 @@ export type CaptureServiceOptions = Omit<CaptureHostOptions, "onSessionClosed">
};
export type CaptureService = {
- /** The collector has an account to upload to (the sign-in gate's question). */
- readonly collectorEnabled: boolean;
+ /** The session uploader has an account to upload to (the sign-in gate's question). */
+ readonly uploadEnabled: boolean;
/** Where capture runs right now. */
mode(): "starting" | "worker" | "local" | "down";
- /** Whether the collector is tracking this session (started and not finished). */
+ /** Whether the session uploader is tracking this session (started and not finished). */
hasSession(sessionId: string): boolean;
startSession(sessionId: string, workspaceId: string, root: string): void;
recordTrace(sessionId: string, type: string, data?: unknown): void;
- /** The "engine.request" event of a collected request (its body parsed off the main thread), plus a prompt's attachments. */
+ /** The "engine.request" event of a captured request (its body parsed off the main thread), plus a prompt's attachments. */
recordPrompt(sessionId: string, prompt: Omit<PromptRecord, "body"> & { body: ArrayBuffer | undefined }): void;
captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed"): void;
- /** Whether the visit is recorded (a tracked session and a collectable URL). */
- recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean;
+ /** Whether the visit is recorded (a tracked session and an uploadable URL). */
+ recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean;
archiveSessionStarted(sessionId: string, root: string, target: EngineTarget): void;
observeSession(sessionId: string, target: EngineTarget): void;
/** An engine was closed and another took over its sessions: turn observers reading it move there. */
@@ -92,7 +92,7 @@ function errorSummary(error: unknown): string {
type QueuedCall = { call: CaptureCall; transfer: ArrayBuffer[] };
class CaptureClient implements CaptureService {
- readonly collectorEnabled: boolean;
+ readonly uploadEnabled: boolean;
private current: "starting" | "worker" | "local" | "down" = "starting";
private worker: Worker | null = null;
private local: CaptureHost | null = null;
@@ -102,16 +102,16 @@ class CaptureClient implements CaptureService {
private readonly replies = new Map<number, (value: unknown) => void>();
/** The worker's requests being served on this thread. */
private readonly served = new Map<number, { controller: AbortController; channel: RequestChannel }>();
- /** Sessions the worker's collector tracks: true while live, false once finishing. */
+ /** Sessions the worker's session uploader tracks: true while live, false once finishing. */
private readonly sessions = new Map<string, boolean>();
private restarts = 0;
private stopping: Promise<void> | null = null;
constructor(private readonly options: CaptureServiceOptions) {
- this.collectorEnabled = workspaceCollectorEnabled({
- upload: Boolean(options.collector.upload),
- gatewayUrl: options.collector.gatewayUrl,
- accessToken: options.collector.accessToken,
+ this.uploadEnabled = sessionUploaderEnabled({
+ upload: Boolean(options.sessionUploader.upload),
+ gatewayUrl: options.sessionUploader.gatewayUrl,
+ accessToken: options.sessionUploader.accessToken,
});
if (options.worker ?? captureWorkerEnabled()) this.spawn();
else this.runLocally(null);
@@ -122,12 +122,12 @@ class CaptureClient implements CaptureService {
}
hasSession(sessionId: string): boolean {
- if (this.local) return this.local.collector.hasSession(sessionId);
+ if (this.local) return this.local.sessionUploader.hasSession(sessionId);
return this.sessions.get(sessionId) === true;
}
startSession(sessionId: string, workspaceId: string, root: string): void {
- if (this.collectorEnabled && SESSION_ID_PATTERN.test(sessionId) && !this.sessions.has(sessionId)) this.sessions.set(sessionId, true);
+ if (this.uploadEnabled && SESSION_ID_PATTERN.test(sessionId) && !this.sessions.has(sessionId)) this.sessions.set(sessionId, true);
this.send({ kind: "call", id: null, method: "startSession", args: [sessionId, workspaceId, root] });
}
@@ -145,9 +145,9 @@ class CaptureClient implements CaptureService {
this.send({ kind: "call", id: null, method: "captureSnapshot", args: [sessionId, trigger] });
}
- recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean {
+ recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
if (this.local) return this.local.recordWebVisit(sessionId, visit);
- if (!this.hasSession(sessionId) || typeof visit.url !== "string" || !isCollectableWebUrl(visit.url)) return false;
+ if (!this.hasSession(sessionId) || typeof visit.url !== "string" || !isUploadableWebUrl(visit.url)) return false;
this.send({ kind: "call", id: null, method: "recordWebVisit", args: [sessionId, visit] });
return true;
}
@@ -206,7 +206,7 @@ class CaptureClient implements CaptureService {
const late = await Promise.race([done.then(() => false), timedOut]);
clearTimeout(timer);
// In-process there is no worker to terminate: its uploads end here instead (spooled for the next start).
- if (late) this.local?.collector.abortUploads();
+ if (late) this.local?.sessionUploader.abortUploads();
const worker = this.worker;
this.worker = null;
this.current = "down";
@@ -265,16 +265,16 @@ class CaptureClient implements CaptureService {
// --- the worker -----------------------------------------------------------------
private workerInit(): CaptureWorkerInit {
- const { collector, archive } = this.options;
+ const { sessionUploader, archive } = this.options;
return {
stateDir: this.options.stateDir,
appVersion: this.options.appVersion,
engineVersion: this.options.engineVersion,
- collector: {
- upload: Boolean(collector.upload),
- refreshAccessToken: Boolean(collector.refreshAccessToken),
- ...(collector.gatewayUrl !== undefined ? { gatewayUrl: collector.gatewayUrl } : {}),
- ...(collector.accessToken !== undefined ? { accessToken: collector.accessToken } : {}),
+ sessionUploader: {
+ upload: Boolean(sessionUploader.upload),
+ refreshAccessToken: Boolean(sessionUploader.refreshAccessToken),
+ ...(sessionUploader.gatewayUrl !== undefined ? { gatewayUrl: sessionUploader.gatewayUrl } : {}),
+ ...(sessionUploader.accessToken !== undefined ? { accessToken: sessionUploader.accessToken } : {}),
},
archive: {
enabled: archive.enabled,
@@ -363,7 +363,7 @@ class CaptureClient implements CaptureService {
/**
* The worker is gone: every caller waiting on it gets an empty result, and
- * every request this thread still serves for it (a collector upload that
+ * every request this thread still serves for it (a session upload that
* outlasted the stop, an archive or egress fetch) is aborted, so none runs
* on for up to its own deadline with no one left to take the answer.
*/
@@ -430,14 +430,14 @@ class CaptureClient implements CaptureService {
}
private async perform(channel: RequestChannel, request: HostRequest, signal: AbortSignal, id: number): Promise<RequestResult> {
- const { collector, archive } = this.options;
+ const { sessionUploader, archive } = this.options;
switch (request.type) {
- case "collect": {
- if (!collector.upload) throw new Error("no collector upload hook");
- return { kind: "result", id, ok: true, response: await serializeResponse(await collector.upload(request.sessionId, request.body, signal)) };
+ case "upload": {
+ if (!sessionUploader.upload) throw new Error("no session upload hook");
+ return { kind: "result", id, ok: true, response: await serializeResponse(await sessionUploader.upload(request.sessionId, request.body, signal)) };
}
case "refreshAccessToken": {
- const refresh = channel === "archive" ? archive.refreshAccessToken : collector.refreshAccessToken;
+ const refresh = channel === "archive" ? archive.refreshAccessToken : sessionUploader.refreshAccessToken;
return { kind: "result", id, ok: true, response: null, token: refresh ? await refresh() : null };
}
case "archiveRequest": {
@@ -451,7 +451,7 @@ class CaptureClient implements CaptureService {
return { kind: "result", id, ok: true, response: await serializeResponse(response) };
}
case "fetch": {
- const egress = (channel === "archive" ? archive.fetch : collector.fetch) ?? externalFetch;
+ const egress = (channel === "archive" ? archive.fetch : sessionUploader.fetch) ?? externalFetch;
const response = await egress(request.url, {
method: request.method,
headers: request.headers,
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 09a5248b..c172937e 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -1,6 +1,6 @@
/**
* Everything the embedded server captures about sessions, under one owner:
- * the workspace collector, the project archive and the turn observers. The
+ * the session uploader, the project archive and the turn observers. The
* server runs it on a worker thread (capture-worker.ts, driven through
* capture-client.ts), so reading, hashing and scrubbing files, building JSON
* and tar streams, compressing and sealing never hold the main event loop
@@ -8,31 +8,31 @@
* same behaviour. Every call takes and returns plain data, so the same calls
* cross the thread boundary unchanged.
*/
-import { collectPromptAttachments, promptBodyForTrace, v2PromptBodyForTrace } from "./collector-attachments.js";
+import { readPromptAttachments, promptBodyForTrace, v2PromptBodyForTrace } from "./session-upload-attachments.js";
import {
createSessionObservers,
currentEngineTarget,
engineReplaced,
- observeCollectedSession,
+ observeUploadedSession,
projectArchiveEngineReads,
promptDispatched,
type EngineReplacement,
type EngineTarget,
type SessionObservers,
-} from "./collector-observer.js";
+} from "./session-upload-observer.js";
import type { CaptureStopOptions } from "./capture-protocol.js";
import { SessionArchiver, type SessionArchiverOptions } from "./session-archive/index.js";
import { ProjectArchiveLifecycle, type ArchiveLifecycleLog } from "./session-archive/lifecycle.js";
-import { WorkspaceCollector, type CollectorMetrics, type CollectorWebVisit } from "./workspace-collector.js";
+import { SessionUploader, type UploadMetrics, type UploadWebVisit } from "./session-uploader.js";
-export type { EngineReplacement, EngineTarget } from "./collector-observer.js";
+export type { EngineReplacement, EngineTarget } from "./session-upload-observer.js";
export type CaptureLog = ArchiveLifecycleLog;
/** Prompt bodies larger than this are not parsed for the trace (nor for attachments). */
const MAX_TRACED_REQUEST_BYTES = 4 * 1024 * 1024;
-/** A collected engine request, as the "engine.request" trace event and the prompt's attachments are built from it. */
+/** A captured engine request, as the "engine.request" trace event and the prompt's attachments are built from it. */
export type PromptRecord = {
method: string;
path: string;
@@ -51,12 +51,12 @@ export type PromptRecord = {
};
export type CaptureHostOptions = {
- /** The collector state dir (the archive keeps its files under it too). */
+ /** The session uploader state dir (the archive keeps its files under it too). */
stateDir: string;
appVersion: string;
engineVersion: string;
log: CaptureLog;
- collector: {
+ sessionUploader: {
upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => Promise<Response>;
refreshAccessToken?: () => Promise<string | null>;
fetch?: (input: string, init?: RequestInit) => Promise<Response>;
@@ -76,7 +76,7 @@ export type CaptureHostOptions = {
};
export type CaptureDiagnostics = {
- metrics: CollectorMetrics;
+ metrics: UploadMetrics;
cache: { roots: number; entries: number };
};
@@ -90,13 +90,13 @@ function requestPayload(body: Uint8Array | null): unknown {
}
export class CaptureHost {
- readonly collector: WorkspaceCollector;
+ readonly sessionUploader: SessionUploader;
readonly archive: ProjectArchiveLifecycle;
private readonly observers: SessionObservers = createSessionObservers();
constructor(options: CaptureHostOptions) {
- this.collector = new WorkspaceCollector({
- ...options.collector,
+ this.sessionUploader = new SessionUploader({
+ ...options.sessionUploader,
stateDir: options.stateDir,
appVersion: options.appVersion,
engineVersion: options.engineVersion,
@@ -108,7 +108,7 @@ export class CaptureHost {
const { enabled, excludedDirs, folderGate, baseIdleMs, baseMaxDeferMs, ...auth } = options.archive;
this.archive = new ProjectArchiveLifecycle({
archiver: new SessionArchiver({ stateDir: options.stateDir, excludedDirs, folderGate, log: options.log, ...auth }),
- enabled: enabled && this.collector.enabled,
+ enabled: enabled && this.sessionUploader.enabled,
log: options.log,
...(baseIdleMs !== undefined ? { baseIdleMs } : {}),
...(baseMaxDeferMs !== undefined ? { baseMaxDeferMs } : {}),
@@ -117,35 +117,35 @@ export class CaptureHost {
}
startSession(sessionId: string, workspaceId: string, root: string): void {
- this.collector.startSession(sessionId, workspaceId, root);
+ this.sessionUploader.startSession(sessionId, workspaceId, root);
}
recordTrace(sessionId: string, type: string, data?: unknown): void {
- this.collector.recordTrace(sessionId, type, data);
+ this.sessionUploader.recordTrace(sessionId, type, data);
}
- /** The "engine.request" event of a collected request and, for a prompt dispatch, one "attachment" event per attached file. */
+ /** The "engine.request" event of a captured request and, for a prompt dispatch, one "attachment" event per attached file. */
recordPrompt(sessionId: string, prompt: PromptRecord): void {
// The turn this prompt follows takes its end snapshot first, ahead of this prompt's own.
- if (prompt.dispatchedAt !== undefined) promptDispatched(this.observers, this.collector, sessionId, prompt.dispatchedAt);
+ if (prompt.dispatchedAt !== undefined) promptDispatched(this.observers, this.sessionUploader, sessionId, prompt.dispatchedAt);
const payload = requestPayload(prompt.body);
- this.collector.recordTrace(sessionId, "engine.request", {
+ this.sessionUploader.recordTrace(sessionId, "engine.request", {
method: prompt.method,
path: prompt.path,
body: prompt.engine === "v2" ? v2PromptBodyForTrace(payload) : promptBodyForTrace(payload),
});
if (!prompt.attachments) return;
- void collectPromptAttachments(payload, prompt.root).then((attachments) => {
- for (const attachment of attachments) this.collector.recordAttachment(sessionId, attachment);
+ void readPromptAttachments(payload, prompt.root).then((attachments) => {
+ for (const attachment of attachments) this.sessionUploader.recordAttachment(sessionId, attachment);
}).catch(() => undefined);
}
captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed"): void {
- this.collector.captureSnapshot(sessionId, trigger);
+ this.sessionUploader.captureSnapshot(sessionId, trigger);
}
- recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean {
- return this.collector.recordWebVisit(sessionId, visit);
+ recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
+ return this.sessionUploader.recordWebVisit(sessionId, visit);
}
/** A prompt was dispatched: the project archive's session start (a base once per session, see lifecycle.ts). */
@@ -158,15 +158,15 @@ export class CaptureHost {
engineReplaced(this.observers, closedBaseUrl, replacement);
}
- /** The engine accepted a collected request: follow the session until its turn settles. */
+ /** The engine accepted a captured request: follow the session until its turn settles. */
observeSession(sessionId: string, target: EngineTarget): void {
- void observeCollectedSession({ collector: this.collector, archive: this.archive, observers: this.observers, sessionId, target });
+ void observeUploadedSession({ sessionUploader: this.sessionUploader, archive: this.archive, observers: this.observers, sessionId, target });
}
/** The session was deleted in the engine. */
sessionDeleted(sessionId: string): void {
- this.collector.recordTrace(sessionId, "session.deleted");
- this.collector.finishSession(sessionId);
+ this.sessionUploader.recordTrace(sessionId, "session.deleted");
+ this.sessionUploader.finishSession(sessionId);
this.archive.sessionEnded(sessionId);
this.observers.lastMessageIds.delete(sessionId);
}
@@ -174,7 +174,7 @@ export class CaptureHost {
/** The account is gone: queued archives and spooled uploads are deleted, nothing more is archived. */
async signOut(): Promise<void> {
await this.archive.signOut();
- await this.collector.clearSpool().catch(() => undefined);
+ await this.sessionUploader.clearSpool().catch(() => undefined);
}
/**
@@ -185,17 +185,17 @@ export class CaptureHost {
async stop(options: CaptureStopOptions = { archiveFinals: true }): Promise<void> {
const archiveStopped = this.archive.stop({ finals: options.archiveFinals });
this.observers.controller.abort();
- await this.collector.stop().catch(() => undefined);
+ await this.sessionUploader.stop().catch(() => undefined);
await archiveStopped;
}
/** Resolves once every queued capture, upload and archive step has settled (tests, profiling). */
async idle(): Promise<void> {
- await this.collector.idleAll();
+ await this.sessionUploader.idleAll();
await this.archive.settled();
}
diagnostics(): CaptureDiagnostics {
- return { metrics: { ...this.collector.metrics }, cache: this.collector.cacheStatus() };
+ return { metrics: { ...this.sessionUploader.metrics }, cache: this.sessionUploader.cacheStatus() };
}
}
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index a4f4ac78..a666596a 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -9,7 +9,7 @@
*/
import type { CaptureHost, EngineReplacement, EngineTarget, PromptRecord } from "./capture-host.js";
import type { FolderGateOptions } from "./session-archive/detect.js";
-import type { CollectorWebVisit } from "./workspace-collector.js";
+import type { UploadWebVisit } from "./session-uploader.js";
/** How the capture stops: `archiveFinals` false (the account is gone) packs no final project archives. */
export type CaptureStopOptions = { archiveFinals: boolean };
@@ -20,7 +20,7 @@ export type CaptureCalls = {
recordTrace: [sessionId: string, type: string, data?: unknown];
recordPrompt: [sessionId: string, prompt: PromptRecord];
captureSnapshot: [sessionId: string, trigger: "prompt" | "turn_completed"];
- recordWebVisit: [sessionId: string, visit: CollectorWebVisit];
+ recordWebVisit: [sessionId: string, visit: UploadWebVisit];
archiveSessionStarted: [sessionId: string, root: string, target: EngineTarget];
observeSession: [sessionId: string, target: EngineTarget];
engineReplaced: [closedBaseUrl: string, replacement: EngineReplacement];
@@ -38,12 +38,12 @@ export type CaptureCall = { [M in CaptureCallName]: { kind: "call"; id: number |
/** What a worker asks of the main thread. `channel` says whose request it is: archive requests are aborted first at shutdown. */
export type HostRequest =
- | { type: "collect"; sessionId: string; body: Uint8Array<ArrayBuffer> }
+ | { type: "upload"; sessionId: string; body: Uint8Array<ArrayBuffer> }
| { type: "refreshAccessToken" }
| { type: "archiveRequest"; path: string; method: "GET" | "POST"; body?: string; refresh?: false }
| { type: "fetch"; url: string; method: string; headers: Array<[string, string]>; body?: Uint8Array<ArrayBuffer> | string };
-export type RequestChannel = "collector" | "archive";
+export type RequestChannel = "uploader" | "archive";
export type SerializedResponse = { status: number; statusText: string; headers: Array<[string, string]>; body: ArrayBuffer | null };
@@ -67,7 +67,7 @@ export type CaptureWorkerInit = {
stateDir: string;
appVersion: string;
engineVersion: string;
- collector: { upload: boolean; refreshAccessToken: boolean; gatewayUrl?: string; accessToken?: string };
+ sessionUploader: { upload: boolean; refreshAccessToken: boolean; gatewayUrl?: string; accessToken?: string };
archive: {
enabled: boolean;
excludedDirs: string[];
diff --git a/apps/server/src/capture-worker.ts b/apps/server/src/capture-worker.ts
index 256e5e1f..2e442c14 100644
--- a/apps/server/src/capture-worker.ts
+++ b/apps/server/src/capture-worker.ts
@@ -1,6 +1,6 @@
/**
* The capture worker: a worker thread running the server's CaptureHost (the
- * workspace collector, the project archive and the turn observers), so their
+ * session uploader, the project archive and the turn observers), so their
* CPU work never holds the main event loop. Started and driven by
* capture-client.ts; the messages are defined in capture-protocol.ts. The
* gateway broker's requests and external egress are made by the main thread
@@ -104,21 +104,21 @@ const host = new CaptureHost({
appVersion: init.appVersion,
engineVersion: init.engineVersion,
log,
- collector: {
- ...(init.collector.upload
+ sessionUploader: {
+ ...(init.sessionUploader.upload
? {
upload: async (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => {
const body = new Uint8Array(compressed);
- const result = await ask("collector", { type: "collect", sessionId, body }, signal);
+ const result = await ask("uploader", { type: "upload", sessionId, body }, signal);
if (!result.response) throw new Error("the main thread returned no response");
return deserializeResponse(result.response);
},
}
: {}),
- ...(init.collector.refreshAccessToken ? { refreshAccessToken: refreshAccessToken("collector") } : {}),
- fetch: hostFetch("collector"),
- ...(init.collector.gatewayUrl !== undefined ? { gatewayUrl: init.collector.gatewayUrl } : {}),
- ...(init.collector.accessToken !== undefined ? { accessToken: init.collector.accessToken } : {}),
+ ...(init.sessionUploader.refreshAccessToken ? { refreshAccessToken: refreshAccessToken("uploader") } : {}),
+ fetch: hostFetch("uploader"),
+ ...(init.sessionUploader.gatewayUrl !== undefined ? { gatewayUrl: init.sessionUploader.gatewayUrl } : {}),
+ ...(init.sessionUploader.accessToken !== undefined ? { accessToken: init.sessionUploader.accessToken } : {}),
},
archive: {
enabled: init.archive.enabled,
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 8feba773..1eb1c3a8 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -57,7 +57,7 @@ export type EmbeddedServerOptions = CliArgs & {
/** Account credentials held by the Desktop shell for the loopback gateway broker. */
omnirushGatewayCredentials?: OmniRushGatewayCredentials;
resumeInterruptedTasks?: boolean;
- /** Version of the embedding desktop app, reported as environment.app_version by the collector. */
+ /** Version of the embedding desktop app, reported as environment.app_version by the session uploader. */
appVersion?: string;
/**
* How the embedding desktop launches its bundled UI-control MCP. Persisted
diff --git a/apps/server/src/engine-pool.ts b/apps/server/src/engine-pool.ts
index bd544b68..6c9baed4 100644
--- a/apps/server/src/engine-pool.ts
+++ b/apps/server/src/engine-pool.ts
@@ -98,7 +98,7 @@ export type EnginePoolHooks = {
/**
* Called when an engine is closed while another serves (a drained
* generation retired, a dead primary replaced), before it closes: whatever
- * still reads the closed engine (the collector's turn observers) moves to
+ * still reads the closed engine (the session uploader's turn observers) moves to
* `replacement`, which reads the same sessions from the shared database.
*/
onEngineReplaced?: (closedBaseUrl: string, replacement: EnginePoolConnection) => void;
diff --git a/apps/server/src/engine-route-path.ts b/apps/server/src/engine-route-path.ts
index 7542452d..e8298289 100644
--- a/apps/server/src/engine-route-path.ts
+++ b/apps/server/src/engine-route-path.ts
@@ -6,7 +6,7 @@
* decoder, and a malformed sequence is left in place. A path classifier that
* looks at the raw proxy path therefore disagrees with the engine, which is
* exactly how an encoded dispatch path could skip the sign-in gate and the
- * collector. Every classifier compares against this decoded form instead; the
+ * session uploader. Every classifier compares against this decoded form instead; the
* request itself is still forwarded verbatim, the engine decodes it itself.
*/
diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.ts
index cc96818f..ac42e0d6 100644
--- a/apps/server/src/engine2/shapes.ts
+++ b/apps/server/src/engine2/shapes.ts
@@ -1,5 +1,5 @@
/**
- * The 2.x engine's records in the 1.x shapes the app, the collector and the
+ * The 2.x engine's records in the 1.x shapes the app, the session uploader and the
* uploaded traces are written against.
*
* OmniRush.ai bundles the opencode 2.x engine but keeps talking the 1.x
diff --git a/apps/server/src/engine2/trace-parity.test.ts b/apps/server/src/engine2/trace-parity.test.ts
index a82c0e52..5490ff59 100644
--- a/apps/server/src/engine2/trace-parity.test.ts
+++ b/apps/server/src/engine2/trace-parity.test.ts
@@ -2,15 +2,15 @@ import { afterAll, describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
-import { createSessionObservers, observeCollectedSession, type EngineTarget, type ObservedCollector, type ObserverTiming } from "../collector-observer.js";
-import type { CollectorChildSession } from "../workspace-collector.js";
+import { createSessionObservers, observeUploadedSession, type EngineTarget, type ObservedUploader, type ObserverTiming } from "../session-upload-observer.js";
+import type { UploadChildSession } from "../session-uploader.js";
import { startEngineFacade, type EngineFacade } from "./facade.js";
/**
* The uploaded trace does not depend on the engine: the turn observer
- * (collector-observer.ts) follows the same recorded conversation (two
+ * (session-upload-observer.ts) follows the same recorded conversation (two
* parallel sub-agents, fixtures/*-sub.json) once on the 1.x engine and once
- * on the 2.x engine behind the engine adapter, and hands the collector the
+ * on the 2.x engine behind the engine adapter, and hands the session uploader the
* same trace events, carrying messages and sub-agent sessions with the same
* fields.
*/
@@ -133,10 +133,10 @@ async function startV2Engine(tree: Tree): Promise<EngineTarget> {
type Entry =
| { kind: "trace"; type: string; data?: unknown }
| { kind: "model"; model: unknown }
- | { kind: "child"; child: CollectorChildSession }
+ | { kind: "child"; child: UploadChildSession }
| { kind: "flush"; final?: unknown };
-class RecordingCollector implements ObservedCollector {
+class RecordingUploader implements ObservedUploader {
readonly enabled = true;
readonly entries: Entry[] = [];
async sessionCheckpoint() {
@@ -155,7 +155,7 @@ class RecordingCollector implements ObservedCollector {
async childSessionIds() {
return [];
}
- recordChildSession(_sessionId: string, child: CollectorChildSession) {
+ recordChildSession(_sessionId: string, child: UploadChildSession) {
this.entries.push({ kind: "child", child });
}
captureSnapshot() {}
@@ -166,15 +166,15 @@ class RecordingCollector implements ObservedCollector {
const timing: Partial<ObserverTiming> = { sleep: async () => undefined };
-async function observe(target: EngineTarget, sessionId: string): Promise<RecordingCollector> {
- const collector = new RecordingCollector();
+async function observe(target: EngineTarget, sessionId: string): Promise<RecordingUploader> {
+ const sessionUploader = new RecordingUploader();
const archive = { turnFollowed: () => undefined, turnCompleted: () => undefined, turnIncomplete: () => undefined };
- await observeCollectedSession({ collector, archive, observers: createSessionObservers(), sessionId, target, timing });
- return collector;
+ await observeUploadedSession({ sessionUploader, archive, observers: createSessionObservers(), sessionId, target, timing });
+ return sessionUploader;
}
/** Sub-agents start concurrently: children are compared by the task they were given. */
-function childKey(child: CollectorChildSession): string {
+function childKey(child: UploadChildSession): string {
const first = (child.messages as Array<{ parts?: Array<{ text?: string }> }>)[0];
return String(first?.parts?.[0]?.text ?? "");
}
@@ -187,14 +187,14 @@ describe("the uploaded trace over the 2.x engine matches the 1.x engine's", () =
for (const node of flatten(v2)) for (const message of node.messages) if (message.type === "assistant" && message.model && typeof message.model === "object") (message.model as Record<string, unknown>).variant = "default";
const before = await observe(startV1Engine(v1), String(v1.session.id));
const after = await observe(await startV2Engine(v2), String(v2.session.id));
- const labels = (collector: RecordingCollector) => collector.entries.map((entry) => (entry.kind === "trace" ? entry.type : entry.kind));
+ const labels = (sessionUploader: RecordingUploader) => sessionUploader.entries.map((entry) => (entry.kind === "trace" ? entry.type : entry.kind));
expect(labels(after)).toEqual(labels(before));
expect(labels(after)).toContain("child");
- const final = (collector: RecordingCollector) => (collector.entries.find((entry) => entry.kind === "flush" && entry.final !== undefined) as { final: { messages: unknown[] } }).final;
+ const final = (sessionUploader: RecordingUploader) => (sessionUploader.entries.find((entry) => entry.kind === "flush" && entry.final !== undefined) as { final: { messages: unknown[] } }).final;
expect(shapeDiff(final(before).messages, final(after).messages)).toEqual([]);
- const children = (collector: RecordingCollector) => collector.entries
+ const children = (sessionUploader: RecordingUploader) => sessionUploader.entries
.flatMap((entry) => (entry.kind === "child" ? [entry.child] : []))
.sort((a, b) => childKey(a).localeCompare(childKey(b)));
const [left, right] = [children(before), children(after)];
@@ -208,7 +208,7 @@ describe("the uploaded trace over the 2.x engine matches the 1.x engine's", () =
});
// The session.model event: the same provider, model, variant and agent.
- const model = (collector: RecordingCollector) => collector.entries.find((entry) => entry.kind === "model");
+ const model = (sessionUploader: RecordingUploader) => sessionUploader.entries.find((entry) => entry.kind === "model");
expect(model(after)).toBeDefined();
expect(model(after)).toEqual(model(before));
});
diff --git a/apps/server/src/headless-threads.e2e.test.ts b/apps/server/src/headless-threads.e2e.test.ts
index 21210b83..d285e371 100644
--- a/apps/server/src/headless-threads.e2e.test.ts
+++ b/apps/server/src/headless-threads.e2e.test.ts
@@ -10,14 +10,14 @@ import type { ServerConfig } from "./types.js";
// These tests dispatch prompts through a local workspace without an omnirush.ai
// account. The server's sign-in gate refuses that unless both development
-// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.
-const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };
+// flags are set; the gate itself is covered by session-uploader.server.e2e.test.ts.
+const uploadGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_SESSION_UPLOAD_OPTIONAL: process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL };
beforeAll(() => {
process.env.OMNIRUSH_DEV_MODE = "1";
- process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";
+ process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = "1";
});
afterAll(() => {
- for (const [name, value] of Object.entries(collectorGateEnv)) {
+ for (const [name, value] of Object.entries(uploadGateEnv)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
diff --git a/apps/server/src/local-workflows.test.ts b/apps/server/src/local-workflows.test.ts
index 8407aeea..1b96d930 100644
--- a/apps/server/src/local-workflows.test.ts
+++ b/apps/server/src/local-workflows.test.ts
@@ -9,10 +9,10 @@ import type { ServerConfig, WorkspaceInfo } from "./types.js";
/**
* A workflow step is a prompt dispatch: it must reach the engine only through
- * the injected dispatcher (the server's gated, collected engine proxy), never
+ * the injected dispatcher (the server's gated, captured engine proxy), never
* through the SDK's prompt route. These tests drive the service with a fake
* engine and a fake dispatcher; the real dispatcher is covered end to end in
- * workspace-collector.server.e2e.test.ts.
+ * session-uploader.server.e2e.test.ts.
*/
type EngineFactory = ConstructorParameters<typeof LocalWorkflowService>[1];
@@ -54,7 +54,7 @@ async function fixture() {
},
session: {
create: async (body: unknown) => { engine.creates.push(body); return { data: { id: `ses_workflow_${engine.creates.length}` }, error: undefined }; },
- prompt: async () => { engine.sdkPrompts += 1; throw new Error("the SDK prompt route bypasses the gate and the collector"); },
+ prompt: async () => { engine.sdkPrompts += 1; throw new Error("the SDK prompt route bypasses the gate and the session uploader"); },
abort: async (input: { sessionID: string }) => { engine.aborts.push(input.sessionID); return { data: true, error: undefined }; },
},
}) as unknown as Engine;
diff --git a/apps/server/src/local-workflows.ts b/apps/server/src/local-workflows.ts
index fed9bd7c..927aa190 100644
--- a/apps/server/src/local-workflows.ts
+++ b/apps/server/src/local-workflows.ts
@@ -20,14 +20,14 @@ export type LocalWorkflowPromptBody = { model: LocalModelRef; parts: Array<{ typ
/**
* How a workflow step reaches the engine. A step is a prompt dispatch like any
* other, so it goes through the server's own engine proxy: the sign-in gate,
- * collector session start, prompt snapshot, request/response trace and turn
+ * session uploader's session start, prompt snapshot, request/response trace and turn
* observer all apply exactly as they do to a prompt sent from the app. The
* service never calls the engine's prompt route directly.
*/
export interface LocalWorkflowPromptDispatcher {
/** Throws the gate's ApiError (403 omnirush_account_required) before any engine session exists. */
assertAllowed(workspace: WorkspaceInfo): void;
- /** Sends the prompt through the collected proxy and resolves with the engine's response. */
+ /** Sends the prompt through the gated, captured engine proxy and resolves with the engine's response. */
prompt(workspace: WorkspaceInfo, sessionId: string, body: LocalWorkflowPromptBody, signal: AbortSignal): Promise<Response>;
}
type ActiveRun = {
diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.ts
index ed36dc8d..16420a20 100644
--- a/apps/server/src/omnirush-gateway-broker.test.ts
+++ b/apps/server/src/omnirush-gateway-broker.test.ts
@@ -324,7 +324,7 @@ describe("OmniRush gateway broker credential adoption", () => {
let invalidated = 0;
let reads = 0;
const broker = adoptingBroker(async () => (reads++ === 0 ? bundle(1) : bundle(2)), refreshCalls, () => { invalidated += 1; });
- const response = await broker.collect("session-1234", new Uint8Array([1, 2, 3]));
+ const response = await broker.uploadSession("session-1234", new Uint8Array([1, 2, 3]));
expect(response.status).toBe(200);
expect(refreshCalls).toEqual(["refresh-1"]);
expect(invalidated).toBe(0);
@@ -630,7 +630,7 @@ describe("OmniRush gateway broker sharing a device session with the desktop acco
describe("OmniRush gateway broker project archive requests", () => {
const archiveId = "0f6c2a7e-5b1d-4c8e-9a3f-2d7b6e1c4a90";
- test("reach the gateway root with the device bearer and refresh an expired one like collect()", async () => {
+ test("reach the gateway root with the device bearer and refresh an expired one like uploadSession()", async () => {
const calls: Array<{ url: string; method: string; authorization: string | null; contentType: string | null; body: unknown }> = [];
const refreshCalls: string[] = [];
const broker = new OmniRushGatewayBroker({
@@ -957,10 +957,10 @@ describe("OmniRush gateway broker model catalog requests", () => {
});
});
-describe("OmniRush gateway broker collect deadline", () => {
+describe("OmniRush gateway broker session upload deadline", () => {
const gatewayUrl = "https://gateway.example/omnirush/v1";
// 200 ms, the body at 1 MiB/s, 200 ms for the answer: 401 ms for a few bytes, 650 ms for 256 KiB.
- const collectUploadBudget = { baseMs: 200, bytesPerSecond: 1024 * 1024, maxSendMs: 5_000, responseMs: 200 };
+ const sessionUploadBudget = { baseMs: 200, bytesPerSecond: 1024 * 1024, maxSendMs: 5_000, responseMs: 200 };
/** Resolves after `ms`, or rejects with the signal's reason once it aborts. */
const sleep = (ms: number, signal: AbortSignal) => new Promise<void>((resolvePromise, reject) => {
@@ -974,12 +974,12 @@ describe("OmniRush gateway broker collect deadline", () => {
type Attempt = { authorization: string | null; signal: AbortSignal };
- /** The gateway accepts `access-2` only; `answer` decides how each collect attempt goes. */
- function collectBroker(attempts: Attempt[], refreshCalls: string[], answer: (attempt: Attempt) => Promise<Response>) {
+ /** The gateway accepts `access-2` only; `answer` decides how each upload attempt goes. */
+ function uploadBroker(attempts: Attempt[], refreshCalls: string[], answer: (attempt: Attempt) => Promise<Response>) {
return new OmniRushGatewayBroker({
credentials: { gatewayUrl, accessToken: "access-1", refreshToken: "refresh-1" },
engineToken: "local-engine-token",
- collectUploadBudget,
+ sessionUploadBudget,
fetch: async (input, init) => {
if (String(input).endsWith("/device/refresh")) {
refreshCalls.push((JSON.parse(String(init?.body)) as { refresh_token: string }).refresh_token);
@@ -994,14 +994,14 @@ describe("OmniRush gateway broker collect deadline", () => {
test("ends at the deadline its body's size sets", async () => {
const attempts: Attempt[] = [];
- const broker = collectBroker(attempts, [], async ({ signal }) => {
+ const broker = uploadBroker(attempts, [], async ({ signal }) => {
// Accepted bearer, but the answer never comes.
await new Promise((_resolvePromise, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }));
return Response.json({ ok: true });
});
const started = performance.now();
const ended = async (bytes: number) => {
- const error = await broker.collect("session-deadline-1", new Uint8Array(bytes)).catch((reason: unknown) => reason);
+ const error = await broker.uploadSession("session-deadline-1", new Uint8Array(bytes)).catch((reason: unknown) => reason);
return { name: (error as Error).name, afterMs: performance.now() - started };
};
const [small, large] = await Promise.all([ended(64), ended(256 * 1024)]);
@@ -1016,7 +1016,7 @@ describe("OmniRush gateway broker collect deadline", () => {
test("gives the retry with a refreshed bearer a deadline of its own", async () => {
const attempts: Attempt[] = [];
const refreshCalls: string[] = [];
- const broker = collectBroker(attempts, refreshCalls, async ({ authorization, signal }) => {
+ const broker = uploadBroker(attempts, refreshCalls, async ({ authorization, signal }) => {
// Each try takes 250 ms of its 401: together they outlast one shared deadline.
await sleep(250, signal);
return authorization === "Bearer access-2"
@@ -1024,7 +1024,7 @@ describe("OmniRush gateway broker collect deadline", () => {
: Response.json({ detail: "invalid_token" }, { status: 401 });
});
const caller = new AbortController();
- const response = await broker.collect("session-deadline-2", new Uint8Array(64), caller.signal);
+ const response = await broker.uploadSession("session-deadline-2", new Uint8Array(64), caller.signal);
expect(response.status).toBe(201);
expect(refreshCalls).toEqual(["refresh-1"]);
expect(attempts.map((attempt) => attempt.authorization)).toEqual(["Bearer access-1", "Bearer access-2"]);
@@ -1035,15 +1035,15 @@ describe("OmniRush gateway broker collect deadline", () => {
test("ends at once when the caller's signal aborts, on the retry with a refreshed bearer too", async () => {
const attempts: Attempt[] = [];
const caller = new AbortController();
- const reason = new DOMException("The collector's deadline", "TimeoutError");
- const broker = collectBroker(attempts, [], async ({ authorization, signal }) => {
+ const reason = new DOMException("The session uploader's deadline", "TimeoutError");
+ const broker = uploadBroker(attempts, [], async ({ authorization, signal }) => {
if (authorization !== "Bearer access-2") return Response.json({ detail: "invalid_token" }, { status: 401 });
setTimeout(() => caller.abort(reason), 50);
await sleep(10_000, signal);
return Response.json({ ok: true }, { status: 201 });
});
const started = performance.now();
- const error = await broker.collect("session-deadline-3", new Uint8Array(64), caller.signal).catch((cause: unknown) => cause);
+ const error = await broker.uploadSession("session-deadline-3", new Uint8Array(64), caller.signal).catch((cause: unknown) => cause);
expect(error).toBe(reason);
expect(performance.now() - started).toBeLessThan(401 - 100);
expect(attempts.map((attempt) => attempt.authorization)).toEqual(["Bearer access-1", "Bearer access-2"]);
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 617eb7ff..a1036d48 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -1,6 +1,6 @@
import { timingSafeEqual } from "node:crypto";
-import { COLLECT_UPLOAD_BUDGET, collectUploadTimeoutMs, type CollectUploadBudget } from "./collect-upload-budget.js";
+import { SESSION_UPLOAD_BUDGET, SESSION_UPLOAD_ENDPOINT_PATH, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";
import { externalFetch } from "./server-fetch.js";
import type { OmniRushGatewayCredentialBundle, OmniRushGatewayCredentials } from "./types.js";
import {
@@ -33,8 +33,8 @@ type BrokerOptions = {
engineToken?: string;
fetch?: typeof externalFetch;
log?: (level: "info" | "warn" | "error", message: string, attributes?: Record<string, unknown>) => void;
- /** collect()'s deadline parameters; COLLECT_UPLOAD_BUDGET unless a test shrinks it. */
- collectUploadBudget?: CollectUploadBudget;
+ /** uploadSession()'s deadline parameters; SESSION_UPLOAD_BUDGET unless a test shrinks it. */
+ sessionUploadBudget?: SessionUploadBudget;
/** Hears every sub-agent request moved to the main model (see subagentFallback). */
onSubagentFallback?: (event: SubagentModelFallbackEvent) => void;
/** The pause before a busy picked model is tried once more; tests shrink it. */
@@ -704,7 +704,7 @@ export class OmniRushGatewayBroker {
private readonly latest?: OmniRushGatewayCredentials["latest"];
private readonly fetcher: typeof externalFetch;
private readonly log?: BrokerOptions["log"];
- private readonly collectUploadBudget: CollectUploadBudget;
+ private readonly sessionUploadBudget: SessionUploadBudget;
private readonly onSubagentFallback?: BrokerOptions["onSubagentFallback"];
private readonly subagentRetryDelayMs: number;
private readonly subagentModelRefused?: (model: string) => boolean;
@@ -734,7 +734,7 @@ export class OmniRushGatewayBroker {
this.latest = options.credentials?.latest;
this.fetcher = options.fetch ?? externalFetch;
this.log = options.log;
- this.collectUploadBudget = options.collectUploadBudget ?? COLLECT_UPLOAD_BUDGET;
+ this.sessionUploadBudget = options.sessionUploadBudget ?? SESSION_UPLOAD_BUDGET;
this.onSubagentFallback = options.onSubagentFallback;
this.subagentRetryDelayMs = options.subagentRetryDelayMs ?? SUBAGENT_RETRY_DELAY_MS;
this.subagentModelRefused = options.subagentModelRefused;
@@ -821,14 +821,14 @@ export class OmniRushGatewayBroker {
}
/**
- * One collector envelope. The deadline grows with the envelope's size
- * (collect-upload-budget.ts), and the retry with a refreshed bearer gets a
- * deadline of its own; `signal`, the collector's own deadline or cancel,
+ * One session uploader envelope. The deadline grows with the envelope's size
+ * (session-upload-budget.ts), and the retry with a refreshed bearer gets a
+ * deadline of its own; `signal`, the session uploader's own deadline or cancel,
* ends either sooner.
*/
- collect(sessionId: string, body: Uint8Array, signal?: AbortSignal): Promise<Response> {
- const timeoutMs = collectUploadTimeoutMs(body.byteLength, this.collectUploadBudget);
- return this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, "collect"), {
+ uploadSession(sessionId: string, body: Uint8Array, signal?: AbortSignal): Promise<Response> {
+ const timeoutMs = sessionUploadTimeoutMs(body.byteLength, this.sessionUploadBudget);
+ return this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, SESSION_UPLOAD_ENDPOINT_PATH), {
method: "POST",
headers: {
Authorization: `Bearer ${state.accessToken}`,
@@ -843,7 +843,7 @@ export class OmniRushGatewayBroker {
/**
* A project archive API call for the session archiver (`archives/key`,
* `archives`, `archives/<id>/parts|complete|abort`), authenticated like
- * collect(): the device bearer and the same bounded 401 refresh. S3 part
+ * uploadSession(): the device bearer and the same bounded 401 refresh. S3 part
* uploads never come through here; they go to their presigned URLs. With
* `refresh: false` (the archiver's all-folders policy probe) it is one
* request: a 401 is returned as it is, with no refresh and no second try.
@@ -864,7 +864,7 @@ export class OmniRushGatewayBroker {
/**
* The account's model catalog (`<gateway>/models`, the backend's
- * GET /omnirush/v1/models), authenticated like collect(): the device bearer
+ * GET /omnirush/v1/models), authenticated like uploadSession(): the device bearer
* and the same bounded 401 refresh. Read by the model catalog sync.
*/
modelCatalog(): Promise<Response> {
@@ -877,7 +877,7 @@ export class OmniRushGatewayBroker {
/**
* One voice segment for the backend's POST /omnirush/v1/audio/transcriptions,
- * authenticated like collect(): the device bearer and the same bounded 401
+ * authenticated like uploadSession(): the device bearer and the same bounded 401
* refresh. The multipart body goes through as it came and is held only
* for this call.
*/
@@ -924,8 +924,8 @@ export class OmniRushGatewayBroker {
/**
* Rotates the device access token through the refresh endpoint and returns
* the bearer to use next, or null once the account is signed out. The
- * workspace collector asks for this when an upload comes back unauthorized
- * after the retry inside collect() has already failed to rotate it.
+ * session uploader asks for this when an upload comes back unauthorized
+ * after the retry inside uploadSession() has already failed to rotate it.
*/
async refreshAccessToken(): Promise<string | null> {
if (!this.state) return null;
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index f991c555..33ba356a 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -14,7 +14,7 @@ import {
import { writeGlobalRuntimeOpencodeConfig, writeRuntimeOpencodeConfig } from "./runtime-opencode-config-store.js";
import { rulesFromPermissionConfig, winningRule } from "./effective-permissions.js";
import { backendCatalogBody } from "./__fixtures__/omnirush-model-catalog.js";
-import { MAX_COLLECTOR_CHILD_SESSION_DEPTH } from "./workspace-collector.js";
+import { MAX_UPLOAD_CHILD_SESSION_DEPTH } from "./session-uploader.js";
import {
OMNIRUSH_SUBAGENT_DEPTH,
OMNIRUSH_SWARM_MAX_PER_TURN,
@@ -349,9 +349,9 @@ describe("omnirush runtime config file", () => {
for (const mode of ["guarded", "full"] as const) {
const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({ approvals: { mode } } as never, undefined, {});
// The engine counts layers below the main session and refuses the task
- // tool at subagent_depth; the collector walks the same number of layers.
+ // tool at subagent_depth; the session uploader walks the same number of layers.
expect(parsed.subagent_depth).toBe(OMNIRUSH_SUBAGENT_DEPTH);
- expect(OMNIRUSH_SUBAGENT_DEPTH).toBe(MAX_COLLECTOR_CHILD_SESSION_DEPTH);
+ expect(OMNIRUSH_SUBAGENT_DEPTH).toBe(MAX_UPLOAD_CHILD_SESSION_DEPTH);
const agents = parsed.agent as Record<string, { permission?: Record<string, unknown>; prompt?: string; mode?: string }>;
// A sub-agent keeps the task tool only when its own rules mention it:
// only general does; no global task rule reaches explore.
diff --git a/apps/server/src/omnirush-subagent-model.ts b/apps/server/src/omnirush-subagent-model.ts
index aae5d055..4d22b7b7 100644
--- a/apps/server/src/omnirush-subagent-model.ts
+++ b/apps/server/src/omnirush-subagent-model.ts
@@ -13,14 +13,14 @@
* - The swarm engine plugin asks POST /omnirush/subagent-model/resolve for
* every prompt of a sub-agent session and puts the answer on the user
* message before it is saved, so the engine runs (and records) that model
- * and effort for the sub-agent, and so do the collector's traces.
+ * and effort for the sub-agent, and so do the session uploader's traces.
* - A picked model that is not in the account's catalog, or that the
* gateway refused recently, resolves to the main model instead (a
* "selection" fallback, noted on the sub-agent session).
* - A request the gateway refuses while a sub-agent runs on the picked
* model is sent again on the main model by the gateway broker (a
* "gateway" fallback), which marks the model refused for a while; the
- * collector then records the main model on those sub-agent messages.
+ * session uploader then records the main model on those sub-agent messages.
*
* Kept free of engine-plugin imports; the plugin talks to it over HTTP.
*/
diff --git a/apps/server/src/omnirush-voice.ts b/apps/server/src/omnirush-voice.ts
index 0ba5db59..f83ec6ee 100644
--- a/apps/server/src/omnirush-voice.ts
+++ b/apps/server/src/omnirush-voice.ts
@@ -4,7 +4,7 @@
* to omnirush.ai's POST /omnirush/v1/audio/transcriptions with the device
* bearer (the renderer never holds it). The audio exists only in this
* request's memory: it is never written, logged, cached or handed to the
- * collector. Only the text the user finally sends becomes a prompt.
+ * session uploader. Only the text the user finally sends becomes a prompt.
*/
import { execFile } from "node:child_process";
import path from "node:path";
diff --git a/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts b/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts
index 8c660b5c..0af73d36 100644
--- a/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts
+++ b/apps/server/src/opencode-plugins/omnirush-chrome-devtools.ts
@@ -2,7 +2,7 @@
// through the desktop's conversation-scoped host. No unrestricted CDP tools.
import { z } from "zod";
import { uiBridgeRequest } from "./omnirush-ui-bridge.js";
-import { reportWebVisit } from "./omnirush-collector-client.js";
+import { reportWebVisit } from "./omnirush-session-upload-client.js";
const tabId = z.string().min(1).optional().describe("A tab returned by browser_tabs or browser_open in this conversation. Defaults to this conversation's active tab.");
const action = z.discriminatedUnion("type", [
diff --git a/apps/server/src/opencode-plugins/omnirush-collector-client.ts b/apps/server/src/opencode-plugins/omnirush-session-upload-client.ts
similarity index 89%
rename from apps/server/src/opencode-plugins/omnirush-collector-client.ts
rename to apps/server/src/opencode-plugins/omnirush-session-upload-client.ts
index 34ba4430..b9f6b170 100644
--- a/apps/server/src/opencode-plugins/omnirush-collector-client.ts
+++ b/apps/server/src/opencode-plugins/omnirush-session-upload-client.ts
@@ -1,5 +1,5 @@
// Reports what the engine's browser tools saw to the OmniRush.ai server's
-// workspace collector, for the session that owns the tool call. Best effort:
+// session uploader, for the session that owns the tool call. Best effort:
// a failed report never affects the tool result, and nothing is sent without
// the server address and token the server injects into the engine's environment.
const ANCESTRY_DEPTH = 4;
@@ -7,7 +7,7 @@ const REPORT_TIMEOUT_MS = 5_000;
/** Client-side bound on page text; the server redacts and applies the contract cap. */
const MAX_TEXT_CHARS = 96_000;
-export type CollectorWebVisitReport = {
+export type UploadWebVisitReport = {
url: string;
title?: string | null;
text?: string | null;
@@ -32,7 +32,7 @@ function serverToken(): string | null {
}
/** Mirrors the server-side rule: only public http(s) pages are ever traced. */
-export function isCollectableWebUrl(raw: string): boolean {
+export function isUploadableWebUrl(raw: string): boolean {
let url: URL;
try {
url = new URL(raw);
@@ -48,7 +48,7 @@ export function isCollectableWebUrl(raw: string): boolean {
/**
* Parent chain of a session (parent, grandparent, ...) so a subagent's visit
- * lands on the root session the collector tracks. Uses the engine SDK client
+ * lands on the root session the session uploader tracks. Uses the engine SDK client
* the plugin was created with; stops quietly when it is unavailable.
*/
export async function sessionAncestry(client: unknown, sessionId: string): Promise<string[]> {
@@ -73,14 +73,14 @@ export async function sessionAncestry(client: unknown, sessionId: string): Promi
return ancestry;
}
-export function reportWebVisit(client: unknown, sessionId: string, visit: CollectorWebVisitReport): void {
+export function reportWebVisit(client: unknown, sessionId: string, visit: UploadWebVisitReport): void {
const base = serverBase();
const token = serverToken();
- if (!base || !token || !sessionId || typeof visit.url !== "string" || !isCollectableWebUrl(visit.url)) return;
+ if (!base || !token || !sessionId || typeof visit.url !== "string" || !isUploadableWebUrl(visit.url)) return;
void (async () => {
const ancestry = await sessionAncestry(client, sessionId);
const text = typeof visit.text === "string" ? visit.text.slice(0, MAX_TEXT_CHARS) : null;
- await fetch(`${base}/collector/events`, {
+ await fetch(`${base}/session-upload/events`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({
diff --git a/apps/server/src/opencode-proxy.e2e.test.ts b/apps/server/src/opencode-proxy.e2e.test.ts
index 13243870..5ddd5461 100644
--- a/apps/server/src/opencode-proxy.e2e.test.ts
+++ b/apps/server/src/opencode-proxy.e2e.test.ts
@@ -8,14 +8,14 @@ import type { ServerConfig, WorkspaceInfo } from "./types.js";
// These tests dispatch prompts through a local workspace without an omnirush.ai
// account. The server's sign-in gate refuses that unless both development
-// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.
-const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };
+// flags are set; the gate itself is covered by session-uploader.server.e2e.test.ts.
+const uploadGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_SESSION_UPLOAD_OPTIONAL: process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL };
beforeAll(() => {
process.env.OMNIRUSH_DEV_MODE = "1";
- process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";
+ process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = "1";
});
afterAll(() => {
- for (const [name, value] of Object.entries(collectorGateEnv)) {
+ for (const [name, value] of Object.entries(uploadGateEnv)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
diff --git a/apps/server/src/project-archive.test.ts b/apps/server/src/project-archive.test.ts
index 3ab27df8..fc16d3f0 100644
--- a/apps/server/src/project-archive.test.ts
+++ b/apps/server/src/project-archive.test.ts
@@ -64,12 +64,12 @@ async function gitProject(): Promise<string> {
const rootSession = { session: async () => ({ id: "ses_project_0001" }), messages: async () => [] };
describe("createProjectArchive", () => {
- test("with an account, archives go through the gateway broker's device session into the collector state dir", async () => {
+ test("with an account, archives go through the gateway broker's device session into the session uploader state dir", async () => {
const server = new FakeArchiveServer();
const gateway = broker(server);
const stateDir = await tempDir("state");
const root = await gitProject();
- const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, collectorEnabled: true, log: () => undefined, env: {}, fetch: server.respond });
+ const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, uploadEnabled: true, log: () => undefined, env: {}, fetch: server.respond });
archive.start();
archive.sessionStarted({ sessionId: "ses_project_0001", root, engine: rootSession });
await archive.settled();
@@ -87,7 +87,7 @@ describe("createProjectArchive", () => {
const stateDir = await tempDir("state");
const root = await gitProject();
const slow = slowPartTwo(server);
- const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, collectorEnabled: true, log: () => undefined, env: {}, fetch: slow.fetch });
+ const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, uploadEnabled: true, log: () => undefined, env: {}, fetch: slow.fetch });
archive.start();
archive.sessionStarted({ sessionId: "ses_project_0001", root, engine: rootSession });
await slow.started;
@@ -117,7 +117,7 @@ describe("createProjectArchive", () => {
const archive = createProjectArchive({
config: serverConfig(stateDir),
gatewayBroker: gateway,
- collectorEnabled: true,
+ uploadEnabled: true,
log: () => undefined,
env: { OMNIRUSH_ARCHIVE_ENABLED: "0", OMNIRUSH_GATEWAY_URL: server.gatewayUrl, OMNIRUSH_ACCESS_TOKEN: server.token },
fetch: async (input, init) => {
@@ -136,19 +136,19 @@ describe("createProjectArchive", () => {
});
test("the desktop's userData dir (OMNIRUSH_DESKTOP_USER_DATA_DIR) is where the all-folders policy may not archive a folder", async () => {
- const input = { config: serverConfig(await tempDir("state")), gatewayBroker: broker(new FakeArchiveServer()), collectorEnabled: true };
+ const input = { config: serverConfig(await tempDir("state")), gatewayBroker: broker(new FakeArchiveServer()), uploadEnabled: true };
expect(projectArchiveSettings({ ...input, env: { OMNIRUSH_DESKTOP_USER_DATA_DIR: " /Users/sam/Library/Application Support/ai.omnirush.desktop " } }).folderGate).toEqual({
userDataDir: "/Users/sam/Library/Application Support/ai.omnirush.desktop",
});
expect(projectArchiveSettings({ ...input, env: {} }).folderGate).toEqual({});
});
- test("signed out (no collector account): the same clearing, nothing archived", async () => {
+ test("signed out (no session uploader account): the same clearing, nothing archived", async () => {
const server = new FakeArchiveServer();
const gateway = { ...broker(server), enabled: false };
const stateDir = await tempDir("state");
await mkdir(join(stateDir, ARCHIVE_STATE_DIRECTORY, "queue"), { recursive: true });
- const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, collectorEnabled: false, log: () => undefined, env: {} });
+ const archive = createProjectArchive({ config: serverConfig(stateDir), gatewayBroker: gateway, uploadEnabled: false, log: () => undefined, env: {} });
archive.start();
archive.sessionStarted({ sessionId: "ses_project_0001", root: await gitProject(), engine: rootSession });
await archive.settled();
diff --git a/apps/server/src/project-archive.ts b/apps/server/src/project-archive.ts
index c979b0dd..cec223f5 100644
--- a/apps/server/src/project-archive.ts
+++ b/apps/server/src/project-archive.ts
@@ -1,9 +1,9 @@
/**
* The embedded server's project archiver (session-archive/README.md,
- * "Wiring"): one per server, authenticated like the workspace collector
- * (through the gateway broker's device session, or the collector's
+ * "Wiring"): one per server, authenticated like the session uploader
+ * (through the gateway broker's device session, or the session uploader's
* environment token when there is no broker), with its files in
- * `<collector state dir>/omnirush-archive/`.
+ * `<session uploader state dir>/omnirush-archive/`.
*/
import { dirname } from "node:path";
import { omnirushConfigDir, omnirushServerDataDir, opencodeCacheDirs, opencodeDataDirs } from "@omnirush/paths";
@@ -39,8 +39,8 @@ function appDirectories(config: ServerConfig): string[] {
type ProjectArchiveInput = {
config: ServerConfig;
gatewayBroker: Pick<OmniRushGatewayBroker, "enabled" | "archiveRequest" | "refreshAccessToken">;
- /** The workspace collector has an account to upload to. */
- collectorEnabled: boolean;
+ /** The session uploader has an account to upload to. */
+ uploadEnabled: boolean;
env?: NodeJS.ProcessEnv;
};
@@ -62,7 +62,7 @@ export function projectArchiveSettings(input: ProjectArchiveInput): {
accessToken?: string;
} {
const env = input.env ?? process.env;
- const enabled = projectArchiveEnabled(env) && input.collectorEnabled;
+ const enabled = projectArchiveEnabled(env) && input.uploadEnabled;
const userDataDir = env.OMNIRUSH_DESKTOP_USER_DATA_DIR?.trim();
const base = { stateDir: runtimeStorageDir(input.config), excludedDirs: appDirectories(input.config), folderGate: userDataDir ? { userDataDir } : {}, enabled };
if (!enabled) return { ...base, auth: "none" };
diff --git a/apps/server/src/routes/local-workflows.ts b/apps/server/src/routes/local-workflows.ts
index 1eb6ca2d..57dd3563 100644
--- a/apps/server/src/routes/local-workflows.ts
+++ b/apps/server/src/routes/local-workflows.ts
@@ -16,7 +16,7 @@ export interface RegisterLocalWorkflowRoutesOptions {
resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
resolveWorkspaceWithoutBootstrap: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
createWorkspaceOpencodeClient: (config: ServerConfig, workspace: WorkspaceInfo, options?: { sessionId?: string }) => ReturnType<typeof createOpencodeClient>;
- /** Step prompts go through the server's gated, collected engine proxy. */
+ /** Step prompts go through the server's gated, captured engine proxy. */
promptDispatcher: LocalWorkflowPromptDispatcher;
}
const previewSchema = z.object({
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 2964cff7..911307ec 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -189,9 +189,9 @@ import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";
import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";
-import { workspaceCollectorEnabled } from "./workspace-collector.js";
+import { sessionUploaderEnabled } from "./session-uploader.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
-import { buildOpencodeProxyUrl, engineTarget } from "./collector-observer.js";
+import { buildOpencodeProxyUrl, engineTarget } from "./session-upload-observer.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
import { startOmniRushModelCatalogSync } from "./omnirush-model-catalog-sync.js";
import { OmniRushVoiceService, voiceProjectContext } from "./omnirush-voice.js";
@@ -224,8 +224,8 @@ const subagentGatewayFallbacks = new WeakMap<ServerConfig, Map<string, Array<Rec
/**
* Records a sub-agent model fallback: a "subagent.model_fallback" trace event
- * on the main session the collector tracks (a gateway fallback also makes the
- * collector record the model those sub-agent messages really ran on), and,
+ * on the main session the session uploader tracks (a gateway fallback also makes the
+ * session uploader record the model those sub-agent messages really ran on), and,
* for a gateway fallback, the per-session note the swarm plugin reads back.
*/
function recordSubagentModelFallback(config: ServerConfig, rootSessionId: string | null, data: Record<string, unknown>): void {
@@ -243,7 +243,7 @@ function recordSubagentModelFallback(config: ServerConfig, rootSessionId: string
while (byChild.size > 512) byChild.delete(byChild.keys().next().value as string);
}
const capture = captureServicesByServer.get(config);
- if (!rootSessionId || !capture?.collectorEnabled || !capture.hasSession(rootSessionId)) return;
+ if (!rootSessionId || !capture?.uploadEnabled || !capture.hasSession(rootSessionId)) return;
capture.recordTrace(rootSessionId, SUBAGENT_MODEL_FALLBACK_TRACE, data);
}
@@ -261,7 +261,11 @@ const AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES = 256 * 1024;
const AGENT_DIAGNOSTICS_DEFAULT_BODY_DEADLINE_MS = 2_000;
const AGENT_DIAGNOSTICS_ERROR_FLUSH_MS = 25;
const COMMAND_ADMISSION_CAPACITY = 10_000;
-const COLLECTOR_EVENTS_MAX_REQUEST_BYTES = 1024 * 1024;
+const UPLOAD_EVENTS_MAX_REQUEST_BYTES = 1024 * 1024;
+/** Where engine plugins report browser visits (opencode-plugins/omnirush-session-upload-client.ts). */
+const SESSION_UPLOAD_EVENTS_ROUTE = "/session-upload/events";
+/** The same route under its pre-2.2.2 name. */
+const LEGACY_SESSION_UPLOAD_EVENTS_ROUTE = "/collector/events";
const COMMAND_ADMISSION_TTL_MS = 24 * 60 * 60 * 1_000;
function rethrowMcpAppHostError(error: unknown): never {
@@ -810,58 +814,59 @@ function isPromptAsyncProxyRequest(method: string, proxyPath: string) {
}
// A prompt dispatch (v1 prompt_async, v2 prompt, or a slash command) is the
-// collector's "prompt" milestone: the workspace is captured as the turn begins.
-function isCollectorPromptDispatch(method: string, proxyPath: string): boolean {
+// session uploader's "prompt" milestone: the workspace is captured as the turn begins.
+function isUploadPromptDispatch(method: string, proxyPath: string): boolean {
return method === "POST" && /^\/session\/[^/]+\/(?:prompt_async|prompt|command)$/.test(normalizeOpencodeProxyPath(proxyPath));
}
/**
* Sign-in gate. A local workspace only runs sessions the omnirush.ai
- * collector can capture; without a connected account the engine prompt
- * dispatch is refused so no uncollected turn ever starts. The bypass exists
+ * session uploader can capture; without a connected account the engine prompt
+ * dispatch is refused so no uncaptured turn ever starts. The bypass exists
* for development and tests, and requires both flags on purpose.
*/
export const OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE = "Sign in to omnirush.ai from Settings to start a session.";
-export function collectorGateBypassed(env: NodeJS.ProcessEnv = process.env): boolean {
- return env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_COLLECTION_OPTIONAL === "1";
+export function uploadGateBypassed(env: NodeJS.ProcessEnv = process.env): boolean {
+ // OMNIRUSH_COLLECTION_OPTIONAL is the pre-2.2.2 name of the second flag, still honoured.
+ return env.OMNIRUSH_DEV_MODE === "1" && (env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL === "1" || env.OMNIRUSH_COLLECTION_OPTIONAL === "1");
}
-function collectorAccountRequiredResponse(): Response {
+function uploadAccountRequiredResponse(): Response {
return jsonResponse({ error: "omnirush_account_required", message: OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE }, 403);
}
/**
* Whether the gate refuses a prompt dispatch on this workspace: a local
- * workspace whose collector cannot capture the turn, without the development
+ * workspace whose session uploader cannot capture the turn, without the development
* bypass. A remote workspace is gated by the server that owns it. Every
* dispatch path (v1 mount, v2 mount, workflow steps) asks this one predicate.
*/
-function collectorDispatchRefused(config: ServerConfig, workspace: WorkspaceInfo | undefined): boolean {
+function uploadDispatchRefused(config: ServerConfig, workspace: WorkspaceInfo | undefined): boolean {
if (!workspace || workspace.workspaceType === "remote") return false;
- return !captureServicesByServer.get(config)?.collectorEnabled && !collectorGateBypassed();
+ return !captureServicesByServer.get(config)?.uploadEnabled && !uploadGateBypassed();
}
/** The gate as an ApiError, for dispatches that are not proxied HTTP requests. */
-export function assertCollectorDispatchAllowed(config: ServerConfig, workspace: WorkspaceInfo | undefined): void {
- if (collectorDispatchRefused(config, workspace)) {
+export function assertUploadDispatchAllowed(config: ServerConfig, workspace: WorkspaceInfo | undefined): void {
+ if (uploadDispatchRefused(config, workspace)) {
throw new ApiError(403, "omnirush_account_required", OMNIRUSH_ACCOUNT_REQUIRED_MESSAGE);
}
}
// The v2 daemon's dispatch routes, matched on the decoded path like the v1 classifier.
-function isCollectorV2PromptDispatch(method: string, routePath: string): boolean {
+function isUploadV2PromptDispatch(method: string, routePath: string): boolean {
return method === "POST" && /^\/api\/session\/[^/]+\/(?:prompt|prompt_async|command|generate)$/.test(routePath.replace(/\/+$/, ""));
}
/**
* Workflow steps are prompt dispatches like any other: they enter the same
- * engine proxy as the app's requests, so the gate, the collector's session
+ * engine proxy as the app's requests, so the gate, the session uploader's session
* start, prompt snapshot, request/response trace and turn observer all apply.
*/
export function createLocalWorkflowPromptDispatcher(config: ServerConfig): LocalWorkflowPromptDispatcher {
return {
- assertAllowed: (workspace) => assertCollectorDispatchAllowed(config, workspace),
+ assertAllowed: (workspace) => assertUploadDispatchAllowed(config, workspace),
prompt: (workspace, sessionId, body, signal) => {
const proxyPath = `/opencode/session/${encodeURIComponent(sessionId)}/prompt`;
const url = new URL(`http://127.0.0.1${proxyPath}`);
@@ -876,15 +881,15 @@ export function createLocalWorkflowPromptDispatcher(config: ServerConfig): Local
};
}
-// The session a collected engine request belongs to, read from the decoded
+// The session a captured engine request belongs to, read from the decoded
// route path exactly as the engine reads its `:id` parameter. Null when the
// path is not a session request or its identifier is malformed.
-function collectorSessionId(proxyPath: string): string | null {
+function uploadSessionId(proxyPath: string): string | null {
const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)\/(?:prompt_async|prompt|command|abort|interrupt)$/);
return match?.[1] ? decodeEngineRouteParam(match[1]) : null;
}
-function collectorDeletedSessionId(method: string, proxyPath: string): string | null {
+function uploadDeletedSessionId(method: string, proxyPath: string): string | null {
if (method !== "DELETE") return null;
const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)$/);
return match?.[1] ? decodeEngineRouteParam(match[1]) : null;
@@ -965,7 +970,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
? {
...gatewayCredentials,
// Revoked or expired omnirush.ai credentials also discard spooled
- // collector uploads and queued project archives: a signed-out
+ // session uploads and queued project archives: a signed-out
// account leaves nothing queued.
invalidate: async () => {
await capture.signOut();
@@ -975,7 +980,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
: undefined,
engineToken: config.omnirushEngineToken,
// A sub-agent request moved to the main model: new sub-agent prompts skip
- // the refused model for a while, and the collector records the model the
+ // the refused model for a while, and the session uploader records the model the
// sub-agent's messages really ran on.
subagentModelRefused: (model) => subagentModelRefusals(config).isRefused(model),
onSubagentFallback: (event) => {
@@ -1002,22 +1007,22 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
const appVersion = config.appVersion?.trim()
|| process.env.OMNIRUSH_APP_VERSION?.trim()
|| SERVER_VERSION;
- // The workspace collector, and whole-folder archives of git projects beside
+ // The session uploader, and whole-folder archives of git projects beside
// it (session-archive/README.md), run on the capture worker: their file
// work never holds this event loop (capture-client.ts).
const archiveSettings = projectArchiveSettings({
config,
gatewayBroker,
- collectorEnabled: workspaceCollectorEnabled({ upload: gatewayBroker.enabled }),
+ uploadEnabled: sessionUploaderEnabled({ upload: gatewayBroker.enabled }),
});
const capture = startCaptureService({
stateDir: runtimeStorageDir(config),
appVersion,
engineVersion: OPENCODE_VERSION,
log: (level, message, attributes) => logger.log(level, message, attributes),
- collector: gatewayBroker.enabled
+ sessionUploader: gatewayBroker.enabled
? {
- upload: (sessionId, compressed, signal) => gatewayBroker.collect(sessionId, compressed, signal),
+ upload: (sessionId, compressed, signal) => gatewayBroker.uploadSession(sessionId, compressed, signal),
refreshAccessToken: () => gatewayBroker.refreshAccessToken(),
}
: {},
@@ -1496,9 +1501,9 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
}
/**
- * The engine v2 preview mount. A prompt dispatch here is gated and collected
+ * The engine v2 preview mount. A prompt dispatch here is gated and captured
* exactly like one on the v1 mount: refused without a connected account
- * (unless both development flags are set), otherwise the collector starts the
+ * (unless both development flags are set), otherwise the session uploader starts the
* session, captures the prompt snapshot, traces the request and response and
* observes the turn until it settles. Exported for the mount's tests.
*/
@@ -1517,7 +1522,7 @@ export async function proxyOpencodeV2Request(input: {
const withoutPrefix = input.proxyPath.slice("/opencode2".length);
const forwardedPath = withoutPrefix || "/";
// Classify on the path as the daemon's router matches it (see engine-route-path),
- // so an encoded spelling of a dispatch route cannot skip the gate or the collector.
+ // so an encoded spelling of a dispatch route cannot skip the gate or the session uploader.
const routePath = decodeEngineRoutePath(forwardedPath);
// The private-route checks match the fully decoded spelling as before; a
// malformed escape (which the daemon leaves in place) falls back to the
@@ -1534,17 +1539,17 @@ export async function proxyOpencodeV2Request(input: {
}
const sessionMatch = routePath.match(/^\/api\/session\/([^/]+)(?:\/|$)/);
const sessionId = sessionMatch?.[1] ? decodeEngineRouteParam(sessionMatch[1]) : null;
- const promptDispatch = isCollectorV2PromptDispatch(method, routePath);
+ const promptDispatch = isUploadV2PromptDispatch(method, routePath);
const collectible = input.workspace.workspaceType !== "remote";
if (promptDispatch && collectible) {
- if (collectorDispatchRefused(input.config, input.workspace)) {
+ if (uploadDispatchRefused(input.config, input.workspace)) {
// Drain the unread body so the client's keep-alive connection stays usable.
await input.request.arrayBuffer().catch(() => undefined);
- return collectorAccountRequiredResponse();
+ return uploadAccountRequiredResponse();
}
if (sessionId === null) {
- // A dispatch is either refused or collected: a session identifier the
- // daemon cannot decode would start a turn the collector cannot attribute.
+ // A dispatch is either refused or captured: a session identifier the
+ // daemon cannot decode would start a turn the session uploader cannot attribute.
await input.request.arrayBuffer().catch(() => undefined);
return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
}
@@ -1651,23 +1656,23 @@ export async function proxyOpencodeV2Request(input: {
// its first dispatch, the prompt milestone is snapshotted, the request and
// response are traced and the turn is observed until it settles.
const capture = collectible ? captureServicesByServer.get(input.config) : undefined;
- const collectedSessionId = capture?.collectorEnabled && promptDispatch && sessionId ? sessionId : null;
- const deletedCollectedSessionId = capture?.collectorEnabled && method === "DELETE" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath)
+ const uploadedSessionId = capture?.uploadEnabled && promptDispatch && sessionId ? sessionId : null;
+ const deletedUploadedSessionId = capture?.uploadEnabled && method === "DELETE" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath)
? sessionId
: null;
- const engine = capture && collectedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;
- if (capture && collectedSessionId && engine) {
- capture.startSession(collectedSessionId, input.workspace.id, input.workspace.path);
- capture.recordPrompt(collectedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
- capture.captureSnapshot(collectedSessionId, "prompt");
- capture.archiveSessionStarted(collectedSessionId, input.workspace.path, engine);
+ const engine = capture && uploadedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;
+ if (capture && uploadedSessionId && engine) {
+ capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path);
+ capture.recordPrompt(uploadedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
+ capture.captureSnapshot(uploadedSessionId, "prompt");
+ capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);
}
const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });
- if (capture && collectedSessionId && engine) {
- capture.recordTrace(collectedSessionId, "engine.response", { method, path: routePath, status: response.status });
- if (response.ok) capture.observeSession(collectedSessionId, engine);
+ if (capture && uploadedSessionId && engine) {
+ capture.recordTrace(uploadedSessionId, "engine.response", { method, path: routePath, status: response.status });
+ if (response.ok) capture.observeSession(uploadedSessionId, engine);
}
- if (capture && deletedCollectedSessionId && response.ok) capture.sessionDeleted(deletedCollectedSessionId);
+ if (capture && deletedUploadedSessionId && response.ok) capture.sessionDeleted(deletedUploadedSessionId);
if (method === "GET" && /^\/api\/provider(?:\/|$)/.test(decodedPath) && response.ok) {
// Provider.Info includes request settings/headers, which may contain the
// mirrored server-owned key. Clients only need public catalog metadata.
@@ -1947,15 +1952,15 @@ export async function proxyOpencodeRequest(input: {
if (method !== "GET" && method !== "HEAD") {
ensureWritable(input.config);
}
- if (workspace && workspace.workspaceType !== "remote" && isCollectorPromptDispatch(method, proxyPath)) {
- if (collectorDispatchRefused(input.config, workspace)) {
+ if (workspace && workspace.workspaceType !== "remote" && isUploadPromptDispatch(method, proxyPath)) {
+ if (uploadDispatchRefused(input.config, workspace)) {
// Drain the unread body so the client's keep-alive connection stays usable.
await input.request.arrayBuffer().catch(() => undefined);
- return collectorAccountRequiredResponse();
+ return uploadAccountRequiredResponse();
}
- if (collectorSessionId(proxyPath) === null) {
- // A dispatch is either refused or collected: a session identifier the
- // engine cannot decode would start a turn the collector cannot attribute.
+ if (uploadSessionId(proxyPath) === null) {
+ // A dispatch is either refused or captured: a session identifier the
+ // engine cannot decode would start a turn the session uploader cannot attribute.
await input.request.arrayBuffer().catch(() => undefined);
return jsonResponse({ error: "invalid_session_id", message: "The session identifier is not valid." }, 400);
}
@@ -1999,12 +2004,12 @@ export async function proxyOpencodeRequest(input: {
? undefined
: await input.request.arrayBuffer().then((buf) => (buf.byteLength > 0 ? buf : undefined));
const capture = workspace ? captureServicesByServer.get(input.config) : undefined;
- const collectedSessionId = collectorSessionId(proxyPath);
- const deletedCollectedSessionId = collectorDeletedSessionId(method, proxyPath);
- if (capture?.collectorEnabled && collectedSessionId && workspace && workspace.workspaceType !== "remote") {
- const promptDispatch = isCollectorPromptDispatch(method, proxyPath);
- capture.startSession(collectedSessionId, workspace.id, workspace.path);
- capture.recordPrompt(collectedSessionId, {
+ const uploadedSessionId = uploadSessionId(proxyPath);
+ const deletedUploadedSessionId = uploadDeletedSessionId(method, proxyPath);
+ if (capture?.uploadEnabled && uploadedSessionId && workspace && workspace.workspaceType !== "remote") {
+ const promptDispatch = isUploadPromptDispatch(method, proxyPath);
+ capture.startSession(uploadedSessionId, workspace.id, workspace.path);
+ capture.recordPrompt(uploadedSessionId, {
method,
path: normalizeOpencodeProxyPath(proxyPath),
body,
@@ -2015,8 +2020,8 @@ export async function proxyOpencodeRequest(input: {
...(promptDispatch ? { dispatchedAt: Date.now() } : {}),
});
if (promptDispatch) {
- capture.captureSnapshot(collectedSessionId, "prompt");
- capture.archiveSessionStarted(collectedSessionId, workspace.path, engineTarget(baseUrl, headers, search));
+ capture.captureSnapshot(uploadedSessionId, "prompt");
+ capture.archiveSessionStarted(uploadedSessionId, workspace.path, engineTarget(baseUrl, headers, search));
}
}
if (pool && method === "GET" && isEngineEventPath(proxyPath)) {
@@ -2098,18 +2103,18 @@ export async function proxyOpencodeRequest(input: {
body,
}).finally(() => release?.()).then((response) => {
enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);
- if (capture?.collectorEnabled && collectedSessionId) {
- capture.recordTrace(collectedSessionId, "engine.response", {
+ if (capture?.uploadEnabled && uploadedSessionId) {
+ capture.recordTrace(uploadedSessionId, "engine.response", {
method,
path: normalizeOpencodeProxyPath(proxyPath),
status: response.status,
});
- if (workspace && response.ok) capture.observeSession(collectedSessionId, engineTarget(baseUrl, headers, search));
+ if (workspace && response.ok) capture.observeSession(uploadedSessionId, engineTarget(baseUrl, headers, search));
}
}).catch((error: unknown) => {
if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(baseUrl, error, workspace);
- if (capture?.collectorEnabled && collectedSessionId) {
- capture.recordTrace(collectedSessionId, "engine.error", {
+ if (capture?.uploadEnabled && uploadedSessionId) {
+ capture.recordTrace(uploadedSessionId, "engine.error", {
method,
path: normalizeOpencodeProxyPath(proxyPath),
error: error instanceof Error ? error.message : "unknown",
@@ -2169,36 +2174,36 @@ export async function proxyOpencodeRequest(input: {
return sanitizeProxyResponse(response);
};
- const forwardAndCollect = async () => {
+ const forwardAndUpload = async () => {
const response = await forward();
- if (capture?.collectorEnabled && collectedSessionId) {
- capture.recordTrace(collectedSessionId, "engine.response", {
+ if (capture?.uploadEnabled && uploadedSessionId) {
+ capture.recordTrace(uploadedSessionId, "engine.response", {
method,
path: normalizeOpencodeProxyPath(proxyPath),
status: response.status,
});
- if (workspace && response.ok) capture.observeSession(collectedSessionId, engineTarget(served.baseUrl, served.headers, search));
+ if (workspace && response.ok) capture.observeSession(uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));
}
- if (capture?.collectorEnabled && deletedCollectedSessionId && response.ok) capture.sessionDeleted(deletedCollectedSessionId);
+ if (capture?.uploadEnabled && deletedUploadedSessionId && response.ok) capture.sessionDeleted(deletedUploadedSessionId);
return response;
};
- if (deletedCollectedSessionId && workspace && workspace.workspaceType !== "remote") {
+ if (deletedUploadedSessionId && workspace && workspace.workspaceType !== "remote") {
await stopSessionTreeBeforeDelete(
pool
? pool.connections().map((connection) => ({ baseUrl: connection.baseUrl, headers: headersForEngineConnection(headers, connection) }))
: [{ baseUrl, headers }],
- deletedCollectedSessionId,
+ deletedUploadedSessionId,
directory,
);
}
if (workspace && workspace.workspaceType !== "remote" && isPromptAsyncProxyRequest(method, proxyPath)) {
- return withEngineDirectoryFence(input.config, workspace, forwardAndCollect);
+ return withEngineDirectoryFence(input.config, workspace, forwardAndUpload);
}
if (pool && workspace && workspace.workspaceType !== "remote" && isSessionListRequest(method, normalizeOpencodeProxyPath(proxyPath))) {
- return serveLocalSessionList(input.config, workspace, search, forwardAndCollect());
+ return serveLocalSessionList(input.config, workspace, search, forwardAndUpload());
}
- return forwardAndCollect();
+ return forwardAndUpload();
}
const emptySessionDirectoriesByServer = new WeakMap<ServerConfig, EmptySessionDirectoryCache>();
@@ -3580,14 +3585,14 @@ function createRoutes(
// Engine plugins (the browser tools) report what they saw for the owning
// session. The evaluation token the managed-policy plugin already holds
// authenticates the call; a client token works too.
- addRoute(routes, "POST", "/collector/events", "policy", async (ctx) => {
+ const sessionUploadEvents = async (ctx: RequestContext) => {
const declared = Number(ctx.request.headers.get("content-length") ?? "0");
- if (Number.isFinite(declared) && declared > COLLECTOR_EVENTS_MAX_REQUEST_BYTES) {
- throw new ApiError(413, "collector_events_too_large", "Collector event payload is too large");
+ if (Number.isFinite(declared) && declared > UPLOAD_EVENTS_MAX_REQUEST_BYTES) {
+ throw new ApiError(413, "session_upload_events_too_large", "Session upload event payload is too large");
}
const raw = await ctx.request.text();
- if (raw.length > COLLECTOR_EVENTS_MAX_REQUEST_BYTES) {
- throw new ApiError(413, "collector_events_too_large", "Collector event payload is too large");
+ if (raw.length > UPLOAD_EVENTS_MAX_REQUEST_BYTES) {
+ throw new ApiError(413, "session_upload_events_too_large", "Session upload event payload is too large");
}
let body: unknown;
try {
@@ -3602,8 +3607,8 @@ function createRoutes(
? body.ancestry.filter((id): id is string => typeof id === "string" && id.length > 0).slice(0, 8)
: [];
const capture = captureServicesByServer.get(config);
- if (!capture?.collectorEnabled) return jsonResponse({ ok: true, recorded: 0 });
- // A subagent's tool call belongs to the root session the collector tracks.
+ if (!capture?.uploadEnabled) return jsonResponse({ ok: true, recorded: 0 });
+ // A subagent's tool call belongs to the root session the session uploader tracks.
const target = [body.sessionId, ...ancestry].find((id) => capture.hasSession(id));
if (!target) return jsonResponse({ ok: true, recorded: 0 });
let recorded = 0;
@@ -3617,7 +3622,10 @@ function createRoutes(
if (capture.recordWebVisit(target, visit)) recorded += 1;
}
return jsonResponse({ ok: true, recorded });
- });
+ };
+ addRoute(routes, "POST", SESSION_UPLOAD_EVENTS_ROUTE, "policy", sessionUploadEvents);
+ // The route's pre-2.2.2 path, kept so an engine plugin built before the rename still reports.
+ addRoute(routes, "POST", LEGACY_SESSION_UPLOAD_EVENTS_ROUTE, "policy", sessionUploadEvents);
// Sub-agent model and effort (omnirush-subagent-model.ts). The app reads
// and writes the setting; the swarm engine plugin resolves every sub-agent
diff --git a/apps/server/src/session-archive/README.md b/apps/server/src/session-archive/README.md
index 31a97e48..ef91e5f2 100644
--- a/apps/server/src/session-archive/README.md
+++ b/apps/server/src/session-archive/README.md
@@ -17,7 +17,7 @@ touched there, see "Touched files" below):
"Final archives" below.
Each archive is a pax tar, compressed with zstd and sealed with ORSEAL01 to the
-omnirush.ai archive key. It is queued durably under the collector state dir and
+omnirush.ai archive key. It is queued durably under the session uploader state dir and
uploaded straight to S3 through presigned multipart URLs.
The normative specification is `docs/omnirush-project-archive.md` in the
@@ -37,8 +37,8 @@ The user-facing description is `docs/project-archive.md`.
| `detect.ts` | `isArchivableProject(root, detectors?, options?)`, `gitMarkerDetector` and `gitParentDetector` (section 4). A pluggable gate; the `.git` marker, in the root or (`git_parent`) in the nearest parent (a `.git` folder there must hold `HEAD`), never at any account's home on any volume or share, a filesystem, drive, share or mount root, or in a system or app directory (on a UNC share such as `\\wsl$\<distro>`, also `usr`, `etc`, `var`, `opt` and `root`). A `git_parent` root is archived alone, without the parent's `.git`. `folderDetector` / `folderRootRefusal` / `refusedFolderRoot` for the all-folders and touched-files policies (4.4): markers `folder` and `touched` |
| `policy.ts` | `parseArchivePolicy`: `policy.all_folders` and `policy.touched_files` from the GET /archives/key body; anything but `true` is off |
| `touched.ts` | Touched-files mode: `TouchedPathStore` (each session's touched paths, appended to `touched/<session>.jsonl`), `scanTouchedFiles` (pass 1 over those paths only: lstat from the root, never through a link out of it, a touched folder never expanded) and `touchedChange` (the delta and the next baseline) |
-| `ignore.ts` | Gitignored content: `ArchiveIgnore` (the scan's per-folder ignore scopes: `git ls-files --others --ignored --exclude-standard --directory` in the root's repository, in a nested repository, or with a private empty `GIT_DIR` for a folder in none; the collector's walkFallback `.gitignore` rules without git) and `touchedIgnoredPaths` (`git check-ignore` over touched files only) |
-| `manifest.ts` | Scan with the exclusions and credential filter (5.2, 5.3; reuses the collector's `isCollectorPathDenied`, `stripRemoteUserinfo` and `clampCollectorBytes`), streaming SHA-256 with the `(path, size, mtimeNs, ctimeNs, ino)` hash cache, delta computation (5.8), `manifest.json` (5.6) and the git block (`path` from `git rev-parse --show-prefix`; git runs with `GIT_CEILING_DIRECTORIES` set to the real home so it never climbs into home) |
+| `ignore.ts` | Gitignored content: `ArchiveIgnore` (the scan's per-folder ignore scopes: `git ls-files --others --ignored --exclude-standard --directory` in the root's repository, in a nested repository, or with a private empty `GIT_DIR` for a folder in none; the session uploader's walkFallback `.gitignore` rules without git) and `touchedIgnoredPaths` (`git check-ignore` over touched files only) |
+| `manifest.ts` | Scan with the exclusions and credential filter (5.2, 5.3; reuses the session uploader's `isUploadPathDenied`, `stripRemoteUserinfo` and `clampUploadBytes`), streaming SHA-256 with the `(path, size, mtimeNs, ctimeNs, ino)` hash cache, delta computation (5.8), `manifest.json` (5.6) and the git block (`path` from `git rev-parse --show-prefix`; git runs with `GIT_CEILING_DIRECTORIES` set to the real home so it never climbs into home) |
| `pack.ts` | Streaming pax tar writer (5.5) with unstable-entry detection (5.9), and the file -> tar -> zstd -> ORSEAL01 -> temp file pipeline (5.10, 13.1) |
| `seal.ts` | Streaming ORSEAL01 sealer and opener (section 6) over Node `crypto` |
| `upload.ts` | Multipart upload client over an injectable `fetch` (sections 7 and 13.5) |
@@ -53,10 +53,10 @@ The user-facing description is `docs/project-archive.md`.
import { SessionArchiver } from "./session-archive/index.js";
const archiver = new SessionArchiver({
- stateDir, // the collector state dir; files go to <stateDir>/omnirush-archive/
+ stateDir, // the session uploader state dir; files go to <stateDir>/omnirush-archive/
request, // authenticated API calls (see "Authentication" below), or:
gatewayUrl, accessToken, // the gateway URL plus a bearer,
- refreshAccessToken, // and the collector's refresh hook
+ refreshAccessToken, // and the session uploader's refresh hook
excludedDirs, // app data/temp dirs to prune when they sit under a project root
archiveIncludeCredentialFiles, // default false
log,
@@ -101,15 +101,15 @@ archiving off.
### As implemented
`../project-archive.ts` works out one archiver per server
-(`projectArchiveSettings`): the collector's state dir
+(`projectArchiveSettings`): the session uploader's state dir
(`runtimeStorageDir(config)`), the gateway broker's `archiveRequest` and
-`refreshAccessToken` (or, without a broker, the collector's
+`refreshAccessToken` (or, without a broker, the session uploader's
`OMNIRUSH_GATEWAY_URL` + `OMNIRUSH_ACCESS_TOKEN`), and the app's config, data
and OpenCode data/cache dirs as `excludedDirs`. The archiver is wrapped in a
-`ProjectArchiveLifecycle`, which is enabled when the collector has an account
+`ProjectArchiveLifecycle`, which is enabled when the session uploader has an account
and `OMNIRUSH_ARCHIVE_ENABLED` is not `0`/`false`/`no`/`off`.
-The lifecycle, its `SessionArchiver` and the workspace collector run
+The lifecycle, its `SessionArchiver` and the session uploader run
together in `../capture-host.ts`, which `server.ts` starts on a worker thread
(`../capture-client.ts`, `../capture-worker.ts`): scanning, hashing, tar,
zstd and sealing never run on the server's main event loop, which in the
@@ -125,14 +125,14 @@ in `captureServicesByServer` and calls:
| Server hook | Lifecycle call |
| --- | --- |
| `startServer` (`startCaptureService`) | `start()`: a drain and the app-start final archives when enabled; otherwise `signOut()` clears what a previous run left (a no-op, touching nothing, when there is no `omnirush-archive/`) |
-| A prompt dispatch on a local workspace (v1 `prompt_async`/`prompt`/`command`, v2 `prompt`/`prompt_async`/`command`/`generate`), after the collector's `startSession` | `sessionStarted({sessionId, root: workspace.path, engine})`, the engine reads built on the worker from the request's engine target |
-| The collector observer starts following a turn (on the worker): the first of an observation, or the next one after a request that came in while a turn settled | `turnFollowed(sessionId)`: the session's idle final archive is off until that turn ends |
-| The collector observer's `turn_completed` (on the worker), with the engine messages it just read (null when it could not read them), however long the turn ran | `turnCompleted(sessionId, messages)` |
-| The collector observer stops following a turn without seeing it settle: `session.observer_timeout` (its 24-hour safety bound) or `session.observer_failed` (an unexpected error; an engine that times out, drops the connection or restarts is waited out). A server stop ends an observation without this call | `turnIncomplete(sessionId)` |
-| The collector's `onPathTouched` (on the worker, in `capture-host.ts`, so no message crosses to the main thread): a path in the root from a trace event (`recordTrace`, a child session's messages), a watcher event, the reconcile pass, the end-of-turn artifact scan, or a change capture's scan, before the collector's own denylist | `pathTouched(sessionId, path)`: passed to `SessionArchiver.recordTouched` for a session this run started that may be archived (resolved with a root, or not resolved yet); a child session's paths are dropped (`forgetTouched`) |
-| `collector.finishSession` (session deleted) | `sessionEnded(sessionId)`: a final archive (`session_deleted`), then the session is forgotten; kicks a drain |
+| A prompt dispatch on a local workspace (v1 `prompt_async`/`prompt`/`command`, v2 `prompt`/`prompt_async`/`command`/`generate`), after the session uploader's `startSession` | `sessionStarted({sessionId, root: workspace.path, engine})`, the engine reads built on the worker from the request's engine target |
+| The session uploader observer starts following a turn (on the worker): the first of an observation, or the next one after a request that came in while a turn settled | `turnFollowed(sessionId)`: the session's idle final archive is off until that turn ends |
+| The session uploader observer's `turn_completed` (on the worker), with the engine messages it just read (null when it could not read them), however long the turn ran | `turnCompleted(sessionId, messages)` |
+| The session uploader observer stops following a turn without seeing it settle: `session.observer_timeout` (its 24-hour safety bound) or `session.observer_failed` (an unexpected error; an engine that times out, drops the connection or restarts is waited out). A server stop ends an observation without this call | `turnIncomplete(sessionId)` |
+| The session uploader's `onPathTouched` (on the worker, in `capture-host.ts`, so no message crosses to the main thread): a path in the root from a trace event (`recordTrace`, a child session's messages), a watcher event, the reconcile pass, the end-of-turn artifact scan, or a change capture's scan, before the session uploader's own denylist | `pathTouched(sessionId, path)`: passed to `SessionArchiver.recordTouched` for a session this run started that may be archived (resolved with a root, or not resolved yet); a child session's paths are dropped (`forgetTouched`) |
+| `sessionUploader.finishSession` (session deleted) | `sessionEnded(sessionId)`: a final archive (`session_deleted`), then the session is forgotten; kicks a drain |
| The broker's `invalidate` hook (revoked or expired account), before `clearSpool()` | `signOut()` |
-| Server shutdown and a failed start | `stop({finals})`, started first: the main thread aborts the part uploads it is making for the worker at once, before the task-recovery checkpoint (up to 10 s), then the worker packs the final archives (at most `QUIT_FINAL_BUDGET_MS`, 5 s) and stops the archiver and the collector; the worker is terminated after 20 s at the latest. A user sign-out reaches the server this way too: the desktop clears the account, then restarts the server. So `server.ts` asks the account store (`omnirushGatewayCredentials.latest()`, at most 1 s) whether the account is still there, and without it no final archive is packed |
+| Server shutdown and a failed start | `stop({finals})`, started first: the main thread aborts the part uploads it is making for the worker at once, before the task-recovery checkpoint (up to 10 s), then the worker packs the final archives (at most `QUIT_FINAL_BUDGET_MS`, 5 s) and stops the archiver and the session uploader; the worker is terminated after 20 s at the latest. A user sign-out reaches the server this way too: the desktop clears the account, then restarts the server. So `server.ts` asks the account store (`omnirushGatewayCredentials.latest()`, at most 1 s) whether the account is still there, and without it no final archive is packed |
What the lifecycle adds on top of the calls below:
@@ -168,7 +168,7 @@ reach the archive with the next turn, or never. A final archive captures it:
- `app_quit`: `stop()` passes the sessions of this app run (resolved, or unresolved but maybe with a base from an earlier run), the most recent first, to `SessionArchiver.stop({finals, budgetMs})`. The drain and its retry timer stop first; the final archives are captured one after the other (a session whose capture is still running goes last), each with an abort signal that the scan and the tar writer check between entries and blocks. When the budget (5 s) runs out, the signal aborts, and the generation is bumped: nothing commits after that. They are uploaded at the next start.
- `app_start`: `start()` asks `startFinalCandidates()` for the sessions active within the last 7 days, not stopped and not ended: every one with a turn captured since its last final archive (`final_due` in its record: the last shutdown did not get to it, or the app was killed), the most recently active one on each other folder (edits while the app was closed), and every touched-files session (its files are its own), also one without a base yet that has touched paths. At most 10, the most recently active first. Active means the session's base, a prompt (`captureBase` on a session with a base, or on a touched-files session registered in an earlier run, once per app run) or a turn end (`captureDelta`, also when nothing changed): `last_activity_at` in its record. A final archive, a rewind and other record updates move `updated_at` but never this, so a chat left alone gets no final archive a week after its last turn, however often the app starts and the folder changes. A record from before 1.1.0 counts from its `updated_at` (its last archive), and keeps that time from then on.
- **Guards.** `captureFinal` needs a base (`no_base` otherwise, also while the base is pending; a touched-files session without one gets its base instead, when it has a touched file), a session that is not stopped and archiving on (`disabled`). It runs the gate of section 4 again on the session root recorded at the base (a plain folder or touched files: the root checks and the folder refusals, and their policy must be on): a folder that is gone, or that the gate refuses now, gets nothing (`not_archivable`). A folder that did not change uploads nothing (`unchanged`: a stat-only scan with the root's hash cache). Only the session root is scanned, with the same exclusions, credential filter and pass 2 checks as every other archive. The lifecycle's rules hold as for any capture: consent off, signed out, `OMNIRUSH_ARCHIVE_ENABLED`, child sessions, the bounded queue. The server's per-upload and per-chat limits count final archives like any other (a 413 stops the session).
-- **Several chats on one folder.** Each session archives the folder in its own chain, so its final archive, like its turn deltas, carries whatever changed in the folder since its own previous archive, including another chat's edits, and each session's quiet window is its own (one timer per session, re-armed by each turn end, never doubled). The collector's rule for a shared root (a chat without a turn in progress leaves the filesystem changes made during another chat's turn to that turn's snapshots, `workspace-collector.ts`) concerns its scrubbed snapshots only: the archive neither waits for it nor schedules anything from it.
+- **Several chats on one folder.** Each session archives the folder in its own chain, so its final archive, like its turn deltas, carries whatever changed in the folder since its own previous archive, including another chat's edits, and each session's quiet window is its own (one timer per session, re-armed by each turn end, never doubled). The session uploader's rule for a shared root (a chat without a turn in progress leaves the filesystem changes made during another chat's turn to that turn's snapshots, `session-uploader.ts`) concerns its scrubbed snapshots only: the archive neither waits for it nor schedules anything from it.
- **A server without final archives.** A backend from before 1.1.0 answers `409 archive_parent_mismatch` to a delta whose turn equals its parent's. Until the server has accepted a final archive in this app run, the first final archive in a chain keeps the chain point before it (`rewind` in the session record, with that archive's baseline, which `start()` keeps too). On that 409 for a final archive, the drain holds the session and, under its lock, puts the chain back there, drops the final archive and every job chained on it, and captures one turn delta again on top (with the highest turn among the dropped turn deltas), so later turns keep uploading. It logs once, and no final archive is captured again until the app restarts (`unsupported`). Once a final archive is uploaded, the rewind point goes (its baseline is deleted) and a later `archive_parent_mismatch` ends the chain as before.
The contract the lifecycle follows is the original wiring note below.
@@ -182,9 +182,9 @@ project takes seconds (about 2 s for 500 MiB and 20k files, about 18 s for
Captures for one session are serialized inside the archiver. Captures for
different sessions may run concurrently.
-#### 1. App start (server startup, next to `new WorkspaceCollector(...)` in `server.ts`)
+#### 1. App start (server startup, next to `new SessionUploader(...)` in `server.ts`)
-Construct one archiver per server, with the same state dir as the collector:
+Construct one archiver per server, with the same state dir as the session uploader:
```ts
const sessionArchiver = new SessionArchiver({
@@ -210,7 +210,7 @@ void sessionArchiver.start().then(() => sessionArchiver.drain());
A job that exhausted its retries waits between drains (1 min, doubling, capped
at 1 h). An unref'd timer drains again when the earliest one is due.
-#### 2. Session start (where `collector.startSession(sessionId, workspaceId, root)` is called)
+#### 2. Session start (where `sessionUploader.startSession(sessionId, workspaceId, root)` is called)
Call once per root session per app run, the first time a prompt is
dispatched for that session id:
@@ -225,7 +225,7 @@ void sessionArchiver.captureBase(sessionId, root, completedTurns).then(() => ses
- Child (sub-agent) sessions share the parent's root and must not be archived. Call this for root sessions only.
- Keep a per-process `Set` of session ids already handed to `captureBase`. `startSession` runs on every prompt dispatch, and each `captureBase` call on a session without a base re-checks consent with one GET.
-#### 3. Turn completed (where `collector.captureSnapshot(sessionId, "turn_completed")` is called)
+#### 3. Turn completed (where `sessionUploader.captureSnapshot(sessionId, "turn_completed")` is called)
```ts
void sessionArchiver.captureDelta(sessionId, root, completedTurns).then(() => sessionArchiver.drain());
@@ -235,7 +235,7 @@ void sessionArchiver.captureDelta(sessionId, root, completedTurns).then(() => se
- An unchanged folder costs a stat-only scan, with no file content read (about 0.1 s for 20k entries, 1.5 s for 200k) and no upload.
- A session whose base is still pending (key unavailable, or a base sealed to a retired key) gets its base here.
-#### 4. Session end (where `collector.finishSession(sessionId)` is called)
+#### 4. Session end (where `sessionUploader.finishSession(sessionId)` is called)
The session was deleted: a final archive of what changed since its last
archive, then kick the queue (as implemented, the lifecycle does both):
@@ -244,7 +244,7 @@ archive, then kick the queue (as implemented, the lifecycle does both):
void sessionArchiver.captureFinal(sessionId, "session_deleted").then(() => sessionArchiver.drain());
```
-#### 5. Sign-out (the broker's `invalidate` hook, next to `workspaceCollector.clearSpool()`)
+#### 5. Sign-out (the broker's `invalidate` hook, next to `sessionUploader.clearSpool()`)
```ts
await sessionArchiver.signOut();
@@ -265,7 +265,7 @@ later under another account. After the next sign-in the archiver starts clean.
In `gatewayUrl` mode, call `setAccessToken(newToken)` after sign-in and on every
token rotation.
-#### 6. App shutdown (where `workspaceCollector.stop()` is called)
+#### 6. App shutdown (where `sessionUploader.stop()` is called)
```ts
await sessionArchiver.stop({ finals: sessionIdsOfThisRun, budgetMs: 5_000 });
@@ -277,7 +277,7 @@ This stops the drain and the retry timer and aborts the part PUT in flight at on
Archive routes authenticate like `POST /omnirush/collect`: a device bearer,
the sign-in gate and consent. The gateway broker owns the device session and
-exposes, next to `collect(sessionId, body)` and `refreshAccessToken()`:
+exposes, next to `uploadSession(sessionId, body)` and `refreshAccessToken()`:
```ts
archiveRequest(path: string, init: { method: "GET" | "POST"; body?: string; signal?: AbortSignal }): Promise<Response>
@@ -286,9 +286,9 @@ archiveRequest(path: string, init: { method: "GET" | "POST"; body?: string; sign
It sends to `<gateway root>/<path>` (`path` is `archives/key`, `archives`,
`archives/<id>/parts`, `archives/<id>/complete`, `archives/<id>/abort`). The
gateway root is the gateway URL with its trailing `/` and `/v1` stripped,
-exactly as for `collect`. The method sets `Authorization: Bearer <device token>`,
+exactly as for `uploadSession()`. The method sets `Authorization: Bearer <device token>`,
plus `Content-Type: application/json` when there is a body, and runs the same
-bounded 401 refresh loop as `collect()`. Any other path answers 404 without a
+bounded 401 refresh loop as `uploadSession()`. Any other path answers 404 without a
request.
Alternatively, pass `gatewayUrl` + `accessToken` and keep them current with
@@ -315,12 +315,12 @@ against a loopback sink).
- **Refusals** (`refusedFolderRoot`), checked on every form of the root (as given and resolved through symlinks; Windows `\\?\`, `\\.\` and `\\?\UNC\` prefixes and trailing dots and spaces folded; macOS and Windows without case) before the policy is asked:
- `root_too_broad`: a disk or share root (`/`, `C:\`, `\\server\share`, `/Volumes/<disk>`, `/mnt/<disk>`, `/media/<user>/<disk>`), the home directory and anything above it, and another account's folder beside home (`/Users/<other>`, `/Users/Shared`, `/home/<other>`, `C:\Users\Public`) itself;
- `root_app_data`: the desktop's userData dir (`OMNIRUSH_DESKTOP_USER_DATA_DIR`, set by the desktop app) and anything inside or above it; an `AppData` or `Library/Application Support` folder anywhere; and, in home and in the account folders beside it, every folder whose name starts with `.`, `Library` on macOS and `snap` on Linux, with anything inside them;
- - `root_credentials`: a credential store anywhere (`.ssh`, `.aws`, `.gnupg`, `.kube`, `.docker`, `.azure`, `.password-store`, `Keychains`, `.config/gcloud`) and any folder the collector's denylist denies as a whole (`isCollectorDirectoryDenied`: `keys`, `secrets`, `credentials*`, `.env*`, `node_modules`, `.git`, key-store suffixes, ...), with anything inside them. The file-level credential filter checks paths relative to the root, so without this a session started in `~/.aws` would upload it;
+ - `root_credentials`: a credential store anywhere (`.ssh`, `.aws`, `.gnupg`, `.kube`, `.docker`, `.azure`, `.password-store`, `Keychains`, `.config/gcloud`) and any folder the session uploader's denylist denies as a whole (`isUploadDirectoryDenied`: `keys`, `secrets`, `credentials*`, `.env*`, `node_modules`, `.git`, key-store suffixes, ...), with anything inside them. The file-level credential filter checks paths relative to the root, so without this a session started in `~/.aws` would upload it;
- `root_system`, outside home only: `/System`, `/Library`, `/Applications`, `/private`, `/usr`, `/bin`, `/sbin`, `/etc`, `/var`, `/opt`, `/cores`, `/proc`, `/sys`, `/dev`, `/boot`, `/lib`, `/lib64`, `/run`, `/root`, `/snap`, `/nix`; `Windows`, `Windows.old`, `Program Files`, `Program Files (x86)`, `ProgramData`, `$Recycle.Bin`, `System Volume Information`, `Recovery` and `PerfLogs` on any drive; with anything inside them.
- **The policy probe.** Only a root that passes every refusal asks for the policy (`folderPolicy`, which answers `all_folders` and `touched_files` together). The answer is kept in memory with the key for `POLICY_TTL_MS` (5 minutes); every full key fetch (a git base, a delta without a key) refreshes it, a 428 or 503 keeps it as off, and sign-out forgets it. Without a kept answer the archiver sends one probe (`ArchiveUploader.probeKey`): a single GET /archives/key within 5 s, no backoff, no bearer refresh on a 401 (through the broker, `archiveRequest(..., { refresh: false })`), shared by the sessions that start meanwhile. Any failure (network, timeout, 401, 5xx, 428, 503, 404, a bad key) counts as off, is kept as off for the same 5 minutes, and never disables archiving or touches the queue. So with the policy off a folder session costs at most one GET per 5 minutes, even during an outage, and a flip on omnirush.ai reaches a running app within 5 minutes with no release.
- **Key and consent.** A folder base reuses the key from the probe it just made. With a kept answer it fetches the key in full, like a git base (consent check, retries); if that response says the policy is now off, nothing is archived. A folder session's deltas pause (`not_archivable`) while the policy is off and catch up on the first delta after it is on again. The server also refuses `folder` archives from a user whose policy is off (`422 archive_marker_not_allowed`), which stops such a session.
- **Touched files.** GET /archives/key also carries `policy.touched_files` (off unless it is the boolean `true`; absent on an older backend). Precedence per session root, in `captureBaseLocked`'s gate: a git repository or a folder inside one (`gitMarkerDetector`, `gitParentDetector`) gets the `.git` archive exactly as before; else, with `all_folders` on, the whole-folder `folder` archive; else, with `touched_files` on and the root passing every folder refusal above, a `touched` chain; else nothing. The same probe, TTL and kept answer serve both flags.
- - **The touched set.** The collector (in the same capture host, on the worker) reports every workspace-relative path a session touches, before its own denylist: tool paths in the trace (`path`, `filePath`, ... of any event, a child session's messages too; `workspaceRelativePath` drops anything outside the root, another drive or share), watcher events (created, modified, deleted, renamed), the reconcile pass, the end-of-turn artifact scan and a change capture's scan (only against an accepted snapshot: with none, as after a refused start snapshot, a scan compares against nothing and reports nothing). `TouchedPathStore` keeps them per session: in memory until the gate has run (a git, folder or refused session drops them), then appended to `omnirush-archive/touched/<session key>.jsonl` within 2 s, and at `stop()`, so they survive a restart; a torn last line is skipped. At most `MAX_TOUCHED_PATHS` (100,000) per session, one `warn` past it. A stopped or deleted session's file goes; `start()` removes the files of sessions that are not touched chains any more, and sign-out removes them all.
+ - **The touched set.** The session uploader (in the same capture host, on the worker) reports every workspace-relative path a session touches, before its own denylist: tool paths in the trace (`path`, `filePath`, ... of any event, a child session's messages too; `workspaceRelativePath` drops anything outside the root, another drive or share), watcher events (created, modified, deleted, renamed), the reconcile pass, the end-of-turn artifact scan and a change capture's scan (only against an accepted snapshot: with none, as after a refused start snapshot, a scan compares against nothing and reports nothing). `TouchedPathStore` keeps them per session: in memory until the gate has run (a git, folder or refused session drops them), then appended to `omnirush-archive/touched/<session key>.jsonl` within 2 s, and at `stop()`, so they survive a restart; a torn last line is skipped. At most `MAX_TOUCHED_PATHS` (100,000) per session, one `warn` past it. A stopped or deleted session's file goes; `start()` removes the files of sessions that are not touched chains any more, and sign-out removes them all.
- **Captures.** At the same moments as a git chain's deltas (turn end) and final archives (idle, turn_incomplete, session_deleted, app_quit, app_start). `captureBase` at session start only registers the session (`unchanged`, with `turn_seen`, the completed turns so far). For a session already registered (resumed after a restart) it runs no gate and asks no policy: it only updates `turn_seen`, and the chain and its touched set are kept whatever the policy answers then (a failed probe included), like a chain with a base; its captures check the policy. The base (sequence 0, no parent, turn = the completed turns so far: the turn's count, or `turn_seen` for a final archive) comes with the first capture that finds a touched file; before that a capture is `unchanged`. Deltas follow the git chain's rules (sequence n+1, the parent, a turn delta's turn above the parent's, a final archive's equal), and a delta's marker is its parent's.
- **What is archived.** `scanTouchedFiles` looks at the session's touched paths and every file the chain holds (to see it go), nothing else: a plain relative path only; walked from the root with `lstat`, each folder on the way a real folder (a symlink or a file in the way: the path is not in the folder); a touched folder is never expanded; a symlink is followed only to a target that is lexically inside the root (as given or as its real path, at most 8 links; its target goes through the same checks), and one pointing outside is skipped (`special`) without anything outside being looked at. The same exclusions as the whole-folder scan: credential files (`isArchiveCredentialPath`, unless `archiveIncludeCredentialFiles`), app state dirs under the root, `__omnirush__` at the root, special files, unreadable files, lone-surrogate names. A file is hashed from the very file `lstat`ed (same `st_dev` and `st_ino`), with the root's hash cache (read and added to, never pruned: the scan sees only part of the root), and pass 2 packs it with the usual checks (`pack.ts`). Any type and size, byte for byte, unscrubbed, sealed like every archive; `workspace.git` is `null`.
- **Manifest.** `"scope": "touched"` in the sealed `manifest.json` of every archive of the chain; `files` lists only touched files (the base: every touched file; a delta: the added and modified ones). A path the manifest does not list is not deleted: a delta deletes, in `deleted`, the files an earlier archive of the chain holds that are no longer a regular file in the folder (gone, a folder, a link, reached through a folder that is now a link). A file that cannot be read for now stays in the baseline as it was.
@@ -329,7 +329,7 @@ against a loopback sink).
- **A root in a repository** (a `.git` root or a `git_parent` folder): one `git ls-files -z --others --ignored --exclude-standard --directory` in the root, with `GIT_CEILING_DIRECTORIES` at home like every archive git run. An ignored directory comes back as one `dir/` line and pass 1 leaves it out before `lstat`ing it, so `node_modules/` with 200k files costs one line of git output and nothing else. Tracked files are never ignored (git does not list them, so a force-added `dist/vendor.js` stays). A folder git lists because everything in it is ignored is left out too (only empty subfolders go with it, which git cannot hold either).
- **A folder in no repository** (all-folders policy, marker `folder`, or git refusing the root's repository): the same command with a private empty bare repository as `GIT_DIR` (`git init --bare --template=` in a fresh `mkdtemp` dir, removed when the scan is done) and the root as `GIT_WORK_TREE`, so the folder's `.gitignore` files apply as git would apply them (`node_modules/` at any depth, negations, nested `.gitignore` files). Nothing is written in the folder.
- **A nested repository** (a folder below the root holding `.git`: a submodule, a cloned dependency): the outer repository's git never looks inside one, so when pass 1 enters it, it asks that repository (ceiling at its parent, so a broken `.git` there never climbs to the outer one) and uses its answer below it.
- - **Without git** (missing, a run over `IGNORE_GIT_TIMEOUT_MS`, 2 min, or more than `MAX_IGNORED_PATHS`, 2M, ignored paths): the `.gitignore` files, applied with the collector's walkFallback rules (`scopedIgnoreRules`, `ignoredByRules`; a directory also matches as `dir/`, so `dist/` prunes `dist`).
+ - **Without git** (missing, a run over `IGNORE_GIT_TIMEOUT_MS`, 2 min, or more than `MAX_IGNORED_PATHS`, 2M, ignored paths): the `.gitignore` files, applied with the session uploader's walkFallback rules (`scopedIgnoreRules`, `ignoredByRules`; a directory also matches as `dir/`, so `dist/` prunes `dist`).
- **Never ignored:** `.git` itself and everything in it (it is not gitignored and keeps the history), and every `.gitignore` file.
- **Touched files.** `scanTouchedFiles` asks `git check-ignore -z --stdin` about the touched files it found (in the root's repository, else in the private one with the root as work tree; a batch git refuses is halved until the refused path is alone, and that path is kept), so the folder is never walked; without git, each path's folders are checked against their `.gitignore` rules. An ignored touched file is skipped and counts as gone, so a delta deletes a copy the chain holds.
- **Deltas.** An ignored path is simply not in the scan, so a path that becomes ignored is in the next delta's `deleted` (with its descendants), and one that stops being ignored is added again; a rename into an ignored folder is a deletion. The hash cache drops ignored paths at the end of the scan.
@@ -389,11 +389,11 @@ cd apps/server && bun --conditions=development test src/session-archive
- the broker request hook.
- `lifecycle.test.ts` (fake archiver and engine, plus runs on the real archiver): touched paths passed on only for a session this run started that may be archived (not before its prompt, not once it is not archivable, deleted or signed out; a child's dropped); the turn count on v1 and v2 message shapes; the feature flag; one base per root session per app run at the real path; child sessions ignored; deltas numbered from the engine and ordered after the base, and after the last archived turn when the messages could not be read; restart resume; a session whose start could not read the engine resolved at its next completed turn (its delta kept, also on the real archiver across an app restart), and a child resolved that way still ignored; an unreadable start retried after 1, 2, 5 and 10 minutes, one retry at a time, and never once archiving stopped; signed-out start clearing; sign-out stopping queued steps; 428 off until the recheck; failures contained. Final archives: one idle final per quiet window, a new prompt cancelling a pending or packing one, and so does a turn the observer follows (also when that turn's prompt came before the previous turn's end); a deleted session, a sign-out and a shutdown clearing both the idle final and the start retry, and a start read that fails after them arming no retry; a turn that ends without completing (delta when the engine's count moved, final otherwise or when the engine cannot be read, and a completed turn whose count did not move); a deleted session (child never); shutdown passing this run's sessions most recent first with the budget, and nothing without a budget, with consent off or with the account gone; app-start finals queued behind other steps; on the real archiver, the idle, quit and app-start finals of one session with the next turn's delta after them.
- `../project-archive.test.ts`: archives go through the broker's `archiveRequest` into `<state dir>/omnirush-archive/`; `OMNIRUSH_ARCHIVE_ENABLED=0` and a signed-out start clear leftovers without any network; a sign-out aborts a slow part PUT within a second and aborts the upload through the broker.
-- `../capture-client.test.ts`: stopping the capture worker packs a final archive, and none when the account is gone; on the worker, a path the collector sees the session touch reaches the touched-files archive (registered at session start, the quit's final archive is its base, with that file only).
-- `../workspace-collector.test.ts`: every path a session touches inside the root reaches `onPathTouched` (a tool's absolute path, a credential name, a file the watcher sees land), none outside it; with the start snapshot refused (no accepted baseline), the later whole-tree scans report only the file the agent wrote, no untouched one.
-- `../collector-observer.test.ts` ("with the project archive", the real lifecycle on a recording archiver, the observer on a fake clock): a turn of three hours, past the old one-hour cap, gets its delta and then the idle final; a turn still busy at the 24-hour safety bound gets `turnIncomplete` (its delta, the engine's count having moved) and then the idle final; a prompt sent while a turn settles keeps the idle final off while its own turn runs. On a fake archive: `turnFollowed`, then `turnCompleted` or `turnIncomplete` once per turn, including a turn after a completed one that fails, and nothing more at a server stop.
+- `../capture-client.test.ts`: stopping the capture worker packs a final archive, and none when the account is gone; on the worker, a path the session uploader sees the session touch reaches the touched-files archive (registered at session start, the quit's final archive is its base, with that file only).
+- `../session-uploader.test.ts`: every path a session touches inside the root reaches `onPathTouched` (a tool's absolute path, a credential name, a file the watcher sees land), none outside it; with the start snapshot refused (no accepted baseline), the later whole-tree scans report only the file the agent wrote, no untouched one.
+- `../session-upload-observer.test.ts` ("with the project archive", the real lifecycle on a recording archiver, the observer on a fake clock): a turn of three hours, past the old one-hour cap, gets its delta and then the idle final; a turn still busy at the 24-hour safety bound gets `turnIncomplete` (its delta, the engine's count having moved) and then the idle final; a prompt sent while a turn settles keeps the idle final off while its own turn runs. On a fake archive: `turnFollowed`, then `turnCompleted` or `turnIncomplete` once per turn, including a turn after a completed one that fails, and nothing more at a server stop.
- `../omnirush-gateway-broker.test.ts`: `archiveRequest` URL, bearer, 401 refresh and path allowlist.
-- `../workspace-collector.server.e2e.test.ts` ("project archive wiring"): through the real proxy and observer, one base then a delta numbered 2 after a changed turn; a turn whose status the engine stops answering is waited out (no `session.observer_failed`) and still gets its delta, numbered from the engine; a history past the 8 MiB read cap (one message over it alone) still gets its base, its turns' transcripts and deltas, and a turn whose messages cannot be read still gets its snapshot and delta; 428 checked once with the chat unaffected; the flag off sends nothing.
+- `../session-uploader.server.e2e.test.ts` ("project archive wiring"): through the real proxy and observer, one base then a delta numbered 2 after a changed turn; a turn whose status the engine stops answering is waited out (no `session.observer_failed`) and still gets its delta, numbered from the engine; a history past the 8 MiB read cap (one message over it alone) still gets its base, its turns' transcripts and deltas, and a turn whose messages cannot be read still gets its snapshot and delta; 428 checked once with the chat unaffected; the flag off sends nothing.
- `index.test.ts`:
- the whole folder: `.git/` present, gitignored `node_modules/` and `dist/` absent (also when a turn rebuilds them), `.env` and `id_rsa` absent unless `archiveIncludeCredentialFiles`; the base then a delta, each decrypted and checked;
- no delta when nothing changed, `stale_turn` and `exists`;
diff --git a/apps/server/src/session-archive/detect.test.ts b/apps/server/src/session-archive/detect.test.ts
index c6d54fca..1f1098bb 100644
--- a/apps/server/src/session-archive/detect.test.ts
+++ b/apps/server/src/session-archive/detect.test.ts
@@ -362,7 +362,7 @@ describe("all-folders gate (4.4)", () => {
[linux, "/srv/backup/sam/.kube", "root_credentials"],
[linux, "/mnt/data/home/.config/gcloud", "root_credentials"],
[windows, "D:\\Backup\\.gnupg", "root_credentials"],
- // Folders the collector's denylist denies as a whole.
+ // Folders the session uploader's denylist denies as a whole.
...["work/keys", "work/secrets", "work/credentials", "work/aws-credentials", "work/prod.secrets", "work/.env.d", "work/certs.pem", "work/app/node_modules/pkg", "work/repo/.git/hooks"].map(
(dir): [FolderGateContext, string, "root_credentials"] => [mac, `/Users/sam/${dir}`, "root_credentials"],
),
diff --git a/apps/server/src/session-archive/detect.ts b/apps/server/src/session-archive/detect.ts
index e34f4851..6425bd98 100644
--- a/apps/server/src/session-archive/detect.ts
+++ b/apps/server/src/session-archive/detect.ts
@@ -12,7 +12,7 @@ import { lstat, open, realpath } from "node:fs/promises";
import { homedir } from "node:os";
import path, { isAbsolute, join, parse, posix, relative, resolve, sep, win32 } from "node:path";
-import { isCollectorDirectoryDenied } from "../workspace-collector.js";
+import { isUploadDirectoryDenied } from "../session-uploader.js";
import type { ArchivePolicy } from "./policy.js";
export type ArchivableProject = {
@@ -291,7 +291,7 @@ export function foldGatePath(path: string, platform: NodeJS.Platform): string {
* - the Electron userData directory, and anything above it;
* - a credential store wherever it is (`.ssh`, `.aws`, `.gnupg`, `.kube`,
* `.docker`, `.azure`, `.password-store`, `Keychains`, `.config/gcloud`),
- * and any folder the collector's denylist denies as a whole (`keys`,
+ * and any folder the session uploader's denylist denies as a whole (`keys`,
* `secrets`, `credentials*`, `.env*`, `node_modules`, `.git`, ...);
* - app data wherever it is (`AppData`, `Library/Application Support`);
* - in the home directory, and in the other folders beside it (other
@@ -317,7 +317,7 @@ export function refusedFolderRoot(root: string, context: FolderGateContext): Fol
const names = target.slice(paths.parse(target).root.length).split(paths.sep).filter(Boolean).map((name) => name.toLowerCase());
const hasPair = (pairs: ReadonlyArray<readonly [string, string]>) => names.some((name, index) => pairs.some(([first, second]) => name === first && names[index + 1] === second));
- if (names.some((name) => CREDENTIAL_DIRS.has(name)) || hasPair(CREDENTIAL_DIR_PAIRS) || isCollectorDirectoryDenied(names.join("/"))) return "root_credentials";
+ if (names.some((name) => CREDENTIAL_DIRS.has(name)) || hasPair(CREDENTIAL_DIR_PAIRS) || isUploadDirectoryDenied(names.join("/"))) return "root_credentials";
if (names.some((name) => APP_DATA_DIRS.has(name)) || hasPair(APP_DATA_DIR_PAIRS)) return "root_app_data";
for (const home of homes) {
diff --git a/apps/server/src/session-archive/files.ts b/apps/server/src/session-archive/files.ts
index 06891bf9..ca3d2ac5 100644
--- a/apps/server/src/session-archive/files.ts
+++ b/apps/server/src/session-archive/files.ts
@@ -70,7 +70,7 @@ export async function readJsonFile(path: string): Promise<unknown> {
/**
* Runs a full garbage collection when the runtime offers one (Bun.gc); a
* no-op elsewhere. Streaming an archive churns through hundreds of MiB of
- * short-lived buffers (zstd output, AES-GCM output) that the collector would
+ * short-lived buffers (zstd output, AES-GCM output) that the session uploader would
* otherwise let pile up well past the stream's bounded working set. Callers
* hint once per 64 MiB of data; a collection takes a few milliseconds at the
* heap sizes involved.
diff --git a/apps/server/src/session-archive/ignore.ts b/apps/server/src/session-archive/ignore.ts
index 568b63df..3e5c98eb 100644
--- a/apps/server/src/session-archive/ignore.ts
+++ b/apps/server/src/session-archive/ignore.ts
@@ -21,7 +21,7 @@
* repository, when the scan enters it: git never looks inside it from the
* outer one;
* - without a working git (missing, timed out, too many ignored paths): the
- * `.gitignore` files, applied with the collector's walkFallback rules.
+ * `.gitignore` files, applied with the session uploader's walkFallback rules.
*
* `.git` itself and the `.gitignore` files are never ignored.
*/
@@ -31,7 +31,7 @@ import { mkdtemp, open, rm } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { delimiter, join } from "node:path";
-import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../workspace-collector.js";
+import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../session-uploader.js";
/** One `git ls-files` or `git check-ignore` run may take this long before the rules fallback. */
export const IGNORE_GIT_TIMEOUT_MS = 120_000;
diff --git a/apps/server/src/session-archive/index.ts b/apps/server/src/session-archive/index.ts
index f9bd0152..c4c86f17 100644
--- a/apps/server/src/session-archive/index.ts
+++ b/apps/server/src/session-archive/index.ts
@@ -8,7 +8,7 @@
* with the touched-files policy on, the same chain holding only the files
* the agent touched there (touched.ts), its base at the first capture that
* has one. Each archive is sealed to the omnirush.ai archive key, queued
- * durably under the collector state dir and uploaded to S3 through
+ * durably under the session uploader state dir and uploaded to S3 through
* presigned multipart URLs. The embedded server drives it through
* lifecycle.ts; see README.md.
*/
@@ -68,7 +68,7 @@ export { gitMarkerDetector, gitParentDetector, isArchivableProject, type Archiva
export { isArchiveCredentialPath, type ArchiveTrigger, type FinalReason } from "./manifest.js";
export type { ArchiveApiRequest } from "./upload.js";
-/** Subdirectory of the collector state dir that holds everything the archiver keeps. */
+/** Subdirectory of the session uploader state dir that holds everything the archiver keeps. */
export const ARCHIVE_STATE_DIRECTORY = "omnirush-archive";
const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/;
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -92,16 +92,16 @@ const MAX_START_FINALS = 10;
export const POLICY_TTL_MS = 5 * 60_000;
export type SessionArchiverOptions = {
- /** As the collector: the archive routes are derived from it like the collect URL. */
+ /** As the session uploader: the archive routes are derived from it like the session upload URL. */
gatewayUrl?: string;
accessToken?: string;
- /** The collector's hook: a fresh bearer after a 401, or null. */
+ /** The session uploader's hook: a fresh bearer after a 401, or null. */
refreshAccessToken?: () => Promise<string | null>;
/** External egress for S3 part PUTs (and API calls without `request`); externalFetch by default. */
fetch?: ArchiveFetch;
/** Authenticated API calls through the device-session owner (the gateway broker); replaces gatewayUrl + accessToken. */
request?: ArchiveApiRequest;
- /** The collector state dir; the archiver keeps its files in `<stateDir>/omnirush-archive/`. */
+ /** The session uploader state dir; the archiver keeps its files in `<stateDir>/omnirush-archive/`. */
stateDir: string;
/** App state/temp/data dirs pruned when under a root (the state dir itself is always pruned). */
excludedDirs?: string[];
@@ -362,7 +362,7 @@ export class SessionArchiver {
return this.started;
}
- /** The device bearer changed (collector token rotation). */
+ /** The device bearer changed (session uploader token rotation). */
setAccessToken(token: string | null): void {
this.uploader.setAccessToken(token);
}
@@ -495,7 +495,7 @@ export class SessionArchiver {
/**
* A path the session touched, workspace-relative (portable `/`), as the
- * collector reports it: a tool's path in the trace, or a change the
+ * session uploader reports it: a tool's path in the trace, or a change the
* watcher saw. Kept (on disk, a moment later) for a touched-files session;
* dropped for any other once the gate has run. Cheap: called for every
* file event.
diff --git a/apps/server/src/session-archive/lifecycle.ts b/apps/server/src/session-archive/lifecycle.ts
index c74f6b74..710d3454 100644
--- a/apps/server/src/session-archive/lifecycle.ts
+++ b/apps/server/src/session-archive/lifecycle.ts
@@ -272,7 +272,7 @@ export class ProjectArchiveLifecycle {
}
/**
- * The collector saw the session touch a path (workspace-relative): a
+ * The session uploader saw the session touch a path (workspace-relative): a
* tool's path in the trace, or a change on disk. Kept for a touched-files
* session (the archiver drops it for any other); nothing for a session
* this app run has not started or knows is not archived.
diff --git a/apps/server/src/session-archive/manifest.test.ts b/apps/server/src/session-archive/manifest.test.ts
index f61e534b..6370ee18 100644
--- a/apps/server/src/session-archive/manifest.test.ts
+++ b/apps/server/src/session-archive/manifest.test.ts
@@ -402,7 +402,7 @@ describe("gitignored content", () => {
expect(listed).not.toContain(".git");
});
- test("without git, the folder's .gitignore files still apply (the collector's walkFallback rules)", async () => {
+ test("without git, the folder's .gitignore files still apply (the session uploader's walkFallback rules)", async () => {
const root = await tempDir("ignored-nogit");
await writeFile(join(root, ".gitignore"), "node_modules/\ndist/\n*.log\n");
await mkdir(join(root, "node_modules/dep"), { recursive: true });
diff --git a/apps/server/src/session-archive/manifest.ts b/apps/server/src/session-archive/manifest.ts
index 379170b9..ebc960e5 100644
--- a/apps/server/src/session-archive/manifest.ts
+++ b/apps/server/src/session-archive/manifest.ts
@@ -12,7 +12,7 @@ import { constants as fsConstants, type BigIntStats } from "node:fs";
import { lstat, open, readdir, readlink, realpath } from "node:fs/promises";
import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
-import { clampCollectorBytes, isCollectorPathDenied, stripRemoteUserinfo } from "../workspace-collector.js";
+import { clampUploadBytes, isUploadPathDenied, stripRemoteUserinfo } from "../session-uploader.js";
import { hintGarbageCollection } from "./files.js";
import { ArchiveIgnore, gitCeilingDirectories, scopeIgnores, type IgnoreScope, type IgnoreSource } from "./ignore.js";
@@ -142,19 +142,19 @@ export function compareArchivePaths(left: string, right: string): number {
/**
* True when a file or symlink must be left out of the archive (section 5.3):
- * the collector's credential denylist, with git internals exempt and
+ * the session uploader's credential denylist, with git internals exempt and
* `node_modules` not counted as a denial.
*/
export function isArchiveCredentialPath(relPath: string): boolean {
const parts = relPath.split("/");
if (parts.some((part) => part.toLowerCase() === ".git")) return false;
const rest = parts.filter((part) => part.toLowerCase() !== "node_modules");
- return rest.length > 0 && isCollectorPathDenied(rest.join("/"));
+ return rest.length > 0 && isUploadPathDenied(rest.join("/"));
}
/** workspace.label: the root's basename, at most 255 UTF-8 bytes. */
export function archiveLabel(root: string): string {
- return clampCollectorBytes(basename(resolve(root)), MAX_LABEL_BYTES).text;
+ return clampUploadBytes(basename(resolve(root)), MAX_LABEL_BYTES).text;
}
// --- hash cache -------------------------------------------------------------------
diff --git a/apps/server/src/session-archive/touched.ts b/apps/server/src/session-archive/touched.ts
index 40396476..9096a344 100644
--- a/apps/server/src/session-archive/touched.ts
+++ b/apps/server/src/session-archive/touched.ts
@@ -2,7 +2,7 @@
* The touched-files archive (policy `touched_files`, README "Touched
* files"): in a session folder that is neither a git repository nor inside
* one, only the files the agent touched there are archived, byte for byte.
- * The collector reports every path the session touched (the trace's tool
+ * The session uploader reports every path the session touched (the trace's tool
* paths, the watcher's changes); TouchedPathStore keeps them per session on
* disk, and scanTouchedFiles turns them into archive entries at capture
* time: regular files inside the root only, never through a symlinked
@@ -378,7 +378,7 @@ export class TouchedPathStore {
},
) {}
- /** A path the collector reported for the session (workspace-relative, portable). Cheap: a repeat is a lookup. */
+ /** A path the session uploader reported for the session (workspace-relative, portable). Cheap: a repeat is a lookup. */
note(sessionId: string, path: string): void {
let session = this.sessions.get(sessionId);
if (!session) {
diff --git a/apps/server/src/session-archive/upload.test.ts b/apps/server/src/session-archive/upload.test.ts
index 2be9d9c5..2b5b09fe 100644
--- a/apps/server/src/session-archive/upload.test.ts
+++ b/apps/server/src/session-archive/upload.test.ts
@@ -46,7 +46,7 @@ function uploader(server: FakeArchiveServer, options: Partial<ArchiveUploaderOpt
}
describe("archive upload client", () => {
- test("the API root is derived like the collect URL", () => {
+ test("the API root is derived like the session upload URL", () => {
expect(resolveArchiveApiRoot("https://api.omnirush.ai/omnirush/v1/")).toBe("https://api.omnirush.ai/omnirush");
expect(resolveArchiveApiRoot("https://api.omnirush.ai/omnirush")).toBe("https://api.omnirush.ai/omnirush");
expect(resolveArchiveApiRoot("http://127.0.0.1:8080/v1")).toBe("http://127.0.0.1:8080");
diff --git a/apps/server/src/session-archive/upload.ts b/apps/server/src/session-archive/upload.ts
index 4b9b9661..e5b97204 100644
--- a/apps/server/src/session-archive/upload.ts
+++ b/apps/server/src/session-archive/upload.ts
@@ -15,7 +15,7 @@ export type ArchiveFetch = (input: string, init?: RequestInit) => Promise<Respon
* An authenticated request to the omnirush.ai API, relative to its root
* (`archives/key`, `archives`, `archives/<id>/parts`, ...). The owner of the
* device session (the gateway broker) attaches the bearer and handles its own
- * rotation, as it does for the collector's `upload` hook.
+ * rotation, as it does for the session uploader's `upload` hook.
*/
export type ArchiveApiRequest = (path: string, init: ArchiveApiRequestInit) => Promise<Response>;
/** `refresh: false` returns a 401 as it is, without refreshing the bearer (the all-folders policy probe); absent means true. */
@@ -76,7 +76,7 @@ const CHAIN_ENDING_CODES = new Set(["archive_id_conflict", "archive_sequence_con
/**
* The omnirush.ai API root derived from the gateway URL exactly like the
- * collect URL: trailing `/` and `/v1` stripped; HTTPS unless loopback.
+ * session upload URL: trailing `/` and `/v1` stripped; HTTPS unless loopback.
*/
export function resolveArchiveApiRoot(rawGatewayUrl: string | undefined): string | null {
const value = rawGatewayUrl?.trim();
diff --git a/apps/server/src/collector-attachments.ts b/apps/server/src/session-upload-attachments.ts
similarity index 92%
rename from apps/server/src/collector-attachments.ts
rename to apps/server/src/session-upload-attachments.ts
index 50ba7798..876c5b62 100644
--- a/apps/server/src/collector-attachments.ts
+++ b/apps/server/src/session-upload-attachments.ts
@@ -3,15 +3,15 @@ import { lstat, readFile } from "node:fs/promises";
import { basename, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES, isCollectorPathDenied, type CollectorAttachment } from "./workspace-collector.js";
+import { MAX_UPLOAD_ATTACHMENT_TEXT_BYTES, isUploadPathDenied, type UploadAttachment } from "./session-uploader.js";
/**
- * Turns the file parts of an engine prompt into collector "attachment" events:
+ * Turns the file parts of an engine prompt into session uploader "attachment" events:
* identity (name, mime, size, sha256) for every file, plus extracted text for
* text-like documents. Bytes come from the part's inline data URL or, for
* files the app copied into the workspace, from a file URL inside the
* workspace root; anything else is left alone. Redaction and the text cap are
- * applied by the collector when the event is recorded.
+ * applied by the session uploader when the event is recorded.
*/
const MAX_ATTACHMENTS_PER_PROMPT = 32;
@@ -155,7 +155,7 @@ async function workspaceFileBytes(url: string, workspaceRoot: string | null): Pr
}
const root = resolve(workspaceRoot);
const relativePath = absolute.startsWith(`${root}/`) || absolute.startsWith(`${root}\\`) ? absolute.slice(root.length + 1) : null;
- if (!relativePath || isCollectorPathDenied(relativePath.replaceAll("\\", "/"))) return null;
+ if (!relativePath || isUploadPathDenied(relativePath.replaceAll("\\", "/"))) return null;
try {
const file = await lstat(absolute);
if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_ATTACHMENT_BYTES) return null;
@@ -180,8 +180,8 @@ async function pdfText(bytes: Buffer): Promise<ExtractedText> {
const text = document.pageText(page);
pages.push(`--- page ${page} ---\n${text}`);
total += Buffer.byteLength(text);
- // The collector caps the event text; pages past the cap never leave the parser.
- if (total > MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES) {
+ // The session uploader caps the event text; pages past the cap never leave the parser.
+ if (total > MAX_UPLOAD_ATTACHMENT_TEXT_BYTES) {
truncated = truncated || page < limit;
break;
}
@@ -196,18 +196,18 @@ async function pdfText(bytes: Buffer): Promise<ExtractedText> {
async function attachmentText(source: FilePartSource, bytes: Buffer): Promise<ExtractedText> {
if (isPdfLike(source.mime, source.name, bytes)) return pdfText(bytes);
if (!isTextLike(source.mime, source.name) || looksBinary(bytes)) return { text: null, truncated: false };
- // Only the part the collector can keep is decoded; the rest never leaves the buffer.
- const limit = MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES + 4;
+ // Only the part the session uploader can keep is decoded; the rest never leaves the buffer.
+ const limit = MAX_UPLOAD_ATTACHMENT_TEXT_BYTES + 4;
return { text: bytes.subarray(0, limit).toString("utf8"), truncated: bytes.length > limit };
}
/**
- * Reads every file attached to the prompt and describes it for the collector.
+ * Reads every file attached to the prompt and describes it for the session uploader.
* Files are read from their inline data or from inside the workspace root
* only; unreadable or out-of-scope parts are skipped rather than guessed at.
*/
-export async function collectPromptAttachments(payload: unknown, workspaceRoot: string | null): Promise<CollectorAttachment[]> {
- const attachments: CollectorAttachment[] = [];
+export async function readPromptAttachments(payload: unknown, workspaceRoot: string | null): Promise<UploadAttachment[]> {
+ const attachments: UploadAttachment[] = [];
for (const source of promptFileParts(payload)) {
const bytes = source.url.startsWith("data:")
? dataUrlBytes(source.url)
diff --git a/apps/server/src/collect-upload-budget.ts b/apps/server/src/session-upload-budget.ts
similarity index 63%
rename from apps/server/src/collect-upload-budget.ts
rename to apps/server/src/session-upload-budget.ts
index 9dd8942a..e497f55a 100644
--- a/apps/server/src/collect-upload-budget.ts
+++ b/apps/server/src/session-upload-budget.ts
@@ -1,5 +1,14 @@
/**
- * How long one collector upload (POST <gateway>/collect) may take.
+ * The omnirush.ai endpoint every session upload is sent to, relative to the
+ * gateway root (the gateway URL without its trailing /v1): with the hosted
+ * gateway that is POST https://<host>/omnirush/collect. The path is the
+ * server's API and stays "collect" whatever the desktop code calls its
+ * uploader; renaming it here would break every upload.
+ */
+export const SESSION_UPLOAD_ENDPOINT_PATH = "collect";
+
+/**
+ * How long one session upload (POST <gateway>/collect) may take.
*
* Envelopes range from a few KiB (a change snapshot) to tens of MiB (the
* start snapshot of a large workspace), so the deadline grows with the body:
@@ -18,22 +27,22 @@
* body sent faster than the assumed rate leaves the unused sending time to the
* response wait.
*/
-export type CollectUploadBudget = {
+export type SessionUploadBudget = {
baseMs: number;
bytesPerSecond: number;
maxSendMs: number;
responseMs: number;
};
-export const COLLECT_UPLOAD_BUDGET: CollectUploadBudget = {
+export const SESSION_UPLOAD_BUDGET: SessionUploadBudget = {
baseMs: 30_000,
bytesPerSecond: 128 * 1024,
maxSendMs: 15 * 60_000,
responseMs: 120_000,
};
-/** The whole-request deadline, in milliseconds, for a collect upload of `bytes`. */
-export function collectUploadTimeoutMs(bytes: number, budget: CollectUploadBudget = COLLECT_UPLOAD_BUDGET): number {
+/** The whole-request deadline, in milliseconds, for a session upload of `bytes`. */
+export function sessionUploadTimeoutMs(bytes: number, budget: SessionUploadBudget = SESSION_UPLOAD_BUDGET): number {
const sendMs = budget.baseMs + Math.ceil((Math.max(0, bytes) * 1_000) / budget.bytesPerSecond);
return Math.min(budget.maxSendMs, sendMs) + budget.responseMs;
}
diff --git a/apps/server/src/collector-observer.test.ts b/apps/server/src/session-upload-observer.test.ts
similarity index 81%
rename from apps/server/src/collector-observer.test.ts
rename to apps/server/src/session-upload-observer.test.ts
index c8224e1b..262717c1 100644
--- a/apps/server/src/collector-observer.test.ts
+++ b/apps/server/src/session-upload-observer.test.ts
@@ -7,17 +7,17 @@ import { zstdDecompressSync } from "node:zlib";
import {
createSessionObservers,
engineReplaced,
- observeCollectedSession,
+ observeUploadedSession,
projectArchiveEngineReads,
promptDispatched,
type EngineTarget,
- type ObservedCollector,
+ type ObservedUploader,
type ObserverTiming,
type SessionObservers,
-} from "./collector-observer.js";
+} from "./session-upload-observer.js";
import type { CaptureResult, DrainResult, FinalReason } from "./session-archive/index.js";
import { ProjectArchiveLifecycle, type ProjectArchiver } from "./session-archive/lifecycle.js";
-import { WorkspaceCollector, type CollectorChildSession } from "./workspace-collector.js";
+import { SessionUploader, type UploadChildSession } from "./session-uploader.js";
/**
* The turn observer against a fake engine, on a fake clock: a turn is
@@ -142,8 +142,8 @@ type Entry =
| { kind: "snapshot"; trigger: string }
| { kind: "flush"; final?: unknown };
-/** Records what the observer hands the collector, in order. */
-class FakeCollector implements ObservedCollector {
+/** Records what the observer hands the session uploader, in order. */
+class FakeUploader implements ObservedUploader {
readonly enabled = true;
checkpoint: string | undefined;
readonly entries: Entry[] = [];
@@ -170,7 +170,7 @@ class FakeCollector implements ObservedCollector {
return [];
}
- recordChildSession(_sessionId: string, _child: CollectorChildSession): void {}
+ recordChildSession(_sessionId: string, _child: UploadChildSession): void {}
captureSnapshot(_sessionId: string, trigger: "prompt" | "turn_completed"): void {
this.entries.push({ kind: "snapshot", trigger });
@@ -217,10 +217,10 @@ function fakeArchive() {
};
}
-type ObservedArchive = Parameters<typeof observeCollectedSession>[0]["archive"];
+type ObservedArchive = Parameters<typeof observeUploadedSession>[0]["archive"];
-function observe(input: { collector: ObservedCollector; archive: ObservedArchive; observers: SessionObservers; target: EngineTarget; timing: Partial<ObserverTiming> }) {
- return observeCollectedSession({ ...input, sessionId: SESSION });
+function observe(input: { sessionUploader: ObservedUploader; archive: ObservedArchive; observers: SessionObservers; target: EngineTarget; timing: Partial<ObserverTiming> }) {
+ return observeUploadedSession({ ...input, sessionId: SESSION });
}
/** A project archiver that records what the real lifecycle asks of it (bases and deltas numbered like the real one). */
@@ -277,23 +277,23 @@ async function archivedSession(engine: ReturnType<typeof startEngine>, finalIdle
return { root, archiver, archive };
}
-describe("collector observer", () => {
+describe("session upload observer", () => {
test("a turn busy for three hours, past the old one-hour cap, gets its messages, snapshot and archive delta, with status reads easing off", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
engine.control.messages = [message("msg_user_0001", "user", "Work on issue 42")];
engine.control.status = () => (clock.elapsed() < 3 * HOUR ? "busy" : "idle");
clock.at(3 * HOUR, () => engine.control.messages.push(message("msg_assistant_0001", "assistant", "Fixed issue 42")));
- await observe({ collector, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
- expect(collector.labels()).not.toContain("session.observer_timeout");
- expect(collector.labels()).not.toContain("session.observer_failed");
- expect(collector.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
- expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
- expect(collector.checkpoint).toBe("msg_assistant_0001");
+ expect(sessionUploader.labels()).not.toContain("session.observer_timeout");
+ expect(sessionUploader.labels()).not.toContain("session.observer_failed");
+ expect(sessionUploader.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(sessionUploader.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
+ expect(sessionUploader.checkpoint).toBe("msg_assistant_0001");
expect(archive.turns).toHaveLength(1);
expect(archive.turns[0]).toHaveLength(2);
// A settled turn, however long, is a completed one for the project archive.
@@ -309,17 +309,17 @@ describe("collector observer", () => {
test("a status read that times out twice, then answers, does not end the observation", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
engine.control.messages = [message("msg_user_0001", "user"), message("msg_assistant_0001", "assistant")];
engine.control.status = () => (clock.elapsed() < 5 * 60_000 ? "busy" : "idle");
// The engine is busy with a large session: its first two status answers take longer than a status read waits.
engine.control.statusDelaysMs = [400, 400];
- await observe({ collector, archive, observers: createSessionObservers(), target: engine.target, timing: { ...clock.timing, statusTimeoutMs: 50 } });
+ await observe({ sessionUploader, archive, observers: createSessionObservers(), target: engine.target, timing: { ...clock.timing, statusTimeoutMs: 50 } });
- expect(collector.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
- expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
+ expect(sessionUploader.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(sessionUploader.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
expect(archive.calls).toEqual(["followed", "completed"]);
// The failed reads backed off (1 s, then 2 s) before the next one.
expect(clock.waits.slice(0, 3)).toEqual([1_000, 1_000, 2_000]);
@@ -329,7 +329,7 @@ describe("collector observer", () => {
const clock = fakeClock();
const before = startEngine();
const after = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
const observers = createSessionObservers();
before.control.messages = [message("msg_user_0001", "user")];
@@ -340,25 +340,25 @@ describe("collector observer", () => {
clock.at(20 * 60_000, () => void before.server.stop(true));
let rejoined: Promise<void> | null = null;
clock.at(25 * 60_000, () => {
- rejoined = observe({ collector, archive, observers, target: after.target, timing: clock.timing });
+ rejoined = observe({ sessionUploader, archive, observers, target: after.target, timing: clock.timing });
});
- const observation = observe({ collector, archive, observers, target: before.target, timing: clock.timing });
+ const observation = observe({ sessionUploader, archive, observers, target: before.target, timing: clock.timing });
await observation;
expect(rejoined as Promise<void> | null).toBe(observation);
- expect(collector.labels()).toEqual([
+ expect(sessionUploader.labels()).toEqual([
"session.engine_unavailable",
"session.engine_recovered",
"session.idle",
"snapshot:turn_completed",
"flush:turn",
]);
- const [unavailable] = collector.trace("session.engine_unavailable") as Array<{ error: string; failures: number }>;
+ const [unavailable] = sessionUploader.trace("session.engine_unavailable") as Array<{ error: string; failures: number }>;
expect(unavailable?.failures).toBeGreaterThan(1);
- const [recovered] = collector.trace("session.engine_recovered") as Array<{ unavailable_ms: number }>;
+ const [recovered] = sessionUploader.trace("session.engine_recovered") as Array<{ unavailable_ms: number }>;
expect(recovered?.unavailable_ms).toBeGreaterThanOrEqual(4 * 60_000);
- expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
+ expect(sessionUploader.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
expect(archive.turns).toHaveLength(1);
// Waiting out the engine is not an incomplete turn, and the request that rejoined followed no turn of its own.
expect(archive.calls).toEqual(["followed", "completed"]);
@@ -368,7 +368,7 @@ describe("collector observer", () => {
test("a prompt sent while the turn settles is followed as a turn of its own", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
const observers = createSessionObservers();
engine.control.messages = [message("msg_user_0001", "user"), message("msg_assistant_0001", "assistant")];
@@ -379,16 +379,16 @@ describe("collector observer", () => {
engine.control.onMessagesRead = null;
busyUntil = clock.elapsed() + 5 * 60_000;
engine.control.messages.push(message("msg_user_0002", "user"), message("msg_assistant_0002", "assistant"));
- void observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ void observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
};
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
- expect(collector.labels()).toEqual([
+ expect(sessionUploader.labels()).toEqual([
"session.idle", "snapshot:turn_completed", "flush:turn",
"session.idle", "snapshot:turn_completed", "flush:turn",
]);
- expect(collector.turnMessageIds()).toEqual([
+ expect(sessionUploader.turnMessageIds()).toEqual([
["msg_user_0001", "msg_assistant_0001"],
["msg_user_0002", "msg_assistant_0002"],
]);
@@ -400,15 +400,15 @@ describe("collector observer", () => {
test("the server stopping mid-turn ends the observation quietly and leaves the checkpoint where it was", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
- collector.checkpoint = "msg_assistant_0000";
+ const sessionUploader = new FakeUploader();
+ sessionUploader.checkpoint = "msg_assistant_0000";
const observers = createSessionObservers();
engine.control.status = () => "busy";
clock.at(2 * HOUR, () => observers.controller.abort());
const archive = fakeArchive();
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
- expect(collector.entries).toEqual([]);
- expect(collector.checkpoint).toBe("msg_assistant_0000");
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
+ expect(sessionUploader.entries).toEqual([]);
+ expect(sessionUploader.checkpoint).toBe("msg_assistant_0000");
// A quit is no incomplete turn: the project archive's stop() packs its final archives.
expect(archive.calls).toEqual(["followed"]);
});
@@ -418,11 +418,11 @@ describe("collector observer", () => {
const engine = startEngine();
const archive = fakeArchive();
const observers = createSessionObservers();
- // A collector that fails on the second turn's idle event, before that turn's snapshot.
+ // A session uploader that fails on the second turn's idle event, before that turn's snapshot.
let idles = 0;
- const collector = new (class extends FakeCollector {
+ const sessionUploader = new (class extends FakeUploader {
override recordTrace(sessionId: string, type: string, data?: unknown): void {
- if (type === "session.idle" && ++idles === 2) throw new Error("the collector failed");
+ if (type === "session.idle" && ++idles === 2) throw new Error("the session uploader failed");
super.recordTrace(sessionId, type, data);
}
})();
@@ -433,12 +433,12 @@ describe("collector observer", () => {
engine.control.onMessagesRead = null;
busyUntil = clock.elapsed() + 5 * 60_000;
engine.control.messages.push(message("msg_user_0002", "user"), message("msg_assistant_0002", "assistant"));
- void observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ void observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
};
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
- expect(collector.labels()).toEqual([
+ expect(sessionUploader.labels()).toEqual([
"session.idle", "snapshot:turn_completed", "flush:turn",
"session.observer_failed", "snapshot:turn_completed", "flush",
]);
@@ -448,7 +448,7 @@ describe("collector observer", () => {
});
});
-describe("collector observer across engine rollovers and queued prompts", () => {
+describe("session upload observer across engine rollovers and queued prompts", () => {
/** A message the engine created at `created` (epoch ms); an assistant one finished. */
const at = (id: string, role: "user" | "assistant", created: number): EngineMessage => {
const each = message(id, role);
@@ -462,7 +462,7 @@ describe("collector observer across engine rollovers and queued prompts", () =>
// Two engine generations over one shared database: the same messages answer on both.
const draining = startEngine();
const primary = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
const observers = createSessionObservers();
const shared = [message("msg_user_0001", "user")];
@@ -479,21 +479,21 @@ describe("collector observer across engine rollovers and queued prompts", () =>
void draining.server.stop(true);
});
- await observe({ collector, archive, observers, target: draining.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: draining.target, timing: clock.timing });
- expect(collector.labels()).not.toContain("session.engine_unavailable");
- expect(collector.labels()).not.toContain("session.observer_timeout");
- expect(collector.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
- expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
+ expect(sessionUploader.labels()).not.toContain("session.engine_unavailable");
+ expect(sessionUploader.labels()).not.toContain("session.observer_timeout");
+ expect(sessionUploader.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(sessionUploader.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"]]);
expect(archive.calls).toEqual(["followed", "completed"]);
// It settled within seconds of the turn's end, reading the new engine with that engine's credentials.
expect(clock.elapsed()).toBeLessThan(100_000);
expect(primary.control.authorizations.length).toBeGreaterThan(0);
expect(new Set(primary.control.authorizations)).toEqual(new Set(["Basic bmV3LWVuZ2luZQ=="]));
// A request that still names the closed engine (it was routed before the close) is read from the new one.
- const late = new FakeCollector();
+ const late = new FakeUploader();
const lateArchive = fakeArchive();
- await observe({ collector: late, archive: lateArchive, observers, target: draining.target, timing: clock.timing });
+ await observe({ sessionUploader: late, archive: lateArchive, observers, target: draining.target, timing: clock.timing });
expect(late.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
expect(observers.sessions.size).toBe(0);
});
@@ -501,7 +501,7 @@ describe("collector observer across engine rollovers and queued prompts", () =>
test("a prompt sent within two seconds of the turn going idle ends that turn: each prompt gets its own snapshot, messages and settle", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
const observers = createSessionObservers();
const start = clock.timing.now!();
@@ -514,27 +514,27 @@ describe("collector observer across engine rollovers and queued prompts", () =>
// the prompt and runs a second turn.
clock.at(60_500, () => {
const dispatchedAt = clock.timing.now!();
- promptDispatched(observers, collector, SESSION, dispatchedAt);
+ promptDispatched(observers, sessionUploader, SESSION, dispatchedAt);
busyUntil = 3 * 60_000;
engine.control.messages.push(at("msg_user_0002", "user", dispatchedAt + 5));
- // The prompt's response reaches the observer like any collected request.
- void observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ // The prompt's response reaches the observer like any captured request.
+ void observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
});
clock.at(3 * 60_000, () => engine.control.messages.push(at("msg_assistant_0002", "assistant", start + 179_000)));
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
- expect(collector.labels()).toEqual([
+ expect(sessionUploader.labels()).toEqual([
// Turn 1's end snapshot is taken as prompt 2 goes out (ahead of prompt 2's own snapshot).
"snapshot:turn_completed",
"session.idle", "flush:turn",
"session.idle", "snapshot:turn_completed", "flush:turn",
]);
- expect(collector.turnMessageIds()).toEqual([
+ expect(sessionUploader.turnMessageIds()).toEqual([
["msg_user_0001", "msg_assistant_0001"],
["msg_user_0002", "msg_assistant_0002"],
]);
- expect(collector.checkpoint).toBe("msg_assistant_0002");
+ expect(sessionUploader.checkpoint).toBe("msg_assistant_0002");
expect(archive.calls).toEqual(["followed", "completed", "followed", "completed"]);
expect(archive.turns.map((turn) => turn?.length)).toEqual([2, 4]);
});
@@ -542,7 +542,7 @@ describe("collector observer across engine rollovers and queued prompts", () =>
test("a prompt sent into a turn still answering waits for that answer to finish before the turn settles", async () => {
const clock = fakeClock();
const engine = startEngine();
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const archive = fakeArchive();
const observers = createSessionObservers();
const start = clock.timing.now!();
@@ -553,25 +553,25 @@ describe("collector observer across engine rollovers and queued prompts", () =>
engine.control.status = () => (clock.elapsed() < 5 * 60_000 ? "busy" : "idle");
clock.at(30_000, () => {
const dispatchedAt = clock.timing.now!();
- promptDispatched(observers, collector, SESSION, dispatchedAt);
+ promptDispatched(observers, sessionUploader, SESSION, dispatchedAt);
engine.control.messages.push(at("msg_user_0002", "user", dispatchedAt + 5));
});
// Turn 1's answer ends a minute later; turn 2 answers after it.
clock.at(90_000, () => { answering.info.time = { created: start + 1_000, completed: start + 90_000 }; answering.info.finish = "stop"; });
clock.at(5 * 60_000, () => engine.control.messages.push(at("msg_assistant_0002", "assistant", start + 200_000)));
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
- expect(collector.turnMessageIds()).toEqual([
+ expect(sessionUploader.turnMessageIds()).toEqual([
["msg_user_0001", "msg_assistant_0001"],
["msg_user_0002", "msg_assistant_0002"],
]);
- expect(collector.labels().filter((label) => label === "snapshot:turn_completed")).toHaveLength(2);
+ expect(sessionUploader.labels().filter((label) => label === "snapshot:turn_completed")).toHaveLength(2);
expect(archive.calls).toEqual(["followed", "completed", "followed", "completed"]);
});
});
-describe("collector observer with the project archive", () => {
+describe("session upload observer with the project archive", () => {
const user = (id: string) => message(`msg_user_${id}`, "user");
const answer = (id: string) => message(`msg_assistant_${id}`, "assistant");
@@ -584,12 +584,12 @@ describe("collector observer with the project archive", () => {
engine.control.status = () => (clock.elapsed() < 3 * HOUR ? "busy" : "idle");
clock.at(3 * HOUR, () => engine.control.messages.push(answer("0001")));
- const collector = new FakeCollector();
- await observe({ collector, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+ const sessionUploader = new FakeUploader();
+ await observe({ sessionUploader, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
await archive.settled();
expect(clock.elapsed()).toBeGreaterThanOrEqual(3 * HOUR);
- expect(collector.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
+ expect(sessionUploader.labels()).toEqual(["session.idle", "snapshot:turn_completed", "flush:turn"]);
expect(archiver.calls).toEqual([`base ${SESSION} ${root} 0`, `delta ${SESSION} ${root} 1`]);
// No prompt follows: the quiet window after the turn ends in a final archive of the folder.
await Bun.sleep(250);
@@ -606,12 +606,12 @@ describe("collector observer with the project archive", () => {
engine.control.status = () => "busy";
clock.at(5 * HOUR, () => engine.control.messages.push(answer("0001")));
- const collector = new FakeCollector();
- await observe({ collector, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
+ const sessionUploader = new FakeUploader();
+ await observe({ sessionUploader, archive, observers: createSessionObservers(), target: engine.target, timing: clock.timing });
await archive.settled();
expect(clock.elapsed()).toBeGreaterThanOrEqual(24 * HOUR);
- expect(collector.labels()).toEqual(["session.observer_timeout", "snapshot:turn_completed", "flush"]);
+ expect(sessionUploader.labels()).toEqual(["session.observer_timeout", "snapshot:turn_completed", "flush"]);
// turnIncomplete read the engine's count again: it moved, so the turn gets its delta.
expect(archiver.calls).toEqual([`base ${SESSION} ${root} 0`, `delta ${SESSION} ${root} 1`]);
await Bun.sleep(250);
@@ -624,7 +624,7 @@ describe("collector observer with the project archive", () => {
const engine = startEngine();
engine.control.messages = [user("0001")];
const { root, archiver, archive } = await archivedSession(engine, 100);
- const collector = new FakeCollector();
+ const sessionUploader = new FakeUploader();
const observers = createSessionObservers();
let busyUntil = 2 * 60_000;
engine.control.status = () => (clock.elapsed() < busyUntil ? "busy" : "idle");
@@ -637,15 +637,15 @@ describe("collector observer with the project archive", () => {
engine.control.messages.push(user("0002"));
clock.at(busyUntil, () => engine.control.messages.push(answer("0002")));
archive.sessionStarted({ sessionId: SESSION, root, engine: projectArchiveEngineReads(engine.target, SESSION) });
- void observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ void observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
// Turn 2's first status answer takes longer than the quiet window.
engine.control.statusDelaysMs = [300];
};
- await observe({ collector, archive, observers, target: engine.target, timing: clock.timing });
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });
await archive.settled();
- expect(collector.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"], ["msg_user_0002", "msg_assistant_0002"]]);
+ expect(sessionUploader.turnMessageIds()).toEqual([["msg_user_0001", "msg_assistant_0001"], ["msg_user_0002", "msg_assistant_0002"]]);
// No idle final archive while turn 2 ran, only after it.
expect(archiver.calls).toEqual([`base ${SESSION} ${root} 0`, `delta ${SESSION} ${root} 1`, `delta ${SESSION} ${root} 2`]);
await Bun.sleep(250);
@@ -659,7 +659,7 @@ describe("collector observer with the project archive", () => {
});
});
-describe("collector observer with the collector", () => {
+describe("session upload observer with the session uploader", () => {
type Envelope = {
snapshot_type: string;
files: Array<{ path: string; content: string }>;
@@ -671,7 +671,7 @@ describe("collector observer with the collector", () => {
cleanups.push(() => rm(root, { recursive: true, force: true }));
await writeFile(join(root, "app.txt"), "hello\n");
const uploads: Envelope[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope);
return Response.json({ ok: true }, { status: 201 });
@@ -679,8 +679,8 @@ describe("collector observer with the collector", () => {
changeDebounceMs: 60_000,
fallbackScanMs: 60_000,
});
- cleanups.push(() => collector.stop());
- collector.startSession(SESSION, "workspace-observer", root);
+ cleanups.push(() => sessionUploader.stop());
+ sessionUploader.startSession(SESSION, "workspace-observer", root);
const engine = startEngine();
const archive = fakeArchive();
const observers = createSessionObservers();
@@ -694,14 +694,14 @@ describe("collector observer with the collector", () => {
clock = fakeClock();
const current = clock;
engine.control.status = () => (current.elapsed() < busyMs ? "busy" : "idle");
- await observe({ collector, archive, observers, target: engine.target, timing: { ...current.timing, ...(maxTurnMs ? { maxTurnMs } : {}) } });
- await collector.idle(SESSION);
+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: { ...current.timing, ...(maxTurnMs ? { maxTurnMs } : {}) } });
+ await sessionUploader.idle(SESSION);
};
// Turn 1 settles normally: the checkpoint is its answer.
engine.control.messages = [message("msg_user_0001", "user"), message("msg_assistant_0001", "assistant")];
await turn(60_000);
- expect((await collector.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0001");
+ expect((await sessionUploader.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0001");
// Turn 2 is still running when the observer's safety bound (two hours here) runs out.
engine.control.messages.push(message("msg_user_0002", "user", "Continue"));
@@ -715,7 +715,7 @@ describe("collector observer with the collector", () => {
// The project archive hears the turn ended without completing (its delta, or a final archive).
expect(archive.calls).toEqual(["followed", "completed", "followed", "incomplete"]);
// Its messages were not sent, so the checkpoint did not move.
- expect((await collector.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0001");
+ expect((await sessionUploader.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0001");
// Turn 3 ("continue") settles: 24 MiB of turn 2 plus its own messages go out in four traces of at most 8 MiB of messages.
const sent = traces().length;
@@ -736,7 +736,7 @@ describe("collector observer with the collector", () => {
expect(document(envelope)).toMatchObject({ trace_truncated: false, dropped_event_count: 0 });
expect(events(envelope).map((event) => event.type)).not.toContain("session.messages_omitted");
}
- expect((await collector.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0003");
+ expect((await sessionUploader.sessionCheckpoint(SESSION)).lastMessageId).toBe("msg_assistant_0003");
// The archive delta counts every completed turn the engine holds.
expect(archive.turns.at(-1)).toHaveLength(13);
diff --git a/apps/server/src/collector-observer.ts b/apps/server/src/session-upload-observer.ts
similarity index 91%
rename from apps/server/src/collector-observer.ts
rename to apps/server/src/session-upload-observer.ts
index cdea8c62..e4dbe8b1 100644
--- a/apps/server/src/collector-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -1,17 +1,17 @@
/**
* The engine reads behind collection: the turn observer that waits for a
- * collected session to settle and hands its messages, model, subagents and
- * turn milestone to the collector and the project archive, and the reads a
- * project archive session start makes. They run beside the collector (on
+ * captured session to settle and hands its messages, model, subagents and
+ * turn milestone to the session uploader and the project archive, and the reads a
+ * project archive session start makes. They run beside the session uploader (on
* the capture worker when there is one, see capture-host.ts), so parsing a
* long transcript never holds the server's main event loop. An engine is
* named by plain data (EngineTarget) so the target can cross threads.
*/
import { loopbackFetch } from "./server-fetch.js";
import { isFinishedAssistantMessage, type ArchiveEngineReads, type ProjectArchiveLifecycle } from "./session-archive/lifecycle.js";
-import { MAX_COLLECTOR_CHILD_SESSION_DEPTH, type CollectorSessionModel, type WorkspaceCollector } from "./workspace-collector.js";
+import { MAX_UPLOAD_CHILD_SESSION_DEPTH, type UploadSessionModel, type SessionUploader } from "./session-uploader.js";
-/** The engine a collected request went to: base URL, request headers (the engine's auth), query and API generation. */
+/** The engine a captured request went to: base URL, request headers (the engine's auth), query and API generation. */
export type EngineTarget = {
baseUrl: string;
headers: Array<[string, string]>;
@@ -30,7 +30,7 @@ export type EngineTarget = {
type FollowedTurn = { snapshotTaken: boolean; cutAt: number | null };
/**
- * A session being observed: the engine its latest collected request went to
+ * A session being observed: the engine its latest captured request went to
* (an engine that restarted may answer on another port), how many requests
* asked for it while it was, the turn being followed, and the observation itself.
*/
@@ -111,18 +111,18 @@ export function engineReplaced(observers: SessionObservers, closedBaseUrl: strin
* the new prompt's own snapshot, so both turns keep their turn.diff, and
* the observer settles it with the messages from before this prompt.
*/
-export function promptDispatched(observers: SessionObservers, collector: Pick<ObservedCollector, "captureSnapshot">, sessionId: string, at: number): void {
+export function promptDispatched(observers: SessionObservers, sessionUploader: Pick<ObservedUploader, "captureSnapshot">, sessionId: string, at: number): void {
const turn = observers.sessions.get(sessionId)?.turn;
if (!turn || turn.cutAt !== null) return;
turn.cutAt = at;
if (turn.snapshotTaken) return;
turn.snapshotTaken = true;
- collector.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
}
-/** What the observer asks of the collector. */
-export type ObservedCollector = Pick<
- WorkspaceCollector,
+/** What the observer asks of the session uploader. */
+export type ObservedUploader = Pick<
+ SessionUploader,
| "enabled"
| "sessionCheckpoint"
| "setSessionCheckpoint"
@@ -164,7 +164,7 @@ function optionalTraceString(value: unknown): string | null {
* (providerID / modelID / mode or agent). The user message that opened the
* turn supplies the variant and agent when the assistant record lacks them.
*/
-function turnModelFromMessages(messages: unknown): CollectorSessionModel | null {
+function turnModelFromMessages(messages: unknown): UploadSessionModel | null {
if (!Array.isArray(messages)) return null;
let userVariant: string | null = null;
let userAgent: string | null = null;
@@ -236,7 +236,7 @@ export type ObserverTiming = {
type EngineFetch = (path: string, query?: Record<string, string>) => Promise<Response>;
-/** Requests to the engine a collected request went to (the current `target()`), with its headers and query plus `query`, each under a fresh `signal()`. */
+/** Requests to the engine a captured request went to (the current `target()`), with its headers and query plus `query`, each under a fresh `signal()`. */
function engineFetch(target: () => EngineTarget, signal: () => AbortSignal): EngineFetch {
return (path, query = {}) => {
const { baseUrl, headers, search } = target();
@@ -279,7 +279,7 @@ function nullOnErrorStatus(error: unknown): null {
* hears the size of each event's messages before it is recorded.
*/
async function captureChildSessions(input: {
- collector: ObservedCollector;
+ sessionUploader: ObservedUploader;
rootSessionId: string;
parentSessionId: string;
depth: number;
@@ -289,7 +289,7 @@ async function captureChildSessions(input: {
visited: Set<string>;
beforeRecord: (bytes: number) => void;
}): Promise<void> {
- if (input.depth > MAX_COLLECTOR_CHILD_SESSION_DEPTH) return;
+ if (input.depth > MAX_UPLOAD_CHILD_SESSION_DEPTH) return;
const children = await readEngineJson(input.fetchEngine, `/session/${encodeURIComponent(input.parentSessionId)}/children`, 1024 * 1024)
.catch(nullOnErrorStatus);
if (!Array.isArray(children)) return;
@@ -301,11 +301,11 @@ async function captureChildSessions(input: {
.catch(nullOnErrorStatus);
const newMessages = history?.delta ?? [];
if (history && history.omitted > 0) {
- input.collector.recordTrace(input.rootSessionId, "session.messages_omitted", { child_session_id: childId, count: history.omitted });
+ input.sessionUploader.recordTrace(input.rootSessionId, "session.messages_omitted", { child_session_id: childId, count: history.omitted });
}
if (newMessages.length > 0 || !input.known.has(childId)) {
input.beforeRecord(history ? sum(history.sizes) : 0);
- input.collector.recordChildSession(input.rootSessionId, {
+ input.sessionUploader.recordChildSession(input.rootSessionId, {
childSessionId: childId,
parentSessionId: input.parentSessionId,
depth: input.depth,
@@ -327,7 +327,7 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : "unknown";
}
-function collectorDelay(ms: number, signal: AbortSignal): Promise<void> {
+function uploadDelay(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolvePromise, reject) => {
if (signal.aborted) {
reject(signal.reason);
@@ -342,7 +342,7 @@ function collectorDelay(ms: number, signal: AbortSignal): Promise<void> {
});
}
-async function readCollectorResponse(response: Response, maxBytes = MAX_ENGINE_READ_BYTES): Promise<unknown> {
+async function readObservedResponse(response: Response, maxBytes = MAX_ENGINE_READ_BYTES): Promise<unknown> {
const reader = response.body?.getReader();
if (!reader) return null;
const chunks: Uint8Array[] = [];
@@ -377,7 +377,7 @@ async function readEngineJson(fetchEngine: EngineFetch, path: string, maxBytes?:
await response.body?.cancel().catch(() => undefined);
throw new EngineReadError(response.status);
}
- return readCollectorResponse(response, maxBytes);
+ return readObservedResponse(response, maxBytes);
}
/**
@@ -444,7 +444,7 @@ async function* engineMessages(fetchEngine: EngineFetch, path: string, paged: bo
const cursor = response.headers.get("x-next-cursor");
let page: EngineMessage[];
try {
- const items = await readCollectorResponse(response);
+ const items = await readObservedResponse(response);
if (!Array.isArray(items)) throw new Error("the engine messages could not be read");
page = items.map((message) => ({ message, whole: true }));
} catch (error) {
@@ -646,7 +646,7 @@ function statusPollDelay(elapsedMs: number): number {
/**
* The engine reads behind a project archive session start (is it a child
- * session, how many turns has it completed), made like the collector
+ * session, how many turns has it completed), made like the session uploader
* observer's: same engine, headers and query, never from the request path.
*/
export function projectArchiveEngineReads(target: EngineTarget | (() => EngineTarget), sessionId: string): ArchiveEngineReads {
@@ -665,7 +665,7 @@ export function projectArchiveEngineReads(target: EngineTarget | (() => EngineTa
}
/**
- * Follows a collected session until its turn settles, then records the
+ * Follows a captured session until its turn settles, then records the
* turn's model, subagents and messages, takes the turn's change snapshot,
* flushes the trace and hands the engine's messages to the project archive.
* The snapshot, the trace and the archive delta never depend on reading
@@ -690,17 +690,17 @@ export function projectArchiveEngineReads(target: EngineTarget | (() => EngineTa
* turn's end armed never runs while this one does. Resolves once the
* observation ended.
*/
-export function observeCollectedSession(input: {
- collector: ObservedCollector;
+export function observeUploadedSession(input: {
+ sessionUploader: ObservedUploader;
archive: Pick<ProjectArchiveLifecycle, "turnFollowed" | "turnCompleted" | "turnIncomplete">;
observers: SessionObservers;
sessionId: string;
target: EngineTarget;
timing?: Partial<ObserverTiming>;
}): Promise<void> {
- if (!input.collector.enabled) return Promise.resolve();
+ if (!input.sessionUploader.enabled) return Promise.resolve();
const observer = input.observers;
- const { collector, sessionId } = input;
+ const { sessionUploader, sessionId } = input;
// A request that reached an engine since closed names it: its sessions are read from the one that took over.
const requestTarget = currentEngineTarget(observer, input.target);
const observed = observer.sessions.get(sessionId);
@@ -713,7 +713,7 @@ export function observeCollectedSession(input: {
observer.sessions.set(sessionId, session);
const timing: ObserverTiming = {
now: () => Date.now(),
- sleep: collectorDelay,
+ sleep: uploadDelay,
statusTimeoutMs: 10_000,
readTimeoutMs: 20_000,
maxTurnMs: MAX_OBSERVED_TURN_MS,
@@ -741,7 +741,7 @@ export function observeCollectedSession(input: {
const turn = turnState();
if (turn.snapshotTaken) return;
turn.snapshotTaken = true;
- collector.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
};
/** The session's status ("idle" when the engine does not list it); throws when the engine does not answer. */
@@ -781,23 +781,23 @@ export function observeCollectedSession(input: {
} catch (error) {
if (stopped.aborted) throw error;
if (error instanceof EngineReadError) unavailable = { status: error.status, unavailable: true };
- collector.recordTrace(sessionId, "session.messages_failed", { error: errorMessage(error) });
+ sessionUploader.recordTrace(sessionId, "session.messages_failed", { error: errorMessage(error) });
}
let parts: MessagePart[] = [{ messages: [], bytes: 0 }];
if (history) {
const lastId = traceMessageId(history.outline.at(-1));
if (lastId) {
observer.lastMessageIds.set(sessionId, lastId);
- void collector.setSessionCheckpoint(sessionId, lastId);
+ void sessionUploader.setSessionCheckpoint(sessionId, lastId);
}
- if (history.omitted > 0) collector.recordTrace(sessionId, "session.messages_omitted", { count: history.omitted });
+ if (history.omitted > 0) sessionUploader.recordTrace(sessionId, "session.messages_omitted", { count: history.omitted });
const model = turnModelFromMessages(history.delta);
- if (model) collector.recordSessionModel(sessionId, model);
+ if (model) sessionUploader.recordSessionModel(sessionId, model);
// More messages than one flush holds: the older ones go ahead, a flush per part.
parts = messageParts(history.delta, history.sizes);
for (const [index, part] of parts.slice(0, -1).entries()) {
- collector.recordTrace(sessionId, "turn.messages", { messages: part.messages, part: index + 1, parts: parts.length });
- collector.flushTrace(sessionId);
+ sessionUploader.recordTrace(sessionId, "turn.messages", { messages: part.messages, part: index + 1, parts: parts.length });
+ sessionUploader.flushTrace(sessionId);
}
}
const newest = parts.at(-1)!;
@@ -806,7 +806,7 @@ export function observeCollectedSession(input: {
let pending = 0;
const room = (bytes: number) => {
if (pending > 0 && pending + bytes > MAX_TURN_MESSAGE_BYTES) {
- collector.flushTrace(sessionId);
+ sessionUploader.flushTrace(sessionId);
pending = 0;
}
pending += bytes;
@@ -815,27 +815,27 @@ export function observeCollectedSession(input: {
if (!v2) {
try {
await captureChildSessions({
- collector,
+ sessionUploader,
rootSessionId: sessionId,
parentSessionId: sessionId,
depth: 1,
fetchEngine,
- checkpoints: await collector.childCheckpoints(sessionId),
- known: new Set(await collector.childSessionIds(sessionId)),
+ checkpoints: await sessionUploader.childCheckpoints(sessionId),
+ known: new Set(await sessionUploader.childSessionIds(sessionId)),
visited: new Set([sessionId]),
beforeRecord: room,
});
} catch (error) {
if (stopped.aborted) throw error;
- collector.recordTrace(sessionId, "session.children_failed", { error: errorMessage(error) });
+ sessionUploader.recordTrace(sessionId, "session.children_failed", { error: errorMessage(error) });
}
}
room(newest.bytes);
- collector.recordTrace(sessionId, "session.idle", { status });
+ sessionUploader.recordTrace(sessionId, "session.idle", { status });
// The turn snapshot runs first so the artifacts it discovers are part of
// the trace flushed right behind it.
captureTurnSnapshot();
- collector.flushTrace(sessionId, { messages: history ? newest.messages : unavailable });
+ sessionUploader.flushTrace(sessionId, { messages: history ? newest.messages : unavailable });
// The delta's turn number is the engine's completed-turn count, which
// survives app restarts; without the messages the archiver numbers it
// right after the last archived turn. It also arms the idle final archive.
@@ -885,12 +885,12 @@ export function observeCollectedSession(input: {
unavailableSince ??= timing.now();
if (!unavailableTraced && timing.now() - unavailableSince >= ENGINE_UNAVAILABLE_TRACE_MS) {
unavailableTraced = true;
- collector.recordTrace(sessionId, "session.engine_unavailable", { error: errorMessage(error), failures });
+ sessionUploader.recordTrace(sessionId, "session.engine_unavailable", { error: errorMessage(error), failures });
}
continue;
}
if (unavailableTraced && unavailableSince !== null) {
- collector.recordTrace(sessionId, "session.engine_recovered", { failures, unavailable_ms: timing.now() - unavailableSince });
+ sessionUploader.recordTrace(sessionId, "session.engine_recovered", { failures, unavailable_ms: timing.now() - unavailableSince });
}
failures = 0;
unavailableSince = null;
@@ -939,12 +939,12 @@ export function observeCollectedSession(input: {
// The server stopping is no timeout: it ends the observation quietly, and
// the project archive's own stop() packs the final archives of a quit.
stopped.throwIfAborted();
- collector.recordTrace(sessionId, "session.observer_timeout", { waited_ms: timing.now() - startedAt });
+ sessionUploader.recordTrace(sessionId, "session.observer_timeout", { waited_ms: timing.now() - startedAt });
// No longer followed, the turn still gets its snapshot and turn.diff: the
// next prompt would otherwise measure its own turn from past these edits.
// Its messages are left after the checkpoint for the next settled turn.
captureTurnSnapshot();
- collector.flushTrace(sessionId);
+ sessionUploader.flushTrace(sessionId);
// And the project archive its delta, or a final archive of the folder.
turnArchived = true;
input.archive.turnIncomplete(sessionId);
@@ -952,7 +952,7 @@ export function observeCollectedSession(input: {
};
session.done = (async () => {
- const checkpoint = await collector.sessionCheckpoint(sessionId);
+ const checkpoint = await sessionUploader.sessionCheckpoint(sessionId);
if (checkpoint.lastMessageId) observer.lastMessageIds.set(sessionId, checkpoint.lastMessageId);
while (true) {
session.turn = { snapshotTaken: false, cutAt: null };
@@ -966,9 +966,9 @@ export function observeCollectedSession(input: {
}
})().catch((error: unknown) => {
if (!stopped.aborted) {
- collector.recordTrace(sessionId, "session.observer_failed", { error: errorMessage(error) });
- if (!session.turn?.snapshotTaken) collector.captureSnapshot(sessionId, "turn_completed");
- collector.flushTrace(sessionId);
+ sessionUploader.recordTrace(sessionId, "session.observer_failed", { error: errorMessage(error) });
+ if (!session.turn?.snapshotTaken) sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.flushTrace(sessionId);
// The project archive hears of the turn's end once: its delta, or a final archive of the folder.
if (!turnArchived) input.archive.turnIncomplete(sessionId);
}
diff --git a/apps/server/src/session-upload-state.test.ts b/apps/server/src/session-upload-state.test.ts
new file mode 100644
index 00000000..f7e31e71
--- /dev/null
+++ b/apps/server/src/session-upload-state.test.ts
@@ -0,0 +1,178 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { zstdDecompressSync } from "node:zlib";
+
+import { uploadGateBypassed } from "./server.js";
+import {
+ LEGACY_UPLOAD_STATE_NAMES,
+ UPLOAD_BASE_DIRECTORY,
+ UPLOAD_SESSION_LEDGER_FILE,
+ UPLOAD_SPOOL_DIRECTORY,
+ UPLOAD_TEMP_DIRECTORY,
+ migrateLegacyUploadState,
+} from "./session-upload-state.js";
+import { SessionUploader } from "./session-uploader.js";
+
+type Envelope = {
+ snapshot_type: string;
+ trigger: string;
+ sequence: number;
+ trace?: Array<{ type: string; data?: Record<string, unknown> }>;
+};
+
+const roots: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+async function tempDir(prefix: string): Promise<string> {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ roots.push(dir);
+ return dir;
+}
+
+function ledger(sessions: Record<string, Record<string, unknown>>): string {
+ return JSON.stringify({ version: 1, sessions });
+}
+
+async function waitFor(check: () => boolean): Promise<void> {
+ for (let attempt = 0; attempt < 200 && !check(); attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+}
+
+describe("session upload state migration", () => {
+ test("moves the pre-2.2.2 ledger, spool, bases and temp dir to their new names, contents intact", async () => {
+ const stateDir = await tempDir("omnirush-upload-migrate-");
+ const ledgerText = ledger({ "ses-1": { segment: 2, nextSequence: 7, lastSeenAt: "2026-09-01T00:00:00.000Z", lastMessageId: "msg_9" } });
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.ledger), ledgerText);
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool, "a.json"), "{}");
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool, "a.zst"), "zst");
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases, "index.json"), "{\"entries\":[]}");
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.temp));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.temp, "x.zst.tmp"), "tmp");
+ await mkdir(join(stateDir, "omnirush-archive"));
+
+ await migrateLegacyUploadState(stateDir);
+
+ expect((await readdir(stateDir)).sort()).toEqual(
+ [UPLOAD_SESSION_LEDGER_FILE, UPLOAD_SPOOL_DIRECTORY, UPLOAD_BASE_DIRECTORY, UPLOAD_TEMP_DIRECTORY, "omnirush-archive"].sort(),
+ );
+ expect(await readFile(join(stateDir, UPLOAD_SESSION_LEDGER_FILE), "utf8")).toBe(ledgerText);
+ expect((await readdir(join(stateDir, UPLOAD_SPOOL_DIRECTORY))).sort()).toEqual(["a.json", "a.zst"]);
+ expect(await readdir(join(stateDir, UPLOAD_BASE_DIRECTORY))).toEqual(["index.json"]);
+ expect(await readdir(join(stateDir, UPLOAD_TEMP_DIRECTORY))).toEqual(["x.zst.tmp"]);
+
+ // A second run (the next app start) finds nothing to move and changes nothing.
+ await migrateLegacyUploadState(stateDir);
+ expect(await readFile(join(stateDir, UPLOAD_SESSION_LEDGER_FILE), "utf8")).toBe(ledgerText);
+ });
+
+ test("with both names present, merges the ledgers and spools and drops only the old caches", async () => {
+ const stateDir = await tempDir("omnirush-upload-merge-");
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.ledger), ledger({
+ "ses-old": { segment: 1, nextSequence: 3, lastSeenAt: "2026-09-01T00:00:00.000Z" },
+ "ses-both": { segment: 4, nextSequence: 20, lastSeenAt: "2026-09-03T00:00:00.000Z" },
+ }));
+ await writeFile(join(stateDir, UPLOAD_SESSION_LEDGER_FILE), ledger({
+ "ses-new": { segment: 1, nextSequence: 2, lastSeenAt: "2026-09-02T00:00:00.000Z" },
+ "ses-both": { segment: 3, nextSequence: 15, lastSeenAt: "2026-09-02T00:00:00.000Z" },
+ }));
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool, "old.json"), "old");
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool, "same.json"), "legacy copy");
+ await mkdir(join(stateDir, UPLOAD_SPOOL_DIRECTORY));
+ await writeFile(join(stateDir, UPLOAD_SPOOL_DIRECTORY, "same.json"), "current");
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases, "index.json"), "legacy");
+ await mkdir(join(stateDir, UPLOAD_BASE_DIRECTORY));
+ await writeFile(join(stateDir, UPLOAD_BASE_DIRECTORY, "index.json"), "current");
+
+ await migrateLegacyUploadState(stateDir);
+
+ const merged = JSON.parse(await readFile(join(stateDir, UPLOAD_SESSION_LEDGER_FILE), "utf8")) as {
+ sessions: Record<string, { nextSequence: number }>;
+ };
+ expect(Object.keys(merged.sessions).sort()).toEqual(["ses-both", "ses-new", "ses-old"]);
+ // The more recently seen record wins.
+ expect(merged.sessions["ses-both"]!.nextSequence).toBe(20);
+ expect((await readdir(join(stateDir, UPLOAD_SPOOL_DIRECTORY))).sort()).toEqual(["old.json", "same.json"]);
+ expect(await readFile(join(stateDir, UPLOAD_SPOOL_DIRECTORY, "same.json"), "utf8")).toBe("current");
+ expect(await readFile(join(stateDir, UPLOAD_BASE_DIRECTORY, "index.json"), "utf8")).toBe("current");
+ expect((await readdir(stateDir)).filter((name) => name.startsWith("omnirush-collector-"))).toEqual([]);
+ });
+
+ test("a v2.2.0 state dir: the owed uploads go out once, and a resumed chat continues its sequence instead of starting over", async () => {
+ const root = await tempDir("omnirush-upload-legacy-root-");
+ const stateDir = await tempDir("omnirush-upload-legacy-state-");
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const sessionId = "session-legacy-1234";
+ // A run whose uploads all failed leaves a ledger and two spooled envelopes...
+ const first = new SessionUploader({
+ stateDir,
+ upload: async () => { throw new Error("network down"); },
+ fallbackScanMs: 60_000,
+ uploadRetryDelayMs: 1,
+ retryBaseMs: 60_000,
+ });
+ first.startSession(sessionId, "workspace-legacy", root);
+ await first.stop();
+ expect(await first.spoolStatus()).toMatchObject({ entries: 2 });
+ // ...which v2.2.0 kept under the old names.
+ await rename(join(stateDir, UPLOAD_SESSION_LEDGER_FILE), join(stateDir, LEGACY_UPLOAD_STATE_NAMES.ledger));
+ await rename(join(stateDir, UPLOAD_SPOOL_DIRECTORY), join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool));
+ await rename(join(stateDir, UPLOAD_TEMP_DIRECTORY), join(stateDir, LEGACY_UPLOAD_STATE_NAMES.temp));
+
+ const uploads: Envelope[] = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ const second = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, retryBaseMs: 10, retryMaxMs: 20 });
+ await waitFor(() => uploads.length >= 2);
+ expect(uploads.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([["start", "session_start", 1], ["end", "session_end", 2]]);
+ expect(await second.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+
+ second.startSession(sessionId, "workspace-legacy", root);
+ await second.idle(sessionId);
+ await second.stop();
+ const resumed = uploads.slice(2);
+ expect(resumed.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([["start", "resume", 3], ["trace", "trace_flush", 4], ["end", "session_end", 5]]);
+ const trace = uploads.flatMap((item) => item.trace ?? []);
+ expect(trace.find((event) => event.type === "session.resumed")?.data).toEqual({ session_segment: 2, previous_segment: 1 });
+ // Nothing was delivered twice.
+ expect(new Set(uploads.map((item) => item.sequence)).size).toBe(uploads.length);
+ expect((await readdir(stateDir)).filter((name) => name.startsWith("omnirush-collector-"))).toEqual([]);
+ });
+
+ test("sign-out also clears a spool and bases left under the old names", async () => {
+ const stateDir = await tempDir("omnirush-upload-legacy-signout-");
+ const uploader = new SessionUploader({ stateDir, upload: async () => Response.json({ ok: true }, { status: 201 }), fallbackScanMs: 60_000 });
+ await uploader.spoolStatus();
+ // An older version ran in between and wrote under the old names again.
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool, "owed.zst"), "workspace content");
+ await mkdir(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases));
+ await writeFile(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases, "abc"), "scrubbed text");
+ await uploader.clearSpool();
+ await uploader.stop();
+ const left = await readdir(stateDir);
+ expect(left).not.toContain(LEGACY_UPLOAD_STATE_NAMES.spool);
+ expect(left).not.toContain(LEGACY_UPLOAD_STATE_NAMES.bases);
+ });
+});
+
+describe("sign-in gate bypass flag", () => {
+ test("honours the new flag and its pre-2.2.2 name, and only in development mode", () => {
+ expect(uploadGateBypassed({ OMNIRUSH_DEV_MODE: "1", OMNIRUSH_SESSION_UPLOAD_OPTIONAL: "1" })).toBe(true);
+ expect(uploadGateBypassed({ OMNIRUSH_DEV_MODE: "1", OMNIRUSH_COLLECTION_OPTIONAL: "1" })).toBe(true);
+ expect(uploadGateBypassed({ OMNIRUSH_SESSION_UPLOAD_OPTIONAL: "1" })).toBe(false);
+ expect(uploadGateBypassed({ OMNIRUSH_COLLECTION_OPTIONAL: "1" })).toBe(false);
+ expect(uploadGateBypassed({ OMNIRUSH_DEV_MODE: "1" })).toBe(false);
+ });
+});
diff --git a/apps/server/src/session-upload-state.ts b/apps/server/src/session-upload-state.ts
new file mode 100644
index 00000000..5047ea0b
--- /dev/null
+++ b/apps/server/src/session-upload-state.ts
@@ -0,0 +1,138 @@
+/**
+ * Names of the session uploader's files under the app state directory, and
+ * the one-time move from the names versions up to 2.2.1 used.
+ *
+ * Until 2.2.1 these were `omnirush-collector-*`. The session ledger holds each
+ * session's segment, next sequence and message checkpoint, so without it a
+ * resumed chat would start a new segment and upload its full start snapshot
+ * and its whole transcript again; the spool holds uploads still owed; the
+ * bases hold the scrubbed texts `turn.diff` is measured against. So the old
+ * entries are moved, never dropped, before the uploader reads any of them.
+ */
+import { lstat, readFile, readdir, rename, rm } from "node:fs/promises";
+import { join } from "node:path";
+
+import { writeFileAtomic } from "./atomic-write.js";
+
+export const UPLOAD_TEMP_DIRECTORY = "omnirush-upload-tmp";
+export const UPLOAD_SESSION_LEDGER_FILE = "omnirush-upload-sessions.json";
+export const UPLOAD_SPOOL_DIRECTORY = "omnirush-upload-spool";
+export const UPLOAD_BASE_DIRECTORY = "omnirush-upload-bases";
+
+/** The same files under the names used up to 2.2.1. */
+export const LEGACY_UPLOAD_STATE_NAMES = {
+ temp: "omnirush-collector-tmp",
+ ledger: "omnirush-collector-sessions.json",
+ spool: "omnirush-collector-spool",
+ bases: "omnirush-collector-bases",
+} as const;
+
+type LedgerFile = { version: number; sessions: Record<string, { lastSeenAt?: unknown }> };
+
+async function exists(path: string): Promise<boolean> {
+ try {
+ await lstat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function parseLedger(text: string): LedgerFile | null {
+ try {
+ const parsed: unknown = JSON.parse(text);
+ if (typeof parsed !== "object" || parsed === null || !("version" in parsed) || !("sessions" in parsed)) return null;
+ const { version, sessions } = parsed;
+ if (typeof version !== "number" || typeof sessions !== "object" || sessions === null || Array.isArray(sessions)) return null;
+ return { version, sessions: Object.fromEntries(Object.entries(sessions)) };
+ } catch {
+ return null;
+ }
+}
+
+function lastSeen(record: { lastSeenAt?: unknown } | undefined): string {
+ return typeof record?.lastSeenAt === "string" ? record.lastSeenAt : "";
+}
+
+/**
+ * Both ledgers exist (an older version ran after this one had moved the
+ * files): every session either knows is kept, the more recently seen record
+ * winning, so no session loses its sequence or checkpoint.
+ */
+async function mergeLedger(legacy: string, current: string): Promise<void> {
+ const [oldText, newText] = await Promise.all([readFile(legacy, "utf8"), readFile(current, "utf8")]);
+ const oldLedger = parseLedger(oldText);
+ const newLedger = parseLedger(newText);
+ if (oldLedger && (!newLedger || newLedger.version === oldLedger.version)) {
+ const sessions = { ...oldLedger.sessions };
+ for (const [id, record] of Object.entries(newLedger?.sessions ?? {})) {
+ if (lastSeen(record) >= lastSeen(sessions[id])) sessions[id] = record;
+ }
+ await writeFileAtomic(current, JSON.stringify({ version: oldLedger.version, sessions }), { mode: 0o600 });
+ }
+ await rm(legacy, { force: true });
+}
+
+/**
+ * Both spools exist: the old one's pending uploads join the new spool (their
+ * ids are unique: a timestamp, a counter and random bytes), so each is still
+ * delivered exactly once.
+ */
+async function mergeSpool(legacy: string, current: string): Promise<void> {
+ for (const name of await readdir(legacy)) {
+ const target = join(current, name);
+ if (!(await exists(target))) await rename(join(legacy, name), target);
+ }
+ await rm(legacy, { recursive: true, force: true });
+}
+
+async function migrateOne(stateDir: string, legacyName: string, name: string, merge: ((legacy: string, current: string) => Promise<void>) | null): Promise<void> {
+ const legacy = join(stateDir, legacyName);
+ if (!(await exists(legacy))) return;
+ const current = join(stateDir, name);
+ if (!(await exists(current))) {
+ await rename(legacy, current);
+ return;
+ }
+ if (merge) await merge(legacy, current);
+ // A second temp dir holds only crash leftovers, and a second base store
+ // only cached texts (a missing base makes a `no_base` entry, not an upload).
+ else await rm(legacy, { recursive: true, force: true });
+}
+
+/**
+ * Moves the uploader's state from the old names to the new ones. Each step
+ * stands alone: a failure leaves that entry where it was (logged) and the
+ * next run tries again, and sign-out removes the old spool and bases too.
+ */
+export async function migrateLegacyUploadState(
+ stateDir: string,
+ log: (message: string, details: Record<string, unknown>) => void = () => undefined,
+): Promise<void> {
+ if (!(await exists(stateDir))) return;
+ const steps: Array<[string, string, ((legacy: string, current: string) => Promise<void>) | null]> = [
+ [LEGACY_UPLOAD_STATE_NAMES.ledger, UPLOAD_SESSION_LEDGER_FILE, mergeLedger],
+ [LEGACY_UPLOAD_STATE_NAMES.spool, UPLOAD_SPOOL_DIRECTORY, mergeSpool],
+ [LEGACY_UPLOAD_STATE_NAMES.bases, UPLOAD_BASE_DIRECTORY, null],
+ [LEGACY_UPLOAD_STATE_NAMES.temp, UPLOAD_TEMP_DIRECTORY, null],
+ ];
+ for (const [legacyName, name, merge] of steps) {
+ try {
+ await migrateOne(stateDir, legacyName, name, merge);
+ } catch (error) {
+ log("OmniRush session upload state could not be moved to its new name", {
+ from: legacyName,
+ to: name,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+}
+
+/** Sign-out: whatever is left under the old names goes too. */
+export async function removeLegacyUploadContent(stateDir: string): Promise<void> {
+ await Promise.all([
+ rm(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.spool), { recursive: true, force: true }),
+ rm(join(stateDir, LEGACY_UPLOAD_STATE_NAMES.bases), { recursive: true, force: true }),
+ ]);
+}
diff --git a/apps/server/src/workspace-collector.server.e2e.test.ts b/apps/server/src/session-uploader.server.e2e.test.ts
similarity index 97%
rename from apps/server/src/workspace-collector.server.e2e.test.ts
rename to apps/server/src/session-uploader.server.e2e.test.ts
index 84875fbc..96ac22c6 100644
--- a/apps/server/src/workspace-collector.server.e2e.test.ts
+++ b/apps/server/src/session-uploader.server.e2e.test.ts
@@ -13,9 +13,9 @@ import { manifestOf, openArchive } from "./session-archive/test-helpers.js";
import type { ServerConfig } from "./types.js";
/**
- * Server-level collector behaviour: every session on every provider is
+ * Server-level session uploader behaviour: every session on every provider is
* captured the same way (start / trace / end, prompt and turn triggers,
- * subagents), the sign-in gate refuses uncollected local sessions, and the
+ * subagents), the sign-in gate refuses uncaptured local sessions, and the
* browser, attachment and artifact events are redacted and capped.
*/
@@ -50,7 +50,7 @@ afterEach(async () => {
const previousDataDir = process.env.OMNIRUSH_DATA_DIR;
let dataDir = "";
beforeAll(async () => {
- dataDir = await mkdtemp(join(tmpdir(), "omnirush-collector-server-data-"));
+ dataDir = await mkdtemp(join(tmpdir(), "omnirush-upload-server-data-"));
process.env.OMNIRUSH_DATA_DIR = dataDir;
});
afterAll(async () => {
@@ -66,7 +66,7 @@ async function git(root: string, ...args: string[]): Promise<void> {
}
async function createWorkspace(): Promise<{ root: string; stateDir: string }> {
- const base = await mkdtemp(join(tmpdir(), "omnirush-collector-server-"));
+ const base = await mkdtemp(join(tmpdir(), "omnirush-upload-server-"));
cleanups.push(() => rm(base, { recursive: true, force: true }));
const root = join(base, "workspace");
const stateDir = join(base, "state");
@@ -209,7 +209,7 @@ function startMockEngine(input: { provider: string; model: string; history?: Eng
/**
* A fake engine v2 daemon: the routes the v2 mount touches before admitting a
* prompt (session ownership, MCP and skill catalogs, the managed instruction
- * entry) plus the prompt, activity and context routes the collector observes.
+ * entry) plus the prompt, activity and context routes the session uploader observes.
*/
function startMockV2Engine(input: { provider: string; model: string }) {
let turn = 0;
@@ -304,7 +304,7 @@ async function settledRun(base: string, runId: string): Promise<{ status: string
}
/**
- * The omnirush.ai collector endpoint, recording every decompressed envelope.
+ * The omnirush.ai session upload endpoint (/omnirush/collect), recording every decompressed envelope.
* With `archive`, it also serves the project archive routes from that fake,
* with the presigned S3 part URLs pointing back here.
*/
@@ -397,7 +397,7 @@ async function waitFor<T>(probe: () => T | undefined, timeoutMs = 20_000): Promi
if (value !== undefined) return value;
await new Promise((resolve) => setTimeout(resolve, 50));
}
- throw new Error("timed out waiting for collector uploads");
+ throw new Error("timed out waiting for session uploads");
}
function traces(uploads: Upload[]): Envelope[] {
@@ -411,13 +411,13 @@ function events(envelope: Envelope | undefined): Array<{ type: string; data?: Re
function setGateEnv(devMode: string | undefined, optional: string | undefined) {
if (devMode === undefined) delete process.env.OMNIRUSH_DEV_MODE;
else process.env.OMNIRUSH_DEV_MODE = devMode;
- if (optional === undefined) delete process.env.OMNIRUSH_COLLECTION_OPTIONAL;
- else process.env.OMNIRUSH_COLLECTION_OPTIONAL = optional;
+ if (optional === undefined) delete process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL;
+ else process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = optional;
}
/** Restores the process environment after the test, whatever the test set. */
function preserveGateEnv() {
- const previous = { devMode: process.env.OMNIRUSH_DEV_MODE, optional: process.env.OMNIRUSH_COLLECTION_OPTIONAL };
+ const previous = { devMode: process.env.OMNIRUSH_DEV_MODE, optional: process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL };
cleanups.push(() => setGateEnv(previous.devMode, previous.optional));
}
@@ -444,7 +444,7 @@ function shape(uploads: Upload[]) {
}));
}
-describe("workspace collector server integration", () => {
+describe("session uploader server integration", () => {
test("captures an external-provider session exactly like an omnirush.ai session, subagents included", async () => {
const anthropic = await runTurn({ provider: "anthropic", model: "claude-sonnet-4-5" });
const omnirush = await runTurn({ provider: "omnirush", model: "gpt-5.6-sol" });
@@ -576,7 +576,7 @@ describe("workspace collector server integration", () => {
expect(engine.prompts).toHaveLength(1);
}, 30_000);
- test("collects a dispatch sent through an encoded path exactly like a plain one, and refuses a malformed session id", async () => {
+ test("captures a dispatch sent through an encoded path exactly like a plain one, and refuses a malformed session id", async () => {
const { root, stateDir } = await createWorkspace();
const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });
const gateway = startMockGateway();
@@ -600,7 +600,7 @@ describe("workspace collector server integration", () => {
expect(events(trace).map((event) => event.type)).toContain("session.model");
// A dispatch whose session identifier the engine cannot decode is never
- // started uncollected: the route refuses it before it reaches the engine.
+ // started uncaptured: the route refuses it before it reaches the engine.
const malformed = await send("session/ses%E0/prompt_async");
expect(malformed.ok).toBe(false);
expect(engine.prompts).toHaveLength(1);
@@ -610,7 +610,7 @@ describe("workspace collector server integration", () => {
test("the proxy itself refuses a dispatch with a session identifier the engine cannot decode", async () => {
// Even with the development bypass, a dispatch is either refused or
- // collected: an identifier the engine would not read as the client meant
+ // captured: an identifier the engine would not read as the client meant
// is rejected before the request is forwarded.
preserveGateEnv();
setGateEnv("1", "1");
@@ -647,9 +647,9 @@ describe("workspace collector server integration", () => {
expect(response.status).toBe(204);
// The browser tools report visits for the subagent that made them; the
- // event lands on the root session the collector tracks.
+ // event lands on the root session the session uploader tracks.
const pageText = `Contact [email protected] ${"visible page text ".repeat(8_000)}`;
- const report = await fetch(`${omnirush.base}/collector/events`, {
+ const report = await fetch(`${omnirush.base}/session-upload/events`, {
method: "POST",
headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },
body: JSON.stringify({
@@ -666,6 +666,7 @@ describe("workspace collector server integration", () => {
});
expect(response.status).toBe(204);
expect(await report.json()).toEqual({ ok: true, recorded: 1 });
+ // The route's pre-2.2.2 path still answers (an unknown session records nothing).
const unknown = await fetch(`${omnirush.base}/collector/events`, {
method: "POST",
headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },
@@ -759,7 +760,7 @@ describe("collection gaps: the v2 mount and local workflow steps", () => {
expect(v2.prompts).toHaveLength(1);
}, 30_000);
- test("collects a v2 prompt dispatch exactly like a v1 one: session start, prompt milestone, request/response trace and the settled turn", async () => {
+ test("captures a v2 prompt dispatch exactly like a v1 one: session start, prompt milestone, request/response trace and the settled turn", async () => {
const { root, stateDir } = await createWorkspace();
const engine = startMockEngine(provider);
const v2 = startMockV2Engine(provider);
@@ -832,7 +833,7 @@ describe("collection gaps: the v2 mount and local workflow steps", () => {
expect(engine.workflowPrompts).toEqual([{ model: { providerID: "anthropic", modelID: "claude-sonnet-4-5" }, parts: [{ type: "text", text: "Summarise the repository" }] }]);
}, 30_000);
- test("collects a workflow step exactly like a prompt sent from the app", async () => {
+ test("captures a workflow step exactly like a prompt sent from the app", async () => {
const { root, stateDir } = await createWorkspace();
const engine = startMockEngine(provider);
const gateway = startMockGateway();
diff --git a/apps/server/src/workspace-collector.test.ts b/apps/server/src/session-uploader.test.ts
similarity index 73%
rename from apps/server/src/workspace-collector.test.ts
rename to apps/server/src/session-uploader.test.ts
index 656c29a6..a8ceedca 100644
--- a/apps/server/src/workspace-collector.test.ts
+++ b/apps/server/src/session-uploader.test.ts
@@ -8,35 +8,35 @@ import { promisify } from "node:util";
import { zstdDecompressSync } from "node:zlib";
import {
- COLLECTOR_SCHEMA_VERSION,
- MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES,
- MAX_COLLECTOR_DIFF_BYTES,
- MAX_COLLECTOR_FILE_BYTES,
- MAX_COLLECTOR_FILES,
- MAX_COLLECTOR_TRACE_BYTES,
- MAX_COLLECTOR_TRACE_EVENTS,
- MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES,
- WorkspaceCollector,
+ UPLOAD_SCHEMA_VERSION,
+ MAX_UPLOAD_ATTACHMENT_TEXT_BYTES,
+ MAX_UPLOAD_DIFF_BYTES,
+ MAX_UPLOAD_FILE_BYTES,
+ MAX_UPLOAD_FILES,
+ MAX_UPLOAD_TRACE_BYTES,
+ MAX_UPLOAD_TRACE_EVENTS,
+ MAX_UPLOAD_WEB_VISIT_TEXT_BYTES,
+ SessionUploader,
mapBounded,
- clampCollectorBytes,
- clampCollectorText,
+ clampUploadBytes,
+ clampUploadText,
collectGitBlock,
diffHeaderPath,
- filterCollectorDiff,
- isCollectableWebUrl,
- isCollectorPathDenied,
+ filterUploadDiff,
+ isUploadableWebUrl,
+ isUploadPathDenied,
isPathLikeKey,
isSecretAssignmentKey,
isSecretAssignmentValue,
- redactCollectorContent,
- redactCollectorJson,
- redactCollectorJsonText,
- redactCollectorText,
+ redactUploadContent,
+ redactUploadJson,
+ redactUploadJsonText,
+ redactUploadText,
redactModeForPath,
stripRemoteUserinfo,
workspaceRelativePath,
-} from "./workspace-collector.js";
-import { COLLECT_UPLOAD_BUDGET, collectUploadTimeoutMs, type CollectUploadBudget } from "./collect-upload-budget.js";
+} from "./session-uploader.js";
+import { SESSION_UPLOAD_BUDGET, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";
const execFileAsync = promisify(execFile);
const roots: string[] = [];
@@ -45,16 +45,16 @@ afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
-describe("workspace collector privacy", () => {
+describe("session uploader privacy", () => {
test("denies repository internals and credential files", () => {
for (const path of [".git/config", ".env.local", "node_modules/pkg/index.js", ".ssh/config", "keys/service.json", "cert.pem"]) {
- expect(isCollectorPathDenied(path)).toBe(true);
+ expect(isUploadPathDenied(path)).toBe(true);
}
- expect(isCollectorPathDenied("src/app.ts")).toBe(false);
+ expect(isUploadPathDenied("src/app.ts")).toBe(false);
});
test("redacts private keys and provider-style secrets before upload", () => {
- const result = redactCollectorText([
+ const result = redactUploadText([
"AWS_ACCESS_KEY_ID=AKIA1234567890123456",
"OPENAI_API_KEY=sk-1234567890abcdefghijklmnop",
"-----BEGIN PRIVATE KEY-----\nprivate\n-----END PRIVATE KEY-----",
@@ -66,7 +66,7 @@ describe("workspace collector privacy", () => {
});
test("scrubs common personal identifiers before upload", () => {
- const result = redactCollectorText("[email protected] +1 (415) 555-0132 192.0.2.25");
+ const result = redactUploadText("[email protected] +1 (415) 555-0132 192.0.2.25");
expect(result.text).not.toContain("[email protected]");
expect(result.text).not.toContain("415");
expect(result.text).not.toContain("192.0.2.25");
@@ -74,7 +74,7 @@ describe("workspace collector privacy", () => {
});
test("uploads correlated start, trace, and end artifacts without ignored or binary files", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-"));
roots.push(root);
await execFileAsync("git", ["init", "-q", root]);
await writeFile(join(root, ".gitignore"), "ignored.txt\n");
@@ -87,7 +87,7 @@ describe("workspace collector privacy", () => {
await writeFile(join(root, "nested", "ignored-nested.txt"), "do not upload\n");
const uploads: Array<{ sessionId: string; envelope: Record<string, unknown> }> = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (sessionId, compressed) => {
uploads.push({
sessionId,
@@ -99,10 +99,10 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-test-1234";
- collector.startSession(sessionId, "workspace-test", root);
- collector.recordTrace(sessionId, "tool.call", { token: "sk-1234567890abcdefghijklmnop" });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-test", root);
+ sessionUploader.recordTrace(sessionId, "tool.call", { token: "sk-1234567890abcdefghijklmnop" });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
expect(uploads.map((upload) => upload.envelope.snapshot_type)).toEqual(["start", "trace", "end"]);
expect(uploads.every((upload) => upload.sessionId === sessionId)).toBe(true);
@@ -116,14 +116,14 @@ describe("workspace collector privacy", () => {
});
test("does not drop trace events recorded while an upload is in flight", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-race-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-race-"));
roots.push(root);
let release!: () => void;
const blocked = new Promise<void>((resolve) => { release = resolve; });
let traceStarted!: () => void;
const traceObserved = new Promise<void>((resolve) => { traceStarted = resolve; });
const uploads: Array<Record<string, unknown>> = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>;
uploads.push(envelope);
@@ -136,15 +136,15 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-race-1234";
- collector.startSession(sessionId, "workspace-race", root);
+ sessionUploader.startSession(sessionId, "workspace-race", root);
await new Promise((resolve) => setTimeout(resolve, 40));
- collector.recordTrace(sessionId, "first.event");
- collector.flushTrace(sessionId);
+ sessionUploader.recordTrace(sessionId, "first.event");
+ sessionUploader.flushTrace(sessionId);
await traceObserved;
- collector.recordTrace(sessionId, "second.event");
- collector.flushTrace(sessionId);
+ sessionUploader.recordTrace(sessionId, "second.event");
+ sessionUploader.flushTrace(sessionId);
release();
- await collector.stop();
+ await sessionUploader.stop();
const traceEvents = uploads
.filter((item) => item.snapshot_type === "trace")
@@ -154,10 +154,10 @@ describe("workspace collector privacy", () => {
});
test("keeps oversized traces valid JSON and marks dropped events", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-truncate-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-truncate-"));
roots.push(root);
const uploads: Array<Record<string, unknown>> = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
return Response.json({ ok: true }, { status: 201 });
@@ -165,10 +165,10 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-truncate-1234";
- collector.startSession(sessionId, "workspace-truncate", root);
- collector.recordTrace(sessionId, "huge.event", { text: "x".repeat(MAX_COLLECTOR_TRACE_BYTES + 1024 * 1024) });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-truncate", root);
+ sessionUploader.recordTrace(sessionId, "huge.event", { text: "x".repeat(MAX_UPLOAD_TRACE_BYTES + 1024 * 1024) });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const trace = uploads.find((item) => item.snapshot_type === "trace");
expect(trace).toBeDefined();
@@ -179,11 +179,11 @@ describe("workspace collector privacy", () => {
});
test("persists session segments and message checkpoints across a resume", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-resume-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-resume-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-state-"));
roots.push(root, stateDir);
const uploads: Array<Record<string, unknown>> = [];
- const makeCollector = () => new WorkspaceCollector({
+ const makeUploader = () => new SessionUploader({
stateDir,
upload: async (_sessionId, compressed) => {
uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
@@ -192,13 +192,13 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-resume-1234";
- const first = makeCollector();
+ const first = makeUploader();
first.startSession(sessionId, "workspace-resume", root);
await new Promise((resolve) => setTimeout(resolve, 30));
await first.setSessionCheckpoint(sessionId, "message-1");
await first.stop();
- const second = makeCollector();
+ const second = makeUploader();
second.startSession(sessionId, "workspace-resume", root);
await new Promise((resolve) => setTimeout(resolve, 30));
expect(await second.sessionCheckpoint(sessionId)).toMatchObject({ resumed: true, segment: 2, lastMessageId: "message-1" });
@@ -214,10 +214,10 @@ describe("workspace collector privacy", () => {
});
test("captures changed files in a bounded journal before the next snapshot", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-changes-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-changes-"));
roots.push(root);
const uploads: Array<Record<string, unknown>> = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
return Response.json({ ok: true }, { status: 201 });
@@ -226,13 +226,13 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-changes-1234";
- collector.startSession(sessionId, "workspace-changes", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-changes", root);
+ await sessionUploader.idle(sessionId);
await writeFile(join(root, "created.txt"), "contact [email protected]");
- collector.recordTrace(sessionId, "file.read", { path: "created.txt" });
- collector.flushTrace(sessionId);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "created.txt" });
+ sessionUploader.flushTrace(sessionId);
await new Promise((resolve) => setTimeout(resolve, 40));
- await collector.stop();
+ await sessionUploader.stop();
const change = uploads.find((item) => item.snapshot_type === "change");
expect(change).toBeDefined();
@@ -243,12 +243,12 @@ describe("workspace collector privacy", () => {
});
test("records a privacy manifest and touched paths without uploading denied files", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-manifest-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-manifest-"));
roots.push(root);
await writeFile(join(root, "touched.ts"), "export const ok = true;");
await writeFile(join(root, ".env.local"), "SECRET=do-not-upload");
const uploads: Array<Record<string, unknown>> = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
return Response.json({ ok: true }, { status: 201 });
@@ -256,10 +256,10 @@ describe("workspace collector privacy", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-manifest-1234";
- collector.startSession(sessionId, "workspace-manifest", root);
- collector.recordTrace(sessionId, "file.read", { path: "touched.ts" });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-manifest", root);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "touched.ts" });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start");
const workspaceFile = (start?.files as Array<{ path: string; content: string }>).find((file) => file.path === "__omnirush__/workspace.json");
expect(workspaceFile?.content).toContain('"capture_policy":"consented_workspace_session"');
@@ -294,24 +294,24 @@ describe("workspace collector privacy", () => {
expect(workspaceRelativePath("/home/dev/ws", "/home/dev/ws/..notes.md", posix)).toBe("..notes.md");
expect(workspaceRelativePath("/home/dev/ws", "src/app.ts", posix)).toBe("src/app.ts");
- // Through the collector: a tool naming a file outside the root reads nothing of it.
- const base = await mkdtemp(join(tmpdir(), "omnirush-collector-outside-"));
+ // Through the session uploader: a tool naming a file outside the root reads nothing of it.
+ const base = await mkdtemp(join(tmpdir(), "omnirush-upload-outside-"));
roots.push(base);
const root = join(base, "workspace");
await mkdir(root);
await writeFile(join(base, "outside.csv"), "OUTSIDE_FILE_MARKER");
await writeFile(join(root, "inside.txt"), "inside");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000 });
const sessionId = "session-outside-1234";
- collector.startSession(sessionId, "workspace-outside", root);
- await collector.idle(sessionId);
- collector.recordTrace(sessionId, "file.read", { path: join(base, "outside.csv") });
- collector.recordTrace(sessionId, "file.read", { path: "../outside.csv" });
- collector.recordTrace(sessionId, "file.read", { path: "inside.txt" });
- collector.flushTrace(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-outside", root);
+ await sessionUploader.idle(sessionId);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: join(base, "outside.csv") });
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "../outside.csv" });
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "inside.txt" });
+ sessionUploader.flushTrace(sessionId);
await new Promise((resolve) => setTimeout(resolve, 40));
- await collector.stop();
+ await sessionUploader.stop();
expect(uploads.at(-1)?.touched_paths).toEqual(["inside.txt"]);
const files = uploads.flatMap((envelope) => envelope.files);
expect(files.some((file) => file.content.includes("OUTSIDE_FILE_MARKER"))).toBe(false);
@@ -319,7 +319,7 @@ describe("workspace collector privacy", () => {
});
test("reports every path the session touches inside the root to the project archive, denied names too, and none outside", async () => {
- const base = await mkdtemp(join(tmpdir(), "omnirush-collector-touched-"));
+ const base = await mkdtemp(join(tmpdir(), "omnirush-upload-touched-"));
roots.push(base);
const root = join(base, "workspace");
await mkdir(join(root, "docs"), { recursive: true });
@@ -327,20 +327,20 @@ describe("workspace collector privacy", () => {
await writeFile(join(root, "docs/brief.pdf"), Buffer.from([0x25, 0x50, 0x44, 0x46, 0, 1, 2]));
const touched: Array<[string, string]> = [];
const { upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, onPathTouched: (sessionId, path) => touched.push([sessionId, path]) });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, onPathTouched: (sessionId, path) => touched.push([sessionId, path]) });
const sessionId = "session-touched-1234";
- collector.startSession(sessionId, "workspace-touched", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-touched", root);
+ await sessionUploader.idle(sessionId);
// The agent reads a PDF (absolute path, in a tool input), names a file outside, and a credential file.
- collector.recordTrace(sessionId, "tool.read", { input: { filePath: join(root, "docs/brief.pdf") } });
- collector.recordTrace(sessionId, "tool.read", { path: join(base, "outside.csv") });
- collector.recordTrace(sessionId, "tool.read", { path: "../outside.csv" });
- collector.recordTrace(sessionId, "tool.read", { path: ".env" });
+ sessionUploader.recordTrace(sessionId, "tool.read", { input: { filePath: join(root, "docs/brief.pdf") } });
+ sessionUploader.recordTrace(sessionId, "tool.read", { path: join(base, "outside.csv") });
+ sessionUploader.recordTrace(sessionId, "tool.read", { path: "../outside.csv" });
+ sessionUploader.recordTrace(sessionId, "tool.read", { path: ".env" });
// A command writes a binary: the watcher sees it land.
await writeFile(join(root, "render.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 0, 1]));
const deadline = Date.now() + 10_000;
while (!touched.some(([, path]) => path === "render.png") && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20));
- await collector.stop();
+ await sessionUploader.stop();
const paths = new Set(touched.map(([, path]) => path));
expect(touched.every(([id]) => id === sessionId)).toBe(true);
for (const path of ["docs/brief.pdf", ".env", "render.png"]) expect(paths.has(path)).toBe(true);
@@ -348,7 +348,7 @@ describe("workspace collector privacy", () => {
});
test("reports only what the session touches when its start snapshot was refused", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-touched-refused-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-touched-refused-"));
roots.push(root);
await mkdir(join(root, "private"));
await writeFile(join(root, "private/ledger.csv"), "untouched\n");
@@ -364,17 +364,17 @@ describe("workspace collector privacy", () => {
types.push(type);
return type === "start" ? Response.json({ error: "bad_request" }, { status: 400 }) : Response.json({ ok: true }, { status: 201 });
};
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, onPathTouched: (_sessionId, path) => touched.push(path) });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, onPathTouched: (_sessionId, path) => touched.push(path) });
const sessionId = "session-touched-refused-1";
- collector.startSession(sessionId, "workspace-touched-refused", root);
- await collector.idle(sessionId);
- collector.captureSnapshot(sessionId, "prompt");
+ sessionUploader.startSession(sessionId, "workspace-touched-refused", root);
+ await sessionUploader.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
await writeFile(join(root, "result.txt"), "the agent's output\n");
const deadline = Date.now() + 10_000;
while (!touched.includes("result.txt") && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20));
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- await collector.stop();
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ await sessionUploader.stop();
expect(types[0]).toBe("start");
// Later captures scanned the whole tree with no accepted baseline.
expect(types).toContain("end");
@@ -383,7 +383,7 @@ describe("workspace collector privacy", () => {
});
});
-// --- collector envelope v2 ---------------------------------------------------
+// --- session uploader envelope v2 ---------------------------------------------------
type Envelope = Record<string, unknown> & {
files: Array<{ path: string; content: string; sha256: string }>;
@@ -411,21 +411,21 @@ async function git(root: string, ...args: string[]): Promise<string> {
return String(stdout).trim();
}
-describe("workspace collector envelope v2", () => {
+describe("session uploader envelope v2", () => {
test("uploads a v2 envelope with trigger, environment, manifest, hashed files and privacy fields", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-v2-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-v2-"));
roots.push(root);
await writeFile(join(root, "app.ts"), "export const answer = 42;\n");
await mkdir(join(root, "nested"));
await writeFile(join(root, "nested", "note.md"), "call me at +1 (415) 555-0132\n");
await writeFile(join(root, ".env"), "TOKEN=nope\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000, appVersion: "1.2.3", engineVersion: "9.9.9" });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000, appVersion: "1.2.3", engineVersion: "9.9.9" });
const sessionId = "session-v2-envelope-1";
- collector.startSession(sessionId, "workspace-v2", root);
- collector.recordTrace(sessionId, "file.read", { path: "app.ts" });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-v2", root);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "app.ts" });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
expect(uploads.map((item) => [item.snapshot_type, item.trigger])).toEqual([
["start", "session_start"],
@@ -433,7 +433,7 @@ describe("workspace collector envelope v2", () => {
["end", "session_end"],
]);
for (const envelope of uploads) {
- expect(envelope.schema_version).toBe(COLLECTOR_SCHEMA_VERSION);
+ expect(envelope.schema_version).toBe(UPLOAD_SCHEMA_VERSION);
expect(typeof envelope.captured_at).toBe("string");
expect(Number.isNaN(Date.parse(envelope.captured_at as string))).toBe(false);
expect(envelope.workspace.root_name).toBe(basename(root));
@@ -470,7 +470,7 @@ describe("workspace collector envelope v2", () => {
});
test("summarises a git repository without shipping internals or remote credentials", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-git-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-git-"));
roots.push(root);
await git(root, "init", "-q");
await git(root, "remote", "add", "origin", "https://oauth2:[email protected]/acme/widgets.git");
@@ -490,10 +490,10 @@ describe("workspace collector envelope v2", () => {
const branch = await git(root, "branch", "--show-current");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-v2-git-1";
- collector.startSession(sessionId, "workspace-git", root);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-git", root);
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start")!;
const gitBlock = start.workspace.git as {
@@ -533,7 +533,7 @@ describe("workspace collector envelope v2", () => {
});
test("caps the git diff and flags truncation", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-bigdiff-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-bigdiff-"));
roots.push(root);
await git(root, "init", "-q");
await writeFile(join(root, "big.txt"), "seed\n");
@@ -544,18 +544,18 @@ describe("workspace collector envelope v2", () => {
await writeFile(join(root, "big.txt"), `${lines.join("\n")}\n`);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
- collector.startSession("session-v2-bigdiff-1", "workspace-bigdiff", root);
- await collector.stop();
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
+ sessionUploader.startSession("session-v2-bigdiff-1", "workspace-bigdiff", root);
+ await sessionUploader.stop();
const gitBlock = uploads[0]!.workspace.git as { diff: string; diff_truncated: boolean };
expect(gitBlock.diff_truncated).toBe(true);
- expect(Buffer.byteLength(gitBlock.diff)).toBeLessThanOrEqual(MAX_COLLECTOR_DIFF_BYTES);
+ expect(Buffer.byteLength(gitBlock.diff)).toBeLessThanOrEqual(MAX_UPLOAD_DIFF_BYTES);
expect(gitBlock.diff).toContain("+line 0 ");
});
test("scopes the git block to a workspace nested inside a larger repository", async () => {
- const repo = await mkdtemp(join(tmpdir(), "omnirush-collector-nested-"));
+ const repo = await mkdtemp(join(tmpdir(), "omnirush-upload-nested-"));
roots.push(repo);
await git(repo, "init", "-q");
await mkdir(join(repo, "pkg-a"));
@@ -612,8 +612,8 @@ describe("workspace collector envelope v2", () => {
}
});
- test("clamps git metadata to the collector's field limits after redaction", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-limits-"));
+ test("clamps git metadata to the session uploader's field limits after redaction", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-limits-"));
roots.push(root);
await git(root, "init", "-q");
await git(root, "checkout", "-q", "-b", `feature/${Array.from({ length: 6 }, () => "x".repeat(100)).join("/")}`);
@@ -639,21 +639,21 @@ describe("workspace collector envelope v2", () => {
});
test("captures prompt and turn_completed snapshots only when the workspace changed", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-triggers-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-triggers-"));
roots.push(root);
await writeFile(join(root, "a.txt"), "alpha\n");
await writeFile(join(root, "b.txt"), "beta\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-v2-triggers-1";
- collector.startSession(sessionId, "workspace-triggers", root);
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-triggers", root);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
expect(uploads.map((item) => item.snapshot_type)).toEqual(["start"]);
await writeFile(join(root, "a.txt"), "alpha changed\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(uploads.map((item) => [item.snapshot_type, item.trigger])).toEqual([["start", "session_start"], ["change", "turn_completed"]]);
const change = uploads[1]!;
const changedPaths = change.files.map((file) => file.path).filter((path) => !path.startsWith("__omnirush__/"));
@@ -663,10 +663,10 @@ describe("workspace collector envelope v2", () => {
expect(change.manifest.find((entry) => entry.path === "a.txt")?.sha256).toBe(sha256("alpha changed\n"));
expect(change.manifest.find((entry) => entry.path === "b.txt")?.sha256).toBe(sha256("beta\n"));
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const triggers = uploads
.filter((item) => item.snapshot_type === "trace")
.flatMap((item) => item.trace ?? [])
@@ -682,16 +682,16 @@ describe("workspace collector envelope v2", () => {
});
});
-describe("workspace collector durable retry", () => {
+describe("session uploader durable retry", () => {
test("spools failed uploads to disk with a failure ledger and delivers them once the gateway recovers", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-spool-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-spool-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-spool-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-spool-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "hello\n");
const uploads: Envelope[] = [];
let healthy = false;
const warnings: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (_sessionId, compressed) => {
if (!healthy) return Response.json({ error: "unavailable" }, { status: 503 });
@@ -704,13 +704,13 @@ describe("workspace collector durable retry", () => {
retryBaseMs: 60_000,
});
const sessionId = "session-spool-1234";
- collector.startSession(sessionId, "workspace-spool", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-spool", root);
+ await sessionUploader.idle(sessionId);
expect(uploads).toHaveLength(0);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
- expect(warnings).toContain("OmniRush collection artifact spooled for retry");
- const spoolDir = join(stateDir, "omnirush-collector-spool");
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(warnings).toContain("OmniRush session upload artifact spooled for retry");
+ const spoolDir = join(stateDir, "omnirush-upload-spool");
const names = (await readdir(spoolDir)).sort();
expect(names.some((name) => name.endsWith(".json"))).toBe(true);
expect(names.some((name) => name.endsWith(".zst"))).toBe(true);
@@ -718,30 +718,30 @@ describe("workspace collector durable retry", () => {
for (const name of names) expect((await stat(join(spoolDir, name))).mode & 0o777).toBe(0o600);
expect((await stat(spoolDir)).mode & 0o777).toBe(0o700);
}
- const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-collector-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
+ const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-upload-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
expect(ledger.sessions[sessionId]).toMatchObject({ failureCount: 1, nextSequence: 1 });
expect(typeof ledger.sessions[sessionId]?.lastFailureAt).toBe("string");
- expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
+ expect(await sessionUploader.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
healthy = true;
- expect(await collector.drainSpool()).toEqual({ delivered: 1, pending: 0 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 1, pending: 0 });
expect(uploads.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([["start", "session_start", 1]]);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
expect(uploads.map((item) => [item.snapshot_type, item.sequence])).toEqual([["start", 1], ["end", 2]]);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- const settled = JSON.parse(await readFile(join(stateDir, "omnirush-collector-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ const settled = JSON.parse(await readFile(join(stateDir, "omnirush-upload-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
expect(typeof settled.sessions[sessionId]?.lastSuccessAt).toBe("string");
expect(settled.sessions[sessionId]).toMatchObject({ failureCount: 1 });
});
- test("retries spooled uploads with backoff on the next collector start", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-respool-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-respool-state-"));
+ test("retries spooled uploads with backoff on the next session uploader start", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-respool-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-respool-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "hello\n");
const sessionId = "session-respool-1234";
- const first = new WorkspaceCollector({
+ const first = new SessionUploader({
stateDir,
upload: async () => { throw new Error("network down"); },
fallbackScanMs: 60_000,
@@ -753,7 +753,7 @@ describe("workspace collector durable retry", () => {
expect(await first.spoolStatus()).toMatchObject({ entries: 2 });
const { uploads, upload } = makeUploads();
- const second = new WorkspaceCollector({ stateDir, upload, fallbackScanMs: 60_000, retryBaseMs: 10, retryMaxMs: 20 });
+ const second = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, retryBaseMs: 10, retryMaxMs: 20 });
for (let attempt = 0; attempt < 100 && uploads.length < 2; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
@@ -763,12 +763,12 @@ describe("workspace collector durable retry", () => {
});
test("bounds the spool, drops permanently rejected uploads and clears on request", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-spoolcap-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-spoolcap-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-spoolcap-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-spoolcap-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "v0\n");
let status = 503;
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async () => Response.json({ error: "nope" }, { status }),
fallbackScanMs: 60_000,
@@ -778,39 +778,39 @@ describe("workspace collector durable retry", () => {
spoolMaxEntries: 2,
});
const sessionId = "session-spoolcap-1234";
- collector.startSession(sessionId, "workspace-spoolcap", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-spoolcap", root);
+ await sessionUploader.idle(sessionId);
for (let version = 1; version <= 3; version += 1) {
await writeFile(join(root, "app.txt"), `v${version}\n`);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
}
- expect(await collector.spoolStatus()).toMatchObject({ entries: 2 });
- const spoolDir = join(stateDir, "omnirush-collector-spool");
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 2 });
+ const spoolDir = join(stateDir, "omnirush-upload-spool");
const sequences = (await Promise.all((await readdir(spoolDir)).filter((name) => name.endsWith(".json"))
.map(async (name) => (JSON.parse(await readFile(join(spoolDir, name), "utf8")) as { sequence: number }).sequence))).sort();
expect(sequences).toEqual([3, 4]);
status = 400;
await writeFile(join(root, "app.txt"), "v4\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 2 });
- expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 5 });
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 2 });
+ expect(await sessionUploader.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 5 });
- await collector.clearSpool();
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- await collector.stop();
+ await sessionUploader.clearSpool();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
});
});
-describe("workspace collector upload deadline and spool drain", () => {
+describe("session upload deadline and spool drain", () => {
// Upload deadlines at 1/100 of real time: one simulated second is 10 ms.
- const hundredth: CollectUploadBudget = {
- baseMs: COLLECT_UPLOAD_BUDGET.baseMs / 100,
- bytesPerSecond: COLLECT_UPLOAD_BUDGET.bytesPerSecond * 100,
- maxSendMs: COLLECT_UPLOAD_BUDGET.maxSendMs / 100,
- responseMs: COLLECT_UPLOAD_BUDGET.responseMs / 100,
+ const hundredth: SessionUploadBudget = {
+ baseMs: SESSION_UPLOAD_BUDGET.baseMs / 100,
+ bytesPerSecond: SESSION_UPLOAD_BUDGET.bytesPerSecond * 100,
+ maxSendMs: SESSION_UPLOAD_BUDGET.maxSendMs / 100,
+ responseMs: SESSION_UPLOAD_BUDGET.responseMs / 100,
};
const simulatedSeconds = (seconds: number) => seconds * 10;
const sleep = (ms: number, signal?: AbortSignal) => new Promise<void>((resolvePromise, reject) => {
@@ -823,7 +823,7 @@ describe("workspace collector upload deadline and spool drain", () => {
/** Writes one spool entry as a failed upload leaves it; ids sort in `index` order. */
async function spoolEntry(stateDir: string, index: number, bytes: number, extra: Record<string, unknown> = {}): Promise<string> {
- const spoolDir = join(stateDir, "omnirush-collector-spool");
+ const spoolDir = join(stateDir, "omnirush-upload-spool");
await mkdir(spoolDir, { recursive: true, mode: 0o700 });
const id = `${index.toString(16).padStart(12, "0")}-${index.toString(16).padStart(6, "0")}-0000000${index}`;
const body = Buffer.alloc(bytes, index);
@@ -843,29 +843,29 @@ describe("workspace collector upload deadline and spool drain", () => {
}
async function spoolMeta(stateDir: string, id: string): Promise<{ attempts: number; last_attempt_at?: string }> {
- return JSON.parse(await readFile(join(stateDir, "omnirush-collector-spool", `${id}.json`), "utf8")) as { attempts: number; last_attempt_at?: string };
+ return JSON.parse(await readFile(join(stateDir, "omnirush-upload-spool", `${id}.json`), "utf8")) as { attempts: number; last_attempt_at?: string };
}
async function drainState(): Promise<string> {
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-drain-state-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-drain-state-"));
roots.push(stateDir);
return stateDir;
}
test("scales the deadline with the envelope and adds the wait for the gateway's answer", () => {
- expect(collectUploadTimeoutMs(0)).toBe(150_000);
+ expect(sessionUploadTimeoutMs(0)).toBe(150_000);
// A 10 MiB start snapshot: 30 s, 80 s of body at 128 KiB/s, 120 s for the answer.
- expect(collectUploadTimeoutMs(10 * 1024 * 1024)).toBe(230_000);
- expect(collectUploadTimeoutMs(10 * 1024 * 1024)).toBeGreaterThan(60_000 + 90_000);
- expect(collectUploadTimeoutMs(1024 * 1024 * 1024)).toBe(15 * 60_000 + 120_000);
- expect(collectUploadTimeoutMs(10 * 1024 * 1024, hundredth)).toBe(2_300);
+ expect(sessionUploadTimeoutMs(10 * 1024 * 1024)).toBe(230_000);
+ expect(sessionUploadTimeoutMs(10 * 1024 * 1024)).toBeGreaterThan(60_000 + 90_000);
+ expect(sessionUploadTimeoutMs(1024 * 1024 * 1024)).toBe(15 * 60_000 + 120_000);
+ expect(sessionUploadTimeoutMs(10 * 1024 * 1024, hundredth)).toBe(2_300);
});
test("delivers a 10 MB envelope over an uplink that needs 60 s for it on the first attempt", async () => {
const stateDir = await drainState();
await spoolEntry(stateDir, 1, 10 * 1024 * 1024);
const calls: { bytes: number; aborted: boolean }[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (_sessionId, compressed, signal) => {
// Throttled: the body trickles out over 60 s (about 170 KiB/s).
@@ -876,17 +876,17 @@ describe("workspace collector upload deadline and spool drain", () => {
uploadBudget: hundredth,
retryBaseMs: 60_000,
});
- expect(await collector.drainSpool()).toEqual({ delivered: 1, pending: 0 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 1, pending: 0 });
expect(calls).toEqual([{ bytes: 10 * 1024 * 1024, aborted: false }]);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
});
test("waits for an answer that comes 90 s after the body is sent", async () => {
const stateDir = await drainState();
await spoolEntry(stateDir, 1, 6 * 1024 * 1024);
const answered: boolean[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
gatewayUrl: "https://gateway.example.test/v1",
accessToken: "device-token",
@@ -901,9 +901,9 @@ describe("workspace collector upload deadline and spool drain", () => {
uploadBudget: hundredth,
retryBaseMs: 60_000,
});
- expect(await collector.drainSpool()).toEqual({ delivered: 1, pending: 0 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 1, pending: 0 });
expect(answered).toEqual([false]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("delivers the entries behind a spooled upload that keeps failing, and backs that one off", async () => {
@@ -913,7 +913,7 @@ describe("workspace collector upload deadline and spool drain", () => {
await spoolEntry(stateDir, 3, 1_024);
const attempts: number[] = [];
const delivered: number[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (sessionId) => {
const index = Number(sessionId.split("-").at(-1));
@@ -927,7 +927,7 @@ describe("workspace collector upload deadline and spool drain", () => {
retryBaseMs: 60_000,
});
- expect(await collector.drainSpool()).toEqual({ delivered: 2, pending: 1 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 2, pending: 1 });
expect(attempts).toEqual([1, 2, 3]);
expect(delivered).toEqual([2, 3]);
const failed = await spoolMeta(stateDir, stuck);
@@ -935,29 +935,29 @@ describe("workspace collector upload deadline and spool drain", () => {
expect(typeof failed.last_attempt_at).toBe("string");
// Within its backoff the failed entry is left alone.
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
expect(attempts).toEqual([1, 2, 3]);
// Once the backoff (the retry base after one failed drain) has passed, it is tried again...
- const spoolDir = join(stateDir, "omnirush-collector-spool");
+ const spoolDir = join(stateDir, "omnirush-upload-spool");
await writeFile(join(spoolDir, `${stuck}.json`), JSON.stringify({ ...failed, last_attempt_at: new Date(Date.now() - 61_000).toISOString() }));
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
expect(attempts).toEqual([1, 2, 3, 1]);
const again = await spoolMeta(stateDir, stuck);
expect(again.attempts).toBe(3);
// ...and the next backoff is twice as long.
await writeFile(join(spoolDir, `${stuck}.json`), JSON.stringify({ ...again, last_attempt_at: new Date(Date.now() - 90_000).toISOString() }));
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
expect(attempts).toEqual([1, 2, 3, 1]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("stops a drain after three failures and leaves the rest to the next one", async () => {
const stateDir = await drainState();
for (let index = 1; index <= 5; index += 1) await spoolEntry(stateDir, index, 512);
const attempts: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (sessionId) => {
attempts.push(sessionId);
@@ -965,9 +965,9 @@ describe("workspace collector upload deadline and spool drain", () => {
},
retryBaseMs: 60_000,
});
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 5 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 5 });
expect(attempts).toEqual(["session-drain-1", "session-drain-2", "session-drain-3"]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("drops an entry once it reaches the attempt limit", async () => {
@@ -975,16 +975,16 @@ describe("workspace collector upload deadline and spool drain", () => {
await spoolEntry(stateDir, 1, 512, { attempts: 23 });
await spoolEntry(stateDir, 2, 512);
const warnings: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async () => Response.json({ error: "unavailable" }, { status: 503 }),
log: (level, message) => { if (level === "warn") warnings.push(message); },
retryBaseMs: 60_000,
});
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 1 });
- expect(warnings).toEqual(["OmniRush collection artifact dropped from spool"]);
- expect(await collector.spoolStatus()).toEqual({ entries: 1, bytes: 512 });
- await collector.stop();
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(warnings).toEqual(["OmniRush session upload artifact dropped from spool"]);
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 1, bytes: 512 });
+ await sessionUploader.stop();
});
test("a sign-out aborts the spooled upload in flight and empties the spool", async () => {
@@ -993,7 +993,7 @@ describe("workspace collector upload deadline and spool drain", () => {
let started!: () => void;
const inFlight = new Promise<void>((resolvePromise) => { started = resolvePromise; });
let aborted = false;
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: (_sessionId, _compressed, signal) => new Promise<Response>((_resolvePromise, reject) => {
signal?.addEventListener("abort", () => {
@@ -1004,17 +1004,17 @@ describe("workspace collector upload deadline and spool drain", () => {
}),
retryBaseMs: 60_000,
});
- const drain = collector.drainSpool();
+ const drain = sessionUploader.drainSpool();
await inFlight;
- await collector.clearSpool();
+ await sessionUploader.clearSpool();
expect(aborted).toBe(true);
expect(await drain).toEqual({ delivered: 0, pending: 1 });
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
});
test("a sign-out aborts the live upload in flight and spools nothing it carried", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-signout-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-signout-"));
roots.push(root);
const stateDir = await drainState();
await writeFile(join(root, "app.txt"), "hello\n");
@@ -1022,7 +1022,7 @@ describe("workspace collector upload deadline and spool drain", () => {
const inFlight = new Promise<void>((resolvePromise) => { started = resolvePromise; });
const signals: AbortSignal[] = [];
const infos: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (_sessionId, _compressed, signal) => {
signals.push(signal!);
@@ -1037,30 +1037,30 @@ describe("workspace collector upload deadline and spool drain", () => {
retryBaseMs: 60_000,
});
const sessionId = "session-signout-1234";
- collector.startSession(sessionId, "workspace-signout", root);
+ sessionUploader.startSession(sessionId, "workspace-signout", root);
await inFlight;
- await collector.clearSpool();
- await collector.idle(sessionId);
+ await sessionUploader.clearSpool();
+ await sessionUploader.idle(sessionId);
expect(signals).toHaveLength(1);
expect(signals[0]!.aborted).toBe(true);
- expect(infos).toContain("OmniRush collection artifact discarded at sign-out");
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- expect(await readdir(join(stateDir, "omnirush-collector-spool")).catch(() => [])).toEqual([]);
+ expect(infos).toContain("OmniRush session upload artifact discarded at sign-out");
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ expect(await readdir(join(stateDir, "omnirush-upload-spool")).catch(() => [])).toEqual([]);
// The next account's uploads are not cancelled by the earlier sign-out.
const next = "session-signout-5678";
- collector.startSession(next, "workspace-signout-next", root);
- await collector.idle(next);
+ sessionUploader.startSession(next, "workspace-signout-next", root);
+ await sessionUploader.idle(next);
expect(signals.length).toBeGreaterThan(1);
expect(signals.slice(1).every((signal) => !signal.aborted)).toBe(true);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
- await collector.clearSpool();
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
+ await sessionUploader.clearSpool();
+ await sessionUploader.stop();
});
test("spools a live upload once an attempt runs out its deadline, and still retries quick failures in band", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-deadline-live-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-deadline-live-"));
roots.push(root);
const stateDir = await drainState();
await writeFile(join(root, "app.txt"), "v0\n");
@@ -1068,7 +1068,7 @@ describe("workspace collector upload deadline and spool drain", () => {
const plan: Array<"hang" | "drop" | "timeout"> = [];
const calls: string[] = [];
const spooled: unknown[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async () => {
const step = plan.shift() ?? "drop";
@@ -1080,7 +1080,7 @@ describe("workspace collector upload deadline and spool drain", () => {
throw new Error("network down");
},
log: (level, message, attributes) => {
- if (level === "warn" && message === "OmniRush collection artifact spooled for retry") spooled.push(attributes?.reason);
+ if (level === "warn" && message === "OmniRush session upload artifact spooled for retry") spooled.push(attributes?.reason);
},
uploadBudget: { baseMs: 50, bytesPerSecond: 128 * 1024 * 1000, maxSendMs: 900, responseMs: 100 },
fallbackScanMs: 60_000,
@@ -1092,30 +1092,30 @@ describe("workspace collector upload deadline and spool drain", () => {
// The start snapshot's first attempt runs out its deadline: spooled, not tried twice more in band.
plan.push("hang");
- collector.startSession(sessionId, "workspace-deadline-live", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-deadline-live", root);
+ await sessionUploader.idle(sessionId);
expect(calls).toEqual(["hang"]);
expect(spooled).toHaveLength(1);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
// The session's queue moved on to its next snapshot, whose quick failures keep their in-band retries.
plan.push("drop", "drop", "drop");
await writeFile(join(root, "app.txt"), "v1\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(calls).toEqual(["hang", "drop", "drop", "drop"]);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 2 });
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 2 });
// A quick failure, then an attempt out of time: no third attempt.
plan.push("drop", "timeout");
await writeFile(join(root, "app.txt"), "v2\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(calls).toEqual(["hang", "drop", "drop", "drop", "drop", "timeout"]);
expect(spooled.slice(1)).toEqual(["network down", "The operation timed out."]);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 3 });
- await collector.clearSpool();
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 3 });
+ await sessionUploader.clearSpool();
+ await sessionUploader.stop();
});
test("a stop mid-drain leaves the spooled entry in flight as it was", async () => {
@@ -1124,7 +1124,7 @@ describe("workspace collector upload deadline and spool drain", () => {
const before = await spoolMeta(stateDir, id);
let started!: () => void;
const inFlight = new Promise<void>((resolvePromise) => { started = resolvePromise; });
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
// Never answers and ignores its signal: the stop ends it all the same.
upload: () => {
@@ -1133,20 +1133,20 @@ describe("workspace collector upload deadline and spool drain", () => {
},
retryBaseMs: 60_000,
});
- const drain = collector.drainSpool();
+ const drain = sessionUploader.drainSpool();
await inFlight;
- await collector.stop();
+ await sessionUploader.stop();
expect(await drain).toEqual({ delivered: 0, pending: 1 });
expect(await spoolMeta(stateDir, id)).toEqual(before);
expect(before).toMatchObject({ attempts: 3, last_attempt_at: expect.any(String) });
- expect(await collector.spoolStatus()).toEqual({ entries: 1, bytes: 1_024 });
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 1, bytes: 1_024 });
});
test("an entry dated in the future (the clock went back) waits one backoff, not until then", async () => {
const stateDir = await drainState();
await spoolEntry(stateDir, 1, 256, { attempts: 2, last_attempt_at: new Date(Date.now() + 30 * 24 * 60 * 60_000).toISOString() });
let calls = 0;
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async () => {
calls += 1;
@@ -1156,16 +1156,16 @@ describe("workspace collector upload deadline and spool drain", () => {
retryMaxMs: 80,
});
// Due at once: the first try fails and records a sane last attempt.
- expect(await collector.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
const deadline = Date.now() + 2_000;
- while ((await collector.spoolStatus()).entries > 0 && Date.now() < deadline) {
+ while ((await sessionUploader.spoolStatus()).entries > 0 && Date.now() < deadline) {
await new Promise((resolvePromise) => setTimeout(resolvePromise, 20));
}
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
// Retried on the capped schedule: a handful of calls, no 1 ms loop.
expect(calls).toBeGreaterThanOrEqual(1);
expect(calls).toBeLessThanOrEqual(4);
- await collector.stop();
+ await sessionUploader.stop();
});
test("a drain asked for while one runs picks up the entries spooled meanwhile", async () => {
@@ -1176,7 +1176,7 @@ describe("workspace collector upload deadline and spool drain", () => {
let started!: () => void;
const inFlight = new Promise<void>((resolvePromise) => { started = resolvePromise; });
const delivered: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (sessionId) => {
if (sessionId === "session-drain-1") {
@@ -1188,30 +1188,30 @@ describe("workspace collector upload deadline and spool drain", () => {
},
retryBaseMs: 60_000,
});
- const running = collector.drainSpool();
+ const running = sessionUploader.drainSpool();
await inFlight;
// Spooled after the running drain listed the spool.
await spoolEntry(stateDir, 2, 512);
- const next = collector.drainSpool();
+ const next = sessionUploader.drainSpool();
// Every call during the run shares the one drain after it.
- expect(collector.drainSpool()).toBe(next);
+ expect(sessionUploader.drainSpool()).toBe(next);
release();
expect(await running).toEqual({ delivered: 1, pending: 0 });
expect(await next).toEqual({ delivered: 1, pending: 0 });
expect(delivered).toEqual(["session-drain-1", "session-drain-2"]);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
});
});
-describe("workspace collector git helpers", () => {
+describe("session uploader git helpers", () => {
test("clamps text by code points without splitting surrogate pairs", () => {
- expect(clampCollectorText("abc", 5)).toBe("abc");
- expect(clampCollectorText("abcdef", 3)).toBe("abc");
+ expect(clampUploadText("abc", 5)).toBe("abc");
+ expect(clampUploadText("abcdef", 3)).toBe("abc");
const faces = "\u{1F600}".repeat(4);
- expect(clampCollectorText(faces, 4)).toBe(faces);
- expect(clampCollectorText(faces, 3)).toBe("\u{1F600}".repeat(3));
- expect(Array.from(clampCollectorText("y".repeat(2_000), 1_024))).toHaveLength(1_024);
+ expect(clampUploadText(faces, 4)).toBe(faces);
+ expect(clampUploadText(faces, 3)).toBe("\u{1F600}".repeat(3));
+ expect(Array.from(clampUploadText("y".repeat(2_000), 1_024))).toHaveLength(1_024);
});
test("strips userinfo from scheme and scp-like remotes", () => {
@@ -1249,7 +1249,7 @@ describe("workspace collector git helpers", () => {
"+{\"private\":true}",
"",
].join("\n");
- const result = filterCollectorDiff(raw);
+ const result = filterUploadDiff(raw);
expect(result.truncated).toBe(false);
expect(result.diff).toContain("diff --git a/app.ts b/app.ts");
expect(result.diff).toContain("[REDACTED]");
@@ -1258,50 +1258,50 @@ describe("workspace collector git helpers", () => {
expect(result.diff).not.toContain("super-secret-value");
expect(result.diff).not.toContain("blob.bin");
expect(result.diff).not.toContain("keys/service.json");
- expect(filterCollectorDiff("")).toEqual({ diff: null, truncated: false });
- expect(filterCollectorDiff("diff --git a/x b/x\n+ok\n", true).truncated).toBe(true);
+ expect(filterUploadDiff("")).toEqual({ diff: null, truncated: false });
+ expect(filterUploadDiff("diff --git a/x b/x\n+ok\n", true).truncated).toBe(true);
});
});
-// --- collector trace additions (contract v2) --------------------------------
+// --- session uploader trace additions (contract v2) --------------------------------
function traceEvents(uploads: Envelope[]): Array<{ type: string; data?: Record<string, unknown> }> {
return uploads.filter((item) => item.snapshot_type === "trace").flatMap((item) => item.trace ?? []);
}
-describe("workspace collector trace additions", () => {
+describe("session uploader trace additions", () => {
test("raises the caps to the contract values", () => {
- expect(MAX_COLLECTOR_FILE_BYTES).toBe(4 * 1024 * 1024);
- expect(MAX_COLLECTOR_DIFF_BYTES).toBe(2 * 1024 * 1024);
- expect(MAX_COLLECTOR_FILES).toBe(50_000);
- expect(MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES).toBe(64 * 1024);
- expect(MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES).toBe(256 * 1024);
+ expect(MAX_UPLOAD_FILE_BYTES).toBe(4 * 1024 * 1024);
+ expect(MAX_UPLOAD_DIFF_BYTES).toBe(2 * 1024 * 1024);
+ expect(MAX_UPLOAD_FILES).toBe(50_000);
+ expect(MAX_UPLOAD_WEB_VISIT_TEXT_BYTES).toBe(64 * 1024);
+ expect(MAX_UPLOAD_ATTACHMENT_TEXT_BYTES).toBe(256 * 1024);
});
test("keeps uploading every snapshot of a session that has already sent more than 512 MiB", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-nocap-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-nocap-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-nocap-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-nocap-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "v0\n");
const sessionId = "session-nocap-1234";
// The session ledger stands in for the running total of a long session:
// it says 600 MiB were already accepted (past the 512 MiB per-session cap
- // the collector used to stop at) without any of that data being written.
+ // the session uploader used to stop at) without any of that data being written.
const sentBefore = 600 * 1024 * 1024;
- await writeFile(join(stateDir, "omnirush-collector-sessions.json"), JSON.stringify({
+ await writeFile(join(stateDir, "omnirush-upload-sessions.json"), JSON.stringify({
version: 1,
sessions: { [sessionId]: { segment: 1, nextSequence: 40, sentBytes: sentBefore, lastSeenAt: new Date().toISOString() } },
}));
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ stateDir, upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
- collector.startSession(sessionId, "workspace-nocap", root);
- await collector.idle(sessionId);
+ const sessionUploader = new SessionUploader({ stateDir, upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ sessionUploader.startSession(sessionId, "workspace-nocap", root);
+ await sessionUploader.idle(sessionId);
await writeFile(join(root, "app.txt"), "v1\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- collector.recordTrace(sessionId, "file.read", { path: "app.txt" });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "app.txt" });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
// Sequence 41 onwards: the seeded total was loaded, and nothing was held back.
expect(uploads.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([
@@ -1317,20 +1317,20 @@ describe("workspace collector trace additions", () => {
const metadata = JSON.parse(uploads[0]!.files.find((file) => file.path === "__omnirush__/workspace.json")!.content) as Record<string, unknown>;
expect(metadata).not.toHaveProperty("max_session_bytes");
// The running total is still counted, for diagnostics only.
- const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-collector-sessions.json"), "utf8")) as { sessions: Record<string, { sentBytes: number }> };
+ const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-upload-sessions.json"), "utf8")) as { sessions: Record<string, { sentBytes: number }> };
expect(ledger.sessions[sessionId]!.sentBytes).toBeGreaterThan(sentBefore);
});
test("records the turn model and child sessions with checkpoints that survive a resume", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-children-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-children-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-children-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-children-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "hello\n");
const { uploads, upload } = makeUploads();
- const makeCollector = () => new WorkspaceCollector({ stateDir, upload, fallbackScanMs: 60_000 });
+ const makeUploader = () => new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000 });
const sessionId = "session-children-1234";
- const first = makeCollector();
+ const first = makeUploader();
first.startSession(sessionId, "workspace-children", root);
await first.idle(sessionId);
expect(uploads.map((item) => item.snapshot_type)).toEqual(["start"]);
@@ -1377,7 +1377,7 @@ describe("workspace collector trace additions", () => {
// A resumed session starts from the persisted checkpoints and reports the
// last known model and children on its very first upload.
- const second = makeCollector();
+ const second = makeUploader();
second.startSession(sessionId, "workspace-children", root);
await second.idle(sessionId);
expect(await second.childCheckpoints(sessionId)).toEqual({ ses_child_1: "cmsg_1" });
@@ -1390,36 +1390,36 @@ describe("workspace collector trace additions", () => {
});
test("sub-agents on their own models keep them; a gateway fallback records the model that really answered", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-subagent-model-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-subagent-model-"));
roots.push(root);
await writeFile(join(root, "app.txt"), "hello\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-subagent-model-1";
- collector.startSession(sessionId, "workspace-subagent-model", root);
- await collector.idle(sessionId);
- collector.recordSessionModel(sessionId, { provider_id: "omnirush", model_id: "gpt-6-astra", variant: "max", agent: "omnirush" });
+ sessionUploader.startSession(sessionId, "workspace-subagent-model", root);
+ await sessionUploader.idle(sessionId);
+ sessionUploader.recordSessionModel(sessionId, { provider_id: "omnirush", model_id: "gpt-6-astra", variant: "max", agent: "omnirush" });
const assistant = (id: string, session: string, modelID: string, variant: string, completed: number) => ({
info: { id, role: "assistant", sessionID: session, providerID: "omnirush", modelID, variant, agent: "general", time: { created: completed - 10, completed } },
parts: [{ type: "text", text: `answer ${id}` }],
});
// The gateway refused GPT 6 Sol for ses_sol at t=2000; ses_muse ran on Muse all along.
- collector.recordTrace(sessionId, "subagent.model_fallback", {
+ sessionUploader.recordTrace(sessionId, "subagent.model_fallback", {
kind: "gateway", child_session_id: "ses_sol", requested_model: "gpt-6-sol", used_model: "gpt-6-astra", used_effort: "high", reason: "model_unavailable", ok: true, at: 2_000,
});
- collector.recordTrace(sessionId, "subagent.model_fallback", {
+ sessionUploader.recordTrace(sessionId, "subagent.model_fallback", {
kind: "selection", child_session_id: "ses_other", requested_model: "meta-muse-spark", used_model: "gpt-6-astra", reason: "not_in_catalog", at: 2_000,
});
- collector.recordChildSession(sessionId, {
+ sessionUploader.recordChildSession(sessionId, {
childSessionId: "ses_muse", parentSessionId: sessionId, depth: 1, title: "Muse task", agent: "general",
messages: [assistant("m1", "ses_muse", "meta-muse-spark", "xhigh", 5_000)], lastMessageId: "m1",
});
- collector.recordChildSession(sessionId, {
+ sessionUploader.recordChildSession(sessionId, {
childSessionId: "ses_sol", parentSessionId: sessionId, depth: 1, title: "Sol task", agent: "general",
messages: [assistant("s1", "ses_sol", "gpt-6-sol", "high", 1_000), assistant("s2", "ses_sol", "gpt-6-sol", "high", 3_000)], lastMessageId: "s2",
});
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const events = traceEvents(uploads);
const child = (id: string) => events.find((event) => event.type === "session.child" && event.data?.child_session_id === id)?.data?.messages as Array<{ info: Record<string, unknown> }>;
@@ -1434,48 +1434,48 @@ describe("workspace collector trace additions", () => {
});
test("keeps only the newest 5,000 events across every push site", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-cap-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-cap-"));
roots.push(root);
await writeFile(join(root, "app.txt"), "hello\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-cap-1234";
- collector.startSession(sessionId, "workspace-cap", root);
- await collector.idle(sessionId);
- expect(MAX_COLLECTOR_TRACE_EVENTS).toBe(5_000);
+ sessionUploader.startSession(sessionId, "workspace-cap", root);
+ await sessionUploader.idle(sessionId);
+ expect(MAX_UPLOAD_TRACE_EVENTS).toBe(5_000);
// Fill the trace, then push one event through each of the newer sites:
// every one of them displaces the oldest event instead of growing the trace.
- for (let index = 0; index < MAX_COLLECTOR_TRACE_EVENTS; index += 1) collector.recordTrace(sessionId, "filler", { index });
- collector.recordSessionModel(sessionId, { provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: null, agent: null });
- collector.recordChildSession(sessionId, { childSessionId: "ses_child_cap", parentSessionId: sessionId, title: null, agent: null, messages: [], lastMessageId: null });
- expect(collector.recordWebVisit(sessionId, { url: "https://example.com/page", title: "Page", text: "text" })).toBe(true);
- collector.recordAttachment(sessionId, { name: "note.txt", mime: "text/plain", bytes: 4, sha256: "0".repeat(64), text: "note", textTruncated: false });
- collector.flushTrace(sessionId);
- await collector.stop();
+ for (let index = 0; index < MAX_UPLOAD_TRACE_EVENTS; index += 1) sessionUploader.recordTrace(sessionId, "filler", { index });
+ sessionUploader.recordSessionModel(sessionId, { provider_id: "anthropic", model_id: "claude-sonnet-4-5", variant: null, agent: null });
+ sessionUploader.recordChildSession(sessionId, { childSessionId: "ses_child_cap", parentSessionId: sessionId, title: null, agent: null, messages: [], lastMessageId: null });
+ expect(sessionUploader.recordWebVisit(sessionId, { url: "https://example.com/page", title: "Page", text: "text" })).toBe(true);
+ sessionUploader.recordAttachment(sessionId, { name: "note.txt", mime: "text/plain", bytes: 4, sha256: "0".repeat(64), text: "note", textTruncated: false });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const events = traceEvents(uploads);
- expect(events).toHaveLength(MAX_COLLECTOR_TRACE_EVENTS);
+ expect(events).toHaveLength(MAX_UPLOAD_TRACE_EVENTS);
expect(events.slice(-4).map((event) => event.type)).toEqual(["session.model", "session.child", "web.visit", "attachment"]);
// The four oldest filler events (indices 0-3) were dropped; the newest filler survives.
expect(events[0]?.data).toEqual({ index: 4 });
- expect(events.filter((event) => event.type === "filler")).toHaveLength(MAX_COLLECTOR_TRACE_EVENTS - 4);
+ expect(events.filter((event) => event.type === "filler")).toHaveLength(MAX_UPLOAD_TRACE_EVENTS - 4);
}, 20_000);
test("traces browser visits with redacted, capped text and never local pages", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-web-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-web-"));
roots.push(root);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-web-1234";
- collector.startSession(sessionId, "workspace-web", root);
+ sessionUploader.startSession(sessionId, "workspace-web", root);
const text = `Contact [email protected] about AKIA1234567890123456 ${"page text ".repeat(20_000)}`;
- expect(collector.recordWebVisit(sessionId, { url: "https://user:[email protected]/docs?q=1#top", title: "Docs [email protected]", text })).toBe(true);
- expect(collector.recordWebVisit(sessionId, { url: "https://example.org/short", title: null, text: "brief" })).toBe(true);
+ expect(sessionUploader.recordWebVisit(sessionId, { url: "https://user:[email protected]/docs?q=1#top", title: "Docs [email protected]", text })).toBe(true);
+ expect(sessionUploader.recordWebVisit(sessionId, { url: "https://example.org/short", title: null, text: "brief" })).toBe(true);
for (const url of ["file:///etc/passwd", "data:text/html,<p>hi</p>", "chrome://settings", "http://localhost:3000/app", "http://127.0.0.1:8080/", "https://[::1]/", "ftp://example.com/x"]) {
- expect(collector.recordWebVisit(sessionId, { url, title: "local", text: "secret local page" })).toBe(false);
+ expect(sessionUploader.recordWebVisit(sessionId, { url, title: "local", text: "secret local page" })).toBe(false);
}
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const visits = traceEvents(uploads).filter((event) => event.type === "web.visit");
expect(visits).toHaveLength(2);
@@ -1483,7 +1483,7 @@ describe("workspace collector trace additions", () => {
expect(long?.data?.url).toBe("https://example.com/docs?q=1#top");
expect(long?.data?.title).toBe("Docs [REDACTED_PII]");
expect(long?.data?.text_truncated).toBe(true);
- expect(Buffer.byteLength(String(long?.data?.text))).toBeLessThanOrEqual(MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES);
+ expect(Buffer.byteLength(String(long?.data?.text))).toBeLessThanOrEqual(MAX_UPLOAD_WEB_VISIT_TEXT_BYTES);
expect(String(long?.data?.text)).not.toContain("[email protected]");
expect(String(long?.data?.text)).not.toContain("AKIA1234567890123456");
expect(short?.data).toEqual({ url: "https://example.org/short", title: null, text: "brief", text_truncated: false });
@@ -1492,17 +1492,17 @@ describe("workspace collector trace additions", () => {
});
test("traces prompt attachments with redacted, capped text", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-attachments-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-attachments-"));
roots.push(root);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-attachment-1234";
- collector.startSession(sessionId, "workspace-attachment", root);
+ sessionUploader.startSession(sessionId, "workspace-attachment", root);
const text = `OPENAI_API_KEY=sk-1234567890abcdefghijklmnop\n${"notes ".repeat(60_000)}`;
- collector.recordAttachment(sessionId, { name: "../notes [email protected] report.txt", mime: "text/plain", bytes: Buffer.byteLength(text), sha256: sha256(text), text });
- collector.recordAttachment(sessionId, { name: "photo.png", mime: "image/png", bytes: 12, sha256: sha256("png"), text: null });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.recordAttachment(sessionId, { name: "../notes [email protected] report.txt", mime: "text/plain", bytes: Buffer.byteLength(text), sha256: sha256(text), text });
+ sessionUploader.recordAttachment(sessionId, { name: "photo.png", mime: "image/png", bytes: 12, sha256: sha256("png"), text: null });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const attachments = traceEvents(uploads).filter((event) => event.type === "attachment");
expect(attachments).toHaveLength(2);
@@ -1512,14 +1512,14 @@ describe("workspace collector trace additions", () => {
expect(note?.data?.bytes).toBe(Buffer.byteLength(text));
expect(note?.data?.sha256).toBe(sha256(text));
expect(note?.data?.text_truncated).toBe(true);
- expect(Buffer.byteLength(String(note?.data?.text))).toBeLessThanOrEqual(MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES);
+ expect(Buffer.byteLength(String(note?.data?.text))).toBeLessThanOrEqual(MAX_UPLOAD_ATTACHMENT_TEXT_BYTES);
expect(String(note?.data?.text)).not.toContain("sk-1234567890abcdefghijklmnop");
expect(String(note?.data?.text)).toContain("[REDACTED]");
expect(photo?.data).toEqual({ name: "photo.png", mime: "image/png", bytes: 12, sha256: sha256("png"), text: null, text_truncated: false });
});
test("emits artifact events for untracked outputs a turn creates or modifies", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-artifacts-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-artifacts-"));
roots.push(root);
await git(root, "init", "-q");
await writeFile(join(root, ".gitignore"), "ignored/\n");
@@ -1528,11 +1528,11 @@ describe("workspace collector trace additions", () => {
await git(root, "add", ".gitignore", "tracked.txt");
await git(root, "commit", "-q", "-m", "init");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-artifacts-1234";
- collector.startSession(sessionId, "workspace-artifacts", root);
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-artifacts", root);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
await new Promise((resolve) => setTimeout(resolve, 20));
await writeFile(join(root, "tracked.txt"), "tracked, edited\n");
@@ -1541,10 +1541,10 @@ describe("workspace collector trace additions", () => {
await writeFile(join(root, "notes.md"), "generated notes\n");
await mkdir(join(root, "ignored"));
await writeFile(join(root, "ignored", "cache.txt"), "ignored output\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const artifacts = traceEvents(uploads).filter((event) => event.type === "artifact").map((event) => event.data);
expect(artifacts.map((artifact) => artifact?.path).sort()).toEqual(["notes.md", "out/report.bin"]);
@@ -1561,18 +1561,18 @@ describe("workspace collector trace additions", () => {
});
test("clamps by bytes without splitting code points and classifies web urls", () => {
- expect(clampCollectorBytes("abc", 10)).toEqual({ text: "abc", truncated: false });
- expect(clampCollectorBytes("a😀b", 4)).toEqual({ text: "a", truncated: true });
- expect(clampCollectorBytes("a😀b", 5)).toEqual({ text: "a😀", truncated: true });
- expect(isCollectableWebUrl("https://example.com/")).toBe(true);
- expect(isCollectableWebUrl("http://example.com:8080/path")).toBe(true);
+ expect(clampUploadBytes("abc", 10)).toEqual({ text: "abc", truncated: false });
+ expect(clampUploadBytes("a😀b", 4)).toEqual({ text: "a", truncated: true });
+ expect(clampUploadBytes("a😀b", 5)).toEqual({ text: "a😀", truncated: true });
+ expect(isUploadableWebUrl("https://example.com/")).toBe(true);
+ expect(isUploadableWebUrl("http://example.com:8080/path")).toBe(true);
for (const url of ["file:///tmp/a", "data:text/plain,a", "chrome://version", "about:blank", "http://localhost/", "http://app.localhost/", "http://127.0.0.1/", "http://[::1]/", "not a url"]) {
- expect(isCollectableWebUrl(url)).toBe(false);
+ expect(isUploadableWebUrl(url)).toBe(false);
}
});
});
-// --- collector secret rails --------------------------------------------------
+// --- session uploader secret rails --------------------------------------------------
const AWS_SECRET = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
// Token samples are assembled at runtime so the source never contains a
@@ -1580,19 +1580,19 @@ const AWS_SECRET = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
const sample = (prefix: string, ...rest: string[]) => prefix + rest.join("");
const GITHUB_TOKEN = sample("ghp_", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef0123");
-describe("workspace collector secret rails", () => {
+describe("session uploader secret rails", () => {
test("drops the incident file by name and counts it in the privacy manifest", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-incident-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-incident-"));
roots.push(root);
await git(root, "init", "-q");
await writeFile(join(root, "AWS master key"), `aws_access_key_id = AKIAIOSFODNN7EXAMPLE\naws_secret_access_key = ${AWS_SECRET}\n`);
await writeFile(join(root, "app.ts"), "export const ok = true;\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-incident-1";
- collector.startSession(sessionId, "workspace-incident", root);
- collector.recordTrace(sessionId, "file.read", { path: "AWS master key" });
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-incident", root);
+ sessionUploader.recordTrace(sessionId, "file.read", { path: "AWS master key" });
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start")!;
expect(start.files.map((file) => file.path).sort()).toEqual(["__omnirush__/workspace.json", "app.ts"]);
@@ -1616,17 +1616,17 @@ describe("workspace collector secret rails", () => {
"AWS master key", "tokens/prod.csv", "backup/wallet.dat", "my-wallet", "seed.csv", "kubeconfig", "id_rsa.pub", "notes/passwords",
".aws/config", ".gnupg/pubring.kbx", ".docker/config.json", "team/mnemonic", "prod secret", "api_key", ".netrc", "passwd",
]) {
- expect(isCollectorPathDenied(path)).toBe(true);
+ expect(isUploadPathDenied(path)).toBe(true);
}
for (const path of [
"src/token/refresh.ts", "design-tokens/colors.ts", "prisma/seed/users.ts", "seed.sql", "password-reset.tsx", "keys.md",
"AWS master key.txt", "kubeconfig.yaml", "keyboard.ts", "hotkey.json", ".docker/daemon.json", "src/app.ts",
]) {
- expect(isCollectorPathDenied(path)).toBe(false);
+ expect(isUploadPathDenied(path)).toBe(false);
}
// The pre-existing rules stay stricter than the extension carve-out.
for (const path of ["credentials.json", "secrets.ts", "secrets/config.yml", "keys/service.json", "server.key", ".env.production", "private-key.md"]) {
- expect(isCollectorPathDenied(path)).toBe(true);
+ expect(isUploadPathDenied(path)).toBe(true);
}
});
@@ -1665,7 +1665,7 @@ describe("workspace collector secret rails", () => {
["token2 = abcdefghijkl", "token2 = [REDACTED]"],
];
for (const [input, expected] of secrets) {
- expect(redactCollectorText(input)).toEqual({ text: expected, count: 1 });
+ expect(redactUploadText(input)).toEqual({ text: expected, count: 1 });
}
const preserved = [
"token_length = abcdefghij", "token_ttl = abcdefghij", "auth_seconds = abcdefghij", "token_count = abcdefghij",
@@ -1679,7 +1679,7 @@ describe("workspace collector secret rails", () => {
"tokenizer_class = BertTokenizer", "tokenize: whitespace", "keyboard_layout = qwerty-intl", "keywords = abcdefghijkl",
"pwdir = /home/user/project", "accessKeyId = abcdefghijkl", 'eos_token: "<|endoftext|>"',
];
- for (const input of preserved) expect(redactCollectorText(input)).toEqual({ text: input, count: 0 });
+ for (const input of preserved) expect(redactUploadText(input)).toEqual({ text: input, count: 0 });
});
test("leaves a real package.json and a tokenizer config byte-identical", () => {
@@ -1696,12 +1696,12 @@ describe("workspace collector secret rails", () => {
"}",
"",
].join("\n");
- expect(redactCollectorContent("package.json", packageJson)).toBe(packageJson);
- expect(redactCollectorText(packageJson)).toEqual({ text: packageJson, count: 0 });
+ expect(redactUploadContent("package.json", packageJson)).toBe(packageJson);
+ expect(redactUploadText(packageJson)).toEqual({ text: packageJson, count: 0 });
const tokenizerConfig = '{"tokenizer_class": "LlamaTokenizer", "bos_token": "<s>", "eos_token": "<|endoftext|>", "add_bos_token": true, "model_max_length": 4096, "clean_up_tokenization_spaces": false}';
- expect(redactCollectorContent("tokenizer_config.json", tokenizerConfig)).toBe(tokenizerConfig);
- expect(redactCollectorText(tokenizerConfig)).toEqual({ text: tokenizerConfig, count: 0 });
- expect(redactCollectorText("tokenizer_class = LlamaTokenizer\nauth_token = abcdefgh1234\n"))
+ expect(redactUploadContent("tokenizer_config.json", tokenizerConfig)).toBe(tokenizerConfig);
+ expect(redactUploadText(tokenizerConfig)).toEqual({ text: tokenizerConfig, count: 0 });
+ expect(redactUploadText("tokenizer_class = LlamaTokenizer\nauth_token = abcdefgh1234\n"))
.toEqual({ text: "tokenizer_class = LlamaTokenizer\nauth_token = [REDACTED]\n", count: 1 });
});
@@ -1727,38 +1727,38 @@ describe("workspace collector secret rails", () => {
["-----BEGIN PGP PRIVATE KEY BLOCK-----\nlQdGBF\n-----END PGP PRIVATE KEY BLOCK-----", "lQdGBF"],
];
for (const [shape, marker] of shapes) {
- const result = redactCollectorText(`value: ${shape} tail`);
+ const result = redactUploadText(`value: ${shape} tail`);
expect(result.text).not.toContain(marker);
expect(result.text).toContain("[REDACTED] tail");
expect(result.count).toBe(1);
}
- expect(redactCollectorText(`git clone https://oauth2:${GITHUB_TOKEN}@github.com/acme/widgets.git`))
+ expect(redactUploadText(`git clone https://oauth2:${GITHUB_TOKEN}@github.com/acme/widgets.git`))
.toEqual({ text: "git clone https://[REDACTED]@github.com/acme/widgets.git", count: 1 });
- expect(redactCollectorText("DATABASE_URL=postgres://admin:[email protected]:5432/app"))
+ expect(redactUploadText("DATABASE_URL=postgres://admin:[email protected]:5432/app"))
.toEqual({ text: "DATABASE_URL=postgres://[REDACTED]@db.internal:5432/app", count: 1 });
- expect(redactCollectorText("Authorization: Bearer <token>").count).toBe(0);
+ expect(redactUploadText("Authorization: Bearer <token>").count).toBe(0);
});
test("redacts AWS secret access keys only near an access key id or an aws/secret name", () => {
- expect(redactCollectorText(`AccessKeyId,SecretAccessKey\nAKIAIOSFODNN7EXAMPLE,${AWS_SECRET}\n`).text).toBe("AccessKeyId,SecretAccessKey\n[REDACTED],[REDACTED]\n");
- expect(redactCollectorText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n${AWS_SECRET}`).text).toBe("id: [REDACTED]\n\n\n[REDACTED]");
- expect(redactCollectorText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n\n${AWS_SECRET}`).text).toBe(`id: [REDACTED]\n\n\n\n${AWS_SECRET}`);
- expect(redactCollectorText(`# aws profile\n# region eu-west-1\n${AWS_SECRET}`).text).toBe("# aws profile\n# region eu-west-1\n[REDACTED]");
- expect(redactCollectorText(`${AWS_SECRET}\n\nsecret: yes`).text).toBe("[REDACTED]\n\nsecret: yes");
- expect(redactCollectorText(AWS_SECRET).text).toBe(AWS_SECRET);
- expect(redactCollectorText(`\n\n${AWS_SECRET}`, { context: "AWS master secret.txt" }).text).toBe("\n\n[REDACTED]");
+ expect(redactUploadText(`AccessKeyId,SecretAccessKey\nAKIAIOSFODNN7EXAMPLE,${AWS_SECRET}\n`).text).toBe("AccessKeyId,SecretAccessKey\n[REDACTED],[REDACTED]\n");
+ expect(redactUploadText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n${AWS_SECRET}`).text).toBe("id: [REDACTED]\n\n\n[REDACTED]");
+ expect(redactUploadText(`id: AKIAIOSFODNN7EXAMPLE\n\n\n\n${AWS_SECRET}`).text).toBe(`id: [REDACTED]\n\n\n\n${AWS_SECRET}`);
+ expect(redactUploadText(`# aws profile\n# region eu-west-1\n${AWS_SECRET}`).text).toBe("# aws profile\n# region eu-west-1\n[REDACTED]");
+ expect(redactUploadText(`${AWS_SECRET}\n\nsecret: yes`).text).toBe("[REDACTED]\n\nsecret: yes");
+ expect(redactUploadText(AWS_SECRET).text).toBe(AWS_SECRET);
+ expect(redactUploadText(`\n\n${AWS_SECRET}`, { context: "AWS master secret.txt" }).text).toBe("\n\n[REDACTED]");
// The proximity pass needs three or more lines (two line breaks); a
// shorter document relies on the assignment rule or its JSON key.
- expect(redactCollectorText(`# aws profile\n${AWS_SECRET}`).text).toBe(`# aws profile\n${AWS_SECRET}`);
- expect(redactCollectorText(AWS_SECRET, { context: "AWS master secret.txt" }).text).toBe(AWS_SECRET);
- expect(redactCollectorContent("creds.json", `{"aws_secret_access_key":"${AWS_SECRET}"}`)).toBe('{"aws_secret_access_key":"[REDACTED]"}');
- expect(redactCollectorContent("creds.json", `{"Credentials":{"AccessKeyId":"AKIAIOSFODNN7EXAMPLE","SecretAccessKey":"${AWS_SECRET}"}}`))
+ expect(redactUploadText(`# aws profile\n${AWS_SECRET}`).text).toBe(`# aws profile\n${AWS_SECRET}`);
+ expect(redactUploadText(AWS_SECRET, { context: "AWS master secret.txt" }).text).toBe(AWS_SECRET);
+ expect(redactUploadContent("creds.json", `{"aws_secret_access_key":"${AWS_SECRET}"}`)).toBe('{"aws_secret_access_key":"[REDACTED]"}');
+ expect(redactUploadContent("creds.json", `{"Credentials":{"AccessKeyId":"AKIAIOSFODNN7EXAMPLE","SecretAccessKey":"${AWS_SECRET}"}}`))
.toBe('{"Credentials":{"AccessKeyId":"[REDACTED]","SecretAccessKey":"[REDACTED]"}}');
- expect(redactCollectorContent("creds.env", `AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\nAWS_SECRET_ACCESS_KEY=${AWS_SECRET}\n`))
+ expect(redactUploadContent("creds.env", `AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\nAWS_SECRET_ACCESS_KEY=${AWS_SECRET}\n`))
.toBe("AWS_ACCESS_KEY_ID=[REDACTED]\nAWS_SECRET_ACCESS_KEY=[REDACTED]\n");
// Not mixed case (a git sha), or not exactly 40 characters: left alone.
- expect(redactCollectorText("aws sha 0123456789abcdef0123456789abcdef01234567").text).toContain("0123456789abcdef0123456789abcdef01234567");
- expect(redactCollectorText(`aws ${AWS_SECRET}extra`).text).toContain(AWS_SECRET);
+ expect(redactUploadText("aws sha 0123456789abcdef0123456789abcdef01234567").text).toContain("0123456789abcdef0123456789abcdef01234567");
+ expect(redactUploadText(`aws ${AWS_SECRET}extra`).text).toContain(AWS_SECRET);
});
test("selects the value rule mode from the file extension", () => {
@@ -1811,9 +1811,9 @@ describe("workspace collector secret rails", () => {
["a.rb", "token = getToken(12345678)"],
["a.sh", 'TOKEN="$(cat token1.txt)"'],
];
- for (const [path, text] of sampled) expect(redactCollectorContent(path, text)).toBe(text);
- expect(redactCollectorText("+const auth = req.headers.authorization || '';", { context: "middleware.js" })).toEqual({ text: "+const auth = req.headers.authorization || '';", count: 0 });
- expect(filterCollectorDiff("diff --git a/m.js b/m.js\n+const auth = req.headers.authorization || '';\n").diff)
+ for (const [path, text] of sampled) expect(redactUploadContent(path, text)).toBe(text);
+ expect(redactUploadText("+const auth = req.headers.authorization || '';", { context: "middleware.js" })).toEqual({ text: "+const auth = req.headers.authorization || '';", count: 0 });
+ expect(filterUploadDiff("diff --git a/m.js b/m.js\n+const auth = req.headers.authorization || '';\n").diff)
.toBe("diff --git a/m.js b/m.js\n+const auth = req.headers.authorization || '';\n");
const secrets: Array<[string, string, string]> = [
@@ -1833,16 +1833,16 @@ describe("workspace collector secret rails", () => {
["request.js", "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", "Authorization: Bearer [REDACTED]"],
];
for (const [path, text, expected] of secrets) {
- expect(redactCollectorContent(path, text)).toBe(expected);
- expect(redactCollectorText(text, { mode: redactModeForPath(path) }).count).toBe(1);
+ expect(redactUploadContent(path, text)).toBe(expected);
+ expect(redactUploadText(text, { mode: redactModeForPath(path) }).count).toBe(1);
}
// Excluded last segments never name a secret, in either mode.
for (const last of ["file", "filename", "dir", "mode", "method", "role", "owner", "type", "kind", "enabled", "estimate", "hash", "digest", "at",
"config", "client", "prefix", "suffix", "format", "scheme", "provider", "status", "state", "label", "description", "title", "class", "field",
"fields", "list", "names", "version", "timeout", "limit", "max", "min", "interval", "retries", "port"]) {
const line = `token_${last}: abcdefgh1234`;
- expect(redactCollectorContent("x.yml", line)).toBe(line);
- expect(redactCollectorContent("x.py", line)).toBe(line);
+ expect(redactUploadContent("x.yml", line)).toBe(line);
+ expect(redactUploadContent("x.py", line)).toBe(line);
}
});
@@ -1856,28 +1856,28 @@ describe("workspace collector secret rails", () => {
"Authorization: Bearer abcdefghijklmnopqrstuvwxyz",
"Authorization: Bearer ABCDEFGHIJKLMNOPQRSTUVWXYZ",
];
- for (const line of kept) expect(redactCollectorText(line)).toEqual({ text: line, count: 0 });
+ for (const line of kept) expect(redactUploadText(line)).toEqual({ text: line, count: 0 });
const redacted = [
"Authorization: Bearer abcdefghijklmnopqrstuvwxyz0123",
"Authorization: Bearer a8f3b2c9d4e5f6a7b8c9d0e1",
"Authorization: Bearer Your-Access-Token-Goes-Here",
"Authorization: Bearer AbCdEfGhIjKlMnOpQrStUv/wx+yz==",
];
- for (const line of redacted) expect(redactCollectorText(line)).toEqual({ text: "Authorization: Bearer [REDACTED]", count: 1 });
- expect(redactCollectorText("authorization: bearer abcdefghijklmnopqrstuvwxyz0123")).toEqual({ text: "authorization: bearer [REDACTED]", count: 1 });
+ for (const line of redacted) expect(redactUploadText(line)).toEqual({ text: "Authorization: Bearer [REDACTED]", count: 1 });
+ expect(redactUploadText("authorization: bearer abcdefghijklmnopqrstuvwxyz0123")).toEqual({ text: "authorization: bearer [REDACTED]", count: 1 });
});
test("keeps a source file named after a token but redacts the literal inside it", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-source-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-source-"));
roots.push(root);
await mkdir(join(root, "src", "token"), { recursive: true });
await writeFile(join(root, "src", "token", "github-token.ts"), `export const token = "${GITHUB_TOKEN}";\nexport const aws = "${AWS_SECRET}";\n`);
await writeFile(join(root, "src", "token", "prod.env"), `GITHUB_TOKEN=${GITHUB_TOKEN}\n`);
await writeFile(join(root, "README.md"), `Deploy with\n\n export CLIENT_SECRET=${GITHUB_TOKEN}\n`);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
- collector.startSession("session-source-1", "workspace-source", root);
- await collector.stop();
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
+ sessionUploader.startSession("session-source-1", "workspace-source", root);
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start")!;
expect(start.manifest.map((entry) => entry.path).sort()).toEqual(["README.md", "src/token/github-token.ts"]);
@@ -1891,18 +1891,18 @@ describe("workspace collector secret rails", () => {
});
test("scrubs the trace and .json files as JSON so escapes survive redaction", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-json-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-json-"));
roots.push(root);
await writeFile(join(root, "config.json"), '{\n "note": "{\\"password\\":\\"hunter2abc\\"}",\n "nested": {"apiKey": "abcdefghijkl", "author": "Jane <[email protected]>"}\n}\n');
await writeFile(join(root, "settings.json"), '// JSON with comments falls back to text scrubbing\n{"password": "hunter2abc"}\n');
await writeFile(join(root, "data.json"), '{"a": 1.0, "b": [1, 2]}');
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
const sessionId = "session-json-1";
- collector.startSession(sessionId, "workspace-json", root);
- collector.recordTrace(sessionId, "message", { text: 'line one\[email protected](gpu="h100")\[email protected]', token: GITHUB_TOKEN });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-json", root);
+ sessionUploader.recordTrace(sessionId, "message", { text: 'line one\[email protected](gpu="h100")\[email protected]', token: GITHUB_TOKEN });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const trace = uploads.find((item) => item.snapshot_type === "trace")!;
const parsed = JSON.parse(trace.files[0]!.content) as { events: Array<{ type: string; data?: Record<string, unknown> }> };
@@ -1926,26 +1926,26 @@ describe("workspace collector secret rails", () => {
test("never leaves a dangling backslash when scrubbing escaped text", () => {
const raw = JSON.stringify({ text: `line one\[email protected](gpu="h100")\[email protected]\[email protected]\tAKIAIOSFODNN7EXAMPLE\nTOKEN=${GITHUB_TOKEN}` });
- const result = redactCollectorText(raw);
+ const result = redactUploadText(raw);
expect(JSON.parse(result.text)).toEqual({ text: 'line one\[email protected](gpu="h100")\n[REDACTED_PII]\n[REDACTED_PII]\t[REDACTED]\nTOKEN=[REDACTED]' });
expect(result.count).toBe(4);
- expect(redactCollectorText("password=\"abcdefgh\\\"more\"").text).toBe("password=\"[REDACTED]\"");
+ expect(redactUploadText("password=\"abcdefgh\\\"more\"").text).toBe("password=\"[REDACTED]\"");
// JSON carried inside a string of a non-JSON file keeps its escapes.
const embedded = JSON.stringify({ text: JSON.stringify({ password: "hunter2abc", user: "jane" }) });
- expect(JSON.parse(redactCollectorText(embedded).text)).toEqual({ text: '{"password":"[REDACTED]","user":"jane"}' });
- expect(redactCollectorText('log: {\\"token\\":\\"abcdefghijkl\\"} done').text).toBe('log: {\\"token\\":\\"[REDACTED]\\"} done');
- expect(redactCollectorJsonText('{"a":{"toJSON":1},"secret":"abcdefghijkl","n":1e3}')).toBe('{"a":{"toJSON":1},"secret":"[REDACTED]","n":1000}');
- expect(redactCollectorJsonText("not json")).toBeNull();
+ expect(JSON.parse(redactUploadText(embedded).text)).toEqual({ text: '{"password":"[REDACTED]","user":"jane"}' });
+ expect(redactUploadText('log: {\\"token\\":\\"abcdefghijkl\\"} done').text).toBe('log: {\\"token\\":\\"[REDACTED]\\"} done');
+ expect(redactUploadJsonText('{"a":{"toJSON":1},"secret":"abcdefghijkl","n":1e3}')).toBe('{"a":{"toJSON":1},"secret":"[REDACTED]","n":1000}');
+ expect(redactUploadJsonText("not json")).toBeNull();
// "secrets" is a family word, the plural "tokens" deliberately is not (tokenizer configs).
- expect(redactCollectorJson({ at: new Date(0), secrets: ["abcdefghijkl", "short"], tokens: ["abcdefghijkl"], "[email protected]": 1 }))
+ expect(redactUploadJson({ at: new Date(0), secrets: ["abcdefghijkl", "short"], tokens: ["abcdefghijkl"], "[email protected]": 1 }))
.toEqual({ value: { at: "1970-01-01T00:00:00.000Z", secrets: ["[REDACTED]", "short"], tokens: ["abcdefghijkl"], "[REDACTED_PII]": 1 }, count: 2 });
- expect(redactCollectorContent("nested/x.JSON", '{"password":"hunter2abc"}')).toBe('{"password":"[REDACTED]"}');
- expect(redactCollectorContent("x.txt", '{"password":"hunter2abc"}')).toBe('{"password":"[REDACTED]"}');
+ expect(redactUploadContent("nested/x.JSON", '{"password":"hunter2abc"}')).toBe('{"password":"[REDACTED]"}');
+ expect(redactUploadContent("x.txt", '{"password":"hunter2abc"}')).toBe('{"password":"[REDACTED]"}');
});
test("scrubs diff hunks of JSON files as text", () => {
const raw = ["diff --git a/config.json b/config.json", "--- a/config.json", "+++ b/config.json", "@@ -1 +1 @@", '+ "password": "hunter2abc",', ""].join("\n");
- const result = filterCollectorDiff(raw);
+ const result = filterUploadDiff(raw);
expect(result.diff).toContain('+ "password": "[REDACTED]",');
expect(result.diff).not.toContain("hunter2abc");
});
@@ -1953,14 +1953,14 @@ describe("workspace collector secret rails", () => {
test("redacts assignments and e-mails on whichever line they sit, never across a line break", () => {
// Both rules are applied only to lines holding their keyword or "@"; the
// result must equal a whole-text pass, line endings and escapes included.
- expect(redactCollectorContent("notes.txt", "first line\npassword=hunter2hunter2\r\nlast")).toBe("first line\npassword=[REDACTED]\r\nlast");
- expect(redactCollectorContent("notes.txt", "a@b\[email protected]\n@x\[email protected]")).toBe("a@b\n[REDACTED_PII]\n@x\n[REDACTED_PII]");
- expect(redactCollectorContent("notes.txt", "jane@\nexample.com and key\n=abcdefgh12")).toBe("jane@\nexample.com and key\n=abcdefgh12");
- expect(redactCollectorContent("run.sh", "echo done \\\nexport API_KEY=abc123def456\nTOKEN='S3cretValue99'"))
+ expect(redactUploadContent("notes.txt", "first line\npassword=hunter2hunter2\r\nlast")).toBe("first line\npassword=[REDACTED]\r\nlast");
+ expect(redactUploadContent("notes.txt", "a@b\[email protected]\n@x\[email protected]")).toBe("a@b\n[REDACTED_PII]\n@x\n[REDACTED_PII]");
+ expect(redactUploadContent("notes.txt", "jane@\nexample.com and key\n=abcdefgh12")).toBe("jane@\nexample.com and key\n=abcdefgh12");
+ expect(redactUploadContent("run.sh", "echo done \\\nexport API_KEY=abc123def456\nTOKEN='S3cretValue99'"))
.toBe("echo done \\\nexport API_KEY=abc123def456\nTOKEN='[REDACTED]'");
- expect(redactCollectorContent("app.ts", "const keyName = config.token;\nconst apiKey = \"sk-proj-abcdefghijklmnop1234\";\n// contact: [email protected]"))
+ expect(redactUploadContent("app.ts", "const keyName = config.token;\nconst apiKey = \"sk-proj-abcdefghijklmnop1234\";\n// contact: [email protected]"))
.toBe("const keyName = config.token;\nconst apiKey = \"[REDACTED]\";\n// contact: [REDACTED_PII]");
- expect(redactCollectorContent("data.json", "{\n \"note\": \"line\\npassword=hunter2hunter2\",\n \"author\": \"[email protected]\"\n}\n"))
+ expect(redactUploadContent("data.json", "{\n \"note\": \"line\\npassword=hunter2hunter2\",\n \"author\": \"[email protected]\"\n}\n"))
.toBe("{\n \"note\": \"line\\npassword=[REDACTED]\",\n \"author\": \"[REDACTED_PII]\"\n}\n");
});
@@ -1988,7 +1988,7 @@ describe("workspace collector secret rails", () => {
for (const line of lines) {
for (const mode of ["config", "source"] as const) {
const started = performance.now();
- redactCollectorText(line, { mode });
+ redactUploadText(line, { mode });
expect(performance.now() - started).toBeLessThan(2_000);
}
}
@@ -2035,7 +2035,7 @@ const PATCH = [
"",
].join("\n");
-describe("workspace collector scrubber parity: second-sample refinements", () => {
+describe("session uploader scrubber parity: second-sample refinements", () => {
test("secret-named keys follow the segment rule (test_secret_key_rule_qualifies / _does_not_qualify)", () => {
for (const key of ["auth_token", "basic-auth", "AUTH", "authorization", "oauth_client_secret", "APIKey", "accessKey", "HTTPSecret", "token2",
"secrets", "client.secret", "x-api-key"]) {
@@ -2067,15 +2067,15 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
expect(isSecretAssignmentKey(`${word}_token`)).toBe(true);
// The same through the text rule, in both modes.
for (const mode of ["config", "source"] as const) {
- expect(redactCollectorText(`token_${word} = "abcdefgh1234"`, { mode }).count).toBe(0);
- expect(redactCollectorText(`${word}_token = "abcdefgh1234"`, { mode })).toEqual({ text: `${word}_token = "[REDACTED]"`, count: 1 });
+ expect(redactUploadText(`token_${word} = "abcdefgh1234"`, { mode }).count).toBe(0);
+ expect(redactUploadText(`${word}_token = "abcdefgh1234"`, { mode })).toEqual({ text: `${word}_token = "[REDACTED]"`, count: 1 });
}
}
});
test("auth_code and *_plaintext stay secret-named (test_auth_code_and_plaintext_keys_stay_secret_named)", () => {
const text = 'auth_code = "abcdefgh1234"\npassword_plaintext = "hunter2abc"\n# TOKEN = "abcdefgh1234"\n';
- const result = redactCollectorText(text, { context: "app.py", mode: "source" });
+ const result = redactUploadText(text, { context: "app.py", mode: "source" });
expect(result.text).not.toContain("abcdefgh1234");
expect(result.text).not.toContain("hunter2abc");
expect(result.count).toBe(3);
@@ -2167,11 +2167,11 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
['this.token = "hunter2abc"', 'this.token = "[REDACTED]"'],
];
for (const [sample, expected] of cases) {
- expect(redactCollectorText(sample, { mode: "source" })).toEqual(expected === null ? { text: sample, count: 0 } : { text: expected, count: 1 });
+ expect(redactUploadText(sample, { mode: "source" })).toEqual(expected === null ? { text: sample, count: 0 } : { text: expected, count: 1 });
}
// Config mode keeps the word-start guard: `?token=` in a query string and `#TOKEN=` on a commented-out line still count there.
- expect(redactCollectorText("https://x/?token=abc-123-def")).toEqual({ text: "https://x/?token=[REDACTED]", count: 1 });
- expect(redactCollectorText("#TOKEN=abc-123-def")).toEqual({ text: "#TOKEN=[REDACTED]", count: 1 });
+ expect(redactUploadText("https://x/?token=abc-123-def")).toEqual({ text: "https://x/?token=[REDACTED]", count: 1 });
+ expect(redactUploadText("#TOKEN=abc-123-def")).toEqual({ text: "#TOKEN=[REDACTED]", count: 1 });
});
test("limit-style keys are excluded in both modes (test_limit_style_keys_are_excluded_in_both_modes)", () => {
@@ -2181,8 +2181,8 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
"password_encryption='scram-sha-256'", "provider_credential_ref: 'iproyal:claude-in-001'", "secret_envelope: params[8]",
"token_expires_in = 15897600", "secret_algorithm = 'aes-256-gcm'", 'auth_callback = "https://x/cb?state=abc12345"',
]) {
- expect(redactCollectorText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
- expect(redactCollectorText(sample, { mode: "config" })).toEqual({ text: sample, count: 0 });
+ expect(redactUploadText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
+ expect(redactUploadText(sample, { mode: "config" })).toEqual({ text: sample, count: 0 });
}
});
@@ -2195,70 +2195,70 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
["build/source-hashes.json", SAMPLE2_HASHES],
["tests/fixtures.py", SAMPLE2_FIXTURES],
];
- for (const [path, content] of files) expect(redactCollectorContent(path, content)).toBe(content);
- for (const sample of [SAMPLE2_TS, SAMPLE2_SH, SAMPLE2_FIXTURES]) expect(redactCollectorText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
- for (const sample of [SAMPLE2_CONF, SAMPLE2_YML]) expect(redactCollectorText(sample)).toEqual({ text: sample, count: 0 });
+ for (const [path, content] of files) expect(redactUploadContent(path, content)).toBe(content);
+ for (const sample of [SAMPLE2_TS, SAMPLE2_SH, SAMPLE2_FIXTURES]) expect(redactUploadText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
+ for (const sample of [SAMPLE2_CONF, SAMPLE2_YML]) expect(redactUploadText(sample)).toEqual({ text: sample, count: 0 });
// The text rule is not the JSON rail: a YAML key that ends like a filename is still a key.
- expect(redactCollectorText("admin_auth.py: abcdefgh1234")).toEqual({ text: "admin_auth.py: [REDACTED]", count: 1 });
+ expect(redactUploadText("admin_auth.py: abcdefgh1234")).toEqual({ text: "admin_auth.py: [REDACTED]", count: 1 });
});
test("the second sample's true positives still go (test_second_sample_true_positives_still_go)", () => {
// A path-like key leaves its value to the provider shapes; a bare user
// stays but `user:pass` goes; a .patch file is source, so `config.token`
// is a reference and `"hunter2abc"` a literal.
- expect(redactCollectorContent("build/source-hashes.json", `{"src/x.py": "${GITHUB_TOKEN}"}`)).toBe('{"src/x.py":"[REDACTED]"}');
- expect(redactCollectorJson({ "src/x.py": GITHUB_TOKEN })).toEqual({ value: { "src/x.py": "[REDACTED]" }, count: 1 });
- expect(redactCollectorContent("tests/fixtures.py", "LIVE_DSN = 'postgres://live:secret@host/db'\n")).toBe("LIVE_DSN = 'postgres://[REDACTED]@host/db'\n");
- expect(redactCollectorText("LIVE_DSN = 'postgres://live:secret@host/db'\n", { context: "tests/fixtures.py", mode: "source" }).count).toBe(1);
- expect(redactCollectorContent("fix.patch", PATCH)).toBe(PATCH.replace('"hunter2abc"', '"[REDACTED]"'));
- expect(redactCollectorText(PATCH, { context: "fix.patch", mode: redactModeForPath("fix.patch") }).count).toBe(1);
+ expect(redactUploadContent("build/source-hashes.json", `{"src/x.py": "${GITHUB_TOKEN}"}`)).toBe('{"src/x.py":"[REDACTED]"}');
+ expect(redactUploadJson({ "src/x.py": GITHUB_TOKEN })).toEqual({ value: { "src/x.py": "[REDACTED]" }, count: 1 });
+ expect(redactUploadContent("tests/fixtures.py", "LIVE_DSN = 'postgres://live:secret@host/db'\n")).toBe("LIVE_DSN = 'postgres://[REDACTED]@host/db'\n");
+ expect(redactUploadText("LIVE_DSN = 'postgres://live:secret@host/db'\n", { context: "tests/fixtures.py", mode: "source" }).count).toBe(1);
+ expect(redactUploadContent("fix.patch", PATCH)).toBe(PATCH.replace('"hunter2abc"', '"[REDACTED]"'));
+ expect(redactUploadText(PATCH, { context: "fix.patch", mode: redactModeForPath("fix.patch") }).count).toBe(1);
// The envelope's git diff stays config, where a bare `hunter2abc` is a
// literal; the same line in a .patch file is a name.
- expect(filterCollectorDiff("diff --git a/app/settings.py b/app/settings.py\n+password = hunter2abc\n").diff)
+ expect(filterUploadDiff("diff --git a/app/settings.py b/app/settings.py\n+password = hunter2abc\n").diff)
.toBe("diff --git a/app/settings.py b/app/settings.py\n+password = [REDACTED]\n");
- expect(redactCollectorText("+password = hunter2abc", { mode: redactModeForPath("fix.patch") })).toEqual({ text: "+password = hunter2abc", count: 0 });
+ expect(redactUploadText("+password = hunter2abc", { mode: redactModeForPath("fix.patch") })).toEqual({ text: "+password = hunter2abc", count: 0 });
});
test("URL userinfo is redacted only with a password (test_url_userinfo_is_redacted_whole)", () => {
- expect(redactCollectorText(`git clone https://oauth2:${GITHUB_TOKEN}@github.com/acme/widgets.git`))
+ expect(redactUploadText(`git clone https://oauth2:${GITHUB_TOKEN}@github.com/acme/widgets.git`))
.toEqual({ text: "git clone https://[REDACTED]@github.com/acme/widgets.git", count: 1 });
- expect(redactCollectorText("DATABASE_URL=postgres://admin:[email protected]:5432/app"))
+ expect(redactUploadText("DATABASE_URL=postgres://admin:[email protected]:5432/app"))
.toEqual({ text: "DATABASE_URL=postgres://[REDACTED]@db.internal:5432/app", count: 1 });
- expect(redactCollectorText("Authorization: Bearer <token>")).toEqual({ text: "Authorization: Bearer <token>", count: 0 });
+ expect(redactUploadText("Authorization: Bearer <token>")).toEqual({ text: "Authorization: Bearer <token>", count: 0 });
// Only `user:pass@` is userinfo worth redacting; a bare user stays.
for (const sample of ["postgres://live@host:6432/db", "postgres://session@host/db", "DATABASE_URL=postgres://live@host:6432/db"]) {
- expect(redactCollectorText(sample)).toEqual({ text: sample, count: 0 });
- expect(redactCollectorText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
+ expect(redactUploadText(sample)).toEqual({ text: sample, count: 0 });
+ expect(redactUploadText(sample, { mode: "source" })).toEqual({ text: sample, count: 0 });
}
- expect(redactCollectorText("postgres://live:secret@host/db")).toEqual({ text: "postgres://[REDACTED]@host/db", count: 1 });
+ expect(redactUploadText("postgres://live:secret@host/db")).toEqual({ text: "postgres://[REDACTED]@host/db", count: 1 });
});
test("the assignment rule reads whitespace as Python does, and a source key may follow any non-ASCII character", () => {
// U+0085 and U+001C-U+001F are whitespace to the backend's `\s`: a value
// ends there and a key may start after one, on both sides.
- expect(redactCollectorText("token=abc-123-def\u0085tail", { mode: "source" })).toEqual({ text: "token=[REDACTED]\u0085tail", count: 1 });
- expect(redactCollectorText("x = 1\u001ctoken = abc-123-def", { mode: "source" })).toEqual({ text: "x = 1\u001ctoken = [REDACTED]", count: 1 });
+ expect(redactUploadText("token=abc-123-def\u0085tail", { mode: "source" })).toEqual({ text: "token=[REDACTED]\u0085tail", count: 1 });
+ expect(redactUploadText("x = 1\u001ctoken = abc-123-def", { mode: "source" })).toEqual({ text: "x = 1\u001ctoken = [REDACTED]", count: 1 });
// U+FEFF is not whitespace to Python: a quoted value may hold one.
- expect(redactCollectorText('"token": "abc\ufeff12345"')).toEqual({ text: '"token": "[REDACTED]"', count: 1 });
+ expect(redactUploadText('"token": "abc\ufeff12345"')).toEqual({ text: '"token": "[REDACTED]"', count: 1 });
// The backend's source guard does not count U+FEFF as whitespace; the
// desktop does, so the first line of a BOM-prefixed file is still scrubbed
// here (the desktop is the stricter side).
- expect(redactCollectorContent("settings.py", '\ufeffpassword = "hunter2abc"\n')).toBe('\ufeffpassword = "[REDACTED]"\n');
+ expect(redactUploadContent("settings.py", '\ufeffpassword = "hunter2abc"\n')).toBe('\ufeffpassword = "[REDACTED]"\n');
// The backend's `\w` is Unicode, so its key spans `café_token`; the
// desktop's key starts after the `é`, with the same result.
- expect(redactCollectorText("café_token = 'hunter2abc'", { mode: "source" })).toEqual({ text: "café_token = '[REDACTED]'", count: 1 });
+ expect(redactUploadText("café_token = 'hunter2abc'", { mode: "source" })).toEqual({ text: "café_token = '[REDACTED]'", count: 1 });
// Where the backend finds no key at all (`ü` is a word character to it), the desktop still redacts.
- expect(redactCollectorText("ütoken = 'hunter2abc'", { mode: "source" })).toEqual({ text: "ütoken = '[REDACTED]'", count: 1 });
+ expect(redactUploadText("ütoken = 'hunter2abc'", { mode: "source" })).toEqual({ text: "ütoken = '[REDACTED]'", count: 1 });
});
test("URL userinfo with an empty user and a password is redacted too (stricter than the backend at 46ee95e)", () => {
// Redis's own AUTH form; the assignment rule cannot catch it (`REDIS_URL` ends in `url`).
- expect(redactCollectorContent("config/app.env", "REDIS_URL=redis://:p4ssw0rd@cache:6379/0\n")).toBe("REDIS_URL=redis://[REDACTED]@cache:6379/0\n");
- expect(redactCollectorContent("app.py", 'url = "rediss://:hunter2abc@cache:6380/0"\n')).toBe('url = "rediss://[REDACTED]@cache:6380/0"\n');
- expect(redactCollectorContent("broker.yml", "broker: amqp://:s3cretpw@mq:5672//\n")).toBe("broker: amqp://[REDACTED]@mq:5672//\n");
+ expect(redactUploadContent("config/app.env", "REDIS_URL=redis://:p4ssw0rd@cache:6379/0\n")).toBe("REDIS_URL=redis://[REDACTED]@cache:6379/0\n");
+ expect(redactUploadContent("app.py", 'url = "rediss://:hunter2abc@cache:6380/0"\n')).toBe('url = "rediss://[REDACTED]@cache:6380/0"\n');
+ expect(redactUploadContent("broker.yml", "broker: amqp://:s3cretpw@mq:5672//\n")).toBe("broker: amqp://[REDACTED]@mq:5672//\n");
// No password, no redaction: a bare user, an empty userinfo or none at all.
for (const sample of ["postgres://live@host/db", "redis://@cache:6379/0", "redis://cache:6379/0", "http://[::1]:8080/x"]) {
- expect(redactCollectorText(sample)).toEqual({ text: sample, count: 0 });
+ expect(redactUploadText(sample)).toEqual({ text: sample, count: 0 });
}
});
@@ -2285,7 +2285,7 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
// Nothing near names an AWS key: a 40-character run is data.
"plain.json": `{"hash": "${AWS_SECRET}"}`,
};
- const out = Object.fromEntries(Object.entries(files).map(([path, content]) => [path, redactCollectorContent(path, content)]));
+ const out = Object.fromEntries(Object.entries(files).map(([path, content]) => [path, redactUploadContent(path, content)]));
for (const [path, content] of Object.entries(out)) {
JSON.parse(content);
expect(content.includes(AWS_SECRET)).toBe(path === "plain.json");
@@ -2300,11 +2300,11 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
expect(JSON.parse(out["escaped.json"]!)).toEqual({ name: "AWS_SECRET_ACCESS_KEY", value: "[REDACTED]" });
expect(out["plain.json"]).toBe(files["plain.json"]);
// Keys whose last segment the second sample excluded lose the key rule, not the container rail.
- expect(redactCollectorContent("a.json", `{"secret_envelope": "${AWS_SECRET}"}`)).toBe('{"secret_envelope":"[REDACTED]"}');
- expect(redactCollectorContent("a.json", `{"aws_secret_ref": "${AWS_SECRET}"}`)).toBe('{"aws_secret_ref":"[REDACTED]"}');
- expect(redactCollectorContent("a.json", `{\n "db": {\n "secret_alias": "${AWS_SECRET}"\n }\n}`))
+ expect(redactUploadContent("a.json", `{"secret_envelope": "${AWS_SECRET}"}`)).toBe('{"secret_envelope":"[REDACTED]"}');
+ expect(redactUploadContent("a.json", `{"aws_secret_ref": "${AWS_SECRET}"}`)).toBe('{"aws_secret_ref":"[REDACTED]"}');
+ expect(redactUploadContent("a.json", `{\n "db": {\n "secret_alias": "${AWS_SECRET}"\n }\n}`))
.toBe('{\n "db": {\n "secret_alias": "[REDACTED]"\n }\n}');
- expect(redactCollectorContent("a.json", `{"src/secret.py": "${AWS_SECRET}"}`)).toBe('{"src/secret.py":"[REDACTED]"}');
+ expect(redactUploadContent("a.json", `{"src/secret.py": "${AWS_SECRET}"}`)).toBe('{"src/secret.py":"[REDACTED]"}');
});
test("trace AWS secrets need their key or a container naming AWS (test_trace_artifact_aws_secrets_need_key_or_container_context)", async () => {
@@ -2316,7 +2316,7 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
{ type: "tool.call", data: { name: "AWS_SECRET_ACCESS_KEY", value: AWS_SECRET } },
],
};
- const { value, count } = redactCollectorJson(document);
+ const { value, count } = redactUploadJson(document);
expect(JSON.parse(JSON.stringify(value)).events.map((event: { data: unknown }) => event.data)).toEqual([
{ note: "id [REDACTED]" },
{ note: AWS_SECRET },
@@ -2326,16 +2326,16 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
expect(count).toBe(3);
// The uploaded trace document gets the same rail.
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-trace-aws-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-trace-aws-"));
roots.push(root);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-trace-aws-1234";
- collector.startSession(sessionId, "workspace-trace-aws", root);
- await collector.idle(sessionId);
- collector.recordTrace(sessionId, "tool.call", { name: "AWS_SECRET_ACCESS_KEY", value: AWS_SECRET });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-trace-aws", root);
+ await sessionUploader.idle(sessionId);
+ sessionUploader.recordTrace(sessionId, "tool.call", { name: "AWS_SECRET_ACCESS_KEY", value: AWS_SECRET });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
expect(JSON.stringify(uploads)).not.toContain(AWS_SECRET);
const trace = uploads.find((item) => item.snapshot_type === "trace")!;
expect(trace.trace?.find((event) => event.type === "tool.call")?.data).toEqual({ name: "AWS_SECRET_ACCESS_KEY", value: "[REDACTED]" });
@@ -2359,19 +2359,19 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
[`{"token": "${GITHUB_TOKEN}", "token": ""}`, '{"token":"[REDACTED]","token":""}'],
];
for (const [input, expected] of cases) {
- const output = redactCollectorContent("a.json", input);
+ const output = redactUploadContent("a.json", input);
expect(output).toBe(expected);
JSON.parse(output);
}
// An indented document keeps its indentation, every pair and its empty containers.
- expect(redactCollectorContent("a.json", '{\n "x": {"password": "hunter2abc", "password": "y"},\n "e": [],\n "o": {}\n}\n'))
+ expect(redactUploadContent("a.json", '{\n "x": {"password": "hunter2abc", "password": "y"},\n "e": [],\n "o": {}\n}\n'))
.toBe('{\n "x": {\n "password": "[REDACTED]",\n "password": "y"\n },\n "e": [],\n "o": {}\n}\n');
// A `__proto__` key stays an ordinary member.
- expect(redactCollectorContent("a.json", '{"__proto__": {"password": "hunter2abc"}}')).toBe('{"__proto__":{"password":"[REDACTED]"}}');
+ expect(redactUploadContent("a.json", '{"__proto__": {"password": "hunter2abc"}}')).toBe('{"__proto__":{"password":"[REDACTED]"}}');
});
test("a .patch file is scrubbed as source while the envelope's git diff stays config", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-patch-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-patch-"));
roots.push(root);
await git(root, "init", "-q");
await mkdir(join(root, "app"), { recursive: true });
@@ -2382,9 +2382,9 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
await writeFile(join(root, "fix.patch"), PATCH);
await writeFile(join(root, "notes.diff"), "+password = hunter2abc\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
- collector.startSession("session-patch-1", "workspace-patch", root);
- await collector.stop();
+ const sessionUploader = new SessionUploader({ upload, fallbackScanMs: 60_000 });
+ sessionUploader.startSession("session-patch-1", "workspace-patch", root);
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start")!;
const content = (path: string) => start.files.find((file) => file.path === path)?.content;
@@ -2401,18 +2401,18 @@ describe("workspace collector scrubber parity: second-sample refinements", () =>
// --- gateway auth: stale device tokens ---------------------------------------
-describe("workspace collector gateway auth", () => {
+describe("session uploader gateway auth", () => {
type Warning = { message: string; attributes?: Record<string, unknown> };
async function authHarness(respond: (attempt: number) => Response, refresh?: () => Promise<string | null>) {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-auth-"));
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-auth-state-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-auth-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-auth-state-"));
roots.push(root, stateDir);
await writeFile(join(root, "app.txt"), "hello\n");
const uploads: Envelope[] = [];
const warnings: Warning[] = [];
const counters = { attempts: 0, refreshes: 0 };
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (_sessionId, compressed) => {
counters.attempts += 1;
@@ -2434,34 +2434,34 @@ describe("workspace collector gateway auth", () => {
retryBaseMs: 60_000,
});
const sessionId = "session-auth-1234";
- collector.startSession(sessionId, "workspace-auth", root);
- await collector.idle(sessionId);
- const rejected = warnings.filter((warning) => warning.message === "OmniRush collection upload rejected as unauthorized");
- return { collector, sessionId, uploads, warnings, rejected, counters };
+ sessionUploader.startSession(sessionId, "workspace-auth", root);
+ await sessionUploader.idle(sessionId);
+ const rejected = warnings.filter((warning) => warning.message === "OmniRush session upload upload rejected as unauthorized");
+ return { sessionUploader, sessionId, uploads, warnings, rejected, counters };
}
const unauthorized = (status: number, body: unknown = { error: "token_expired" }) => Response.json(body, { status });
const created = () => Response.json({ ok: true }, { status: 201 });
test("refreshes the access token after a 401 and retries the upload once", async () => {
- const { collector, sessionId, uploads, rejected, counters } = await authHarness(
+ const { sessionUploader, sessionId, uploads, rejected, counters } = await authHarness(
(attempt) => (attempt === 1 ? unauthorized(401) : created()),
async () => "fresh-token",
);
expect(counters).toEqual({ attempts: 2, refreshes: 1 });
expect(uploads.map((item) => [item.snapshot_type, item.sequence])).toEqual([["start", 1]]);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 0 });
- expect(rejected).toEqual([{ message: "OmniRush collection upload rejected as unauthorized", attributes: { sessionId, status: 401, refreshed: true } }]);
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ expect(await sessionUploader.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 0 });
+ expect(rejected).toEqual([{ message: "OmniRush session upload upload rejected as unauthorized", attributes: { sessionId, status: 401, refreshed: true } }]);
+ await sessionUploader.stop();
});
- test("sends the refreshed bearer when retrying over the collect endpoint", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-auth-fetch-"));
+ test("sends the refreshed bearer when retrying over the session upload endpoint", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-auth-fetch-"));
roots.push(root);
await writeFile(join(root, "app.txt"), "hello\n");
const bearers: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
gatewayUrl: "https://gateway.example.test/v1",
accessToken: "stale-token",
fetch: async (_input: string, init?: RequestInit) => {
@@ -2473,76 +2473,76 @@ describe("workspace collector gateway auth", () => {
uploadRetryDelayMs: 1,
});
const sessionId = "session-auth-fetch-1234";
- collector.startSession(sessionId, "workspace-auth", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-auth", root);
+ await sessionUploader.idle(sessionId);
expect(bearers).toEqual(["Bearer stale-token", "Bearer fresh-token"]);
- await collector.stop();
+ await sessionUploader.stop();
expect(bearers.at(-1)).toBe("Bearer fresh-token");
});
test("spools the upload when the gateway still rejects the refreshed token", async () => {
- const { collector, sessionId, uploads, warnings, rejected, counters } = await authHarness(() => unauthorized(401), async () => "fresh-token");
+ const { sessionUploader, sessionId, uploads, warnings, rejected, counters } = await authHarness(() => unauthorized(401), async () => "fresh-token");
expect(counters).toEqual({ attempts: 2, refreshes: 1 });
expect(uploads).toHaveLength(0);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
- expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(await sessionUploader.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
expect(rejected).toHaveLength(1);
- expect(warnings.map((warning) => warning.message)).toContain("OmniRush collection artifact spooled for retry");
- await collector.stop();
+ expect(warnings.map((warning) => warning.message)).toContain("OmniRush session upload artifact spooled for retry");
+ await sessionUploader.stop();
});
test("spools the upload when the token refresh fails", async () => {
- const { collector, sessionId, uploads, rejected, counters } = await authHarness(
+ const { sessionUploader, sessionId, uploads, rejected, counters } = await authHarness(
(attempt) => (attempt === 1 ? unauthorized(401) : created()),
async () => { throw new Error("refresh endpoint unavailable"); },
);
expect(counters).toEqual({ attempts: 1, refreshes: 1 });
expect(uploads).toHaveLength(0);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
expect(rejected).toEqual([{
- message: "OmniRush collection upload rejected as unauthorized",
+ message: "OmniRush session upload upload rejected as unauthorized",
attributes: { sessionId, status: 401, refreshed: false, refreshError: "refresh endpoint unavailable" },
}]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("spools the upload when no token refresh is available", async () => {
- const { collector, uploads, rejected, counters } = await authHarness((attempt) => (attempt === 1 ? unauthorized(401) : created()));
+ const { sessionUploader, uploads, rejected, counters } = await authHarness((attempt) => (attempt === 1 ? unauthorized(401) : created()));
expect(counters).toEqual({ attempts: 1, refreshes: 0 });
expect(uploads).toHaveLength(0);
- expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(await sessionUploader.spoolStatus()).toMatchObject({ entries: 1 });
expect(rejected[0]?.attributes).toMatchObject({ status: 401, refreshed: false });
- await collector.stop();
+ await sessionUploader.stop();
});
test("drops the upload without a refresh or spool entry when the account is signed out", async () => {
for (const status of [403, 401]) {
- const { collector, sessionId, uploads, warnings, rejected, counters } = await authHarness(
+ const { sessionUploader, sessionId, uploads, warnings, rejected, counters } = await authHarness(
() => unauthorized(status, { error: "omnirush_account_required" }),
async () => "fresh-token",
);
expect(counters).toEqual({ attempts: 1, refreshes: 0 });
expect(uploads).toHaveLength(0);
expect(rejected).toHaveLength(0);
- expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
- expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
- const failed = warnings.find((warning) => warning.message === "OmniRush collection operation failed");
- expect(failed?.attributes).toMatchObject({ error: `collector upload failed with status ${status} (omnirush_account_required)` });
- await collector.stop();
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ expect(await sessionUploader.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
+ const failed = warnings.find((warning) => warning.message === "OmniRush session upload operation failed");
+ expect(failed?.attributes).toMatchObject({ error: `sessionUploader upload failed with status ${status} (omnirush_account_required)` });
+ await sessionUploader.stop();
}
});
});
// --- snapshot cap ------------------------------------------------------------
-describe("workspace collector snapshot cap", () => {
+describe("session uploader snapshot cap", () => {
const KIB = 1024;
const CAP = 3 * 1024 * 1024; // leaves 1 MiB for content once the 2 MiB wrapper margin is reserved
const NAMES = Array.from({ length: 20 }, (_, index) => `file-${String(index).padStart(2, "0")}.txt`);
/** Twenty files growing by 8 KiB each, 1.6 MiB in all: more than CAP leaves for content. */
async function largeWorkspace(): Promise<string> {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-cap-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-cap-"));
roots.push(root);
const line = "alpha beta gamma delta\n";
await Promise.all(NAMES.map((name, index) => writeFile(join(root, name), line.repeat(Math.ceil(((index + 1) * 8 * KIB) / line.length)))));
@@ -2553,7 +2553,7 @@ describe("workspace collector snapshot cap", () => {
const uploads: Envelope[] = [];
const rawBytes: number[] = [];
const warnings: string[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
const buffer = zstdDecompressSync(compressed);
rawBytes.push(buffer.length);
@@ -2565,10 +2565,10 @@ describe("workspace collector snapshot cap", () => {
...(options.snapshotMaxBytes ? { snapshotMaxBytes: options.snapshotMaxBytes } : {}),
});
const sessionId = "session-cap-1234";
- collector.startSession(sessionId, "workspace-cap", root);
- for (const path of options.touched ?? []) collector.recordTrace(sessionId, "file.read", { path });
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-cap", root);
+ for (const path of options.touched ?? []) sessionUploader.recordTrace(sessionId, "file.read", { path });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const start = uploads.find((item) => item.snapshot_type === "start")!;
const startBytes = rawBytes[uploads.indexOf(start)]!;
const sent = start.files.map((file) => file.path).filter((path) => !path.startsWith("__omnirush__/"));
@@ -2601,7 +2601,7 @@ describe("workspace collector snapshot cap", () => {
snapshot_cap_omitted_count: omitted.length,
snapshot_cap_omitted_bytes: omitted.reduce((sum, path) => sum + size(path), 0),
});
- expect(warnings.filter((message) => message === "OmniRush collection snapshot trimmed to the snapshot cap")).toHaveLength(1);
+ expect(warnings.filter((message) => message === "OmniRush session upload snapshot trimmed to the snapshot cap")).toHaveLength(1);
expect(notes).toHaveLength(1);
expect(notes[0]).toMatchObject({ data: { snapshot_type: "start", trigger: "session_start", omitted_count: omitted.length } });
expect(notes[0]?.data?.budget_bytes).toBeLessThan(CAP);
@@ -2625,18 +2625,18 @@ describe("workspace collector snapshot cap", () => {
expect([...sent].sort()).toEqual(NAMES);
expect(start.privacy).toMatchObject({ files_truncated: false, snapshot_cap_omitted_count: 0, snapshot_cap_omitted_bytes: 0 });
expect(notes).toHaveLength(0);
- expect(warnings).not.toContain("OmniRush collection snapshot trimmed to the snapshot cap");
+ expect(warnings).not.toContain("OmniRush session upload snapshot trimmed to the snapshot cap");
});
});
// --- incremental snapshots, watcher discipline and memory --------------------
-describe("workspace collector incremental snapshots", () => {
+describe("session uploader incremental snapshots", () => {
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** A git workspace with tracked sources, a dependency tree and gitignored build output. */
async function workspace(prefix: string, sourceFiles = 30): Promise<string> {
- const root = await mkdtemp(join(tmpdir(), `omnirush-collector-${prefix}-`));
+ const root = await mkdtemp(join(tmpdir(), `omnirush-upload-${prefix}-`));
roots.push(root);
await git(root, "init", "-q");
await writeFile(join(root, ".gitignore"), "dist/\nnode_modules/\n");
@@ -2682,18 +2682,18 @@ describe("workspace collector incremental snapshots", () => {
test("a change snapshot reads only the changed file and reuses digests across sessions on one root", async () => {
const root = await workspace("cache");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const first = "session-cache-first-1";
- collector.startSession(first, "workspace-cache", root);
- await collector.idle(first);
- const afterStart = { ...collector.metrics };
+ sessionUploader.startSession(first, "workspace-cache", root);
+ await sessionUploader.idle(first);
+ const afterStart = { ...sessionUploader.metrics };
expect(afterStart.fullScans).toBe(1);
expect(afterStart.fileReads).toBeGreaterThanOrEqual(31);
await writeFile(join(root, "src", "f06.txt"), "source file 6, edited\n");
- collector.captureSnapshot(first, "turn_completed");
- await collector.idle(first);
- const afterChange = { ...collector.metrics };
+ sessionUploader.captureSnapshot(first, "turn_completed");
+ await sessionUploader.idle(first);
+ const afterChange = { ...sessionUploader.metrics };
const change = changes(uploads)[0]!;
expect(contentPaths(change)).toEqual(["src/f06.txt"]);
expect(change.files_scope).toBe("changed");
@@ -2708,9 +2708,9 @@ describe("workspace collector incremental snapshots", () => {
// A second chat on the same workspace starts from the shared cache: a stat per file, no reads.
const second = "session-cache-second-1";
- collector.startSession(second, "workspace-cache", root);
- await collector.idle(second);
- const afterSecond = { ...collector.metrics };
+ sessionUploader.startSession(second, "workspace-cache", root);
+ await sessionUploader.idle(second);
+ const afterSecond = { ...sessionUploader.metrics };
expect(afterSecond.fullScans).toBe(2);
const secondStart = uploads.find((item) => item.snapshot_type === "start" && item.session_id === second)!;
expect(secondStart.files_scope).toBe("full");
@@ -2719,24 +2719,24 @@ describe("workspace collector incremental snapshots", () => {
// file as it is on disk, verified by digest, without the regex pipeline.
expect(afterSecond.fileReads - afterChange.fileReads).toBe(32);
expect(afterSecond.fileRedactions - afterChange.fileRedactions).toBe(0);
- expect(collector.cacheStatus()).toEqual({ roots: 1, entries: 32 });
- await collector.stop();
- expect(collector.cacheStatus()).toEqual({ roots: 0, entries: 0 });
+ expect(sessionUploader.cacheStatus()).toEqual({ roots: 1, entries: 32 });
+ await sessionUploader.stop();
+ expect(sessionUploader.cacheStatus()).toEqual({ roots: 0, entries: 0 });
});
test("skips a milestone capture outright when nothing is dirty, and rescans after a new directory appears", async () => {
const root = await workspace("dirty", 10);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-dirty-1234";
- collector.startSession(sessionId, "workspace-dirty", root);
- await collector.idle(sessionId);
- expect(collector.sessionDiagnostics(sessionId)).toMatchObject({ watchMode: "watching", dirtyPaths: 0, dirtyOverflow: false });
- const before = { ...collector.metrics };
- collector.captureSnapshot(sessionId, "turn_completed");
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
- const after = { ...collector.metrics };
+ sessionUploader.startSession(sessionId, "workspace-dirty", root);
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessionId)).toMatchObject({ watchMode: "watching", dirtyPaths: 0, dirtyOverflow: false });
+ const before = { ...sessionUploader.metrics };
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
+ const after = { ...sessionUploader.metrics };
expect(after.capturesSkipped - before.capturesSkipped).toBe(2);
expect(after.fileStats - before.fileStats).toBe(0);
expect(after.fullScans + after.dirtyScans).toBe(before.fullScans + before.dirtyScans);
@@ -2748,14 +2748,14 @@ describe("workspace collector incremental snapshots", () => {
await mkdir(join(root, "feature"));
await writeFile(join(root, "feature", "new.txt"), "brand new\n");
await sleep(150);
- expect(collector.sessionDiagnostics(sessionId)?.dirtyOverflow).toBe(true);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- expect(collector.metrics.fullScans).toBe(before.fullScans + 1);
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.dirtyOverflow).toBe(true);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.metrics.fullScans).toBe(before.fullScans + 1);
expect(contentPaths(changes(uploads)[0]!)).toEqual(["feature/new.txt"]);
- expect(collector.sessionDiagnostics(sessionId)?.watchedPaths).toContain("feature");
- collector.flushTrace(sessionId);
- await collector.stop();
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.watchedPaths).toContain("feature");
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
expect(triggerEvents(uploads)).toEqual([
{ trigger: "turn_completed", captured: false },
{ trigger: "prompt", captured: false },
@@ -2766,30 +2766,30 @@ describe("workspace collector incremental snapshots", () => {
test("watches only directories with eligible files, batches ignore checks and polls past the watched-files cap", async () => {
const root = await workspace("watch", 6);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000 });
const sessionId = "session-watch-1234";
- collector.startSession(sessionId, "workspace-watch", root);
- await collector.idle(sessionId);
- expect(collector.sessionDiagnostics(sessionId)?.watchedPaths.sort()).toEqual([".", "src"]);
- const before = { ...collector.metrics };
+ sessionUploader.startSession(sessionId, "workspace-watch", root);
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.watchedPaths.sort()).toEqual([".", "src"]);
+ const before = { ...sessionUploader.metrics };
// Churn in the dependency tree and in gitignored output never reaches a callback.
for (let index = 0; index < 200; index += 1) {
await writeFile(join(root, "node_modules", "pkg", `churn-${index}.js`), `// ${index}\n`);
await writeFile(join(root, "dist", `chunk-${index}.js`), `// ${index}\n`);
}
await sleep(250);
- await collector.idle(sessionId);
- expect(collector.metrics.watchEvents - before.watchEvents).toBe(0);
- expect(collector.metrics.ignoreCheckSpawns - before.ignoreCheckSpawns).toBe(0);
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.metrics.watchEvents - before.watchEvents).toBe(0);
+ expect(sessionUploader.metrics.ignoreCheckSpawns - before.ignoreCheckSpawns).toBe(0);
expect(changes(uploads)).toHaveLength(0);
- await collector.stop();
+ await sessionUploader.stop();
expect(JSON.stringify(uploads)).not.toContain("churn-");
expect(JSON.stringify(uploads)).not.toContain("chunk-");
// New files are put to git's ignore rules in one spawn per burst, not one
// per file (the production debounce is 2 s).
const batched = makeUploads();
- const batcher = new WorkspaceCollector({ upload: batched.upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const batcher = new SessionUploader({ upload: batched.upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const batchedId = "session-batched-1234";
batcher.startSession(batchedId, "workspace-batched", root);
await batcher.idle(batchedId);
@@ -2812,7 +2812,7 @@ describe("workspace collector incremental snapshots", () => {
// Past the cap the tree is polled: no watchers, and a milestone rescans it.
const polled = makeUploads();
- const poller = new WorkspaceCollector({ upload: polled.upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000, maxWatchedFiles: 3 });
+ const poller = new SessionUploader({ upload: polled.upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000, maxWatchedFiles: 3 });
const polledId = "session-polled-1234";
poller.startSession(polledId, "workspace-polled", root);
await poller.idle(polledId);
@@ -2827,11 +2827,11 @@ describe("workspace collector incremental snapshots", () => {
test("labels snapshot scope and re-sends changes the gateway never accepted", async () => {
const root = await workspace("scope", 4);
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-scope-state-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-scope-state-"));
roots.push(stateDir);
let status = 201;
const uploads: Envelope[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
stateDir,
upload: async (_sessionId, compressed) => {
if (status !== 201) return Response.json({ error: "rejected" }, { status });
@@ -2842,45 +2842,45 @@ describe("workspace collector incremental snapshots", () => {
fallbackScanMs: 60_000,
});
const sessionId = "session-scope-1234";
- collector.startSession(sessionId, "workspace-scope", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-scope", root);
+ await sessionUploader.idle(sessionId);
expect(uploads[0]).toMatchObject({ snapshot_type: "start", files_scope: "full" });
expect(uploads[0]).not.toHaveProperty("changed_paths");
await writeFile(join(root, "src", "f00.txt"), "rejected edit\n");
status = 400;
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(changes(uploads)).toHaveLength(0);
status = 201;
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const resent = changes(uploads)[0]!;
expect(contentPaths(resent)).toEqual(["src/f00.txt"]);
expect(resent.changed_paths).toEqual(["src/f00.txt"]);
expect(resent.files_scope).toBe("changed");
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
const end = uploads.find((item) => item.snapshot_type === "end")!;
expect(end.files_scope).toBe("changed");
expect(end.changed_paths).toEqual([]);
expect(uploads.find((item) => item.snapshot_type === "trace")?.files_scope).toBe("full");
// Envelopes are streamed through a temp file that never outlives the upload.
- expect((await readdir(join(stateDir, "omnirush-collector-tmp")).catch(() => [])).filter((name) => name.endsWith(".tmp"))).toEqual([]);
- expect(collector.sessionDiagnostics(sessionId)).toBeNull();
+ expect((await readdir(join(stateDir, "omnirush-upload-tmp")).catch(() => [])).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ expect(sessionUploader.sessionDiagnostics(sessionId)).toBeNull();
});
test("spaces filesystem-driven change snapshots by the minimum interval while milestones capture at once", async () => {
const root = await workspace("interval", 4);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, minChangeIntervalMs: 500 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, minChangeIntervalMs: 500 });
const sessionId = "session-interval-1234";
- collector.startSession(sessionId, "workspace-interval", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-interval", root);
+ await sessionUploader.idle(sessionId);
await writeFile(join(root, "src", "f00.txt"), "first burst\n");
await sleep(120);
- await collector.idle(sessionId);
+ await sessionUploader.idle(sessionId);
expect(changes(uploads)).toHaveLength(1);
const firstAt = Date.parse(changes(uploads)[0]!.captured_at as string);
// Two edits inside the window merge into one deferred snapshot.
@@ -2888,120 +2888,120 @@ describe("workspace collector incremental snapshots", () => {
await sleep(60);
await writeFile(join(root, "src", "f02.txt"), "second burst b\n");
await sleep(120);
- await collector.idle(sessionId);
+ await sessionUploader.idle(sessionId);
expect(changes(uploads)).toHaveLength(1);
- expect(collector.metrics.capturesDeferred).toBeGreaterThanOrEqual(1);
+ expect(sessionUploader.metrics.capturesDeferred).toBeGreaterThanOrEqual(1);
await sleep(500);
- await collector.idle(sessionId);
+ await sessionUploader.idle(sessionId);
expect(changes(uploads)).toHaveLength(2);
expect(contentPaths(changes(uploads)[1]!).sort()).toEqual(["src/f01.txt", "src/f02.txt"]);
expect(Date.parse(changes(uploads)[1]!.captured_at as string) - firstAt).toBeGreaterThanOrEqual(450);
// A turn milestone inside the window is not held back.
await writeFile(join(root, "src", "f03.txt"), "milestone edit\n");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(changes(uploads)).toHaveLength(3);
expect(contentPaths(changes(uploads)[2]!)).toEqual(["src/f03.txt"]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("neither watches nor rescans a rebuilt gitignored directory, and rescans once .gitignore changes", async () => {
const root = await workspace("ignored", 6);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-ignored-1234";
- collector.startSession(sessionId, "workspace-ignored", root);
- await collector.idle(sessionId);
- const before = { ...collector.metrics };
+ sessionUploader.startSession(sessionId, "workspace-ignored", root);
+ await sessionUploader.idle(sessionId);
+ const before = { ...sessionUploader.metrics };
// A build that wipes and recreates its gitignored output directory.
await rm(join(root, "dist"), { recursive: true, force: true });
await mkdir(join(root, "dist"));
await writeFile(join(root, "dist", "bundle.js"), "rebuilt\n");
await sleep(200);
- expect(collector.sessionDiagnostics(sessionId)).toMatchObject({ dirtyOverflow: false });
- expect(collector.sessionDiagnostics(sessionId)?.watchedPaths).not.toContain("dist");
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
- expect(collector.metrics.fullScans).toBe(before.fullScans);
+ expect(sessionUploader.sessionDiagnostics(sessionId)).toMatchObject({ dirtyOverflow: false });
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.watchedPaths).not.toContain("dist");
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.metrics.fullScans).toBe(before.fullScans);
expect(changes(uploads)).toHaveLength(0);
// An untracked log goes out; a new ignore rule then hides it, and the
// edit to .gitignore makes the next capture rescan the tree under it.
await writeFile(join(root, "notes.log"), "scratch notes\n");
await sleep(150);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(changes(uploads).at(-1)!.manifest.map((entry) => entry.path)).toContain("notes.log");
await writeFile(join(root, ".gitignore"), "dist/\nnode_modules/\n*.log\n");
await sleep(150);
- expect(collector.sessionDiagnostics(sessionId)?.dirtyOverflow).toBe(true);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.dirtyOverflow).toBe(true);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const last = changes(uploads).at(-1)!;
- expect(collector.metrics.fullScans).toBe(before.fullScans + 1);
+ expect(sessionUploader.metrics.fullScans).toBe(before.fullScans + 1);
expect(last.manifest.map((entry) => entry.path)).not.toContain("notes.log");
expect(last.changed_paths).toEqual([".gitignore"]);
- await collector.stop();
+ await sessionUploader.stop();
});
test("drops the files of a directory moved out of the workspace without rescanning the tree", async () => {
const root = await workspace("moved", 10);
- const outside = await mkdtemp(join(tmpdir(), "omnirush-collector-moved-out-"));
+ const outside = await mkdtemp(join(tmpdir(), "omnirush-upload-moved-out-"));
roots.push(outside);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-moved-1234";
- collector.startSession(sessionId, "workspace-moved", root);
- await collector.idle(sessionId);
- const before = { ...collector.metrics };
+ sessionUploader.startSession(sessionId, "workspace-moved", root);
+ await sessionUploader.idle(sessionId);
+ const before = { ...sessionUploader.metrics };
// One event for the directory, none for the five files inside it.
await rename(join(root, "src", "lib"), join(outside, "lib"));
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[0]!;
const paths = change.manifest.map((entry) => entry.path);
expect(paths.filter((path) => path.startsWith("src/lib/"))).toEqual([]);
expect(paths).toContain("src/f00.txt");
- expect(collector.metrics.fullScans).toBe(before.fullScans);
- expect(collector.metrics.dirtyScans).toBe(before.dirtyScans + 1);
- await collector.stop();
+ expect(sessionUploader.metrics.fullScans).toBe(before.fullScans);
+ expect(sessionUploader.metrics.dirtyScans).toBe(before.dirtyScans + 1);
+ await sessionUploader.stop();
});
test("polls a workspace with more top-level directories than it watches", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-wide-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-wide-"));
roots.push(root);
for (let index = 0; index < 65; index += 1) {
await mkdir(join(root, `dir${index}`));
await writeFile(join(root, `dir${index}`, "a.txt"), `file ${index}\n`);
}
const { upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-wide-1234";
- collector.startSession(sessionId, "workspace-wide", root);
- await collector.idle(sessionId);
- expect(collector.sessionDiagnostics(sessionId)).toMatchObject({ watchMode: "polling", watchedPaths: [], dirtyOverflow: true });
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-wide", root);
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessionId)).toMatchObject({ watchMode: "polling", watchedPaths: [], dirtyOverflow: true });
+ await sessionUploader.stop();
});
test("keeps a file larger than the change journal out of it, and still snapshots the file", async () => {
const root = await workspace("journal", 4);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-journal-1234";
- collector.startSession(sessionId, "workspace-journal", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-journal", root);
+ await sessionUploader.idle(sessionId);
await writeFile(join(root, "src", "small.txt"), "small edit\n");
await writeFile(join(root, "src", "large.txt"), "large log line\n".repeat(70_000));
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[0]!;
expect(contentPaths(change).sort()).toEqual(["src/large.txt", "src/small.txt"]);
const journal = change.files.find((file) => file.path === "__omnirush__/changes.json")!;
expect(journal.content).toContain('"path":"src/small.txt"');
expect(journal.content).not.toContain("src/large.txt");
- await collector.stop();
+ await sessionUploader.stop();
});
test("runs one reconcile pass per interval for every session on a root, and it finds what no watcher reported", async () => {
@@ -3010,18 +3010,18 @@ describe("workspace collector incremental snapshots", () => {
await fillWatchSlots(root);
await mkdir(join(root, "assets"));
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 300, minChangeIntervalMs: 0 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 300, minChangeIntervalMs: 0 });
const sessions = ["session-reconcile-a1", "session-reconcile-b1"];
- for (const sessionId of sessions) collector.startSession(sessionId, "workspace-reconcile", root);
- for (const sessionId of sessions) await collector.idle(sessionId);
- expect(collector.sessionDiagnostics(sessions[0]!)).toMatchObject({ watchMode: "watching" });
- expect(collector.sessionDiagnostics(sessions[0]!)?.watchedPaths).toHaveLength(65);
- expect(collector.sessionDiagnostics(sessions[0]!)?.watchedPaths).not.toContain("assets");
- const before = collector.metrics.reconciles;
+ for (const sessionId of sessions) sessionUploader.startSession(sessionId, "workspace-reconcile", root);
+ for (const sessionId of sessions) await sessionUploader.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessions[0]!)).toMatchObject({ watchMode: "watching" });
+ expect(sessionUploader.sessionDiagnostics(sessions[0]!)?.watchedPaths).toHaveLength(65);
+ expect(sessionUploader.sessionDiagnostics(sessions[0]!)?.watchedPaths).not.toContain("assets");
+ const before = sessionUploader.metrics.reconciles;
await writeFile(join(root, "assets", "found.txt"), "found by the reconcile pass\n");
await sleep(1_000);
- for (const sessionId of sessions) await collector.idle(sessionId);
- const passes = collector.metrics.reconciles - before;
+ for (const sessionId of sessions) await sessionUploader.idle(sessionId);
+ const passes = sessionUploader.metrics.reconciles - before;
// About three passes in a second at a 300 ms interval; per-session passes would make six.
expect(passes).toBeGreaterThanOrEqual(1);
expect(passes).toBeLessThanOrEqual(4);
@@ -3029,22 +3029,22 @@ describe("workspace collector incremental snapshots", () => {
const change = changes(uploads).find((item) => item.session_id === sessionId);
expect(change && contentPaths(change)).toEqual(["assets/found.txt"]);
}
- await collector.stop();
+ await sessionUploader.stop();
});
test("two chats on one folder: only the one running a turn uploads the edits made meanwhile, and each still captures its own milestones", async () => {
const root = await workspace("shared", 4);
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 150, minChangeIntervalMs: 0 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 150, minChangeIntervalMs: 0 });
const working = "session-shared-working-1";
const idle = "session-shared-idle-0001";
const both = [working, idle];
- for (const sessionId of both) collector.startSession(sessionId, "workspace-shared", root);
- for (const sessionId of both) await collector.idle(sessionId);
+ for (const sessionId of both) sessionUploader.startSession(sessionId, "workspace-shared", root);
+ for (const sessionId of both) await sessionUploader.idle(sessionId);
const settle = async () => {
// Past the debounce and several reconcile passes.
await sleep(600);
- for (const sessionId of both) await collector.idle(sessionId);
+ for (const sessionId of both) await sessionUploader.idle(sessionId);
};
const changesOf = (sessionId: string) => changes(uploads)
.filter((item) => item.session_id === sessionId)
@@ -3052,16 +3052,16 @@ describe("workspace collector incremental snapshots", () => {
// Whichever of the watcher and the reconcile pass saw the edit first.
const edit = expect.stringMatching(/^(?:fs_change|periodic)$/);
- collector.captureSnapshot(working, "prompt");
- await collector.idle(working);
+ sessionUploader.captureSnapshot(working, "prompt");
+ await sessionUploader.idle(working);
await writeFile(join(root, "src", "f00.txt"), "the agent's edit\n");
await settle();
expect(changesOf(working)).toEqual([[edit, ["src/f00.txt"]]]);
expect(changesOf(idle)).toEqual([]);
- expect(collector.metrics.capturesHeld).toBeGreaterThan(0);
+ expect(sessionUploader.metrics.capturesHeld).toBeGreaterThan(0);
// The turn ends: the other chat still leaves that turn's edits alone, reconcile passes included.
- collector.captureSnapshot(working, "turn_completed");
+ sessionUploader.captureSnapshot(working, "turn_completed");
await settle();
expect(changesOf(idle)).toEqual([]);
@@ -3073,18 +3073,18 @@ describe("workspace collector incremental snapshots", () => {
// The other chat's own prompt carries what it has not sent yet; while it
// runs its turn, the first chat holds back in turn.
- collector.captureSnapshot(idle, "prompt");
- await collector.idle(idle);
+ sessionUploader.captureSnapshot(idle, "prompt");
+ await sessionUploader.idle(idle);
expect(changesOf(idle)).toEqual([["prompt", ["README.md", "src/f00.txt"]]]);
const sentByWorking = changesOf(working).length;
await writeFile(join(root, "src", "f02.txt"), "the other agent's edit\n");
await settle();
expect(changesOf(idle).at(-1)).toEqual([edit, ["src/f02.txt"]]);
expect(changesOf(working)).toHaveLength(sentByWorking);
- collector.captureSnapshot(idle, "turn_completed");
- await collector.idle(idle);
- for (const sessionId of both) collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.captureSnapshot(idle, "turn_completed");
+ await sessionUploader.idle(idle);
+ for (const sessionId of both) sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
for (const sessionId of both) {
const milestones = uploads
.filter((item) => item.snapshot_type === "trace" && item.session_id === sessionId)
@@ -3096,16 +3096,16 @@ describe("workspace collector incremental snapshots", () => {
});
test("keeps gitignored files out of change snapshots and the journal in a workspace git does not manage", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-nogit-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-nogit-"));
roots.push(root);
await writeFile(join(root, ".gitignore"), "*.log\nbuild/\n");
await mkdir(join(root, "src"));
await writeFile(join(root, "src", "a.txt"), "a\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-nogit-1234";
- collector.startSession(sessionId, "workspace-nogit", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-nogit", root);
+ await sessionUploader.idle(sessionId);
// git answers nothing here: the watcher-reported paths go through the
// .gitignore files the listing walker applies.
await writeFile(join(root, "src", "debug.log"), "debug output\n");
@@ -3113,12 +3113,12 @@ describe("workspace collector incremental snapshots", () => {
await writeFile(join(root, "build", "out.txt"), "build output\n");
await writeFile(join(root, "src", "b.txt"), "b\n");
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[0]!;
expect(contentPaths(change)).toEqual(["src/b.txt"]);
expect(change.manifest.map((entry) => entry.path).sort()).toEqual([".gitignore", "src/a.txt", "src/b.txt"]);
- await collector.stop();
+ await sessionUploader.stop();
expect(JSON.stringify(uploads)).not.toContain("debug.log");
expect(JSON.stringify(uploads)).not.toContain("out.txt");
});
@@ -3139,20 +3139,20 @@ describe("workspace collector incremental snapshots", () => {
await mkdir(join(root, "scripts")); // empty
await mkdir(join(root, "secrets")); // a denied name
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, minChangeIntervalMs: 0 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 10, fallbackScanMs: 60_000, minChangeIntervalMs: 0 });
const sessionId = "session-unlisted-1234";
- collector.startSession(sessionId, "workspace-unlisted", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-unlisted", root);
+ await sessionUploader.idle(sessionId);
// Not dist/ (gitignored), node_modules/, secrets/ or .git/ (denied).
- expect(collector.sessionDiagnostics(sessionId)?.watchedPaths.sort()).toEqual([".", "config", "scripts", "src"]);
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.watchedPaths.sort()).toEqual([".", "config", "scripts", "src"]);
// Another editor writes next to the denied file: the watcher sees it at once.
await writeFile(join(root, "config", "app.yml"), "mode: production\n");
await sleep(300);
- await collector.idle(sessionId);
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[0]!;
expect(change.trigger).toBe("fs_change");
expect(contentPaths(change)).toEqual(["config/app.yml"]);
- await collector.stop();
+ await sessionUploader.stop();
expect(JSON.stringify(uploads)).not.toContain("API=1");
});
@@ -3161,23 +3161,23 @@ describe("workspace collector incremental snapshots", () => {
await fillWatchSlots(root);
await mkdir(join(root, "assets"));
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-unwatched-1234";
- collector.startSession(sessionId, "workspace-unwatched", root);
- await collector.idle(sessionId);
- expect(collector.sessionDiagnostics(sessionId)?.watchedPaths).not.toContain("assets");
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-unwatched", root);
+ await sessionUploader.idle(sessionId);
+ expect(sessionUploader.sessionDiagnostics(sessionId)?.watchedPaths).not.toContain("assets");
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
// A bash tool writes it; no trace event names it and no watcher covers assets/.
await mkdir(join(root, "assets", "db"));
await writeFile(join(root, "assets", "db", "migrate.sh"), "#!/bin/sh\necho migrate\n");
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
// The end-of-turn artifact scan marks it dirty for the turn's own snapshot.
expect(contentPaths(changes(uploads)[0]!)).toEqual(["assets/db/migrate.sh"]);
- collector.flushTrace(sessionId);
- await collector.stop();
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
expect(triggerEvents(uploads)).toEqual([
{ trigger: "prompt", captured: false },
{ trigger: "turn_completed", captured: true },
@@ -3185,7 +3185,7 @@ describe("workspace collector incremental snapshots", () => {
});
test.skipIf(process.platform === "win32")("a path git refuses to answer for (beyond a symlinked directory) neither changes the ignore answer for its batch nor gets read", async () => {
- const base = await mkdtemp(join(tmpdir(), "omnirush-collector-symlink-"));
+ const base = await mkdtemp(join(tmpdir(), "omnirush-upload-symlink-"));
roots.push(base);
const root = join(base, "repo");
const outside = join(base, "shared-lib");
@@ -3200,23 +3200,23 @@ describe("workspace collector incremental snapshots", () => {
await git(root, "add", "-A");
await git(root, "commit", "-q", "-m", "init");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = "session-symlink-1234";
- collector.startSession(sessionId, "workspace-symlink", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-symlink", root);
+ await sessionUploader.idle(sessionId);
// In one ignore batch: a note git ignores only through .git/info/exclude,
// the agent's traced read through the symlinked package, and a real edit.
await writeFile(join(root, "private-notes.txt"), "PRIVATE: salary negotiation notes\n");
- collector.recordTrace(sessionId, "tool.read", { filePath: "linked/util.ts" });
+ sessionUploader.recordTrace(sessionId, "tool.read", { filePath: "linked/util.ts" });
await writeFile(join(root, "src", "app.ts"), "export const app = 2;\n");
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[0]!;
expect(contentPaths(change)).toEqual(["src/app.ts"]);
expect(change.manifest.map((entry) => entry.path)).toEqual(["src/app.ts"]);
expect(change.files.find((file) => file.path === "__omnirush__/changes.json")?.content).toContain('"path":"src/app.ts"');
- await collector.stop();
+ await sessionUploader.stop();
const all = JSON.stringify(uploads);
expect(all).not.toContain("salary negotiation");
expect(all).not.toContain("OUTSIDE_WORKSPACE");
@@ -3227,16 +3227,16 @@ describe("workspace collector incremental snapshots", () => {
const root = await workspace(`newly-ignored-${via}`, 4);
await writeFile(join(root, "notes.txt"), "scratch v1\n"); // untracked, not ignored yet
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const sessionId = `session-newly-ignored-${via}`;
- collector.startSession(sessionId, "workspace-newly-ignored", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-newly-ignored", root);
+ await sessionUploader.idle(sessionId);
expect(uploads[0]!.manifest.map((entry) => entry.path)).toContain("notes.txt");
- // An edit while it is still collected: git's "not ignored" is now cached.
+ // An edit while it is still uploaded: git's "not ignored" is now cached.
await writeFile(join(root, "notes.txt"), "scratch v1b\n");
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
expect(contentPaths(changes(uploads)[0]!)).toEqual(["notes.txt"]);
// The user hides it from git (.git/info/exclude raises no event), then writes something private into it.
if (via === "gitignore") await writeFile(join(root, ".gitignore"), "dist/\nnode_modules/\nnotes.txt\n");
@@ -3244,23 +3244,23 @@ describe("workspace collector incremental snapshots", () => {
await sleep(150);
await writeFile(join(root, "notes.txt"), "PRIVATE: do not share v2\n");
await sleep(200);
- collector.captureSnapshot(sessionId, "turn_completed");
- await collector.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ await sessionUploader.idle(sessionId);
const change = changes(uploads)[1]!;
expect(change.manifest.map((entry) => entry.path)).not.toContain("notes.txt");
expect(contentPaths(change)).not.toContain("notes.txt");
- await collector.stop();
+ await sessionUploader.stop();
expect(JSON.stringify(uploads)).not.toContain("do not share v2");
}
});
test("a resumed session's start snapshot carries every file again, even when its earlier start never reached the backend", async () => {
const root = await workspace("resume-full", 4);
- const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-resume-full-state-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-resume-full-state-"));
roots.push(stateDir);
const sessionId = "session-resume-full-1";
// Offline: the start snapshot is only spooled, and sign-out then deletes the spool.
- const offline = new WorkspaceCollector({
+ const offline = new SessionUploader({
stateDir,
upload: async () => new Response("unavailable", { status: 503 }),
uploadRetryDelayMs: 1,
@@ -3277,10 +3277,10 @@ describe("workspace collector incremental snapshots", () => {
await writeFile(join(root, "src", "f00.txt"), "source file 0, edited while the app was closed\n");
const { uploads, upload } = makeUploads();
for (let run = 0; run < 2; run += 1) {
- const collector = new WorkspaceCollector({ stateDir, upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
- collector.startSession(sessionId, "workspace-resume-full", root);
- await collector.idle(sessionId);
- await collector.stop();
+ const sessionUploader = new SessionUploader({ stateDir, upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ sessionUploader.startSession(sessionId, "workspace-resume-full", root);
+ await sessionUploader.idle(sessionId);
+ await sessionUploader.stop();
}
const starts = uploads.filter((item) => item.snapshot_type === "start");
expect(starts.map((item) => [item.trigger, item.session_segment, item.files_scope, contentPaths(item).length])).toEqual([
@@ -3295,19 +3295,19 @@ describe("workspace collector incremental snapshots", () => {
await writeFile(join(root, "src", "contact.txt"), "mail [email protected] about it\n");
await writeFile(join(root, "src", "config.yml"), "password: hunter2hunter2\n");
const { uploads, upload } = makeUploads();
- const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionUploader = new SessionUploader({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
const start = (id: string) => uploads.find((item) => item.snapshot_type === "start" && item.session_id === id)!;
const content = (envelope: Envelope, path: string) => envelope.files.find((file) => file.path === path)?.content;
- collector.startSession("session-texts-first-1", "workspace-texts", root);
- await collector.idle("session-texts-first-1");
+ sessionUploader.startSession("session-texts-first-1", "workspace-texts", root);
+ await sessionUploader.idle("session-texts-first-1");
// The scan scrubbed each file once; the upload pass reused that text for the two files the scrubber changed.
- expect(collector.metrics.redactedTextHits).toBe(2);
- const before = { ...collector.metrics };
- collector.startSession("session-texts-second", "workspace-texts", root);
- await collector.idle("session-texts-second");
- expect(collector.metrics.fileRedactions - before.fileRedactions).toBe(0);
- expect(collector.metrics.redactedTextHits - before.redactedTextHits).toBe(2);
+ expect(sessionUploader.metrics.redactedTextHits).toBe(2);
+ const before = { ...sessionUploader.metrics };
+ sessionUploader.startSession("session-texts-second", "workspace-texts", root);
+ await sessionUploader.idle("session-texts-second");
+ expect(sessionUploader.metrics.fileRedactions - before.fileRedactions).toBe(0);
+ expect(sessionUploader.metrics.redactedTextHits - before.redactedTextHits).toBe(2);
const first = start("session-texts-first-1");
const second = start("session-texts-second");
expect(content(second, "src/contact.txt")).toBe("mail [REDACTED_PII] about it\n");
@@ -3317,16 +3317,16 @@ describe("workspace collector incremental snapshots", () => {
// New bytes are scrubbed again, never served from the text of the old ones.
await writeFile(join(root, "src", "contact.txt"), "mail [email protected] instead of jane\n");
- const edited = { ...collector.metrics };
- collector.startSession("session-texts-third1", "workspace-texts", root);
- await collector.idle("session-texts-third1");
+ const edited = { ...sessionUploader.metrics };
+ sessionUploader.startSession("session-texts-third1", "workspace-texts", root);
+ await sessionUploader.idle("session-texts-third1");
expect(content(start("session-texts-third1"), "src/contact.txt")).toBe("mail [REDACTED_PII] instead of jane\n");
- expect(collector.metrics.fileRedactions - edited.fileRedactions).toBeGreaterThanOrEqual(1);
- await collector.stop();
+ expect(sessionUploader.metrics.fileRedactions - edited.fileRedactions).toBeGreaterThanOrEqual(1);
+ await sessionUploader.stop();
});
test("snapshots a 60 MiB workspace with peak RSS growth under 120 MB", async () => {
- const root = await mkdtemp(join(tmpdir(), "omnirush-collector-memory-"));
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-memory-"));
roots.push(root);
await mkdir(join(root, "src"));
// Pseudo-random words so the content neither compresses away nor trips the scrubber.
@@ -3355,7 +3355,7 @@ describe("workspace collector incremental snapshots", () => {
expect(total).toBeGreaterThanOrEqual(58 * 1024 * 1024);
const compressedEnvelopes: Uint8Array[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
compressedEnvelopes.push(compressed);
return Response.json({ ok: true }, { status: 201 });
@@ -3370,11 +3370,11 @@ describe("workspace collector incremental snapshots", () => {
let peak = baseline;
const sampler = setInterval(() => { peak = Math.max(peak, process.memoryUsage().rss); }, 20);
const sessionId = "session-memory-1234";
- collector.startSession(sessionId, "workspace-memory", root);
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-memory", root);
+ await sessionUploader.idle(sessionId);
peak = Math.max(peak, process.memoryUsage().rss);
clearInterval(sampler);
- await collector.stop();
+ await sessionUploader.stop();
const growthMB = (peak - baseline) / (1024 * 1024);
expect(growthMB).toBeLessThan(120);
diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/session-uploader.ts
similarity index 93%
rename from apps/server/src/workspace-collector.ts
rename to apps/server/src/session-uploader.ts
index 67ca1431..3ee137aa 100644
--- a/apps/server/src/workspace-collector.ts
+++ b/apps/server/src/session-uploader.ts
@@ -8,37 +8,45 @@ import { promisify } from "node:util";
import { createZstdCompress } from "node:zlib";
import { minimatch } from "minimatch";
-import { COLLECT_UPLOAD_BUDGET, collectUploadTimeoutMs, type CollectUploadBudget } from "./collect-upload-budget.js";
+import { SESSION_UPLOAD_BUDGET, SESSION_UPLOAD_ENDPOINT_PATH, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";
import { externalFetch } from "./server-fetch.js";
+import {
+ UPLOAD_BASE_DIRECTORY,
+ UPLOAD_SESSION_LEDGER_FILE,
+ UPLOAD_SPOOL_DIRECTORY,
+ UPLOAD_TEMP_DIRECTORY,
+ migrateLegacyUploadState,
+ removeLegacyUploadContent,
+} from "./session-upload-state.js";
import { TurnBaseStore, TurnDiffBuilder, type TurnDiffInput } from "./turn-diff.js";
import { SUBAGENT_MODEL_FALLBACK_TRACE } from "./omnirush-swarm.js";
import { writeFileAtomic } from "./atomic-write.js";
const execFileAsync = promisify(execFile);
-export const COLLECTOR_SCHEMA_VERSION = 2;
-// Caps shared with the omnirush.ai collector endpoint (contract v2); the
+export const UPLOAD_SCHEMA_VERSION = 2;
+// Caps shared with the omnirush.ai session upload endpoint, /omnirush/collect (contract v2); the
// backend enforces identical values, so a change here must land on both sides.
// Every cap is per file or per request: there is no per-session storage cap, so
// a session keeps uploading snapshots however much it has sent before.
-export const MAX_COLLECTOR_FILE_BYTES = 4 * 1024 * 1024;
-export const MAX_COLLECTOR_DIFF_BYTES = 2 * 1024 * 1024;
-export const MAX_COLLECTOR_FILES = 50_000;
-export const MAX_COLLECTOR_SNAPSHOT_BYTES = 64 * 1024 * 1024;
-export const MAX_COLLECTOR_TRACE_BYTES = 16 * 1024 * 1024;
-export const MAX_COLLECTOR_COMPRESSED_BYTES = 64 * 1024 * 1024;
+export const MAX_UPLOAD_FILE_BYTES = 4 * 1024 * 1024;
+export const MAX_UPLOAD_DIFF_BYTES = 2 * 1024 * 1024;
+export const MAX_UPLOAD_FILES = 50_000;
+export const MAX_UPLOAD_SNAPSHOT_BYTES = 64 * 1024 * 1024;
+export const MAX_UPLOAD_TRACE_BYTES = 16 * 1024 * 1024;
+export const MAX_UPLOAD_COMPRESSED_BYTES = 64 * 1024 * 1024;
/** Visible page text carried by one "web.visit" trace event, after redaction. */
-export const MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES = 64 * 1024;
+export const MAX_UPLOAD_WEB_VISIT_TEXT_BYTES = 64 * 1024;
/** Extracted text carried by one "attachment" trace event, after redaction. */
-export const MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES = 256 * 1024;
+export const MAX_UPLOAD_ATTACHMENT_TEXT_BYTES = 256 * 1024;
/** Task-tool subagent nesting captured below a root session (children, grandchildren, ...). */
-export const MAX_COLLECTOR_CHILD_SESSION_DEPTH = 3;
+export const MAX_UPLOAD_CHILD_SESSION_DEPTH = 3;
// Events kept per session between trace flushes; older events are dropped
// first. Every push site goes through appendTrace so the cap holds for the
// model, child, browser, attachment and artifact events too.
-export const MAX_COLLECTOR_TRACE_EVENTS = 5_000;
-const MAX_FILES = MAX_COLLECTOR_FILES;
-const MAX_SNAPSHOT_BYTES = MAX_COLLECTOR_SNAPSHOT_BYTES;
+export const MAX_UPLOAD_TRACE_EVENTS = 5_000;
+const MAX_FILES = MAX_UPLOAD_FILES;
+const MAX_SNAPSHOT_BYTES = MAX_UPLOAD_SNAPSHOT_BYTES;
// Uncompressed room kept free inside MAX_SNAPSHOT_BYTES for what surrounds
// files[]: the session and environment blocks, touched paths, the metadata and
// change-journal files. The manifest and the git block are measured instead,
@@ -47,8 +55,8 @@ const SNAPSHOT_WRAPPER_MARGIN_BYTES = 2 * 1024 * 1024;
// JSON punctuation plus the sha256 field of one files[] entry, on top of its
// path and serialised content.
const SNAPSHOT_FILE_ENTRY_OVERHEAD_BYTES = 128;
-const MAX_TRACE_BYTES = MAX_COLLECTOR_TRACE_BYTES;
-const MAX_COMPRESSED_BYTES = MAX_COLLECTOR_COMPRESSED_BYTES;
+const MAX_TRACE_BYTES = MAX_UPLOAD_TRACE_BYTES;
+const MAX_COMPRESSED_BYTES = MAX_UPLOAD_COMPRESSED_BYTES;
const MAX_ARTIFACT_EVENTS_PER_TURN = 500;
const MAX_ARTIFACT_HASH_BYTES = 64 * 1024 * 1024;
const MAX_CHILD_SESSIONS = 200;
@@ -59,12 +67,12 @@ const MAX_ATTACHMENT_MIME_CHARS = 128;
const CHANGE_DEBOUNCE_MS = 2_000;
// While a workspace is watched, a reconcile pass (listing + lstat, no reads)
// runs this often to catch events the watcher missed; a polled workspace (see
-// MAX_COLLECTOR_WATCHED_FILES) is rescanned on snapshots only, never on a timer.
+// MAX_UPLOAD_WATCHED_FILES) is rescanned on snapshots only, never on a timer.
const FALLBACK_SCAN_MS = 60_000;
/** Change snapshots are at least this far apart; triggers inside the window merge into one deferred capture. */
-export const MIN_COLLECTOR_CHANGE_INTERVAL_MS = 30_000;
+export const MIN_UPLOAD_CHANGE_INTERVAL_MS = 30_000;
/** A workspace with more eligible files than this is polled on snapshots instead of watched. */
-export const MAX_COLLECTOR_WATCHED_FILES = 20_000;
+export const MAX_UPLOAD_WATCHED_FILES = 20_000;
// Paths the watcher reported since the last capture. Past the cap the set is
// dropped and the next capture rescans the whole tree.
const MAX_DIRTY_PATHS = 8_192;
@@ -85,7 +93,6 @@ const IGNORE_CHECK_BATCH_MS = 50;
const MILESTONE_SETTLE_MS = 100;
const IGNORE_CHECK_BATCH_MAX = 2_000;
const MAX_IGNORED_CACHE_ENTRIES = 8_192;
-const TEMP_DIRECTORY = "omnirush-collector-tmp";
const ENVELOPE_WRITE_CHUNK_BYTES = 64 * 1024;
const MAX_CHANGE_JOURNAL_ENTRIES = 512;
const MAX_CHANGE_JOURNAL_BYTES = 768 * 1024;
@@ -95,7 +102,7 @@ const MAX_GIT_STATUS_ENTRIES = 500;
const MAX_GIT_RECENT_COMMITS = 50;
const MAX_GIT_REMOTES = 10;
const GIT_DIFF_READ_BYTES = 8 * 1024 * 1024;
-// Field limits enforced by the omnirush.ai collector endpoint (counted in code
+// Field limits enforced by the omnirush.ai session upload endpoint, /omnirush/collect (counted in code
// points). A longer value is rejected with 400, which is never retried or
// spooled, so every free-text field is clamped here *after* redaction: a
// replacement marker can be longer than the text it replaces.
@@ -106,13 +113,9 @@ const MAX_GIT_REMOTE_URL_CHARS = 2048;
const MAX_GIT_PATH_CHARS = 4096;
const MAX_ROOT_NAME_CHARS = 255;
const MAX_ENVIRONMENT_FIELD_CHARS = 256;
-const SESSION_LEDGER_FILE = "omnirush-collector-sessions.json";
// Redacted text of files the scrubber changed, kept so a later full upload of
// the same bytes (a new chat on the same workspace) skips the regex pipeline.
const REDACTED_TEXT_CACHE_BYTES = 32 * 1024 * 1024;
-const SPOOL_DIRECTORY = "omnirush-collector-spool";
-/** The scrubbed texts "turn.diff" events are measured against (turn-diff.ts). */
-const BASE_DIRECTORY = "omnirush-collector-bases";
/**
* An mtime this far ahead of the clock (an unpacked archive, a share on
* another machine) is no write of the current turn's.
@@ -137,7 +140,7 @@ const ACCOUNT_REQUIRED_MARKER = "omnirush_account_required";
type SnapshotType = "start" | "change" | "end" | "trace";
-export type CollectorTrigger =
+export type UploadTrigger =
| "session_start"
| "resume"
| "prompt"
@@ -147,9 +150,9 @@ export type CollectorTrigger =
| "session_end"
| "trace_flush";
-type ChangeTrigger = Extract<CollectorTrigger, "prompt" | "turn_completed" | "fs_change" | "periodic">;
+type ChangeTrigger = Extract<UploadTrigger, "prompt" | "turn_completed" | "fs_change" | "periodic">;
-type CollectorFile = {
+type UploadFile = {
path: string;
content: string;
sha256: string;
@@ -159,7 +162,7 @@ type GitRemote = { name: string; url: string };
type GitCommit = { sha: string; at: string; subject: string };
type GitStatusEntry = { code: string; path: string };
-export type CollectorGitBlock = {
+export type UploadGitBlock = {
commit: string | null;
branch: string | null;
dirty: boolean;
@@ -173,7 +176,7 @@ export type CollectorGitBlock = {
diff_truncated: boolean;
};
-export type CollectorEnvironment = {
+export type UploadEnvironment = {
os: string;
os_version: string;
arch: string;
@@ -201,7 +204,7 @@ type ChangeJournalEntry = {
};
/** Latest model selection observed for a session (from the turn's first assistant message). */
-export type CollectorSessionModel = {
+export type UploadSessionModel = {
provider_id: string | null;
model_id: string | null;
variant: string | null;
@@ -209,14 +212,14 @@ export type CollectorSessionModel = {
};
/** Envelope-level "session" block: latest known values for every snapshot type. */
-export type CollectorSessionBlock = {
+export type UploadSessionBlock = {
provider_id: string | null;
model_id: string | null;
variant: string | null;
child_session_ids: string[];
};
-/** A "subagent.model_fallback" trace event of kind "gateway", as the collector keeps it. */
+/** A "subagent.model_fallback" trace event of kind "gateway", as the session uploader keeps it. */
type SubagentModelFallback = { requested: string; used: string; effort: string | null; at: number };
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -262,7 +265,7 @@ function withSubagentFallbacks(messages: unknown[], fallbacks: readonly Subagent
});
}
-export type CollectorChildSession = {
+export type UploadChildSession = {
childSessionId: string;
parentSessionId: string;
/** Sub-agent layer below the root session: 1 for a child, 2 for a grandchild, ... */
@@ -275,13 +278,13 @@ export type CollectorChildSession = {
lastMessageId: string | null;
};
-export type CollectorWebVisit = {
+export type UploadWebVisit = {
url: string;
title?: string | null;
text?: string | null;
};
-export type CollectorAttachment = {
+export type UploadAttachment = {
name: string;
mime: string;
bytes: number;
@@ -302,7 +305,7 @@ type SessionLedgerRecord = {
failureCount?: number;
lastFailureAt?: string;
lastSuccessAt?: string;
- model?: CollectorSessionModel;
+ model?: UploadSessionModel;
childSessionIds?: string[];
/** child session id -> id of its last captured message */
childCheckpoints?: Record<string, string>;
@@ -331,7 +334,7 @@ type SpoolMeta = {
id: string;
session_id: string;
snapshot_type: SnapshotType;
- trigger: CollectorTrigger;
+ trigger: UploadTrigger;
sequence: number;
bytes: number;
created_at: string;
@@ -404,7 +407,7 @@ type SessionState = {
lastChangeAt: number;
/** Untracked-but-not-ignored files as they stood when the current turn began. */
artifactBaseline: Promise<Map<string, ArtifactStat>> | null;
- model: CollectorSessionModel | null;
+ model: UploadSessionModel | null;
childSessionIds: string[];
childCheckpoints: Map<string, string>;
/**
@@ -421,11 +424,11 @@ type SessionState = {
tail: Promise<void>;
};
-type CollectorOptions = {
+type SessionUploaderOptions = {
gatewayUrl?: string;
accessToken?: string;
fetch?: typeof externalFetch;
- /** Sends one envelope; `signal` aborts at the upload deadline (collect-upload-budget.ts) or when the spool is cleared. */
+ /** Sends one envelope; `signal` aborts at the upload deadline (session-upload-budget.ts) or when the spool is cleared. */
upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => Promise<Response>;
/**
* Asks the account layer for a fresh access token once the gateway rejects
@@ -443,15 +446,15 @@ type CollectorOptions = {
uploadRetryDelayMs?: number;
retryBaseMs?: number;
retryMaxMs?: number;
- /** The upload deadline's parameters; COLLECT_UPLOAD_BUDGET unless a test shrinks it. */
- uploadBudget?: CollectUploadBudget;
+ /** The upload deadline's parameters; SESSION_UPLOAD_BUDGET unless a test shrinks it. */
+ uploadBudget?: SessionUploadBudget;
spoolMaxEntries?: number;
spoolMaxBytes?: number;
/** Uncompressed envelope cap; the backend's MAX_SNAPSHOT_BYTES unless a test lowers it. */
snapshotMaxBytes?: number;
- /** Minimum spacing between change snapshots; MIN_COLLECTOR_CHANGE_INTERVAL_MS unless a test lowers it. */
+ /** Minimum spacing between change snapshots; MIN_UPLOAD_CHANGE_INTERVAL_MS unless a test lowers it. */
minChangeIntervalMs?: number;
- /** Watcher cap; MAX_COLLECTOR_WATCHED_FILES unless a test lowers it. */
+ /** Watcher cap; MAX_UPLOAD_WATCHED_FILES unless a test lowers it. */
maxWatchedFiles?: number;
/** Budget of the redacted-text cache; REDACTED_TEXT_CACHE_BYTES unless a test changes it. */
redactedTextCacheBytes?: number;
@@ -699,23 +702,23 @@ const PRIVACY_POLICY = {
denied_path_classes: [".env*", "credentials", "keys", "secrets", "tokens", "passwords", ".aws", ".ssh", ".gnupg", ".git", "node_modules", "binaries_over_4MiB"],
redaction: ["provider_secrets", "secret_assignments", "private_keys", "pii"],
manifest_hash_basis: "sha256_of_redacted_utf8",
- max_file_bytes: MAX_COLLECTOR_FILE_BYTES,
+ max_file_bytes: MAX_UPLOAD_FILE_BYTES,
max_files: MAX_FILES,
- max_diff_bytes: MAX_COLLECTOR_DIFF_BYTES,
+ max_diff_bytes: MAX_UPLOAD_DIFF_BYTES,
} as const;
/**
- * WorkspaceCollector's `enabled` for these options, without building one: an
- * upload hook, or a collect URL and a bearer (from the options or the
+ * SessionUploader's `enabled` for these options, without building one: an
+ * upload hook, or an upload URL and a bearer (from the options or the
* environment, as the constructor reads them).
*/
-export function workspaceCollectorEnabled(input: { upload: boolean; gatewayUrl?: string; accessToken?: string }): boolean {
+export function sessionUploaderEnabled(input: { upload: boolean; gatewayUrl?: string; accessToken?: string }): boolean {
if (input.upload) return true;
const token = (input.accessToken ?? process.env.OMNIRUSH_ACCESS_TOKEN ?? "").trim();
- return Boolean(resolveCollectUrl(input.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL) && token);
+ return Boolean(resolveUploadUrl(input.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL) && token);
}
-function resolveCollectUrl(rawGatewayUrl: string | undefined): string | null {
+function resolveUploadUrl(rawGatewayUrl: string | undefined): string | null {
const value = rawGatewayUrl?.trim();
if (!value) return null;
try {
@@ -723,7 +726,7 @@ function resolveCollectUrl(rawGatewayUrl: string | undefined): string | null {
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) {
return null;
}
- url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + "/collect";
+ url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + `/${SESSION_UPLOAD_ENDPOINT_PATH}`;
url.search = "";
url.hash = "";
return url.toString();
@@ -754,15 +757,15 @@ export function workspaceRelativePath(root: string, candidate: string, paths: Pl
return path.split(paths.sep).join("/");
}
-export function collectorPathForUpload(path: string): string {
- return redactCollectorText(path).text;
+export function portablePathForUpload(path: string): string {
+ return redactUploadText(path).text;
}
/**
* Truncates text to `limit` code points without splitting a surrogate pair.
* The backend counts code points, so this never exceeds its limit.
*/
-export function clampCollectorText(text: string, limit: number): string {
+export function clampUploadText(text: string, limit: number): string {
if (text.length <= limit) return text;
const points = Array.from(text);
return points.length <= limit ? text : points.slice(0, limit).join("");
@@ -773,7 +776,7 @@ export function clampCollectorText(text: string, limit: number): string {
* Clamps text to a UTF-8 byte budget without splitting a code point. Used for
* the free-text fields of trace events whose caps are expressed in bytes.
*/
-export function clampCollectorBytes(text: string, maxBytes: number): { text: string; truncated: boolean } {
+export function clampUploadBytes(text: string, maxBytes: number): { text: string; truncated: boolean } {
if (Buffer.byteLength(text) <= maxBytes) return { text, truncated: false };
let low = 0;
let high = text.length;
@@ -789,16 +792,16 @@ export function clampCollectorBytes(text: string, maxBytes: number): { text: str
}
/** Redacts then clamps free text destined for a trace event. */
-function collectorTextForTrace(text: string | null | undefined, maxBytes: number): { text: string | null; truncated: boolean } {
+function uploadTextForTrace(text: string | null | undefined, maxBytes: number): { text: string | null; truncated: boolean } {
if (typeof text !== "string") return { text: null, truncated: false };
- return clampCollectorBytes(redactCollectorText(text).text, maxBytes);
+ return clampUploadBytes(redactUploadText(text).text, maxBytes);
}
/**
* Whether a browser visit may be traced. Local pages, inline documents and
* browser-internal URLs never leave the machine.
*/
-export function isCollectableWebUrl(raw: string): boolean {
+export function isUploadableWebUrl(raw: string): boolean {
let url: URL;
try {
url = new URL(raw);
@@ -813,7 +816,7 @@ export function isCollectableWebUrl(raw: string): boolean {
}
function workspaceRootName(root: string): string {
- return clampCollectorText(collectorPathForUpload(root.split(sep).filter(Boolean).at(-1) ?? "workspace"), MAX_ROOT_NAME_CHARS);
+ return clampUploadText(portablePathForUpload(root.split(sep).filter(Boolean).at(-1) ?? "workspace"), MAX_ROOT_NAME_CHARS);
}
function sha256Hex(input: string | Buffer): string {
@@ -847,13 +850,13 @@ function hasScrubbedExtension(lower: string): boolean {
}
/**
- * Whether the collector denies every file under this directory path, whatever
+ * Whether the session uploader denies every file under this directory path, whatever
* the file is called: one of its components meets the unconditional rules
* (`.ssh`, `.aws`, `.gnupg`, `keys`, `secrets`, `credentials*`, `.env*`,
* `node_modules`, `.git`, a key-store suffix, ...). The project archive
* refuses such a folder as the root of an all-folders archive.
*/
-export function isCollectorDirectoryDenied(path: string): boolean {
+export function isUploadDirectoryDenied(path: string): boolean {
return hasDeniedComponent(pathComponents(path));
}
@@ -864,7 +867,7 @@ export function isCollectorDirectoryDenied(path: string): boolean {
* key", "tokens/prod.csv") denies the file unless it has a source-code or docs
* extension, in which case it is kept and scrubbed like any other source file.
*/
-export function isCollectorPathDenied(path: string): boolean {
+export function isUploadPathDenied(path: string): boolean {
const parts = pathComponents(path);
if (hasDeniedComponent(parts)) return true;
const name = parts.at(-1)?.toLowerCase();
@@ -1102,7 +1105,7 @@ function nextAssignmentKeyword(text: string, from: number): number {
return ASSIGNMENT_LINE_GATE.exec(text)?.index ?? -1;
}
-export type RedactCollectorTextOptions = {
+export type RedactUploadTextOptions = {
/** Text that counts as context for context-dependent rules: the file path, or the JSON key a value sits under. */
context?: string;
/** Value rule mode; CONFIG when omitted (git diffs, the trace, JSON). See redactModeForPath. */
@@ -1116,7 +1119,7 @@ export type RedactCollectorTextOptions = {
* assignments, provider token shapes and personal identifiers. The output
* never contains a dangling backslash, so JSON-escaped text stays escapable.
*/
-export function redactCollectorText(input: string, options: RedactCollectorTextOptions = {}): { text: string; count: number } {
+export function redactUploadText(input: string, options: RedactUploadTextOptions = {}): { text: string; count: number } {
const tally = { count: 0 };
let text = input.includes("-----BEGIN ") ? applyRedaction(input, PRIVATE_KEY_BLOCK, tally) : input;
if (text.includes("://")) text = applyRedaction(text, URL_USERINFO, tally);
@@ -1181,7 +1184,7 @@ function redactJsonValue(value: unknown, key: string | undefined, tally: JsonTal
tally.count += 1;
return REDACTED;
}
- const result = redactCollectorText(value, { context: key, awsContext });
+ const result = redactUploadText(value, { context: key, awsContext });
tally.count += result.count;
return result.text;
}
@@ -1199,7 +1202,7 @@ function redactJsonValue(value: unknown, key: string | undefined, tally: JsonTal
tally.members += value.pairs.length;
const context = awsContext || membersNameAws(value.pairs);
return new JsonPairs(value.pairs.map(([childKey, childValue]) => {
- const scrubbedKey = redactCollectorText(childKey, { awsContext: context });
+ const scrubbedKey = redactUploadText(childKey, { awsContext: context });
tally.count += scrubbedKey.count;
return [scrubbedKey.text, redactJsonValue(childValue, childKey, tally, depth + 1, context, maxDepth)];
}));
@@ -1212,7 +1215,7 @@ function redactJsonValue(value: unknown, key: string | undefined, tally: JsonTal
// No prototype, so a `__proto__` key stays an ordinary member.
const output: Record<string, unknown> = Object.create(null);
for (const [childKey, childValue] of entries) {
- const scrubbedKey = redactCollectorText(childKey, { awsContext: context });
+ const scrubbedKey = redactUploadText(childKey, { awsContext: context });
tally.count += scrubbedKey.count;
output[scrubbedKey.text] = redactJsonValue(childValue, childKey, tally, depth + 1, context, maxDepth);
}
@@ -1227,7 +1230,7 @@ function redactJsonValue(value: unknown, key: string | undefined, tally: JsonTal
* never produce a broken escape, which scrubbing serialised JSON as text could.
* The backend's _redact_json_value.
*/
-export function redactCollectorJson(value: unknown): { value: unknown; count: number } {
+export function redactUploadJson(value: unknown): { value: unknown; count: number } {
const tally: JsonTally = { count: 0, members: 0 };
return { value: redactJsonValue(value, undefined, tally), count: tally.count };
}
@@ -1345,7 +1348,7 @@ function stringifyJsonPairs(value: unknown, indent: string | undefined, current
* MAX_JSON_FILE_DEPTH, which the caller scrubs as text. The backend's
* sanitize_json_file.
*/
-export function redactCollectorJsonText(text: string, path?: string): string | null {
+export function redactUploadJsonText(text: string, path?: string): string | null {
const raw = redactAwsSecrets(text, path, { count: 0 });
let parsed: unknown;
try {
@@ -1378,17 +1381,17 @@ export function redactCollectorJsonText(text: string, path?: string): string | n
* back to text when they do not parse), everything else as text with the path
* as context and the value rule mode the extension selects.
*/
-export function redactCollectorContent(path: string, text: string): string {
- return redactCollectorContentCounted(path, text).text;
+export function redactUploadContent(path: string, text: string): string {
+ return redactUploadContentCounted(path, text).text;
}
-/** redactCollectorContent plus how many redactions it made (0 means the text is byte-identical). */
-function redactCollectorContentCounted(path: string, text: string): { text: string; count: number } {
+/** redactUploadContent plus how many redactions it made (0 means the text is byte-identical). */
+function redactUploadContentCounted(path: string, text: string): { text: string; count: number } {
if (/\.json$/i.test(path)) {
- const json = redactCollectorJsonText(text, path);
+ const json = redactUploadJsonText(text, path);
if (json !== null) return { text: json, count: json === text ? 0 : 1 };
}
- return redactCollectorText(text, { context: path, mode: redactModeForPath(path) });
+ return redactUploadText(text, { context: path, mode: redactModeForPath(path) });
}
/**
@@ -1548,7 +1551,7 @@ function gitIgnoredPaths(root: string, paths: string[]): Promise<Set<string> | n
* one bad path never changes the answer for the others (and never sends them
* to the .gitignore-only fallback, which knows nothing of `.git/info/exclude`
* or `core.excludesFile`). A path git refuses on its own counts as ignored:
- * it is never collected. Null only when the workspace is not a git work tree
+ * it is never uploaded. Null only when the workspace is not a git work tree
* (or git is missing), where the caller applies the .gitignore files itself.
* `onSpawn` counts each `git check-ignore` run.
*/
@@ -1622,10 +1625,10 @@ function nullableString(value: unknown): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
}
-function ledgerModel(value: unknown): CollectorSessionModel | undefined {
+function ledgerModel(value: unknown): UploadSessionModel | undefined {
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
- const model: CollectorSessionModel = {
+ const model: UploadSessionModel = {
provider_id: nullableString(record.provider_id),
model_id: nullableString(record.model_id),
variant: nullableString(record.variant),
@@ -1690,7 +1693,7 @@ function boundedTracePayload(
// dangling backslash that made the whole document unparseable. Header and
// events are scrubbed as the one document the backend scrubs, so a header
// value naming an AWS key is container context for the events there too.
- const { events: scrubbed, ...header } = redactCollectorJson({
+ const { events: scrubbed, ...header } = redactUploadJson({
schema_version: 1,
session_id: state.id,
workspace_id: state.workspaceId,
@@ -1710,7 +1713,7 @@ function boundedTracePayload(
// is its wrapper plus the events' serialised bytes and the commas between
// them, so the longest prefix that fits follows from a running total. Every
// probe used to be a full serialisation of the prefix, which made a flush
- // at the MAX_COLLECTOR_TRACE_EVENTS cap peak at many times the payload.
+ // at the MAX_UPLOAD_TRACE_EVENTS cap peak at many times the payload.
let payload = encode(scrubbed, false);
if (payload.byteLength <= maxBytes) return payload;
const wrapperBytes = (included: number) => Buffer.byteLength(JSON.stringify({
@@ -1767,7 +1770,7 @@ async function walkFallback(root: string, directory = root, rules: string[] = []
if (hasDeniedComponent(pathComponents(path))) listing.denied += 1;
else await walkFallback(root, fullPath, ignoreRules, listing);
} else if (entry.isFile()) {
- if (isCollectorPathDenied(path)) listing.denied += 1;
+ if (isUploadPathDenied(path)) listing.denied += 1;
else listing.paths.push(path);
}
}
@@ -1778,7 +1781,7 @@ function filterListing(candidates: string[]): WorkspaceListing {
const listing: WorkspaceListing = { paths: [], denied: 0 };
for (const path of candidates) {
if (!path) continue;
- if (isCollectorPathDenied(path)) listing.denied += 1;
+ if (isUploadPathDenied(path)) listing.denied += 1;
else if (listing.paths.length < MAX_FILES) listing.paths.push(path);
}
return listing;
@@ -1881,9 +1884,9 @@ function parseGitStatus(raw: string, prefix = ""): { entries: GitStatusEntry[];
const path = repoPath.slice(prefix.length);
if (!path) continue;
if (code !== "??" && code !== "!!") dirty = true;
- if (isCollectorPathDenied(path)) continue;
+ if (isUploadPathDenied(path)) continue;
if (entries.length >= MAX_GIT_STATUS_ENTRIES) continue;
- const uploadPath = collectorPathForUpload(path);
+ const uploadPath = portablePathForUpload(path);
if (uploadPath.length > MAX_GIT_PATH_CHARS) continue;
entries.push({ code, path: uploadPath });
}
@@ -1901,8 +1904,8 @@ function parseGitRemotes(raw: string): GitRemote[] {
return [...remotes.entries()]
.slice(0, MAX_GIT_REMOTES)
.map(([name, url]) => ({
- name: clampCollectorText(collectorPathForUpload(name), MAX_GIT_REMOTE_NAME_CHARS),
- url: clampCollectorText(collectorPathForUpload(stripRemoteUserinfo(url)), MAX_GIT_REMOTE_URL_CHARS),
+ name: clampUploadText(portablePathForUpload(name), MAX_GIT_REMOTE_NAME_CHARS),
+ url: clampUploadText(portablePathForUpload(stripRemoteUserinfo(url)), MAX_GIT_REMOTE_URL_CHARS),
}));
}
@@ -1911,7 +1914,7 @@ function parseGitLog(raw: string): GitCommit[] {
for (const record of raw.split("\0")) {
const [sha, at, subject] = record.replace(/^\n/, "").split("\x1f");
if (!sha || !/^[0-9a-f]{7,64}$/.test(sha) || !at) continue;
- commits.push({ sha, at, subject: clampCollectorText(collectorPathForUpload(subject ?? ""), MAX_GIT_SUBJECT_CHARS) });
+ commits.push({ sha, at, subject: clampUploadText(portablePathForUpload(subject ?? ""), MAX_GIT_SUBJECT_CHARS) });
if (commits.length >= MAX_GIT_RECENT_COMMITS) break;
}
return commits;
@@ -1975,7 +1978,7 @@ export function diffHeaderPath(header: string): string | null {
* them, and caps the result. Sections whose header cannot be parsed are
* dropped: an unreadable path must never leak a denied file's contents.
*/
-export function filterCollectorDiff(raw: string, inputTruncated = false): { diff: string | null; truncated: boolean } {
+export function filterUploadDiff(raw: string, inputTruncated = false): { diff: string | null; truncated: boolean } {
let output = "";
let used = 0;
let truncated = inputTruncated;
@@ -1983,15 +1986,15 @@ export function filterCollectorDiff(raw: string, inputTruncated = false): { diff
if (!section.startsWith("diff --git ")) continue;
const headerEnd = section.indexOf("\n");
const path = diffHeaderPath(headerEnd === -1 ? section : section.slice(0, headerEnd));
- if (!path || isCollectorPathDenied(path)) continue;
+ if (!path || isUploadPathDenied(path)) continue;
if (/^(?:Binary files .* differ|GIT binary patch)/m.test(section)) continue;
// A diff is text even when the file is JSON: hunks are not parseable documents.
- const redacted = redactCollectorText(section, { context: path }).text;
+ const redacted = redactUploadText(section, { context: path }).text;
const size = Buffer.byteLength(redacted);
- if (used + size > MAX_COLLECTOR_DIFF_BYTES) {
+ if (used + size > MAX_UPLOAD_DIFF_BYTES) {
truncated = true;
if (used === 0) {
- output = Buffer.from(redacted).subarray(0, MAX_COLLECTOR_DIFF_BYTES).toString("utf8").replace(/�+$/, "");
+ output = Buffer.from(redacted).subarray(0, MAX_UPLOAD_DIFF_BYTES).toString("utf8").replace(/�+$/, "");
}
break;
}
@@ -2014,7 +2017,7 @@ async function gitDiff(root: string, hasHead: boolean): Promise<{ diff: string |
const options = { maxBytes: GIT_DIFF_READ_BYTES, timeoutMs: 20_000 };
if (hasHead) {
const result = await runGit(root, ["diff", "HEAD", ...common, ...scope], options);
- if (result.ok) return filterCollectorDiff(result.stdout.toString("utf8"), result.truncated);
+ if (result.ok) return filterUploadDiff(result.stdout.toString("utf8"), result.truncated);
}
// An unborn branch has no HEAD to diff against: combine the index (against
// the empty tree) with the working tree changes on top of it.
@@ -2024,7 +2027,7 @@ async function gitDiff(root: string, hasHead: boolean): Promise<{ diff: string |
]);
if (!staged.ok && !unstaged.ok) return { diff: null, truncated: false };
const text = `${staged.ok ? staged.stdout.toString("utf8") : ""}${unstaged.ok ? unstaged.stdout.toString("utf8") : ""}`;
- return filterCollectorDiff(text, staged.truncated || unstaged.truncated);
+ return filterUploadDiff(text, staged.truncated || unstaged.truncated);
}
/**
@@ -2034,7 +2037,7 @@ async function gitDiff(root: string, hasHead: boolean): Promise<{ diff: string |
* upstream, remotes without userinfo, recent subjects) and what is in flight
* (porcelain status and the combined text diff), all redacted.
*/
-export async function collectGitBlock(root: string): Promise<CollectorGitBlock | null> {
+export async function collectGitBlock(root: string): Promise<UploadGitBlock | null> {
const inside = await gitText(root, ["rev-parse", "--is-inside-work-tree"]);
if (inside !== "true") return null;
// Where the workspace sits inside the repository ("" at the top level,
@@ -2067,9 +2070,9 @@ export async function collectGitBlock(root: string): Promise<CollectorGitBlock |
const diff = await gitDiff(root, Boolean(commit));
return {
commit,
- branch: branch ? clampCollectorText(collectorPathForUpload(branch), MAX_GIT_REF_CHARS) : null,
+ branch: branch ? clampUploadText(portablePathForUpload(branch), MAX_GIT_REF_CHARS) : null,
dirty: parsedStatus.dirty,
- upstream: upstream ? clampCollectorText(collectorPathForUpload(upstream), MAX_GIT_REF_CHARS) : null,
+ upstream: upstream ? clampUploadText(portablePathForUpload(upstream), MAX_GIT_REF_CHARS) : null,
ahead,
behind,
remotes: remotes ? parseGitRemotes(remotes) : [],
@@ -2174,7 +2177,7 @@ class ReadPool {
/** Runs `use` with the file's bytes; the view must not escape `use`. */
async read<T>(absolute: string, expectedSize: number, use: (bytes: Buffer) => Promise<T> | T): Promise<T | null> {
- if (expectedSize > MAX_COLLECTOR_FILE_BYTES) return null;
+ if (expectedSize > MAX_UPLOAD_FILE_BYTES) return null;
if (expectedSize < this.capacity) {
const buffer = await this.acquire();
try {
@@ -2190,10 +2193,10 @@ class ReadPool {
private readLarge<T>(absolute: string, use: (bytes: Buffer) => Promise<T> | T): Promise<T | null> {
const run = this.largeTail.then(async () => {
- this.large ??= Buffer.allocUnsafeSlow(MAX_COLLECTOR_FILE_BYTES + 1);
+ this.large ??= Buffer.allocUnsafeSlow(MAX_UPLOAD_FILE_BYTES + 1);
const length = await readInto(absolute, this.large);
- // Past the cap by now: not a file the collector takes.
- return length > MAX_COLLECTOR_FILE_BYTES ? null : await use(this.large.subarray(0, length));
+ // Past the cap by now: not a file the session uploader takes.
+ return length > MAX_UPLOAD_FILE_BYTES ? null : await use(this.large.subarray(0, length));
});
this.largeTail = run.catch(() => undefined);
return run;
@@ -2290,7 +2293,7 @@ export async function mapBounded<T, R>(items: readonly T[], limit: number, opera
}
/** Work counters for tests and profiling; never uploaded. */
-export type CollectorMetrics = {
+export type UploadMetrics = {
fileStats: number;
fileReads: number;
fileRedactions: number;
@@ -2308,7 +2311,7 @@ export type CollectorMetrics = {
redactedTextHits: number;
};
-function freshMetrics(): CollectorMetrics {
+function freshMetrics(): UploadMetrics {
return {
fileStats: 0, fileReads: 0, fileRedactions: 0, fullScans: 0, dirtyScans: 0, reconciles: 0,
capturesSkipped: 0, capturesDeferred: 0, capturesHeld: 0, ignoreCheckSpawns: 0, watchEvents: 0, envelopesWritten: 0, redactedTextHits: 0,
@@ -2326,10 +2329,10 @@ function redactedCacheEntry(
size: number,
mtimeMs: number,
uploadPath: string,
- metrics: CollectorMetrics,
+ metrics: UploadMetrics,
texts?: { cache: RedactedTextCache; absolute: string },
): { entry: HashCacheEntry; text: string } {
- const redacted = redactCollectorContentCounted(path, buffer.toString("utf8"));
+ const redacted = redactUploadContentCounted(path, buffer.toString("utf8"));
metrics.fileRedactions += 1;
const entry: HashCacheEntry = {
size,
@@ -2351,7 +2354,7 @@ function redactedCacheEntry(
/** The redacted upload path, sharing the listing's string when redaction left it unchanged. */
function uploadPathFor(path: string, cached: HashCacheEntry | undefined): string {
if (cached) return cached.uploadPath;
- const uploadPath = collectorPathForUpload(path);
+ const uploadPath = portablePathForUpload(path);
return uploadPath === path ? path : uploadPath;
}
@@ -2389,13 +2392,13 @@ type ScanContext = {
rootPrefix: string;
cache: Map<string, HashCacheEntry>;
texts: RedactedTextCache;
- metrics: CollectorMetrics;
+ metrics: UploadMetrics;
yielder: LoopYielder;
pool: ReadPool;
ancestors: AncestorCache;
};
-function scanContext(root: string, cache: Map<string, HashCacheEntry>, texts: RedactedTextCache, metrics: CollectorMetrics): ScanContext {
+function scanContext(root: string, cache: Map<string, HashCacheEntry>, texts: RedactedTextCache, metrics: UploadMetrics): ScanContext {
const base = resolve(root);
return {
root,
@@ -2428,7 +2431,7 @@ async function inspectFile(context: ScanContext, path: string): Promise<HashCach
return null;
}
metrics.fileStats += 1;
- if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) return null;
+ if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_UPLOAD_FILE_BYTES) return null;
const cached = cache.get(path);
if (cached && cached.size === file.size && cached.mtimeMs === file.mtimeMs) return cached;
const uploadPath = uploadPathFor(path, cached);
@@ -2465,7 +2468,7 @@ async function readUploadContent(
path: string,
cache: Map<string, HashCacheEntry>,
texts: RedactedTextCache,
- metrics: CollectorMetrics,
+ metrics: UploadMetrics,
pool: ReadPool,
ancestors: AncestorCache,
): Promise<UploadContent | null> {
@@ -2478,7 +2481,7 @@ async function readUploadContent(
} catch {
return null;
}
- if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) return null;
+ if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_UPLOAD_FILE_BYTES) return null;
const cached = cache.get(path);
try {
return await pool.read(absolute, file.size, (buffer): UploadContent | null => {
@@ -2539,7 +2542,7 @@ type SnapshotCandidate = {
};
/**
- * The workspace as a turn began, by path: null for a file the collector only
+ * The workspace as a turn began, by path: null for a file the session uploader only
* ever saw once the turn had written it (it was there, but what it held
* before the turn is unknown).
*/
@@ -2645,7 +2648,7 @@ async function scanWorkspaceFull(
texts: RedactedTextCache,
previous: Manifest | null,
includeAll: boolean,
- metrics: CollectorMetrics,
+ metrics: UploadMetrics,
onListing?: (paths: readonly string[]) => void,
): Promise<ScanResult> {
metrics.fullScans += 1;
@@ -2692,7 +2695,7 @@ async function scanDirtyPaths(
dirty: readonly string[],
ignored: ReadonlySet<string>,
listing: { denied: number; truncated: boolean },
- metrics: CollectorMetrics,
+ metrics: UploadMetrics,
): Promise<ScanResult> {
metrics.dirtyScans += 1;
const context = scanContext(root, cache, texts, metrics);
@@ -2745,13 +2748,13 @@ async function scanDirtyPaths(
* Paths whose content a capped snapshot keeps first: what the session touched
* plus what git reports as modified, keyed the way files[] names them.
*/
-function snapshotPriorityPaths(touched: Iterable<string>, git: CollectorGitBlock | null): Set<string> {
+function snapshotPriorityPaths(touched: Iterable<string>, git: UploadGitBlock | null): Set<string> {
const paths = new Set<string>();
- for (const path of touched) paths.add(collectorPathForUpload(path));
+ for (const path of touched) paths.add(portablePathForUpload(path));
for (const entry of git?.status ?? []) paths.add(entry.path);
for (const line of git?.diff?.split("\n") ?? []) {
const path = diffHeaderPath(line);
- if (path) paths.add(collectorPathForUpload(path));
+ if (path) paths.add(portablePathForUpload(path));
}
return paths;
}
@@ -2902,14 +2905,14 @@ type EnvelopeBody = {
/** Envelope fields written before files[]: workspace, environment, touched paths, scope. */
extras: Record<string, unknown>;
/** Streams files[] one entry at a time through `emit`. */
- writeFiles: (emit: (file: CollectorFile) => Promise<void>) => Promise<void>;
+ writeFiles: (emit: (file: UploadFile) => Promise<void>) => Promise<void>;
manifest: () => Iterable<HashCacheEntry>;
/** Computed once files[] is written, so cap omissions are known. */
privacy: () => Record<string, unknown>;
trace?: unknown[];
};
-function collectorEnvironment(appVersion: string | undefined, engineVersion: string | undefined, gitVersion: string | null): CollectorEnvironment {
+function uploadEnvironment(appVersion: string | undefined, engineVersion: string | undefined, gitVersion: string | null): UploadEnvironment {
let locale: string | null = null;
let timezone: string | null = null;
try {
@@ -2921,7 +2924,7 @@ function collectorEnvironment(appVersion: string | undefined, engineVersion: str
}
const shellPath = process.platform === "win32" ? process.env.COMSPEC : process.env.SHELL;
const field = (value: string | null | undefined): string | null =>
- value?.trim() ? clampCollectorText(value.trim(), MAX_ENVIRONMENT_FIELD_CHARS) : null;
+ value?.trim() ? clampUploadText(value.trim(), MAX_ENVIRONMENT_FIELD_CHARS) : null;
return {
os: process.platform,
os_version: field(osRelease()) ?? "",
@@ -2974,7 +2977,7 @@ function parseSpoolMeta(value: unknown): SpoolMeta | null {
id: record.id,
session_id: record.session_id,
snapshot_type: record.snapshot_type as SnapshotType,
- trigger: record.trigger as CollectorTrigger,
+ trigger: record.trigger as UploadTrigger,
sequence: record.sequence,
bytes: record.bytes,
created_at: record.created_at,
@@ -2983,16 +2986,19 @@ function parseSpoolMeta(value: unknown): SpoolMeta | null {
};
}
-export class WorkspaceCollector {
- private readonly collectUrl: string | null;
+export class SessionUploader {
+ private readonly uploadUrl: string | null;
private token: string;
private readonly fetcher: typeof externalFetch;
- private readonly uploader?: CollectorOptions["upload"];
- private readonly refreshAccessToken?: CollectorOptions["refreshAccessToken"];
- private readonly log: NonNullable<CollectorOptions["log"]>;
+ private readonly uploader?: SessionUploaderOptions["upload"];
+ private readonly refreshAccessToken?: SessionUploaderOptions["refreshAccessToken"];
+ private readonly log: NonNullable<SessionUploaderOptions["log"]>;
private readonly ledgerPath: string | null;
private readonly spoolDir: string | null;
private readonly ledgerReady: Promise<void>;
+ private readonly stateDir: string | null;
+ /** The move of pre-2.2.2 state names (session-upload-state.ts); every state read waits for it. */
+ private readonly stateMigrated: Promise<void>;
private ledger: SessionLedger = { version: 1, sessions: {} };
private ledgerWriteTail: Promise<void> = Promise.resolve();
private readonly sessions = new Map<string, SessionState>();
@@ -3003,11 +3009,11 @@ export class WorkspaceCollector {
private readonly uploadRetryDelayMs: number;
private readonly retryBaseMs: number;
private readonly retryMaxMs: number;
- private readonly uploadBudget: CollectUploadBudget;
+ private readonly uploadBudget: SessionUploadBudget;
private readonly spoolMaxEntries: number;
private readonly spoolMaxBytes: number;
private readonly snapshotMaxBytes: number;
- private environmentCache: Promise<CollectorEnvironment> | null = null;
+ private environmentCache: Promise<UploadEnvironment> | null = null;
private spoolCounter = 0;
private spoolTail: Promise<void> = Promise.resolve();
private retryTimer: ReturnType<typeof setTimeout> | null = null;
@@ -3040,19 +3046,24 @@ export class WorkspaceCollector {
private readonly onSessionClosed?: (sessionId: string) => void;
private readonly onPathTouched?: (sessionId: string, path: string) => void;
/** Work counters for tests and profiling. */
- readonly metrics: CollectorMetrics = freshMetrics();
+ readonly metrics: UploadMetrics = freshMetrics();
- constructor(options: CollectorOptions = {}) {
- this.collectUrl = resolveCollectUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);
+ constructor(options: SessionUploaderOptions = {}) {
+ this.uploadUrl = resolveUploadUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);
this.token = (options.accessToken ?? process.env.OMNIRUSH_ACCESS_TOKEN ?? "").trim();
this.fetcher = options.fetch ?? externalFetch;
this.uploader = options.upload;
this.refreshAccessToken = options.refreshAccessToken;
this.log = options.log ?? (() => undefined);
const stateDir = options.stateDir ? resolve(options.stateDir) : null;
- this.ledgerPath = stateDir ? join(stateDir, SESSION_LEDGER_FILE) : null;
- this.spoolDir = stateDir ? join(stateDir, SPOOL_DIRECTORY) : null;
- this.ledgerReady = this.loadLedger();
+ this.stateDir = stateDir;
+ this.ledgerPath = stateDir ? join(stateDir, UPLOAD_SESSION_LEDGER_FILE) : null;
+ this.spoolDir = stateDir ? join(stateDir, UPLOAD_SPOOL_DIRECTORY) : null;
+ // State left under the pre-2.2.2 names is moved before anything reads it.
+ this.stateMigrated = stateDir
+ ? migrateLegacyUploadState(stateDir, (message, details) => this.log("warn", message, details))
+ : Promise.resolve();
+ this.ledgerReady = this.stateMigrated.then(() => this.loadLedger());
this.changeDebounceMs = options.changeDebounceMs ?? CHANGE_DEBOUNCE_MS;
this.fallbackScanMs = options.fallbackScanMs ?? FALLBACK_SCAN_MS;
this.appVersion = options.appVersion;
@@ -3060,18 +3071,22 @@ export class WorkspaceCollector {
this.uploadRetryDelayMs = options.uploadRetryDelayMs ?? UPLOAD_RETRY_DELAY_MS;
this.retryBaseMs = options.retryBaseMs ?? RETRY_BASE_MS;
this.retryMaxMs = options.retryMaxMs ?? RETRY_MAX_MS;
- this.uploadBudget = options.uploadBudget ?? COLLECT_UPLOAD_BUDGET;
+ this.uploadBudget = options.uploadBudget ?? SESSION_UPLOAD_BUDGET;
this.spoolMaxEntries = options.spoolMaxEntries ?? MAX_SPOOL_ENTRIES;
this.spoolMaxBytes = options.spoolMaxBytes ?? MAX_SPOOL_BYTES;
this.snapshotMaxBytes = options.snapshotMaxBytes ?? MAX_SNAPSHOT_BYTES;
- this.minChangeIntervalMs = options.minChangeIntervalMs ?? MIN_COLLECTOR_CHANGE_INTERVAL_MS;
- this.maxWatchedFiles = options.maxWatchedFiles ?? MAX_COLLECTOR_WATCHED_FILES;
+ this.minChangeIntervalMs = options.minChangeIntervalMs ?? MIN_UPLOAD_CHANGE_INTERVAL_MS;
+ this.maxWatchedFiles = options.maxWatchedFiles ?? MAX_UPLOAD_WATCHED_FILES;
this.texts = new RedactedTextCache(options.redactedTextCacheBytes ?? REDACTED_TEXT_CACHE_BYTES);
this.onSessionClosed = options.onSessionClosed;
this.onPathTouched = options.onPathTouched;
- this.tempDir = stateDir ? join(stateDir, TEMP_DIRECTORY) : join(tmpdir(), `omnirush-collector-${process.pid}`);
- this.bases = new TurnBaseStore(stateDir ? join(stateDir, BASE_DIRECTORY) : join(this.tempDir, BASE_DIRECTORY));
- void this.cleanTempDir(60 * 60_000).catch(() => undefined);
+ this.tempDir = stateDir ? join(stateDir, UPLOAD_TEMP_DIRECTORY) : join(tmpdir(), `omnirush-upload-${process.pid}`);
+ this.bases = new TurnBaseStore(
+ stateDir ? join(stateDir, UPLOAD_BASE_DIRECTORY) : join(this.tempDir, UPLOAD_BASE_DIRECTORY),
+ undefined,
+ this.stateMigrated,
+ );
+ void this.stateMigrated.then(() => this.cleanTempDir(60 * 60_000)).catch(() => undefined);
if (this.spoolDir) {
if (this.enabled) {
// Uploads spooled by a previous process are retried once this one is up.
@@ -3202,10 +3217,10 @@ export class WorkspaceCollector {
}
get enabled(): boolean {
- return Boolean(this.uploader || (this.collectUrl && this.token));
+ return Boolean(this.uploader || (this.uploadUrl && this.token));
}
- private environment(): Promise<CollectorEnvironment> {
+ private environment(): Promise<UploadEnvironment> {
this.environmentCache ??= (async () => {
let gitVersion: string | null = null;
try {
@@ -3214,7 +3229,7 @@ export class WorkspaceCollector {
} catch {
gitVersion = null;
}
- return collectorEnvironment(this.appVersion, this.engineVersion, gitVersion);
+ return uploadEnvironment(this.appVersion, this.engineVersion, gitVersion);
})();
return this.environmentCache;
}
@@ -3344,7 +3359,7 @@ export class WorkspaceCollector {
state.watchMode = "polling";
state.dirtyOverflow = true;
this.stopReconcile(state);
- this.log("info", "OmniRush collection polls this workspace on snapshots instead of watching it", {
+ this.log("info", "OmniRush session upload polls this workspace on snapshots instead of watching it", {
sessionId: state.id,
files,
limit: this.maxWatchedFiles,
@@ -3396,7 +3411,7 @@ export class WorkspaceCollector {
const path = workspaceRelativePath(state.root, prefix ? `${prefix}/${relative}` : relative);
if (!path) return;
this.reportTouched(state, path);
- if (isCollectorPathDenied(path)) return;
+ if (isUploadPathDenied(path)) return;
if (path === ".gitignore" || path.endsWith("/.gitignore")) {
// New ignore rules can hide or reveal any number of files: forget what
// git answered so far and rescan the tree with the rules as they stand.
@@ -3495,7 +3510,7 @@ export class WorkspaceCollector {
await mapBounded(listing.paths, SCAN_CONCURRENCY, async (path) => {
const file = await lstat(resolve(state.root, path)).catch(() => null);
if (file) this.metrics.fileStats += 1;
- const eligible = file && file.isFile() && !file.isSymbolicLink() && file.size <= MAX_COLLECTOR_FILE_BYTES ? file : null;
+ const eligible = file && file.isFile() && !file.isSymbolicLink() && file.size <= MAX_UPLOAD_FILE_BYTES ? file : null;
const cached = cache.get(path);
for (const session of sessions) {
const known = session.manifest?.get(path);
@@ -3577,7 +3592,7 @@ export class WorkspaceCollector {
* asks git about every path whatever the cache holds, and refreshes the
* cache with the answers: a snapshot decides what leaves the machine on
* that answer, since `.git/info/exclude` or `core.excludesFile` can change
- * with no event the collector sees.
+ * with no event the session uploader sees.
*/
private async ignoredPaths(state: SessionState, paths: string[], fresh = false): Promise<Set<string>> {
const ignored = new Set<string>();
@@ -3676,24 +3691,24 @@ export class WorkspaceCollector {
this.appendTrace(state, type, data);
}
- /** Appends one trace event, keeping only the newest MAX_COLLECTOR_TRACE_EVENTS. */
+ /** Appends one trace event, keeping only the newest MAX_UPLOAD_TRACE_EVENTS. */
private appendTrace(state: SessionState, type: string, data?: unknown): void {
state.trace.push({ at: new Date().toISOString(), type, ...(data === undefined ? {} : { data }) });
- if (state.trace.length > MAX_COLLECTOR_TRACE_EVENTS) state.trace.splice(0, state.trace.length - MAX_COLLECTOR_TRACE_EVENTS);
+ if (state.trace.length > MAX_UPLOAD_TRACE_EVENTS) state.trace.splice(0, state.trace.length - MAX_UPLOAD_TRACE_EVENTS);
}
private recordTouchedPath(state: SessionState, candidate: string): void {
const path = workspaceRelativePath(state.root, candidate.replaceAll("\\", "/"));
if (!path) return;
this.reportTouched(state, path);
- if (isCollectorPathDenied(path) || state.touchedPaths.has(path)) return;
+ if (isUploadPathDenied(path) || state.touchedPaths.has(path)) return;
state.touchedPaths.add(path);
this.markDirty(state, path);
this.queueChangedPath(state, path);
this.scheduleChange(state, "fs_change");
}
- /** Whether the collector is currently tracking this session. */
+ /** Whether the session uploader is currently tracking this session. */
hasSession(sessionId: string): boolean {
const state = this.sessions.get(sessionId);
return Boolean(state && !state.finished);
@@ -3704,11 +3719,11 @@ export class WorkspaceCollector {
* message) as a "session.model" event and remembers it for the envelope's
* "session" block. Identical for omnirush.ai and every external provider.
*/
- recordSessionModel(sessionId: string, model: CollectorSessionModel): void {
+ recordSessionModel(sessionId: string, model: UploadSessionModel): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
- const clamp = (value: string | null) => (value ? clampCollectorText(value, MAX_ENVIRONMENT_FIELD_CHARS) : null);
- const cleaned: CollectorSessionModel = {
+ const clamp = (value: string | null) => (value ? clampUploadText(value, MAX_ENVIRONMENT_FIELD_CHARS) : null);
+ const cleaned: UploadSessionModel = {
provider_id: clamp(model.provider_id),
model_id: clamp(model.model_id),
variant: clamp(model.variant),
@@ -3740,7 +3755,7 @@ export class WorkspaceCollector {
* once the root turn settled: one "session.child" event carrying the child's
* new messages, plus the child's checkpoint for the next capture.
*/
- recordChildSession(sessionId: string, child: CollectorChildSession): void {
+ recordChildSession(sessionId: string, child: UploadChildSession): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
if (!/^[A-Za-z0-9._:-]{1,256}$/.test(child.childSessionId)) return;
@@ -3753,9 +3768,9 @@ export class WorkspaceCollector {
this.appendTrace(state, "session.child", {
child_session_id: child.childSessionId,
parent_session_id: child.parentSessionId,
- ...(Number.isSafeInteger(child.depth) && child.depth! >= 1 && child.depth! <= MAX_COLLECTOR_CHILD_SESSION_DEPTH ? { depth: child.depth } : {}),
- title: child.title ? clampCollectorText(child.title, MAX_GIT_SUBJECT_CHARS) : null,
- agent: child.agent ? clampCollectorText(child.agent, MAX_ENVIRONMENT_FIELD_CHARS) : null,
+ ...(Number.isSafeInteger(child.depth) && child.depth! >= 1 && child.depth! <= MAX_UPLOAD_CHILD_SESSION_DEPTH ? { depth: child.depth } : {}),
+ title: child.title ? clampUploadText(child.title, MAX_GIT_SUBJECT_CHARS) : null,
+ agent: child.agent ? clampUploadText(child.agent, MAX_ENVIRONMENT_FIELD_CHARS) : null,
messages: withSubagentFallbacks(child.messages, state.subagentFallbacks.get(child.childSessionId)),
});
void this.persistOnceReady(state);
@@ -3766,18 +3781,18 @@ export class WorkspaceCollector {
* browser-internal URLs are never traced; page text is redacted and capped.
* Returns whether the visit was recorded.
*/
- recordWebVisit(sessionId: string, visit: CollectorWebVisit): boolean {
+ recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return false;
- if (typeof visit.url !== "string" || !isCollectableWebUrl(visit.url)) return false;
+ if (typeof visit.url !== "string" || !isUploadableWebUrl(visit.url)) return false;
const url = new URL(visit.url);
url.username = "";
url.password = "";
- const title = collectorTextForTrace(visit.title ?? null, MAX_WEB_VISIT_TITLE_CHARS * 4);
- const text = collectorTextForTrace(visit.text ?? null, MAX_COLLECTOR_WEB_VISIT_TEXT_BYTES);
+ const title = uploadTextForTrace(visit.title ?? null, MAX_WEB_VISIT_TITLE_CHARS * 4);
+ const text = uploadTextForTrace(visit.text ?? null, MAX_UPLOAD_WEB_VISIT_TEXT_BYTES);
this.appendTrace(state, "web.visit", {
- url: clampCollectorText(redactCollectorText(url.toString()).text, MAX_WEB_VISIT_URL_CHARS),
- title: title.text === null ? null : clampCollectorText(title.text, MAX_WEB_VISIT_TITLE_CHARS),
+ url: clampUploadText(redactUploadText(url.toString()).text, MAX_WEB_VISIT_URL_CHARS),
+ title: title.text === null ? null : clampUploadText(title.text, MAX_WEB_VISIT_TITLE_CHARS),
text: text.text,
text_truncated: text.truncated,
});
@@ -3785,13 +3800,13 @@ export class WorkspaceCollector {
}
/** Records a file attached to a prompt: identity, size, and redacted, capped text when extractable. */
- recordAttachment(sessionId: string, attachment: CollectorAttachment): void {
+ recordAttachment(sessionId: string, attachment: UploadAttachment): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
- const text = collectorTextForTrace(attachment.text, MAX_COLLECTOR_ATTACHMENT_TEXT_BYTES);
+ const text = uploadTextForTrace(attachment.text, MAX_UPLOAD_ATTACHMENT_TEXT_BYTES);
this.appendTrace(state, "attachment", {
- name: clampCollectorText(redactCollectorText(basename(attachment.name || "attachment")).text, MAX_ATTACHMENT_NAME_CHARS),
- mime: clampCollectorText(attachment.mime || "application/octet-stream", MAX_ATTACHMENT_MIME_CHARS),
+ name: clampUploadText(redactUploadText(basename(attachment.name || "attachment")).text, MAX_ATTACHMENT_NAME_CHARS),
+ mime: clampUploadText(attachment.mime || "application/octet-stream", MAX_ATTACHMENT_MIME_CHARS),
bytes: Math.max(0, Math.floor(attachment.bytes)),
sha256: attachment.sha256,
text: text.text,
@@ -3811,7 +3826,7 @@ export class WorkspaceCollector {
}
}
- private sessionBlock(state: SessionState): CollectorSessionBlock {
+ private sessionBlock(state: SessionState): UploadSessionBlock {
return {
provider_id: state.model?.provider_id ?? null,
model_id: state.model?.model_id ?? null,
@@ -3843,7 +3858,7 @@ export class WorkspaceCollector {
if (emitted >= MAX_ARTIFACT_EVENTS_PER_TURN || stat.size > MAX_ARTIFACT_HASH_BYTES) continue;
try {
const sha256 = await sha256File(resolve(state.root, path));
- this.appendTrace(state, "artifact", { path: collectorPathForUpload(path), sha256, bytes: stat.size });
+ this.appendTrace(state, "artifact", { path: portablePathForUpload(path), sha256, bytes: stat.size });
state.touchedPaths.add(path);
emitted += 1;
} catch {
@@ -3943,14 +3958,14 @@ export class WorkspaceCollector {
private async turnDiffInput(state: SessionState, change: TurnChange, pool: ReadPool, ancestors: AncestorCache, texts: boolean): Promise<TurnDiffInput | null> {
const { path, before, after, unseen } = change;
const input = {
- path: (after ?? before)?.uploadPath ?? collectorPathForUpload(path),
+ path: (after ?? before)?.uploadPath ?? portablePathForUpload(path),
before_sha256: before?.sha256 ?? null,
after_sha256: after?.sha256 ?? null,
before: null,
after: null,
};
if (after) {
- // Changed by the turn from a form the collector never saw: nothing to diff against.
+ // Changed by the turn from a form the session uploader never saw: nothing to diff against.
if (unseen) return { ...input, status: "no_base" };
if (before && !(await this.bases.has(before.sha256))) return { ...input, status: "no_base" };
if (!texts) return { ...input, status: before ? "modified" : "added" };
@@ -3971,7 +3986,7 @@ export class WorkspaceCollector {
return base === null ? { ...input, status: "no_base" } : { ...input, status: "deleted", before: base };
}
if (!file.isFile() || file.isSymbolicLink()) return null;
- if (file.size <= MAX_COLLECTOR_FILE_BYTES && !state.cache.get(path)?.binary && !(await startsBinary(absolute))) return null;
+ if (file.size <= MAX_UPLOAD_FILE_BYTES && !state.cache.get(path)?.binary && !(await startsBinary(absolute))) return null;
return { ...input, after_sha256: null, status: "skipped" };
}
@@ -4208,7 +4223,7 @@ export class WorkspaceCollector {
private queueChangedPath(state: SessionState, filename: string): void {
if (state.finished) return;
const path = workspaceRelativePath(state.root, filename);
- if (!path || isCollectorPathDenied(path)) return;
+ if (!path || isUploadPathDenied(path)) return;
// Several events for one path before its capture starts collapse into one read.
if (state.pendingJournal.has(path)) return;
state.pendingJournal.add(path);
@@ -4247,7 +4262,7 @@ export class WorkspaceCollector {
const file = await lstat(absolute);
const written = writtenThisTurn(state.turnStartedAt, state.cache.get(path), file);
if (file.isFile() && !file.isSymbolicLink() && file.size > MAX_CHANGE_JOURNAL_BYTES && written) state.turnSkipped.set(path, file.mtimeMs);
- if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) {
+ if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_UPLOAD_FILE_BYTES) {
entry = { path, at: new Date().toISOString(), status: "skipped" };
} else if (file.size > MAX_CHANGE_JOURNAL_BYTES) {
// Larger than the whole journal: it could only evict every other entry
@@ -4257,7 +4272,7 @@ export class WorkspaceCollector {
} else {
const buffer = await readFile(absolute);
this.metrics.fileReads += 1;
- if (buffer.length > MAX_COLLECTOR_FILE_BYTES || isBinary(buffer)) {
+ if (buffer.length > MAX_UPLOAD_FILE_BYTES || isBinary(buffer)) {
if (written) state.turnSkipped.set(path, file.mtimeMs);
entry = { path, at: new Date().toISOString(), status: "skipped" };
} else {
@@ -4295,7 +4310,7 @@ export class WorkspaceCollector {
private enqueue(state: SessionState, operation: () => Promise<void>): void {
state.tail = state.tail.then(operation).catch((error: unknown) => {
- this.log("warn", "OmniRush collection operation failed", {
+ this.log("warn", "OmniRush session upload operation failed", {
sessionId: state.id,
error: error instanceof Error ? error.message : "unknown",
});
@@ -4303,7 +4318,7 @@ export class WorkspaceCollector {
}
private touchedPathsForUpload(state: SessionState): string[] {
- return [...state.touchedPaths].slice(0, MAX_TOUCHED_PATHS).map(collectorPathForUpload);
+ return [...state.touchedPaths].slice(0, MAX_TOUCHED_PATHS).map(portablePathForUpload);
}
/**
@@ -4317,7 +4332,7 @@ export class WorkspaceCollector {
* and covers the whole tree otherwise. Resolves with whether a snapshot went
* out.
*/
- private async uploadWorkspace(state: SessionState, type: Exclude<SnapshotType, "trace">, trigger: CollectorTrigger): Promise<boolean> {
+ private async uploadWorkspace(state: SessionState, type: Exclude<SnapshotType, "trace">, trigger: UploadTrigger): Promise<boolean> {
const cache = state.cache;
// Paths reported from here on belong to the next capture.
const dirty = state.dirty;
@@ -4331,7 +4346,7 @@ export class WorkspaceCollector {
// listing vouches for (the paths a targeted scan inspects, and every
// journal entry), in one batch: nothing git ignores now leaves the
// machine, whatever it answered when the event arrived.
- const reported = targeted && previous !== null ? [...dirty].filter((path) => !isCollectorPathDenied(path)) : [];
+ const reported = targeted && previous !== null ? [...dirty].filter((path) => !isUploadPathDenied(path)) : [];
const journaled = type === "change" || type === "end" ? [...state.changeJournal.values()] : [];
const checked = [...new Set([...reported, ...journaled.map((entry) => entry.path)])];
const ignored = checked.length > 0 ? await this.ignoredPaths(state, checked, true) : new Set<string>();
@@ -4351,7 +4366,7 @@ export class WorkspaceCollector {
if (previous !== null) for (const path of scan.changed ?? []) this.reportTouched(state, path);
// A change capture that found nothing moved stops at one `git rev-parse`
// (a commit changes history without touching a file); the full git block
- // with its status, log and diff is collected only for a snapshot that goes out.
+ // with its status, log and diff is read only for a snapshot that goes out.
if (type === "change" && scan.changed !== null && scan.changed.size === 0 && scan.removed === 0 && !this.journalHasChanges(state)
&& (await gitHead(state.root)) === state.lastHead) {
accepted = true;
@@ -4364,7 +4379,7 @@ export class WorkspaceCollector {
const rootName = workspaceRootName(state.root);
const touchedPaths = this.touchedPathsForUpload(state);
const metadata = JSON.stringify({
- schema_version: COLLECTOR_SCHEMA_VERSION,
+ schema_version: UPLOAD_SCHEMA_VERSION,
workspace_id: state.workspaceId,
session_id: state.id,
session_segment: state.segment,
@@ -4376,12 +4391,12 @@ export class WorkspaceCollector {
root_name: rootName,
git: { commit: git?.commit ?? null, branch: git?.branch ?? null, dirty: git ? String(git.dirty) : "false" },
});
- const leading: CollectorFile[] = [{ path: "__omnirush__/workspace.json", content: metadata, sha256: sha256Hex(metadata) }];
+ const leading: UploadFile[] = [{ path: "__omnirush__/workspace.json", content: metadata, sha256: sha256Hex(metadata) }];
if (journal.length > 0) {
const changes = JSON.stringify({
schema_version: 1,
session_id: state.id,
- entries: journal.map((entry) => ({ ...entry, path: collectorPathForUpload(entry.path) })),
+ entries: journal.map((entry) => ({ ...entry, path: portablePathForUpload(entry.path) })),
});
leading.push({ path: "__omnirush__/changes.json", content: changes, sha256: sha256Hex(changes) });
}
@@ -4456,7 +4471,7 @@ export class WorkspaceCollector {
omitted_bytes: omittedBytes,
budget_bytes: budget,
});
- this.log("warn", "OmniRush collection snapshot trimmed to the snapshot cap", {
+ this.log("warn", "OmniRush session upload snapshot trimmed to the snapshot cap", {
sessionId: state.id,
snapshotType: type,
trigger,
@@ -4511,7 +4526,7 @@ export class WorkspaceCollector {
/**
* One POST of an envelope, ended by `deadline` (the attempt's size-scaled
- * deadline, collect-upload-budget.ts: fetch reports no upload progress, so
+ * deadline, session-upload-budget.ts: fetch reports no upload progress, so
* sending the body and the gateway's answer share one deadline) or sooner
* by `cancel`.
*/
@@ -4519,7 +4534,7 @@ export class WorkspaceCollector {
const signal = cancel ? AbortSignal.any([deadline, cancel]) : deadline;
if (signal.aborted) return Promise.reject(signal.reason);
if (this.uploader) return untilAborted(this.uploader(sessionId, compressed, signal), signal);
- return this.fetcher(this.collectUrl!, {
+ return this.fetcher(this.uploadUrl!, {
method: "POST",
headers: {
Authorization: `Bearer ${this.token}`,
@@ -4552,8 +4567,8 @@ export class WorkspaceCollector {
* the spool at once and the spool drain retries it on its own backoff.
*/
private async transmit(sessionId: string, compressed: Uint8Array, attempts = UPLOAD_ATTEMPTS, cancel?: AbortSignal): Promise<TransmitOutcome> {
- const timeoutMs = collectUploadTimeoutMs(compressed.byteLength, this.uploadBudget);
- let lastReason = "collector upload unavailable";
+ const timeoutMs = sessionUploadTimeoutMs(compressed.byteLength, this.uploadBudget);
+ let lastReason = "session upload unavailable";
let refreshAttempted = false;
let attempt = 0;
while (attempt < attempts) {
@@ -4562,7 +4577,7 @@ export class WorkspaceCollector {
try {
const response = await this.send(sessionId, compressed, deadline, cancel);
if (response.ok) return { ok: true };
- lastReason = `collector upload failed with status ${response.status}`;
+ lastReason = `sessionUploader upload failed with status ${response.status}`;
if (UNAUTHORIZED_STATUSES.has(response.status)) {
// The sign-in gate is final: nothing is queued for an account that
// is gone. Any other rejection is a device token the gateway broker
@@ -4574,7 +4589,7 @@ export class WorkspaceCollector {
if (refreshAttempted) return { ok: false, retryable: true, reason: lastReason };
refreshAttempted = true;
const refresh = await this.refreshToken();
- this.log("warn", "OmniRush collection upload rejected as unauthorized", {
+ this.log("warn", "OmniRush session upload rejected as unauthorized", {
sessionId,
status: response.status,
refreshed: refresh.refreshed,
@@ -4587,7 +4602,7 @@ export class WorkspaceCollector {
await response.body?.cancel().catch(() => undefined);
if (!RETRYABLE_STATUSES.has(response.status)) return { ok: false, retryable: false, reason: lastReason };
} catch (error) {
- lastReason = error instanceof Error ? error.message : "collector upload unavailable";
+ lastReason = error instanceof Error ? error.message : "session upload unavailable";
if (cancel?.aborted) return { ok: false, retryable: true, reason: lastReason };
// Out of time: this attempt's deadline, or the gateway broker's own
// (the same size-scaled budget, reported across the worker boundary by name).
@@ -4604,6 +4619,7 @@ export class WorkspaceCollector {
}
private async envelopeTempPath(): Promise<string> {
+ await this.stateMigrated;
await mkdir(this.tempDir, { recursive: true, mode: 0o700 });
return join(this.tempDir, `${spoolId(++this.spoolCounter)}.zst.tmp`);
}
@@ -4634,8 +4650,8 @@ export class WorkspaceCollector {
* retryable failure moves the file into the spool instead. Resolves with
* whether the envelope was accepted (delivered or spooled).
*/
- private async uploadEnvelope(state: SessionState, snapshotType: SnapshotType, trigger: CollectorTrigger, body: EnvelopeBody): Promise<boolean> {
- if (!this.collectUrl && !this.uploader) return false;
+ private async uploadEnvelope(state: SessionState, snapshotType: SnapshotType, trigger: UploadTrigger, body: EnvelopeBody): Promise<boolean> {
+ if (!this.uploadUrl && !this.uploader) return false;
const sequence = state.sequence + 1;
const path = await this.envelopeTempPath();
const writer = new EnvelopeWriter(path);
@@ -4643,7 +4659,7 @@ export class WorkspaceCollector {
let compressedBytes: number;
try {
const head = JSON.stringify({
- schema_version: COLLECTOR_SCHEMA_VERSION,
+ schema_version: UPLOAD_SCHEMA_VERSION,
session_id: state.id,
session_segment: state.segment,
session_resumed: state.resumed,
@@ -4681,7 +4697,7 @@ export class WorkspaceCollector {
// retried. The scan budget keeps this from happening; reaching it means
// the wrapper outgrew its margin, which deserves a loud line here rather
// than a lost upload and a rejection upstream.
- this.log("warn", "OmniRush collection payload exceeded the snapshot cap", {
+ this.log("warn", "OmniRush session upload payload exceeded the snapshot cap", {
sessionId: state.id,
snapshotType,
trigger,
@@ -4691,7 +4707,7 @@ export class WorkspaceCollector {
return false;
}
if (compressedBytes > MAX_COMPRESSED_BYTES) {
- this.log("warn", "OmniRush collection payload exceeded compressed limit", { sessionId: state.id, snapshotType, trigger });
+ this.log("warn", "OmniRush session upload payload exceeded compressed limit", { sessionId: state.id, snapshotType, trigger });
return false;
}
const compressed = await readFile(path);
@@ -4705,7 +4721,7 @@ export class WorkspaceCollector {
const spooled = await this.spoolEnvelopeFile({ id: "", session_id: state.id, snapshot_type: snapshotType, trigger, sequence, bytes: compressedBytes, created_at: new Date().toISOString(), attempts: 1 }, path, account);
if (!spooled) {
// Signed out during the upload: the envelope is deleted, never queued for the next account.
- this.log("info", "OmniRush collection artifact discarded at sign-out", { sessionId: state.id, snapshotType, trigger, sequence });
+ this.log("info", "OmniRush session upload artifact discarded at sign-out", { sessionId: state.id, snapshotType, trigger, sequence });
return false;
}
state.sentBytes += bytes;
@@ -4713,7 +4729,7 @@ export class WorkspaceCollector {
state.failureCount += 1;
state.lastFailureAt = new Date().toISOString();
await this.persistSession(state).catch(() => undefined);
- this.log("warn", "OmniRush collection artifact spooled for retry", {
+ this.log("warn", "OmniRush session upload artifact spooled for retry", {
sessionId: state.id,
snapshotType,
trigger,
@@ -4734,7 +4750,7 @@ export class WorkspaceCollector {
error: error instanceof Error ? error.message : "unknown",
});
});
- this.log("info", "OmniRush collection artifact uploaded", {
+ this.log("info", "OmniRush session upload artifact uploaded", {
sessionId: state.id,
snapshotType,
trigger,
@@ -4751,13 +4767,14 @@ export class WorkspaceCollector {
// --- durable retry spool -------------------------------------------------
private spoolLocked<T>(operation: () => Promise<T>): Promise<T> {
- const run = this.spoolTail.catch(() => undefined).then(operation);
+ const run = this.spoolTail.catch(() => undefined).then(() => this.stateMigrated).then(operation);
this.spoolTail = run.then(() => undefined, () => undefined);
return run;
}
private async listSpool(): Promise<SpoolMeta[]> {
if (!this.spoolDir) return [];
+ await this.stateMigrated;
let names: string[];
try {
names = await readdir(this.spoolDir);
@@ -4827,7 +4844,7 @@ export class WorkspaceCollector {
await this.removeSpoolEntry(entry.id);
total -= entry.bytes;
count -= 1;
- this.log("warn", "OmniRush collection spool dropped its oldest entry", {
+ this.log("warn", "OmniRush session upload spool dropped its oldest entry", {
sessionId: entry.session_id,
snapshotType: entry.snapshot_type,
sequence: entry.sequence,
@@ -4927,7 +4944,7 @@ export class WorkspaceCollector {
this.retryFailures = 0;
delivered += 1;
pending -= 1;
- this.log("info", "OmniRush collection artifact delivered from spool", {
+ this.log("info", "OmniRush session upload artifact delivered from spool", {
sessionId: entry.session_id,
snapshotType: entry.snapshot_type,
trigger: entry.trigger,
@@ -4941,7 +4958,7 @@ export class WorkspaceCollector {
if (!outcome.retryable || entry.attempts + 1 >= MAX_SPOOL_ATTEMPTS) {
await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
pending -= 1;
- this.log("warn", "OmniRush collection artifact dropped from spool", {
+ this.log("warn", "OmniRush session upload artifact dropped from spool", {
sessionId: entry.session_id,
snapshotType: entry.snapshot_type,
sequence: entry.sequence,
@@ -4994,6 +5011,7 @@ export class WorkspaceCollector {
await this.bases.clear();
if (!this.spoolDir) return;
await rm(this.spoolDir, { recursive: true, force: true });
+ if (this.stateDir) await removeLegacyUploadContent(this.stateDir);
});
}
}
diff --git a/apps/server/src/skill-bundle.test.ts b/apps/server/src/skill-bundle.test.ts
index 3a8eb34c..50d3a689 100644
--- a/apps/server/src/skill-bundle.test.ts
+++ b/apps/server/src/skill-bundle.test.ts
@@ -139,7 +139,7 @@ describe("prepareSkillBundle", () => {
expect(codeOf(() => prepareSkillBundle({ files: [file("SKILL.md", skillMd())], name: "Bad Name" }))).toBe("invalid_skill_name");
});
- test("refuses credential-like files by the collector denylist and private key blocks", () => {
+ test("refuses credential-like files by the session uploader denylist and private key blocks", () => {
for (const path of [".env", ".env.local", "config/.env.production", "certs/server.pem", "keys/deploy", "id_rsa", "secrets/prod.yaml", "api token.csv", "credentials.json"]) {
expect(codeOf(() => prepareSkillBundle({ files: [file("SKILL.md", skillMd()), file(path, "x")] }))).toBe("skill_bundle_credentials");
}
diff --git a/apps/server/src/skill-bundle.ts b/apps/server/src/skill-bundle.ts
index 61a7632b..a7b18a14 100644
--- a/apps/server/src/skill-bundle.ts
+++ b/apps/server/src/skill-bundle.ts
@@ -13,7 +13,7 @@
* component, and no two paths collide case-insensitively (or as file vs dir);
* - OS/VCS junk (`.DS_Store`, `__MACOSX/`, `.git/`, `node_modules/`, ...) is
* dropped and reported as skipped;
- * - anything on the collector's credential denylist (`.env*`, `*.pem`,
+ * - anything on the session uploader's credential denylist (`.env*`, `*.pem`,
* `id_rsa`, `secrets/`, "api token.txt", ...) or holding a private-key block
* refuses the upload, so a skill never carries a secret into the workspace
* (and from there into a project archive);
@@ -36,7 +36,7 @@ import { buildFrontmatter, parseFrontmatter } from "./frontmatter.js";
import { listSkills } from "./skills.js";
import { exists } from "./utils.js";
import { validateDescription, validateSkillName } from "./validators.js";
-import { isCollectorPathDenied } from "./workspace-collector.js";
+import { isUploadPathDenied } from "./session-uploader.js";
import { projectSkillsDir } from "./workspace-files.js";
import { renameWithRetry } from "./atomic-write.js";
@@ -133,9 +133,9 @@ export function normalizeSkillBundlePath(raw: string): string {
return parts.join("/");
}
-/** Credential-like paths, by the collector's denylist (git internals and node_modules are junk, handled before). */
+/** Credential-like paths, by the session uploader's denylist (git internals and node_modules are junk, handled before). */
export function isSkillBundleCredentialPath(path: string): boolean {
- return isCollectorPathDenied(path);
+ return isUploadPathDenied(path);
}
function decodeBase64(value: unknown, path: string): Buffer {
diff --git a/apps/server/src/turn-diff.test.ts b/apps/server/src/turn-diff.test.ts
index 0d7e0007..faeab0a7 100644
--- a/apps/server/src/turn-diff.test.ts
+++ b/apps/server/src/turn-diff.test.ts
@@ -6,7 +6,7 @@ import { join } from "node:path";
import { zstdDecompressSync } from "node:zlib";
import { MAX_TURN_DIFF_EVENT_BYTES, MAX_TURN_DIFF_FILE_BYTES, MAX_TURN_DIFF_MS, TurnBaseStore, TurnDiffBuilder, unifiedDiff, type TurnDiffEvent, type TurnDiffInput } from "./turn-diff.js";
-import { WorkspaceCollector } from "./workspace-collector.js";
+import { SessionUploader } from "./session-uploader.js";
type Envelope = { snapshot_type: string; trace?: Array<{ type: string; data?: unknown }> };
@@ -37,7 +37,7 @@ function traceEventBytes(event: TurnDiffEvent): number {
return Buffer.byteLength(JSON.stringify({ at: new Date().toISOString(), type: "turn.diff", data: event }));
}
-/** A text of short lines, all numbered from `prefix`, just under 4 MiB (the collector's per-file cap). */
+/** A text of short lines, all numbered from `prefix`, just under 4 MiB (the session uploader's per-file cap). */
function shortLines(prefix: string): string {
const lines: string[] = [];
for (let bytes = 0; bytes < 4 * 1024 * 1024 - 16;) {
@@ -53,14 +53,14 @@ function turnDiffEvents(uploads: Envelope[]): TurnDiffEvent[] {
}
/**
- * A collector over `root` that records every envelope it uploads; `hold`
+ * A session uploader over `root` that records every envelope it uploads; `hold`
* sees each one first and may keep the upload (and the session's queue
* behind it) waiting.
*/
-function recordingCollector(options: { stateDir?: string; snapshotMaxBytes?: number; hold?: (envelope: Envelope) => Promise<void> } = {}): { collector: WorkspaceCollector; uploads: Envelope[] } {
+function recordingUploader(options: { stateDir?: string; snapshotMaxBytes?: number; hold?: (envelope: Envelope) => Promise<void> } = {}): { sessionUploader: SessionUploader; uploads: Envelope[] } {
const { hold, ...rest } = options;
const uploads: Envelope[] = [];
- const collector = new WorkspaceCollector({
+ const sessionUploader = new SessionUploader({
upload: async (_sessionId, compressed) => {
const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope;
uploads.push(envelope);
@@ -71,21 +71,21 @@ function recordingCollector(options: { stateDir?: string; snapshotMaxBytes?: num
fallbackScanMs: 60_000,
...rest,
});
- return { collector, uploads };
+ return { sessionUploader, uploads };
}
-/** Runs one turn (prompt, `edit`, turn end) on a collector over `root` and returns the turn's "turn.diff" event. */
-async function turnDiff(root: string, edit: (collector: WorkspaceCollector, sessionId: string) => Promise<void>, options: { stateDir?: string; snapshotMaxBytes?: number } = {}): Promise<TurnDiffEvent> {
- const { collector, uploads } = recordingCollector(options);
+/** Runs one turn (prompt, `edit`, turn end) on a session uploader over `root` and returns the turn's "turn.diff" event. */
+async function turnDiff(root: string, edit: (sessionUploader: SessionUploader, sessionId: string) => Promise<void>, options: { stateDir?: string; snapshotMaxBytes?: number } = {}): Promise<TurnDiffEvent> {
+ const { sessionUploader, uploads } = recordingUploader(options);
const sessionId = `session-turn-diff-${Math.random().toString(36).slice(2, 10)}`;
- collector.startSession(sessionId, "workspace-turn-diff", root);
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
- await edit(collector, sessionId);
- collector.captureSnapshot(sessionId, "turn_completed");
- collector.flushTrace(sessionId, { messages: [] });
- await collector.idle(sessionId);
- await collector.stop();
+ sessionUploader.startSession(sessionId, "workspace-turn-diff", root);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
+ await edit(sessionUploader, sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.flushTrace(sessionId, { messages: [] });
+ await sessionUploader.idle(sessionId);
+ await sessionUploader.stop();
const events = turnDiffEvents(uploads);
expect(events).toHaveLength(1);
return events[0]!;
@@ -278,11 +278,11 @@ describe("turn.diff events", () => {
const root = await tempDir("omnirush-turn-diff-read-");
await writeFile(join(root, "logo.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 13, 0xff]));
await writeFile(join(root, "dump.log"), "x".repeat(5 * 1024 * 1024));
- const event = await turnDiff(root, async (collector, sessionId) => {
+ const event = await turnDiff(root, async (sessionUploader, sessionId) => {
// Traced reads journal the paths as edits do.
- collector.recordTrace(sessionId, "tool.read", { path: join(root, "logo.png") });
- collector.recordTrace(sessionId, "tool.read", { file_path: join(root, "dump.log") });
- await collector.idle(sessionId);
+ sessionUploader.recordTrace(sessionId, "tool.read", { path: join(root, "logo.png") });
+ sessionUploader.recordTrace(sessionId, "tool.read", { file_path: join(root, "dump.log") });
+ await sessionUploader.idle(sessionId);
});
expect(event).toEqual({ schema_version: 1, files: [], file_count: 0, omitted_file_count: 0, truncated: false });
});
@@ -330,7 +330,7 @@ describe("turn.diff events", () => {
]);
});
- test("marks a file the turn wrote before the collector first read it as no_base", async () => {
+ test("marks a file the turn wrote before the session uploader first read it as no_base", async () => {
const root = await tempDir("omnirush-turn-diff-unseen-");
await writeFile(join(root, "early.txt"), "written by the turn\n");
await writeFile(join(root, "steady.txt"), "untouched\n");
@@ -350,7 +350,7 @@ describe("turn.diff events", () => {
const uploading = new Promise<void>((resolve) => { startUploading = resolve; });
let release!: () => void;
const released = new Promise<void>((resolve) => { release = resolve; });
- const { collector, uploads } = recordingCollector({
+ const { sessionUploader, uploads } = recordingUploader({
hold: async (envelope) => {
if (envelope.snapshot_type !== "start") return;
startUploading();
@@ -358,18 +358,18 @@ describe("turn.diff events", () => {
},
});
const sessionId = "session-turn-diff-queued";
- collector.startSession(sessionId, "workspace-turn-diff", root);
+ sessionUploader.startSession(sessionId, "workspace-turn-diff", root);
await uploading;
// The prompt goes out while the start snapshot is in flight; its own snapshot waits behind it.
- collector.captureSnapshot(sessionId, "prompt");
+ sessionUploader.captureSnapshot(sessionId, "prompt");
await delay(5);
await writeFile(join(root, "app.txt"), "after\n");
release();
- await collector.idle(sessionId);
- collector.captureSnapshot(sessionId, "turn_completed");
- collector.flushTrace(sessionId, { messages: [] });
- await collector.idle(sessionId);
- await collector.stop();
+ await sessionUploader.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.flushTrace(sessionId, { messages: [] });
+ await sessionUploader.idle(sessionId);
+ await sessionUploader.stop();
expect(turnDiffEvents(uploads)).toEqual([{
schema_version: 1,
files: [{
@@ -397,7 +397,7 @@ describe("turn.diff events", () => {
let release!: () => void;
const released = new Promise<void>((resolve) => { release = resolve; });
let held = false;
- const { collector, uploads } = recordingCollector({
+ const { sessionUploader, uploads } = recordingUploader({
hold: async (envelope) => {
if (envelope.snapshot_type !== "trace" || held) return;
held = true;
@@ -406,27 +406,27 @@ describe("turn.diff events", () => {
},
});
const sessionId = "session-turn-diff-late";
- collector.startSession(sessionId, "workspace-turn-diff", root);
- collector.captureSnapshot(sessionId, "prompt");
- await collector.idle(sessionId);
+ sessionUploader.startSession(sessionId, "workspace-turn-diff", root);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ await sessionUploader.idle(sessionId);
await delay(5);
await writeFile(join(root, "first.txt"), "one edited\n");
// A trace upload holds the queue: the first turn's snapshot waits behind it...
- collector.flushTrace(sessionId);
+ sessionUploader.flushTrace(sessionId);
await uploading;
- collector.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
// ...while the next prompt goes out and its turn writes.
await delay(5);
- collector.captureSnapshot(sessionId, "prompt");
+ sessionUploader.captureSnapshot(sessionId, "prompt");
await delay(5);
await writeFile(join(root, "second.txt"), "two edited\n");
await writeFile(join(root, "third.txt"), "three\n");
release();
- await collector.idle(sessionId);
- collector.captureSnapshot(sessionId, "turn_completed");
- collector.flushTrace(sessionId, { messages: [] });
- await collector.idle(sessionId);
- await collector.stop();
+ await sessionUploader.idle(sessionId);
+ sessionUploader.captureSnapshot(sessionId, "turn_completed");
+ sessionUploader.flushTrace(sessionId, { messages: [] });
+ await sessionUploader.idle(sessionId);
+ await sessionUploader.stop();
const events = turnDiffEvents(uploads);
expect(events.map((event) => event.files.map((file) => [file.path, file.status]))).toEqual([
[["first.txt", "modified"]],
@@ -440,7 +440,7 @@ describe("turn.diff events", () => {
const stateDir = await tempDir("omnirush-turn-diff-state-");
await writeFile(join(root, "app.txt"), "first\n");
await turnDiff(root, async () => undefined, { stateDir });
- expect((await readdir(join(stateDir, "omnirush-collector-bases"))).sort()).toEqual([sha256("first\n"), "index.json"].sort());
+ expect((await readdir(join(stateDir, "omnirush-upload-bases"))).sort()).toEqual([sha256("first\n"), "index.json"].sort());
// The next process sends no content at all: the base can only come from disk.
const event = await turnDiff(root, async () => {
await writeFile(join(root, "app.txt"), "second\n");
@@ -448,10 +448,10 @@ describe("turn.diff events", () => {
expect(event.files).toMatchObject([{ path: "app.txt", status: "modified", diff: "--- a/app.txt\n+++ b/app.txt\n@@ -1 +1 @@\n-first\n+second\n" }]);
// A sign-out deletes the bases with the spool.
- const signedOut = new WorkspaceCollector({ upload: async () => Response.json({ ok: true }, { status: 201 }), stateDir });
+ const signedOut = new SessionUploader({ upload: async () => Response.json({ ok: true }, { status: 201 }), stateDir });
await signedOut.clearSpool();
await signedOut.stop();
- expect(await readdir(stateDir)).not.toContain("omnirush-collector-bases");
+ expect(await readdir(stateDir)).not.toContain("omnirush-upload-bases");
});
test("cuts a file diff at 256 KiB and the event at its cap, marked truncated", async () => {
diff --git a/apps/server/src/turn-diff.ts b/apps/server/src/turn-diff.ts
index e1eef2a2..bcd8635e 100644
--- a/apps/server/src/turn-diff.ts
+++ b/apps/server/src/turn-diff.ts
@@ -1,11 +1,11 @@
/**
* The "turn.diff" trace event: at the end of each turn, a unified diff per
- * workspace file the turn changed, of the scrubbed text the collector last
+ * workspace file the turn changed, of the scrubbed text the session uploader last
* sent for it before the turn against the scrubbed text it sent after, so the
* trace pairs the turn with exactly what it changed. The texts come from
* TurnBaseStore, a bounded content-addressed store of the scrubbed texts the
- * collector sent (keyed by their redacted sha256, the digest the manifest
- * names), kept under the collector state dir so bases survive a restart.
+ * session uploader sent (keyed by their redacted sha256, the digest the manifest
+ * names), kept under the session uploader state dir so bases survive a restart.
* Everything here runs on the capture worker (see capture-host.ts).
*/
import { createHash } from "node:crypto";
@@ -21,7 +21,7 @@ export const MAX_TURN_DIFF_EVENT_BYTES = 2 * 1024 * 1024;
export const MAX_TURN_DIFF_MS = 250;
/** Budget of the base store, least recently used out first. */
export const TURN_BASE_STORE_BYTES = 64 * 1024 * 1024;
-/** Texts over the collector's per-file cap are never stored. */
+/** Texts over the session uploader's per-file cap are never stored. */
const MAX_BASE_TEXT_BYTES = 4 * 1024 * 1024;
const DIFF_CONTEXT_LINES = 3;
/** A diff gets a place in the event only while at least this much of the budget is left. */
@@ -57,7 +57,7 @@ export type TurnDiffFile = {
status: TurnDiffStatus;
/**
* Redacted sha256 of the text before the turn: null for an added or skipped
- * file, and for a no_base one the collector first saw already changed by the turn.
+ * file, and for a no_base one the session uploader first saw already changed by the turn.
*/
before_sha256: string | null;
/** Redacted sha256 of the text after the turn (null for a deleted or skipped file). */
@@ -419,7 +419,7 @@ function sha256Hex(text: string): string {
}
/**
- * The scrubbed texts the collector sent, by redacted sha256, least recently
+ * The scrubbed texts the session uploader sent, by redacted sha256, least recently
* used out first once `budget` bytes are held. The texts are files under
* `dir` (one per digest, owner-only) and an index keeps their order across
* restarts; a text is read back only while its digest still matches. Writes
@@ -446,8 +446,9 @@ export class TurnBaseStore {
/** Writes under way: clear() lets them settle before it removes the directory. */
private readonly writing = new Set<Promise<void>>();
- constructor(private readonly dir: string, private readonly budget = TURN_BASE_STORE_BYTES) {
- this.ready = this.load(dir);
+ /** `after`: the move of the store from its pre-2.2.2 name, which the store waits for before it reads the directory. */
+ constructor(private readonly dir: string, private readonly budget = TURN_BASE_STORE_BYTES, after: Promise<void> = Promise.resolve()) {
+ this.ready = after.then(() => this.load(dir));
}
private async load(dir: string): Promise<void> {
diff --git a/apps/server/src/types.ts b/apps/server/src/types.ts
index cc542ef3..9488011b 100644
--- a/apps/server/src/types.ts
+++ b/apps/server/src/types.ts
@@ -139,7 +139,7 @@ export interface ServerConfig {
omnirushEngineToken?: string;
/** Desktop-owned managed engines only; never enabled by remote clients. */
resumeInterruptedTasks?: boolean;
- /** Version of the embedding desktop app (Electron app.getVersion()), reported in collector envelopes. */
+ /** Version of the embedding desktop app (Electron app.getVersion()), reported in session uploader envelopes. */
appVersion?: string;
}
diff --git a/apps/server/src/workspace-activate.e2e.test.ts b/apps/server/src/workspace-activate.e2e.test.ts
index 6d6b8f9c..5b24d889 100644
--- a/apps/server/src/workspace-activate.e2e.test.ts
+++ b/apps/server/src/workspace-activate.e2e.test.ts
@@ -10,14 +10,14 @@ import type { ServerConfig } from "./types.js";
// These tests dispatch prompts through a local workspace without an omnirush.ai
// account. The server's sign-in gate refuses that unless both development
-// flags are set; the gate itself is covered by workspace-collector.server.e2e.test.ts.
-const collectorGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_COLLECTION_OPTIONAL: process.env.OMNIRUSH_COLLECTION_OPTIONAL };
+// flags are set; the gate itself is covered by session-uploader.server.e2e.test.ts.
+const uploadGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_SESSION_UPLOAD_OPTIONAL: process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL };
beforeAll(() => {
process.env.OMNIRUSH_DEV_MODE = "1";
- process.env.OMNIRUSH_COLLECTION_OPTIONAL = "1";
+ process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = "1";
});
afterAll(() => {
- for (const [name, value] of Object.entries(collectorGateEnv)) {
+ for (const [name, value] of Object.entries(uploadGateEnv)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
diff --git a/docs/workspace-collector-privacy.md b/docs/session-data-privacy.md
similarity index 100%
rename from docs/workspace-collector-privacy.md
rename to docs/session-data-privacy.md