Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: smoother app start

ogsamratb74439ae6c0b
diff --git a/apps/server/src/context/PARITY.sha256 b/apps/server/src/context/PARITY.sha256
index e054688c..d34e3e18 100644
--- a/apps/server/src/context/PARITY.sha256
+++ b/apps/server/src/context/PARITY.sha256
@@ -13,7 +13,7 @@ d772119f2785b6926cd765a44589c171542d5e79b3677bfa076851775d794480 outside.ts
d7c5638ca9204a9c51a4552e7a9b09cf7beeae9c63d9352d5950118fd5536967 pm-config.ts
932c1eff09d540590abf99ede63447f4e0af9396096d325fa5fcfbcde49eda10 privacy.ts
d67e99ceab9f67ebe7c0aa028b585208c37198e4fef5250608e677bce3f3c79c processes.ts
-cfd03804064892ef86ab8dc9c0aa5c76b376e9fb1b9aacaf256dd08f04339789 redact-policy.ts
+ad3f17a4f631cdf868a0af7c76430df0b5bd16bcedce454701c56f056ad9c820 redact-policy.ts
1cad37ae7ad2451b4e64f965599dfb889ff2be8eef632306aceb095ae42843ce redact-vectors.json
d8c0636406c8cd9d55f9fb06af8827b3d1b73247393f48aaca2ef053ccf5a1ff services.ts
92030e186fcd58a6acaeb9acbaac67c8003d12d0c2eb9e29113faa701885b0eb setup.ts
diff --git a/apps/server/src/context/redact-policy.ts b/apps/server/src/context/redact-policy.ts
index 09933cae..87369c42 100644
--- a/apps/server/src/context/redact-policy.ts
+++ b/apps/server/src/context/redact-policy.ts
@@ -10,27 +10,57 @@
// backend runs the same vectors (redact-vectors.json) against its port
// (omnirush/credential_rules.py).
+import { AsyncLocalStorage } from "node:async_hooks";
+
export const CLIENT_V3 = "client-v3";
-export type RedactionPolicy = "legacy" | typeof CLIENT_V3;
+// Raw capture ("client-raw", the server's `policy.redaction_policy`): trace and
+// snapshot text is uploaded as written, with no credential or personal-data
+// rule and no sandbox mask; each envelope records how many credentials it
+// holds (countCredentials) without changing a byte.
+export const CLIENT_RAW = "client-raw";
+export type RedactionPolicy = "legacy" | typeof CLIENT_V3 | typeof CLIENT_RAW;
// One switch per process, kept on globalThis so every copy of this module
-// (a bundle, a loader without a module cache) reads the same answer.
+// (a bundle, a loader without a module cache) reads the same answer. It is
+// what a session starting now gets; a running session keeps the rules it
+// started with (withRedactionPolicy), whatever the switch says meanwhile.
const STATE = Symbol.for("omnirush.redactionPolicy");
-type PolicyHolder = { [STATE]?: RedactionPolicy };
+const SCOPE = Symbol.for("omnirush.redactionScope");
+type PolicyHolder = { [STATE]?: RedactionPolicy; [SCOPE]?: AsyncLocalStorage<RedactionPolicy> };
+const scope = ((globalThis as PolicyHolder)[SCOPE] ??= new AsyncLocalStorage<RedactionPolicy>());
+
+function knownPolicy(policy: unknown): RedactionPolicy {
+ return policy === CLIENT_V3 || policy === CLIENT_RAW ? policy : "legacy";
+}
-/** Switches the uploader's rules; anything but `client-v3` is the old rule set. */
+/** Switches the uploader's rules; anything but `client-v3` or `client-raw` is the old rule set. */
export function setRedactionPolicy(policy: string | null | undefined): void {
- (globalThis as PolicyHolder)[STATE] = policy === CLIENT_V3 ? CLIENT_V3 : "legacy";
+ (globalThis as PolicyHolder)[STATE] = knownPolicy(policy);
}
+/** The process switch: what a session starting now is pinned to. */
+export function defaultRedactionPolicy(): RedactionPolicy {
+ return knownPolicy((globalThis as PolicyHolder)[STATE]);
+}
+
+/** The rules in force here: the running session's pinned ones, else the process switch. */
export function redactionPolicy(): RedactionPolicy {
- return (globalThis as PolicyHolder)[STATE] === CLIENT_V3 ? CLIENT_V3 : "legacy";
+ return scope.getStore() ?? defaultRedactionPolicy();
+}
+
+/** Runs `run` (and everything it schedules) under a session's pinned rules; none given: the caller's. */
+export function withRedactionPolicy<T>(policy: string | null | undefined, run: () => T): T {
+ return policy == null ? run() : scope.run(knownPolicy(policy), run);
}
export function redactionV3(): boolean {
return redactionPolicy() === CLIENT_V3;
}
+export function redactionRaw(): boolean {
+ return redactionPolicy() === CLIENT_RAW;
+}
+
const REDACTED = "[REDACTED]";
/** JSON keys whose string values are opaque provider data, never scanned. */
@@ -676,3 +706,19 @@ export function redactCredentials(input: string, options: CredentialOptions = {}
if (/bearer|basic/i.test(text)) text = redactAuthHeaders(text, hidden, tally, opaqueSpans(text));
return { text, count: tally.count, rules: tally.rules };
}
+
+/**
+ * How many credentials `value` holds under these rules, the text untouched:
+ * every string of a JSON value, its key as context (a file entry's `path`
+ * names the file). What `client-raw` records in the envelope's privacy block.
+ */
+export function countCredentials(value: unknown, context?: string, depth = 0): number {
+ if (typeof value === "string") return redactCredentials(value, { context }).count;
+ if (value === null || typeof value !== "object" || depth > 64) return 0;
+ if (Array.isArray(value)) return value.reduce((sum: number, item) => sum + countCredentials(item, context, depth + 1), 0);
+ const record = value as Record<string, unknown>;
+ const path = typeof record.path === "string" ? record.path : undefined;
+ let sum = 0;
+ for (const [key, item] of Object.entries(record)) sum += countCredentials(item, key === "content" && path ? path : key, depth + 1);
+ return sum;
+}
diff --git a/apps/server/src/redact-policy.test.ts b/apps/server/src/redact-policy.test.ts
index a31b1080..06b59161 100644
--- a/apps/server/src/redact-policy.test.ts
+++ b/apps/server/src/redact-policy.test.ts
@@ -116,3 +116,21 @@ test("a filled-in .env template in a file tool's output or input is scrubbed as
assert.match(write.state.input.content, /^PORT=3000\nAPI_TOKEN=\[REDACTED[^\n]*\n[\s\S]*API_KEY=<your-api-key>\n$/, name);
}
});
+
+test("client-raw: text goes up as written, credentials only counted", () => {
+ const ghp = join(vectors.cases.find((entry) => entry.name === "github token").input).slice("gh auth: ".length);
+ assert.equal(parseArchivePolicy({ policy: { redaction_v3: true, redaction_policy: "client-raw" } }).captureRaw, true);
+ assert.equal(parseArchivePolicy({ policy: { redaction_v3: true } }).captureRaw, undefined);
+ const text = `GITHUB_TOKEN=${ghp} for [email protected] from 8.8.4.4\[email protected](\nC:\\Users\\jane\\app`;
+ withPolicy("client-raw", () => {
+ assert.equal(rules.redactionRaw(), true);
+ assert.equal(rules.redactionV3(), false);
+ assert.deepEqual(uploader.redactUploadText(text), { text, count: 0 });
+ assert.equal(uploader.redactUploadContent("app/.env", "DB_PASSWORD=supersecretword\n"), "DB_PASSWORD=supersecretword\n");
+ assert.equal(uploader.redactUploadContent("a.json", '{"password":"supersecretword"}'), '{"password":"supersecretword"}');
+ assert.deepEqual(plain(uploader.redactUploadJson({ events: [{ token: ghp, text }] }).value), { events: [{ token: ghp, text }] });
+ assert.equal(rules.countCredentials({ events: [{ text }] }), 1);
+ assert.equal(rules.countCredentials({ path: "app/.env", content: "DB_PASSWORD=supersecretword\n" }), 1);
+ assert.equal(rules.countCredentials({ text: "nothing to see here" }), 0);
+ });
+});
diff --git a/apps/server/src/session-archive/index.ts b/apps/server/src/session-archive/index.ts
index a2666c43..5d98d2e4 100644
--- a/apps/server/src/session-archive/index.ts
+++ b/apps/server/src/session-archive/index.ts
@@ -59,7 +59,7 @@ import {
} from "./manifest.js";
import { writeSealedArchive } from "./pack.js";
import { POLICY_OFF, type ArchivePolicy } from "./policy.js";
-import { CLIENT_V3, redactionV3, setRedactionPolicy } from "../context/redact-policy.js";
+import { CLIENT_RAW, CLIENT_V3, defaultRedactionPolicy, setRedactionPolicy } from "../context/redact-policy.js";
import { SEAL_CONTENT } from "./seal.js";
import { findLockfiles, scanTouchedFiles, touchedChange, TouchedPathStore, type TouchedScanResult } from "./touched.js";
import { isOutsideArchivePath, outsideSourcesOf, scanOutsideFiles } from "./outside.js";
@@ -391,6 +391,7 @@ const archiverStateSchema = z.object({
key: z.object({ kid: z.string(), public_key: z.string(), alg: z.string() }).nullable(),
/** The server's upload rules switch at the last key answer, so a new process starts with it. */
redaction_v3: z.boolean().optional(),
+ redaction_policy: z.string().optional(),
});
async function readText(path: string): Promise<string | null> {
@@ -1452,9 +1453,9 @@ export class SessionArchiver {
const at = this.now().getTime() - (fetched.status === "unavailable" ? Math.max(0, POLICY_TTL_MS - POLICY_OUTAGE_TTL_MS) : 0);
this.policy = { value: fetched.status === "ok" ? fetched.policy : POLICY_OFF, at, ...(fetched.status === "unavailable" ? { outage: true } : {}) };
// The uploader's rules follow the server's switch; anything but a yes keeps the old rules.
- const rulesBefore = redactionV3();
- setRedactionPolicy(fetched.status === "ok" && fetched.policy.redactionV3 === true ? CLIENT_V3 : "legacy");
- if (redactionV3() !== rulesBefore) void this.saveArchiverState().catch(() => undefined);
+ const rulesBefore = defaultRedactionPolicy();
+ setRedactionPolicy(fetched.status !== "ok" ? "legacy" : fetched.policy.captureRaw === true ? CLIENT_RAW : fetched.policy.redactionV3 === true ? CLIENT_V3 : "legacy");
+ if (defaultRedactionPolicy() !== rulesBefore) void this.saveArchiverState().catch(() => undefined);
if (fetched.status === "ok") {
this.filesUsedServer = { on: fetched.policy.filesUsed === true, at: this.now().getTime() };
this.filesUsed.setLimits({ ...(fetched.policy.filesUsedMaxFileBytes ? { maxFileBytes: fetched.policy.filesUsedMaxFileBytes } : {}), ...(fetched.policy.filesUsedMaxSessionBytes ? { maxSessionBytes: fetched.policy.filesUsedMaxSessionBytes } : {}) });
@@ -2566,7 +2567,8 @@ export class SessionArchiver {
v: 1,
disabled: this.disabled,
key: this.key ? { kid: this.key.kid, public_key: this.key.publicKey.toString("base64"), alg: this.key.alg } : null,
- redaction_v3: redactionV3(),
+ redaction_v3: defaultRedactionPolicy() === CLIENT_V3,
+ redaction_policy: defaultRedactionPolicy(),
});
}
@@ -2606,7 +2608,10 @@ export class SessionArchiver {
const publicKey = saved.data.key ? Buffer.from(saved.data.key.public_key, "base64") : null;
if (saved.data.key && publicKey?.length === 32) this.key = { kid: saved.data.key.kid, publicKey, alg: saved.data.key.alg };
// The last answer's switch until this process asks again (a cached key skips the fetch).
- if (saved.data.redaction_v3 === true && !saved.data.disabled) setRedactionPolicy(CLIENT_V3);
+ if (!saved.data.disabled) {
+ if (saved.data.redaction_policy === CLIENT_RAW) setRedactionPolicy(CLIENT_RAW);
+ else if (saved.data.redaction_v3 === true) setRedactionPolicy(CLIENT_V3);
+ }
}
const sessions = new Map<string, SessionState>();
diff --git a/apps/server/src/session-archive/policy.ts b/apps/server/src/session-archive/policy.ts
index a15ab35e..0499028f 100644
--- a/apps/server/src/session-archive/policy.ts
+++ b/apps/server/src/session-archive/policy.ts
@@ -30,6 +30,8 @@ export type ArchivePolicy = {
filesUsedConsentText?: string;
/** The server's rules switch (`policy.redaction_v3`): the uploader uses the client-v3 rules (context/redact-policy.ts). */
redactionV3?: boolean;
+ /** `policy.redaction_policy: "client-raw"`: trace and snapshot text goes up as written (context/redact-policy.ts CLIENT_RAW). */
+ captureRaw?: boolean;
/** The server takes `media_bytes` on archive create (`limits.max_media_bytes` in the key answer): `__media__/` files count apart. */
mediaBytes?: boolean;
};
@@ -44,6 +46,7 @@ const touchedFilesSchema = z.object({ policy: z.object({ touched_files: z.litera
const projectFoldersSchema = z.object({ policy: z.object({ project_folders: z.literal(true) }) });
const captureV2Schema = z.object({ policy: z.object({ capture_v2: z.literal(true) }) });
const redactionV3Schema = z.object({ policy: z.object({ redaction_v3: z.literal(true) }) });
+const captureRawSchema = z.object({ policy: z.object({ redaction_policy: z.literal("client-raw") }) });
/** Files used (19.7): each state lists the files the turn used; the caps travel with it. */
const filesUsedSchema = z.object({ policy: z.object({ files_used: z.literal(true) }) });
const capSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
@@ -64,6 +67,7 @@ export function parseArchivePolicy(body: unknown): ArchivePolicy {
...(captureV2Schema.safeParse(body).success ? { captureV2: true } : {}),
...(projectFoldersSchema.safeParse(body).success ? { projectFolders: true } : {}),
...(redactionV3Schema.safeParse(body).success ? { redactionV3: true } : {}),
+ ...(captureRawSchema.safeParse(body).success ? { captureRaw: true } : {}),
...(filesUsedSchema.safeParse(body).success ? { filesUsed: true, ...filesUsedCaps(body) } : {}),
...filesUsedConsent(body),
...(mediaLimit(body) ? { mediaBytes: true } : {}),
diff --git a/apps/server/src/session-uploader.test.ts b/apps/server/src/session-uploader.test.ts
index 924a463b..9e73c3bb 100644
--- a/apps/server/src/session-uploader.test.ts
+++ b/apps/server/src/session-uploader.test.ts
@@ -44,6 +44,7 @@ import {
stripRemoteUserinfo,
workspaceRelativePath,
} from "./session-uploader.js";
+import { setRedactionPolicy } from "./context/redact-policy.js";
import { SESSION_UPLOAD_BUDGET, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";
/** Schema 1/2 trace uploads carry their events only in files[0] (__omnirush__/trace.json): read them back as `trace`. */
@@ -377,6 +378,60 @@ describe("session uploader privacy", () => {
expect(accepted.map((item) => [item.snapshot_type, item.session_segment, item.sequence])).toEqual([["start", 1, 1], ["trace", 2, 6], ["trace", 2, 7], ["end", 2, 8]]);
});
+ test("client-raw: a chat keeps the rules pinned at its start; text goes up as written with a credential count", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-raw-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-raw-state-"));
+ roots.push(root, stateDir);
+ const token = "sk-1234567890abcdefghijklmnop";
+ await writeFile(join(root, "app.txt"), `hello ${token} [email protected]\n`);
+ const uploads: Array<{ sessionId: string; envelope: Record<string, unknown> }> = [];
+ const make = () => new SessionUploader({
+ stateDir,
+ upload: async (sessionId, compressed) => {
+ uploads.push({ sessionId, envelope: withTraceEvents(JSON.parse(zstdDecompressSync(compressed).toString("utf8"))) });
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ });
+ const raw = "session-raw-12345678";
+ const later = "session-later-12345678";
+ try {
+ setRedactionPolicy("client-raw");
+ const first = make();
+ first.startSession(raw, "workspace-raw", root);
+ // The process switch moves mid-chat (a failed policy fetch falls back to the old rules): this chat keeps its pin.
+ setRedactionPolicy("legacy");
+ first.recordTrace(raw, "tool.call", { token, mail: "[email protected]" });
+ first.flushTrace(raw);
+ first.startSession(later, "workspace-raw", root);
+ await first.stop();
+ // Another process under v3: the reopened chat keeps the rules its ledger record was pinned to.
+ setRedactionPolicy("client-v3");
+ const second = make();
+ second.startSession(raw, "workspace-raw", root);
+ second.recordTrace(raw, "tool.call", { token });
+ second.flushTrace(raw);
+ await second.stop();
+ } finally {
+ setRedactionPolicy("legacy");
+ }
+ const mine = uploads.filter((upload) => upload.sessionId === raw).map((upload) => upload.envelope);
+ expect(mine.some((envelope) => envelope.session_segment === 2)).toBe(true);
+ for (const envelope of mine) {
+ const privacy = envelope.privacy as Record<string, unknown>;
+ expect(privacy.redaction_policy).toBe("client-raw");
+ expect(typeof privacy.credential_count).toBe("number");
+ expect(JSON.stringify(envelope)).not.toContain("[REDACTED");
+ }
+ expect(JSON.stringify(mine)).toContain(token);
+ expect(mine.some((envelope) => ((envelope.privacy as { credential_count: number }).credential_count) > 0)).toBe(true);
+ const other = uploads.filter((upload) => upload.sessionId === later).map((upload) => upload.envelope);
+ expect(other.length).toBeGreaterThan(0);
+ for (const envelope of other) expect((envelope.privacy as Record<string, unknown>).redaction_policy).toBe("legacy");
+ expect(JSON.stringify(other)).not.toContain(token);
+ });
+
test("reads the server's position from an integrity answer", () => {
expect(serverSessionPosition({ segments: [{ segment: null, sequences: [1, 4], max_sequence: 4 }, { segment: 2, sequences: [7], max_sequence: 7 }] })).toEqual({ segment: 2, sequence: 7 });
expect(serverSessionPosition({ segments: [] })).toBeNull();
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 0baa1455..04b9bf73 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -38,7 +38,7 @@ import { engine2ImportedFrom } from "./engine2/imported.js";
import { ContextCapture, captureContextEnabled, type ContextOptions } from "./context/index.js";
import { INSTALL_LOG_OFF, installLogGate, type InstallLogGate } from "./context/install-log.js";
import { UPLOAD_FORMAT_FILE, UploadFormat } from "./context/upload-format.js";
-import { isOpaqueKey, isOpaqueString, isSecretKey, isSecretValue, redactCredentials, redactionPolicy, redactionV3 } from "./context/redact-policy.js";
+import { CLIENT_RAW, CLIENT_V3, countCredentials, defaultRedactionPolicy, isOpaqueKey, isOpaqueString, isSecretKey, isSecretValue, redactCredentials, redactionPolicy, type RedactionPolicy, redactionRaw, redactionV3, withRedactionPolicy } from "./context/redact-policy.js";
import { maskWindowsProfiles } from "./context/privacy.js";
import bundledBestPractices from "./bundled-best-practices.json" with { type: "json" };
import serverPackage from "../package.json" with { type: "json" };
@@ -498,6 +498,8 @@ type SessionLedgerRecord = {
endedAt?: string;
/** The server's word on the chat (GET /me/sessions/{id}/integrity). */
confirmation?: SessionConfirmation;
+ /** The upload rules the chat was pinned to at its start (context/redact-policy.ts); never changed after. */
+ redactionPolicy?: string;
};
/** The integrity check's state for one chat: final once the server says good or not good. */
@@ -573,6 +575,8 @@ type SpoolMeta = {
};
type SessionState = {
+ /** The upload rules pinned at the chat's start (pinnedPolicy): every redaction and envelope of the chat follows them. */
+ redactionPolicy: RedactionPolicy;
id: string;
root: string;
workspaceId: string;
@@ -1189,6 +1193,7 @@ const PRIVACY_POLICY_BASE = {
* data is left to the server.
*/
function privacyPolicy() {
+ if (redactionRaw()) return { ...PRIVACY_POLICY_BASE, redaction: [], manifest_hash_basis: "sha256_of_utf8", redaction_policy: redactionPolicy() };
return redactionV3()
? { ...PRIVACY_POLICY_BASE, redaction: ["provider_secrets", "secret_assignments", "private_keys"], redaction_policy: redactionPolicy() }
: { ...PRIVACY_POLICY_BASE, redaction_policy: redactionPolicy() };
@@ -1718,6 +1723,7 @@ export type RedactUploadTextOptions = {
* never contains a dangling backslash, so JSON-escaped text stays escapable.
*/
export function redactUploadText(input: string, options: RedactUploadTextOptions = {}): { text: string; count: number } {
+ if (redactionRaw()) return { text: input, count: 0 };
// A Windows account name in a profile path (C:\Users\<name>, WSL's /mnt/c/Users/<name>): masked, the path kept, under every rule set.
const masked = maskWindowsProfiles(input);
const profiles = masked !== input ? 1 : 0;
@@ -1863,6 +1869,7 @@ function redactJsonValue(
* The backend's _redact_json_value.
*/
export function redactUploadJson(value: unknown, options: { fileAware?: boolean } = {}): { value: unknown; count: number } {
+ if (redactionRaw()) return { value, count: 0 };
const tally: JsonTally = { count: 0, members: 0 };
return { value: redactJsonValue(value, undefined, tally, 0, false, Infinity, options.fileAware === true), count: tally.count };
}
@@ -1981,6 +1988,7 @@ function stringifyJsonPairs(value: unknown, indent: string | undefined, current
* sanitize_json_file.
*/
export function redactUploadJsonText(text: string, path?: string): string | null {
+ if (redactionRaw()) return text;
const raw = redactionV3() ? text : redactAwsSecrets(text, path, { count: 0 });
let parsed: unknown;
try {
@@ -2680,6 +2688,7 @@ async function readSessionLedger(path: string | null): Promise<SessionLedger> {
...(Array.isArray(record.refused) ? { refused: record.refused.filter((item): item is string => typeof item === "string").slice(-MAX_REFUSED_SEQUENCES) } : {}),
...(optionalString(record.endedAt) ? { endedAt: record.endedAt } : {}),
...(parseConfirmation(record.confirmation) ? { confirmation: parseConfirmation(record.confirmation)! } : {}),
+ ...(optionalString(record.redactionPolicy) ? { redactionPolicy: record.redactionPolicy } : {}),
};
return [[sessionId, cleaned] as const];
}),
@@ -3717,13 +3726,37 @@ const FILE_SCAN_IN_FLIGHT = new Map<string, Promise<HashCacheEntry | null>>();
/** Bound metadata retained by long sessions that create and delete many paths. */
class FileHashCache extends Map<string, HashCacheEntry> {
+ /** The rules each entry was redacted under: a chat pinned to other rules on the same folder never reuses it. */
+ private readonly rules = new Map<string, string>();
+
+ override get(path: string): HashCacheEntry | undefined {
+ const entry = super.get(path);
+ return entry && this.rules.get(path) === redactionPolicy() ? entry : undefined;
+ }
+
override set(path: string, entry: HashCacheEntry): this {
if (!this.has(path) && this.size >= MAX_FILES) {
const oldest = this.keys().next().value;
if (oldest !== undefined) this.delete(oldest);
}
+ this.rules.set(path, redactionPolicy());
return super.set(path, entry);
}
+
+ override delete(path: string): boolean {
+ this.rules.delete(path);
+ return super.delete(path);
+ }
+}
+
+/**
+ * A chat's rules: the ones its ledger record was pinned to; a chat recorded
+ * before pins existed went up redacted, so it never turns raw; else the
+ * process switch at its start.
+ */
+function pinnedPolicy(record: SessionLedgerRecord | undefined, current: RedactionPolicy): RedactionPolicy {
+ if (record?.redactionPolicy === CLIENT_RAW || record?.redactionPolicy === CLIENT_V3 || record?.redactionPolicy === "legacy") return record.redactionPolicy;
+ return record && current === CLIENT_RAW ? CLIENT_V3 : current;
}
function scanContext(root: string, cache: Map<string, HashCacheEntry>, texts: RedactedTextCache, metrics: UploadMetrics): ScanContext {
@@ -3781,6 +3814,8 @@ async function inspectFile(context: ScanContext, path: string): Promise<HashCach
signature.ctimeMs,
signature.ino,
signature.dev,
+ // Sessions pinned to other rules never share a scan (FileHashCache).
+ redactionPolicy(),
].join("\0");
const existing = FILE_SCAN_IN_FLIGHT.get(scanKey);
if (existing) {
@@ -4599,6 +4634,9 @@ const NO_UPLOAD_FEATURES: UploadFeatures = { idempotencyKey: false, integrity: f
/** What a /collect upload carries besides its body. */
export type UploadRequestOptions = { idempotencyKey?: string };
+/** The public calls that record or send for one session (first argument its id): run under its pinned rules. */
+const PINNED_SESSION_METHODS = ["recordProjectArchive", "recordTrace", "markComputerUse", "recordSessionModel", "recordChildSession", "recordWebVisit", "recordAttachment", "steerTurn", "recordCommand", "captureSnapshot", "finishSession", "flushTrace"] as const;
+
export class SessionUploader {
private readonly uploadUrl: string | null;
private token: string;
@@ -4752,6 +4790,15 @@ export class SessionUploader {
? migrateLegacyUploadState(stateDir, (message, details) => this.log("warn", message, details))
: Promise.resolve();
this.ledgerReady = this.stateMigrated.then(() => this.loadLedger());
+ // A session's work runs under the rules pinned at its start, whatever the process switch says meanwhile.
+ for (const name of PINNED_SESSION_METHODS) {
+ const method = this[name] as unknown as (sessionId: string, ...rest: unknown[]) => unknown;
+ Object.defineProperty(this, name, {
+ configurable: true,
+ writable: true,
+ value: (sessionId: string, ...rest: unknown[]) => withRedactionPolicy(this.sessions.get(sessionId)?.redactionPolicy, () => method.call(this, sessionId, ...rest)),
+ });
+ }
this.changeDebounceMs = options.changeDebounceMs ?? CHANGE_DEBOUNCE_MS;
this.fallbackScanMs = options.fallbackScanMs ?? FALLBACK_SCAN_MS;
this.appVersion = options.appVersion;
@@ -4936,6 +4983,7 @@ export class SessionUploader {
...(state.refused.length > 0 ? { refused: state.refused.slice(-MAX_REFUSED_SEQUENCES) } : {}),
// A new segment is judged again once it ends.
...(state.endedAt ? { endedAt: state.endedAt } : {}),
+ redactionPolicy: state.redactionPolicy,
};
}
@@ -4960,6 +5008,7 @@ export class SessionUploader {
state.lastFailureAt = previous?.lastFailureAt;
state.lastSuccessAt = previous?.lastSuccessAt;
state.refused = [...(previous?.refused ?? [])];
+ state.redactionPolicy = pinnedPolicy(previous, state.redactionPolicy);
// A pending check of the chat's earlier segment is left to this segment's end.
this.cancelConfirm(state.id);
// Events recorded before the ledger loaded take precedence over what the
@@ -5242,6 +5291,7 @@ export class SessionUploader {
private newSessionState(sessionId: string, workspaceId: string, root: string, cache: Map<string, HashCacheEntry>): SessionState {
return {
+ redactionPolicy: defaultRedactionPolicy(),
id: sessionId,
root,
workspaceId,
@@ -6611,7 +6661,8 @@ export class SessionUploader {
}
private enqueue(state: SessionState, operation: () => Promise<void>): void {
- state.tail = state.tail.then(operation).catch((error: unknown) => {
+ // The pin is final once the ledger was read (prepareSession): the operation runs under it.
+ state.tail = state.tail.then(() => state.ready.catch(() => undefined)).then(() => withRedactionPolicy(state.redactionPolicy, operation)).catch((error: unknown) => {
this.log("warn", "OmniRush session upload operation failed", {
sessionId: state.id,
error: error instanceof Error ? error.message : "unknown",
@@ -7132,7 +7183,10 @@ export class SessionUploader {
...body.extras,
});
await writer.write(`${head.slice(0, -1)},"files":[`);
+ // client-raw: nothing is removed; the envelope says how many credentials it carries.
+ let credentials = 0;
await body.writeFiles(async (file) => {
+ if (redactionRaw()) credentials += countCredentials(file);
await writer.write(`${fileCount > 0 ? "," : ""}${JSON.stringify(file)}`);
fileCount += 1;
});
@@ -7142,7 +7196,9 @@ export class SessionUploader {
await writer.write(`${first ? "" : ","}${manifestEntryJson(entry)}`);
first = false;
}
- await writer.write(`],"privacy":${JSON.stringify(body.privacy())}`);
+ if (redactionRaw() && body.trace) credentials += countCredentials(body.trace);
+ const privacy = redactionRaw() ? { ...body.privacy(), credential_count: credentials } : body.privacy();
+ await writer.write(`],"privacy":${JSON.stringify(privacy)}`);
for (const [key, value] of Object.entries(body.trailer ? await body.trailer() : {})) {
await writer.write(`,${JSON.stringify(key)}:${JSON.stringify(value)}`);
}