mirror of
https://github.com/openclaw/openclaw.git
synced 2026-08-12 21:53:00 -06:00
73bdb4b924
* feat(agents): record run-end worktree cleanup outcome Persist removed, retained, and failed run-end cleanup outcomes on managed worktree records. Operators and QA can inspect the durable fact through worktrees.list and openclaw worktrees list --json. Release note: Managed worktree run-end cleanup now records why a checkout was removed or retained in worktree list JSON. * test(qa): prove dirty worktree retention outcome * chore(protocol): regenerate swift gateway models * fix(agents): harden worktree cleanup recovery Register run_end_cleanup_json as a lazy compatible column so same-version v6 index repair and read-only doctor migration can recover databases created before the column existed. Type removal contention at the registry boundary; unexpected claim failures now best-effort record a bounded failed outcome and rethrow the original error. * fix(ci): clear repo-wide lint debt blocking merge gates The red-main landing rule requires this PR to repair repository-wide merge-gate debt instead of bypassing it. Apply the current lint contracts mechanically and split turn-transition coverage into a concept-named sibling with per-file-safe test state. Exact line delta: +676/-574 (net +102) across 44 test/support files. * fix(ci): preserve cached health refresh proof Require the public refresh call to exist before accepting that sensitive fields were omitted, so the boundary proof cannot pass on a missing call. * fix(ci): correct test typing left by the lint sweep Literal-widened totalTokensVersion fixtures, a WebSocket RawData overload mismatch, and the protocol schema document cast broke check-test-types after the repo-wide lint repair. Aligns the fixtures with SessionEntry, narrows Buffer handling per RawData, and keeps the JSON-shaped undefined omission under structuredClone. * test(agents): reuse upstream resource-loader test support The session-loop split and #120463's helper extraction landed the same createResourceLoader/createCompactionHandlers twice; the rebase kept both, orphaning main's agent-session-loop-resource-loader.test-support.ts and failing the dead-code gate. Import the upstream helpers and delete the duplicates. * fix(agents): reject finalized rows at the worktree removal claim Address the accepted ClawSweeper late-claim finding by rereading and rejecting missing or finalized worktree rows inside the synchronous removal-claim transaction. Preserve the authoritative cleanup invariant: finalized contenders record nothing, while retained-busy is written only while the row remains live. * refactor(agents): reuse registry update for busy outcomes Keep the live-row conditional write in the canonical registry update path so the finalized-claim repair stays below the registry max-lines ratchet without weakening the authoritative-outcome invariant. * test(agents): drop session test duplicates after rebase Keep current main as the canonical owner of next-turn lifecycle coverage and correctness test support after replaying the older lint-debt split. * fix(agents): guard post-abort cleanup outcomes against finalization After abortWorktreeRemoval releases a stale remover's claim, its retained or failed write raced a finalizing remover and could overwrite the authoritative removed-lossless fact. Route every retained/failed write through the live-row condition; only the finalizing remover's own removed-lossless write stays unconditional. * fix(agents): persist the removal outcome atomically with finalization A delayed removed-lossless write after remove() finalized could race a restore plus newer cleanup and overwrite the newer operator-visible fact. The run-end outcome now rides remove()'s finalization update; every other cleanup write stays live-row conditional, so no post-finalize write path remains. * test(qa): restore strict cached-health contract assertions The lint sweep's Boolean() coercions let truthy non-booleans satisfy the wire-typed cached-meta contract. Assert the literal boolean for unknown-typed fields and use nullish-coalesced strict equivalents for boolean chains. * fix(agents): clear the stale cleanup outcome when restoring a worktree A restored checkout begins a new lifecycle; leaving the removed-lossless fact on the live row showed operators a stale result until the next cleanup. Restore clears the recorded outcome and the regression asserts the cleared state before the next cleanup records fresh truth. * fix(agents): scope stale cleanup outcomes to their observed lifecycle A stale remover's retained/failed write raced a concurrent remove-plus- restore: the revived row is live again, so the live-row condition alone could stamp a prior-lifecycle outcome. Condition those writes on the activity stamp the remover observed; restore bumps lastActiveAt, making any prior-lifecycle write a no-op. * fix(agents): advance the restore activity stamp within one millisecond Stale cleanup writes fence on the activity stamp they observed; a restore completing in the same millisecond could revive the row with an identical stamp and let the fence match. Restore now always advances past the stored value, and the ABA regression pins the clock to prove the same-millisecond case.
259 lines
8.2 KiB
TypeScript
259 lines
8.2 KiB
TypeScript
// QA evidence for the real Gateway support-export CLI and zip privacy boundary.
|
|
import assert from "node:assert/strict";
|
|
import fs from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
import JSZip from "jszip";
|
|
import { formatErrorMessage } from "../../../../src/infra/errors.js";
|
|
import {
|
|
createOpenClawTestInstance,
|
|
type OpenClawTestInstance,
|
|
} from "../../../helpers/openclaw-test-instance.js";
|
|
import { createQaScriptEvidenceWriter } from "./script-evidence.js";
|
|
|
|
const SOURCE_PATH = "test/e2e/qa-lab/runtime/gateway-support-export-runtime.ts";
|
|
const SCENARIO_ID = "gateway-support-export";
|
|
|
|
export type GatewaySupportExportRuntimeOptions = {
|
|
artifactBase: string;
|
|
repoRoot: string;
|
|
};
|
|
|
|
type DiagnosticsExportResult = {
|
|
path: string;
|
|
bytes: number;
|
|
manifest: {
|
|
contents: Array<{ path: string; bytes: number; mediaType: string }>;
|
|
privacy: {
|
|
payloadFree: boolean;
|
|
rawLogsIncluded: boolean;
|
|
notes: string[];
|
|
};
|
|
};
|
|
};
|
|
|
|
type GatewaySupportExportSummary = {
|
|
archive: string;
|
|
bytes: number;
|
|
entries: string[];
|
|
payloadFree: boolean;
|
|
privateMode: boolean;
|
|
rawLogsIncluded: boolean;
|
|
};
|
|
|
|
function parseOptions(
|
|
argv: string[],
|
|
repoRoot = process.cwd(),
|
|
): GatewaySupportExportRuntimeOptions {
|
|
let artifactBase: string | undefined;
|
|
for (let index = 0; index < argv.length; index += 1) {
|
|
const option = argv[index];
|
|
const value = argv[index + 1];
|
|
if (option !== "--artifact-base") {
|
|
throw new Error(`unknown argument: ${option}`);
|
|
}
|
|
if (!value || value.startsWith("--")) {
|
|
throw new Error("--artifact-base requires a value");
|
|
}
|
|
artifactBase = value;
|
|
index += 1;
|
|
}
|
|
if (!artifactBase) {
|
|
throw new Error("--artifact-base is required");
|
|
}
|
|
return { artifactBase: path.resolve(repoRoot, artifactBase), repoRoot };
|
|
}
|
|
|
|
function parseCliJson<T>(
|
|
label: string,
|
|
result: Awaited<ReturnType<OpenClawTestInstance["cli"]>>,
|
|
parse: (value: unknown) => T = (value) => value as T,
|
|
): T {
|
|
if (result.code !== 0) {
|
|
throw new Error(
|
|
`${label} failed with exit ${String(result.code)}\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`,
|
|
);
|
|
}
|
|
try {
|
|
return parse(JSON.parse(result.stdout) as unknown);
|
|
} catch (error) {
|
|
throw new Error(
|
|
`${label} returned invalid JSON: ${formatErrorMessage(error)}\n${result.stdout}`,
|
|
{ cause: error },
|
|
);
|
|
}
|
|
}
|
|
|
|
async function readZipEntries(file: string): Promise<Record<string, string>> {
|
|
const zip = await JSZip.loadAsync(await fs.readFile(file));
|
|
const entries: Record<string, string> = {};
|
|
for (const [name, entry] of Object.entries(zip.files)) {
|
|
if (!entry.dir) {
|
|
entries[name] = await entry.async("string");
|
|
}
|
|
}
|
|
return entries;
|
|
}
|
|
|
|
function assertSafeArchiveEntries(entries: readonly string[]): void {
|
|
for (const entry of entries) {
|
|
assert.ok(entry.length > 0, "support zip entry must not be empty");
|
|
assert.equal(path.posix.isAbsolute(entry), false, `absolute support zip entry: ${entry}`);
|
|
assert.equal(
|
|
entry.split("/").some((part) => part === "" || part === "." || part === ".."),
|
|
false,
|
|
`unsafe support zip entry: ${entry}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
function createWriter(options: GatewaySupportExportRuntimeOptions) {
|
|
return createQaScriptEvidenceWriter({
|
|
artifactBase: options.artifactBase,
|
|
logFileName: "gateway-support-export.log",
|
|
primaryModel: "gateway/diagnostics-export",
|
|
providerMode: "mock-openai",
|
|
repoRoot: options.repoRoot,
|
|
target: {
|
|
id: SCENARIO_ID,
|
|
title: "Gateway support diagnostics export",
|
|
sourcePath: SOURCE_PATH,
|
|
docsRefs: ["docs/gateway/diagnostics.md", "docs/cli/gateway.md"],
|
|
codeRefs: [
|
|
SOURCE_PATH,
|
|
"src/cli/gateway-cli/register.ts",
|
|
"src/logging/diagnostic-support-export.ts",
|
|
"src/logging/diagnostic-support-bundle.ts",
|
|
],
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function runGatewaySupportExportRuntime(options: GatewaySupportExportRuntimeOptions) {
|
|
await fs.mkdir(options.artifactBase, { recursive: true });
|
|
const writer = createWriter(options);
|
|
const startedAt = Date.now();
|
|
let instance: OpenClawTestInstance | undefined;
|
|
try {
|
|
instance = await createOpenClawTestInstance({
|
|
name: "qa-gateway-support-export",
|
|
config: {
|
|
diagnostics: { enabled: true },
|
|
},
|
|
env: {
|
|
OPENCLAW_TEST_FILE_LOG: "1",
|
|
},
|
|
});
|
|
await instance.startGateway();
|
|
|
|
const outputPath = path.join(options.artifactBase, "gateway-support-export.zip");
|
|
const result = parseCliJson<DiagnosticsExportResult>(
|
|
"gateway diagnostics export",
|
|
await instance.cli(
|
|
[
|
|
"gateway",
|
|
"diagnostics",
|
|
"export",
|
|
"--output",
|
|
outputPath,
|
|
"--log-lines",
|
|
"7",
|
|
"--log-bytes",
|
|
"4096",
|
|
"--url",
|
|
instance.url,
|
|
"--token",
|
|
instance.gatewayToken,
|
|
"--timeout",
|
|
"10000",
|
|
"--json",
|
|
],
|
|
{ timeoutMs: 120_000 },
|
|
),
|
|
);
|
|
|
|
assert.equal(path.resolve(result.path), path.resolve(outputPath));
|
|
assert.ok(result.bytes > 0, "diagnostics export must be nonempty");
|
|
assert.equal(result.manifest.privacy.payloadFree, true);
|
|
assert.equal(result.manifest.privacy.rawLogsIncluded, false);
|
|
|
|
const entries = await readZipEntries(outputPath);
|
|
const entryNames = Object.keys(entries).toSorted();
|
|
assertSafeArchiveEntries(entryNames);
|
|
for (const required of [
|
|
"config/sanitized.json",
|
|
"config/shape.json",
|
|
"diagnostics.json",
|
|
"health/gateway-health.json",
|
|
"logs/openclaw-sanitized.jsonl",
|
|
"manifest.json",
|
|
"status/gateway-status.json",
|
|
"summary.md",
|
|
]) {
|
|
assert.ok(entryNames.includes(required), `support zip missing ${required}`);
|
|
}
|
|
|
|
const combined = Object.values(entries).join("\n");
|
|
for (const [label, privateValue] of [
|
|
["Gateway token", instance.gatewayToken],
|
|
["hook token", instance.hookToken],
|
|
["home directory", instance.homeDir],
|
|
["state directory", instance.stateDir],
|
|
] as const) {
|
|
assert.equal(combined.includes(privateValue), false, `support zip leaked ${label}`);
|
|
}
|
|
assert.match(combined, /payload[- ]free/iu);
|
|
assert.match(combined, /sanitized/iu);
|
|
|
|
const mode = (await fs.stat(outputPath)).mode & 0o777;
|
|
const privateMode = process.platform === "win32" || mode === 0o600;
|
|
assert.equal(privateMode, true, `support zip mode must be 0600, got ${mode.toString(8)}`);
|
|
|
|
const summary: GatewaySupportExportSummary = {
|
|
archive: path.basename(outputPath),
|
|
bytes: result.bytes,
|
|
entries: entryNames,
|
|
payloadFree: result.manifest.privacy.payloadFree,
|
|
privateMode,
|
|
rawLogsIncluded: result.manifest.privacy.rawLogsIncluded,
|
|
};
|
|
const summaryPath = path.join(options.artifactBase, "gateway-support-export-summary.json");
|
|
await fs.writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
|
|
writer.appendLog(
|
|
`gateway-support-export: files=${entryNames.length} bytes=${result.bytes} privateMode=${String(privateMode)}\n`,
|
|
);
|
|
return await writer.write({
|
|
artifacts: [
|
|
{ kind: "summary", filePath: summaryPath },
|
|
{ kind: "archive", filePath: outputPath },
|
|
],
|
|
details: `real CLI wrote ${entryNames.length} sanitized files in a private payload-free zip`,
|
|
durationMs: Math.max(1, Date.now() - startedAt),
|
|
status: "pass",
|
|
});
|
|
} catch (error) {
|
|
const details = formatErrorMessage(error);
|
|
writer.appendLog(`gateway-support-export: ${details}\n`);
|
|
return await writer.write({
|
|
details,
|
|
durationMs: Math.max(1, Date.now() - startedAt),
|
|
status: "fail",
|
|
});
|
|
} finally {
|
|
await instance?.cleanup();
|
|
}
|
|
}
|
|
|
|
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
|
runGatewaySupportExportRuntime(parseOptions(process.argv.slice(2)))
|
|
.then((evidence) => {
|
|
const status = evidence.entries[0]?.result.status;
|
|
process.stdout.write(`gateway-support-export: ${status}\n`);
|
|
process.exitCode = status === "pass" ? 0 : 1;
|
|
})
|
|
.catch((error: unknown) => {
|
|
process.stderr.write(`gateway-support-export: ${formatErrorMessage(error)}\n`);
|
|
process.exitCode = 1;
|
|
});
|
|
}
|