feat: self-heal the chatgpt.com scraper with codex and open a PR

After SELFHEAL_FAILURE_THRESHOLD consecutive UI_CHANGED/TURN_TIMED_OUT
failures the queue snapshots the logged-in profile and runs
scripts/selfheal.sh: codex exec in yolo mode on a throwaway clone, with a
Playwright + playwright-stealth inspector to study the live frontend.
Changes are limited to src/chatgpt and test fixtures, must pass typecheck
and tests, and are pushed as a pull request for human review.
Disabled by default (SELFHEAL_ENABLED).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-07 20:13:11 +02:00
1 parent f7e7148135
commit 550396d7ed
13 files changed
+823 -3

No files matched your search

+12
View File
@@ -1,3 +1,6 @@
import { cp, mkdtemp } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { Page } from "playwright";
import { imageDimensions } from "../image.js";
import { audit } from "../log.js";
@@ -16,6 +19,8 @@ export const MIN_IMAGE_BYTES = 20_000;
export interface ImageProvider {
generateImages(generationId: string, request: ImageRequest): Promise<StoredOutput[]>;
checkSession(): Promise<boolean>;
/** Closes the browser and copies the logged-in profile to a new temporary directory. */
snapshotProfile(): Promise<string>;
close(): Promise<void>;
}
@@ -62,6 +67,13 @@ export class ChatGptImageProvider implements ImageProvider {
}
}
async snapshotProfile(): Promise<string> {
await this.browser.close();
const target = await mkdtemp(path.join(os.tmpdir(), "chatgpt-profile-"));
await cp(this.config.profileDir, target, { recursive: true, filter: (source) => !/Singleton(Lock|Socket|Cookie)$/.test(source) });
return target;
}
async close(): Promise<void> {
await this.browser.close();
}
+2 -1
View File
@@ -8,11 +8,12 @@ import { JobManager } from "./jobs.js";
import { audit, auditError } from "./log.js";
import { cleanupOrphanMedia, ensureMediaDir, isOutputFilename, mediaDir, resolvePublicOutput } from "./media.js";
import { publicMediaSigningConfigured, validatePublicMediaSignature } from "./public-media.js";
import { SelfHealer } from "./selfheal.js";
import { registerTools } from "./tools.js";
import { registerUpdateRoutes } from "./update.js";
const provider = new ChatGptImageProvider();
const jobs = new JobManager(provider);
const jobs = new JobManager(provider, undefined, new SelfHealer());
const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168;
await ensureMediaDir();
const orphanCleanup = async () => {
+29 -2
View File
@@ -4,6 +4,7 @@ import type { NormalizedArguments } from "./arguments.js";
import { SessionNotReady, toJobError, UsageLimitReached } from "./chatgpt/errors.js";
import type { ImageProvider } from "./chatgpt/provider.js";
import { audit, auditError } from "./log.js";
import type { SelfHealer } from "./selfheal.js";
import { generationWasPurged, loadPersistedJob, loadPersistedJobs, outputExists, persistCompletedJob, purgeGeneration } from "./media.js";
import type { GenerationJob, InlineReferenceImage, JobError, ReferenceImage } from "./types.js";
@@ -36,7 +37,8 @@ interface Circuit {
type Task =
| { kind: "generate"; job: GenerationJob }
| { kind: "session_check"; resolve: (loggedIn: boolean) => void; reject: (error: unknown) => void };
| { kind: "session_check"; resolve: (loggedIn: boolean) => void; reject: (error: unknown) => void }
| { kind: "selfheal_prepare"; reason: string };
/**
* Serial queue: one Chromium profile means one generation at a time. Adds random pacing between
@@ -50,7 +52,11 @@ export class JobManager {
private circuit?: Circuit;
private session: { loggedIn?: boolean; checkedAt?: string } = {};
constructor(private readonly provider: ImageProvider, private readonly options: JobManagerOptions = jobManagerOptionsFromEnv()) {}
constructor(
private readonly provider: ImageProvider,
private readonly options: JobManagerOptions = jobManagerOptionsFromEnv(),
private readonly selfHealer?: SelfHealer,
) {}
async submit(model: string, args: NormalizedArguments, taskTraceId?: string): Promise<GenerationJob> {
this.assertAccepting();
@@ -95,6 +101,7 @@ export class JobManager {
running: [...this.jobs.values()].some((job) => job.status === "RUNNING"),
session: this.session,
circuit: circuit ? { reason: circuit.reason, retryAfter: new Date(circuit.until).toISOString(), message: circuit.message } : null,
selfHeal: this.selfHealer?.view() ?? null,
};
}
@@ -147,6 +154,11 @@ export class JobManager {
await this.runSessionCheck(task);
continue;
}
if (task.kind === "selfheal_prepare") {
this.queue.shift();
await this.prepareSelfHeal(task.reason);
continue;
}
const circuit = this.openCircuit();
if (circuit) {
this.queue.shift();
@@ -180,11 +192,17 @@ export class JobManager {
job.status = "COMPLETED"; job.outputs = outputs; job.completedAt = new Date().toISOString(); job.updatedAt = job.completedAt;
job.request = undefined;
this.session = { loggedIn: true, checkedAt: job.completedAt };
this.selfHealer?.recordSuccess();
await persistCompletedJob(job);
audit("generation_completed", { generationId: job.generationId, outputCount: outputs.length, outputBytes: outputs.reduce((sum, output) => sum + output.sizeBytes, 0), durationMs: Date.now() - new Date(job.startedAt).getTime() });
} catch (error) {
this.tripCircuit(error);
this.fail(job, error);
const selfHealReason = job.error && this.selfHealer?.recordFailure(job.error.code);
if (job.error && selfHealReason) {
job.error.message += " A self-heal run was started; check get_usage for its pull request.";
this.queue.unshift({ kind: "selfheal_prepare", reason: selfHealReason });
}
} finally {
this.lastFinishedAt = Date.now();
}
@@ -203,6 +221,15 @@ export class JobManager {
}
}
/** Runs inside the queue so the profile is copied while no generation uses the browser. */
private async prepareSelfHeal(reason: string): Promise<void> {
try {
this.selfHealer?.launch(reason, await this.provider.snapshotProfile());
} catch (error) {
this.selfHealer?.abort(error);
}
}
private tripCircuit(error: unknown): void {
let reason: Circuit["reason"] | undefined;
let cooldown = 0;
+135
View File
@@ -0,0 +1,135 @@
import { spawn } from "node:child_process";
import { closeSync, mkdirSync, openSync, readFileSync } from "node:fs";
import path from "node:path";
import { audit, auditError } from "./log.js";
// Failures a selector patch can plausibly fix. Usage limits, lost sessions, refusals and text
// replies are excluded: no change to selectors.ts would help with those.
export const SELFHEAL_TRIGGER_CODES = new Set(["UI_CHANGED", "TURN_TIMED_OUT"]);
export interface SelfHealOptions {
enabled: boolean;
threshold: number;
cooldownMs: number;
script: string;
logFile: string;
diagnosticsDir: string;
}
export function selfHealOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): SelfHealOptions {
return {
enabled: env.SELFHEAL_ENABLED === "true",
threshold: Number(env.SELFHEAL_FAILURE_THRESHOLD) || 3,
cooldownMs: (Number(env.SELFHEAL_COOLDOWN_HOURS) || 6) * 60 * 60 * 1000,
script: path.resolve(env.SELFHEAL_SCRIPT || "scripts/selfheal.sh"),
logFile: path.resolve(env.SELFHEAL_LOG_FILE || "logs/selfheal.log"),
diagnosticsDir: path.resolve(env.DIAGNOSTICS_DIR || "diagnostics"),
};
}
export interface SelfHealStatus {
enabled: boolean;
state: "idle" | "running" | "succeeded" | "failed";
consecutiveFailures: number;
threshold: number;
lastStartedAt: string | null;
lastFinishedAt: string | null;
lastExitCode: number | null;
lastPullRequest: string | null;
nextAllowedAt: string | null;
}
/**
* Counts consecutive scraper-type failures and, past the threshold, runs scripts/selfheal.sh in the
* background. The script runs codex (yolo mode) in a throwaway clone with a snapshot of the logged-in
* profile, so it can inspect the live chatgpt.com frontend with Playwright + playwright-stealth and
* patch src/chatgpt/. The result is a pull request for human review; nothing is deployed automatically.
*/
export class SelfHealer {
private consecutiveFailures = 0;
private running = false;
private lastStartedAt = 0;
private status: Pick<SelfHealStatus, "state" | "lastStartedAt" | "lastFinishedAt" | "lastExitCode" | "lastPullRequest"> = {
state: "idle", lastStartedAt: null, lastFinishedAt: null, lastExitCode: null, lastPullRequest: null,
};
constructor(private readonly options: SelfHealOptions = selfHealOptionsFromEnv()) {}
recordSuccess(): void {
this.consecutiveFailures = 0;
}
/**
* Returns the reason when this failure should start a self-heal run. The run is then reserved:
* the caller prepares the profile snapshot and calls launch() (or abort() if that fails).
*/
recordFailure(code: string): string | undefined {
if (!SELFHEAL_TRIGGER_CODES.has(code)) return undefined;
this.consecutiveFailures += 1;
if (!this.options.enabled || this.consecutiveFailures < this.options.threshold) return undefined;
if (this.running || Date.now() < this.lastStartedAt + this.options.cooldownMs) return undefined;
this.running = true;
this.lastStartedAt = Date.now();
this.status = { ...this.status, state: "running", lastStartedAt: new Date(this.lastStartedAt).toISOString(), lastFinishedAt: null, lastExitCode: null };
return `${this.consecutiveFailures} consecutive ${code} failures`;
}
abort(error: unknown): void {
this.finish(null, error);
}
view(): SelfHealStatus {
return {
enabled: this.options.enabled,
...this.status,
consecutiveFailures: this.consecutiveFailures,
threshold: this.options.threshold,
nextAllowedAt: this.lastStartedAt ? new Date(this.lastStartedAt + this.options.cooldownMs).toISOString() : null,
};
}
launch(reason: string, profileSnapshot: string): void {
audit("selfheal_started", { reason });
let fd: number | undefined;
try {
mkdirSync(path.dirname(this.options.logFile), { recursive: true });
fd = openSync(this.options.logFile, "a");
const child = spawn("bash", [this.options.script], {
cwd: path.resolve(path.dirname(this.options.script), ".."),
env: { ...process.env, SELFHEAL_DIAGNOSTICS_DIR: this.options.diagnosticsDir, SELFHEAL_PROFILE_SNAPSHOT: profileSnapshot, SELFHEAL_REASON: reason },
stdio: ["ignore", fd, fd],
});
child.on("error", (error) => this.finish(null, error));
child.on("exit", (code) => this.finish(code));
} catch (error) {
this.finish(null, error);
} finally {
if (fd !== undefined) closeSync(fd);
}
}
private finish(exitCode: number | null, error?: unknown): void {
if (!this.running) return;
this.running = false;
this.consecutiveFailures = 0;
const pullRequest = exitCode === 0 ? lastPullRequestUrl(this.options.logFile) : null;
this.status = {
state: exitCode === 0 ? "succeeded" : "failed",
lastStartedAt: this.status.lastStartedAt,
lastFinishedAt: new Date().toISOString(),
lastExitCode: exitCode,
lastPullRequest: pullRequest ?? this.status.lastPullRequest,
};
if (error) auditError("selfheal_failed", error);
audit("selfheal_finished", { exitCode, pullRequest });
}
}
export function lastPullRequestUrl(logFile: string): string | null {
try {
const matches = [...readFileSync(logFile, "utf8").matchAll(/^SELFHEAL_PR_CREATED (\S+)/gm)];
return matches.at(-1)?.[1] ?? null;
} catch {
return null;
}
}