@sagentlab/navarch-runtime 0.1.161 → 0.1.164
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +1 -1
- package/dist/git-worktree.cjs +9 -0
- package/dist/qa-fixture.cjs +179 -0
- package/dist/qa-report.js +110 -0
- package/dist/qa-runner.cjs +75 -87
- package/dist/session.cjs +9 -3
- package/package.json +1 -1
package/dist/api.cjs
CHANGED
|
@@ -136,7 +136,7 @@ class NavarchApiClient {
|
|
|
136
136
|
}
|
|
137
137
|
/** schema-design.md §7 — `POST /api/dispatch/claim {machine_capacity, capabilities} → task + context bundle`. */
|
|
138
138
|
async claim(req) {
|
|
139
|
-
const result = await this.request("POST", "/api/dispatch/claim", req, { allowEmpty: true });
|
|
139
|
+
const result = await this.request("POST", "/api/dispatch/claim", { ...req, delivery_baseline_protocol: 1 }, { allowEmpty: true });
|
|
140
140
|
if (!result || result.task == null)
|
|
141
141
|
return null;
|
|
142
142
|
return result;
|
package/dist/git-worktree.cjs
CHANGED
|
@@ -72,6 +72,7 @@ class GitWorktree {
|
|
|
72
72
|
sessionTokenMarker;
|
|
73
73
|
hostedCheckpointRef;
|
|
74
74
|
hostedCheckpointLocalRef;
|
|
75
|
+
hostedCheckpointLeaseId;
|
|
75
76
|
/** Set when the resumed remote branch had lost its ownership commit and must be re-marked. */
|
|
76
77
|
adoptedUnmarkedBranch = false;
|
|
77
78
|
constructor(options) {
|
|
@@ -122,6 +123,7 @@ class GitWorktree {
|
|
|
122
123
|
this.ownershipCommitIdentity = options.ownershipCommitIdentity ?? { name: "Navarch", email: "runtime@navarch.local" };
|
|
123
124
|
this.hostedCheckpointRef = options.restoreHostedCheckpoint ? hostedCheckpointRef(options.taskId) : null;
|
|
124
125
|
this.hostedCheckpointLocalRef = `refs/navarch/restored-checkpoints/${taskKey}`;
|
|
126
|
+
this.hostedCheckpointLeaseId = options.hostedCheckpointLeaseId;
|
|
125
127
|
}
|
|
126
128
|
async prepare(signal) {
|
|
127
129
|
signal?.throwIfAborted();
|
|
@@ -331,6 +333,13 @@ class GitWorktree {
|
|
|
331
333
|
if (!/^[0-9a-f]{40,64}$/i.test(sha) || !/^[0-9a-f]{40,64}$/i.test(parent)) {
|
|
332
334
|
throw new Error("the checkpoint ref did not resolve to a snapshot commit with a parent");
|
|
333
335
|
}
|
|
336
|
+
if (this.hostedCheckpointLeaseId !== undefined) {
|
|
337
|
+
const body = (await this.runGit(["--git-dir", this.repositoryPath, "show", "-s", "--format=%B", sha], false)).stdout;
|
|
338
|
+
const leases = body.split("\n").filter(line => line.startsWith("Navarch-Checkpoint-Lease:"));
|
|
339
|
+
if (leases.length !== 1 || leases[0] !== `Navarch-Checkpoint-Lease: ${this.hostedCheckpointLeaseId}`) {
|
|
340
|
+
throw new Error("checkpoint lease identity is missing or different; remote checkpoint preserved");
|
|
341
|
+
}
|
|
342
|
+
}
|
|
334
343
|
return { ref, sha: sha, parent: parent };
|
|
335
344
|
}
|
|
336
345
|
catch (error) {
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.QaFixtureError = void 0;
|
|
7
|
+
exports.createQaFixture = createQaFixture;
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
10
|
+
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const node_http_1 = require("node:http");
|
|
12
|
+
class QaFixtureError extends Error {
|
|
13
|
+
reason;
|
|
14
|
+
failure_class = "resource";
|
|
15
|
+
constructor(reason) {
|
|
16
|
+
super(reason);
|
|
17
|
+
this.reason = reason;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
exports.QaFixtureError = QaFixtureError;
|
|
21
|
+
/** Keep the listening socket: finding a free port then releasing it is a race. */
|
|
22
|
+
async function createQaFixture(options) {
|
|
23
|
+
const budget = options.operationTimeoutMs ?? 5000;
|
|
24
|
+
if (!Number.isInteger(budget) || budget < 1 || budget > 10_000 ||
|
|
25
|
+
options.scenarios.length > 100 || options.scenarios.some(name => !/^[a-z][a-z0-9_-]{0,63}$/.test(name))) {
|
|
26
|
+
throw new Error("Invalid local fixture limits");
|
|
27
|
+
}
|
|
28
|
+
const namespace = `qa-${(0, node_crypto_1.randomUUID)()}`;
|
|
29
|
+
const root = await node_fs_1.promises.mkdtemp(node_path_1.default.join(await node_fs_1.promises.realpath(options.worktree), ".qa-fixture-"));
|
|
30
|
+
const databaseDir = node_path_1.default.join(root, "db");
|
|
31
|
+
const token = (0, node_crypto_1.randomBytes)(32).toString("hex");
|
|
32
|
+
const lifetime = new AbortController();
|
|
33
|
+
const context = { namespace, databaseDir, signal: lifetime.signal };
|
|
34
|
+
let closed = false, uncertain = false;
|
|
35
|
+
let pending;
|
|
36
|
+
const handlers = new Set();
|
|
37
|
+
const send = (res, status, reason) => {
|
|
38
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
39
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
40
|
+
res.end(JSON.stringify({ namespace, reason, ...(status >= 400 ? { failure_class: "resource" } : {}) }));
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const server = (0, node_http_1.createServer)((req, res) => {
|
|
44
|
+
void (async () => {
|
|
45
|
+
if (closed) {
|
|
46
|
+
send(res, 503, "fixture_closed");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (!req.url?.startsWith("/__qa/")) {
|
|
50
|
+
const handling = Promise.resolve().then(() => options.handle(req, res, context));
|
|
51
|
+
handlers.add(handling);
|
|
52
|
+
try {
|
|
53
|
+
await handling;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
handlers.delete(handling);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (req.headers["x-navarch-fixture-token"] !== token) {
|
|
61
|
+
send(res, 403, "fixture_scope_denied");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const action = req.url === `/__qa/${namespace}/seed` ? "seed" : req.url === `/__qa/${namespace}/reset` ? "reset" : undefined;
|
|
65
|
+
if (req.method !== "POST" || !action) {
|
|
66
|
+
send(res, 404, "fixture_route_missing");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (pending || uncertain) {
|
|
70
|
+
send(res, 409, uncertain ? "fixture_completion_unknown" : "fixture_busy");
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
// Claim the slot before reading the body, including slow/chunked clients.
|
|
74
|
+
let release;
|
|
75
|
+
pending = new Promise(resolve => { release = resolve; });
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
const abort = () => controller.abort();
|
|
78
|
+
lifetime.signal.addEventListener("abort", abort, { once: true });
|
|
79
|
+
let started = false;
|
|
80
|
+
const deadline = performance.now() + budget;
|
|
81
|
+
const timer = setTimeout(() => {
|
|
82
|
+
uncertain = started;
|
|
83
|
+
controller.abort();
|
|
84
|
+
send(res, 504, started ? "fixture_completion_unknown" : "fixture_request_timeout");
|
|
85
|
+
if (!started)
|
|
86
|
+
req.destroy();
|
|
87
|
+
}, budget);
|
|
88
|
+
try {
|
|
89
|
+
let body = "";
|
|
90
|
+
for await (const chunk of req) {
|
|
91
|
+
body += Buffer.from(chunk).toString("utf8");
|
|
92
|
+
if (Buffer.byteLength(body) > 1024) {
|
|
93
|
+
send(res, 413, "fixture_body_too_large");
|
|
94
|
+
req.destroy();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
let value;
|
|
99
|
+
try {
|
|
100
|
+
value = JSON.parse(body || "{}");
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
send(res, 400, "fixture_scenario_invalid");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
107
|
+
Object.keys(value).some(key => action !== "seed" || key !== "scenario") ||
|
|
108
|
+
(action === "seed" && !(typeof value.scenario === "string" && options.scenarios.includes(value.scenario)))) {
|
|
109
|
+
send(res, 400, "fixture_scenario_invalid");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (controller.signal.aborted)
|
|
113
|
+
return;
|
|
114
|
+
started = true;
|
|
115
|
+
await options.mutate(action, value.scenario, { ...context, signal: controller.signal });
|
|
116
|
+
if (performance.now() >= deadline) {
|
|
117
|
+
uncertain = true;
|
|
118
|
+
controller.abort();
|
|
119
|
+
send(res, 504, "fixture_completion_unknown");
|
|
120
|
+
}
|
|
121
|
+
else if (!controller.signal.aborted)
|
|
122
|
+
send(res, 200, "fixture_ready");
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// A rejected adapter may have committed a write. Never replay it.
|
|
126
|
+
uncertain = started;
|
|
127
|
+
send(res, 503, started ? "fixture_completion_unknown" : "fixture_request_failed");
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
lifetime.signal.removeEventListener("abort", abort);
|
|
132
|
+
release();
|
|
133
|
+
pending = undefined;
|
|
134
|
+
}
|
|
135
|
+
})().catch(() => send(res, 500, "fixture_runtime_error"));
|
|
136
|
+
});
|
|
137
|
+
server.requestTimeout = budget;
|
|
138
|
+
server.headersTimeout = budget;
|
|
139
|
+
const remove = () => node_fs_1.promises.rm(root, { recursive: true, force: true });
|
|
140
|
+
try {
|
|
141
|
+
await node_fs_1.promises.mkdir(databaseDir, { mode: 0o700 });
|
|
142
|
+
await node_fs_1.promises.writeFile(node_path_1.default.join(root, "owner.json"), JSON.stringify({ namespace, workerId: options.workerId, pid: process.pid }));
|
|
143
|
+
await new Promise((resolve, reject) => {
|
|
144
|
+
server.once("error", reject);
|
|
145
|
+
server.listen(0, "127.0.0.1", () => { server.removeListener("error", reject); resolve(); });
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
server.close();
|
|
150
|
+
await remove();
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
const url = `http://127.0.0.1:${server.address().port}`;
|
|
154
|
+
const mutate = async (action, scenario) => {
|
|
155
|
+
const response = await fetch(`${url}/__qa/${namespace}/${action}`, { method: "POST",
|
|
156
|
+
headers: { "x-navarch-fixture-token": token, "content-type": "application/json" },
|
|
157
|
+
body: JSON.stringify(scenario === undefined ? {} : { scenario }), signal: AbortSignal.timeout(budget + 1000) });
|
|
158
|
+
const result = await response.json();
|
|
159
|
+
if (!response.ok)
|
|
160
|
+
throw new QaFixtureError(result.reason);
|
|
161
|
+
};
|
|
162
|
+
let closing;
|
|
163
|
+
return { namespace, databaseDir, url, token,
|
|
164
|
+
seed: (scenario) => mutate("seed", scenario), reset: () => mutate("reset"),
|
|
165
|
+
close: () => closing ??= (async () => {
|
|
166
|
+
closed = true;
|
|
167
|
+
lifetime.abort();
|
|
168
|
+
server.closeAllConnections();
|
|
169
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
170
|
+
// A timed-out adapter can still be writing. Retain its directory until it
|
|
171
|
+
// settles, even if it ignores abort. Never delete data beneath a writer.
|
|
172
|
+
const active = [...handlers, ...(pending ? [pending] : [])];
|
|
173
|
+
if (active.length)
|
|
174
|
+
void Promise.allSettled(active).then(remove).catch(() => { });
|
|
175
|
+
else
|
|
176
|
+
await remove();
|
|
177
|
+
})(),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.QA_CONFIG_LOADER = exports.qaCaseGrep = void 0;
|
|
4
|
+
exports.parseQaReport = parseQaReport;
|
|
5
|
+
exports.runnerCommandScript = runnerCommandScript;
|
|
6
|
+
/** Aggregate every matching test/project: one failed viewport fails the case. */
|
|
7
|
+
function parseQaReport(raw, assignment, missingReason = "automation_missing", missingClass = "setup", sanitize = text => text) {
|
|
8
|
+
if (!raw || typeof raw !== "object" || !Array.isArray(raw.suites))
|
|
9
|
+
throw new Error("Invalid Playwright JSON report");
|
|
10
|
+
const globalErrors = raw.errors ?? [];
|
|
11
|
+
const found = new Map();
|
|
12
|
+
const selected = new Set(assignment.items.map(item => item.case_id));
|
|
13
|
+
const walk = (suite, parents) => {
|
|
14
|
+
const titles = [...parents, suite.title ?? ""];
|
|
15
|
+
for (const spec of suite.specs ?? []) {
|
|
16
|
+
for (const test of spec.tests ?? []) {
|
|
17
|
+
const text = [...titles, spec.title ?? "", ...(spec.tags ?? []).map(tag => tag.startsWith("@") ? tag : `@${tag}`), ...(test.tags ?? []).map(tag => tag.startsWith("@") ? tag : `@${tag}`)].join(" ");
|
|
18
|
+
const ids = new Set([...text.matchAll(/@TC-[A-Z0-9]+(?:-[A-Z0-9]+)*(?:#[1-9][0-9]*)?(?![A-Za-z0-9_#-])/g)].map(match => match[0].slice(1)));
|
|
19
|
+
const attempts = test.results ?? [];
|
|
20
|
+
const last = attempts.at(-1);
|
|
21
|
+
// Expected failures are still product failures for case reporting.
|
|
22
|
+
const status = last?.status === "passed" ? "passed" : last?.status === "skipped" ? "skipped" : last?.status === "interrupted" && missingReason === "runner_timeout" ? "blocked" : "failed";
|
|
23
|
+
const annotatedClass = test.annotations?.find(a => a.type === "navarch:failure_class")?.description;
|
|
24
|
+
const failures = attempts.filter(result => ["failed", "timedOut", "interrupted"].includes(result.status ?? "")).map(result => ({
|
|
25
|
+
retry: Math.min(32767, Math.max(0, result.retry ?? 0)),
|
|
26
|
+
failure_class: (result.status !== "failed" ? "runtime" : ["setup", "resource", "runtime", "product_assertion"].includes(annotatedClass ?? "") ? annotatedClass : "product_assertion"),
|
|
27
|
+
summary: sanitize(result.error?.message?.trim() || `Playwright: ${result.status}`).slice(0, 2000),
|
|
28
|
+
}));
|
|
29
|
+
for (const id of ids) {
|
|
30
|
+
if (!selected.has(id) || !last)
|
|
31
|
+
continue;
|
|
32
|
+
const rows = found.get(id) ?? [];
|
|
33
|
+
rows.push({ run_id: assignment.run.id, case_id: id, attempt: 1, status,
|
|
34
|
+
flaky: status === "passed" && ((last.retry ?? 0) > 0 || attempts.some(result => ["failed", "timedOut", "interrupted"].includes(result.status ?? ""))),
|
|
35
|
+
duration_ms: Math.min(2147483647, attempts.reduce((sum, result) => sum + Math.max(0, result.duration ?? 0), 0)),
|
|
36
|
+
...(["failed", "blocked"].includes(status) ? { failure_summary: status === "blocked" ? missingReason : sanitize(last.error?.message?.trim() || `Playwright: ${last.status ?? "unknown"}`).slice(0, 8000) } : {}),
|
|
37
|
+
...(failures.length ? { failure_class: failures[0].failure_class, failure_attempts: failures.slice(0, 50), failure_attempts_truncated: failures.length > 50 } : {}),
|
|
38
|
+
traces: attempts.flatMap(result => (result.attachments ?? []).filter(a => a.name === "trace" && a.path).map(a => a.path)),
|
|
39
|
+
});
|
|
40
|
+
found.set(id, rows);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
for (const child of suite.suites ?? [])
|
|
45
|
+
walk(child, titles);
|
|
46
|
+
};
|
|
47
|
+
walk(raw, []);
|
|
48
|
+
return assignment.items.filter(item => ["queued", "running"].includes(item.status)).map(item => {
|
|
49
|
+
const rows = found.get(item.case_id) ?? [];
|
|
50
|
+
const failed = rows.find(row => row.status === "failed");
|
|
51
|
+
const blocked = rows.find(row => row.status === "blocked");
|
|
52
|
+
const skipped = rows.some(row => row.status === "skipped");
|
|
53
|
+
const failures = rows.flatMap(row => row.failure_attempts ?? []);
|
|
54
|
+
const result = { run_id: assignment.run.id, case_id: item.case_id, attempt: item.attempt ?? 1,
|
|
55
|
+
status: failed ? "failed" : blocked ? "blocked" : skipped ? "skipped" : rows.length ? "passed" : "blocked",
|
|
56
|
+
flaky: rows.some(row => row.flaky), duration_ms: Math.min(2147483647, rows.reduce((sum, row) => sum + (row.duration_ms ?? 0), 0)),
|
|
57
|
+
...(!rows.length ? { failure_summary: missingReason } : failed || blocked ? { failure_summary: (failed ?? blocked).failure_summary } : {}),
|
|
58
|
+
...(!rows.length ? { failure_class: missingClass } : failures.length ? {
|
|
59
|
+
failure_class: (failed ?? blocked)?.failure_class ?? failures[0].failure_class,
|
|
60
|
+
failure_attempts: failures.slice(0, 50), failure_attempts_truncated: failures.length > 50 || rows.some(row => row.failure_attempts_truncated),
|
|
61
|
+
} : {}),
|
|
62
|
+
traces: [...new Set(rows.flatMap(row => row.traces))], };
|
|
63
|
+
if (globalErrors.length) {
|
|
64
|
+
const failure_class = found.size ? "runtime" : missingClass;
|
|
65
|
+
const diagnostics = globalErrors.slice(0, 50).map(error => ({ retry: 0, failure_class,
|
|
66
|
+
summary: sanitize(error.message?.trim() || "Playwright global error").slice(0, 2000) }));
|
|
67
|
+
if (result.status !== "failed") {
|
|
68
|
+
result.status = "blocked";
|
|
69
|
+
result.failure_class = failure_class;
|
|
70
|
+
result.failure_summary = diagnostics[0].summary;
|
|
71
|
+
}
|
|
72
|
+
result.failure_attempts_truncated ||= (result.failure_attempts?.length ?? 0) + globalErrors.length > 50;
|
|
73
|
+
result.failure_attempts = [...result.failure_attempts ?? [], ...diagnostics].slice(0, 50);
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const qaCaseGrep = (ids) => `@(?:${ids.map(id => id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})(?![A-Za-z0-9_#-])`;
|
|
79
|
+
exports.qaCaseGrep = qaCaseGrep;
|
|
80
|
+
/** Forward explicit positional args, or append them to a final simple CLI.
|
|
81
|
+
* Reject ambiguous shell syntax before executing an unfiltered suite. */
|
|
82
|
+
function runnerCommandScript(run) {
|
|
83
|
+
let body = run.trimEnd();
|
|
84
|
+
let last = body.split("\n").at(-1) ?? "";
|
|
85
|
+
// npm consumes unknown options before its separator instead of forwarding
|
|
86
|
+
// Playwright's selection, reporter and retry flags to the actual test CLI.
|
|
87
|
+
if (/^\s*npm\s+(?:run|run-script|test|t)\b/.test(last) && !/\s--(?:\s|$)/.test(last)) {
|
|
88
|
+
last = /"\$(?:@|\{@\})"$/.test(last)
|
|
89
|
+
? last.replace(/"\$(?:@|\{@\})"$/, '-- "$@"') : `${last} --`;
|
|
90
|
+
body = [...body.split("\n").slice(0, -1), last].join("\n");
|
|
91
|
+
}
|
|
92
|
+
if (!last.includes("#") && /"\$(?:@|\{@\})"$/.test(last))
|
|
93
|
+
return body;
|
|
94
|
+
if (!last.trim() || /[#;{}|&<>`]/.test(last) || /^\s*(?:if|then|else|fi|do|done|esac|case|for|while|until)\b/.test(last)) {
|
|
95
|
+
throw new Error('Runner command must end in a simple CLI invocation or forward "$@" explicitly');
|
|
96
|
+
}
|
|
97
|
+
return `${body} "$@"`;
|
|
98
|
+
}
|
|
99
|
+
/** Use Playwright's require hook for CommonJS TypeScript on Node 20. An ESM
|
|
100
|
+
* import of that file bypasses the hook on older supported Node versions. */
|
|
101
|
+
exports.QA_CONFIG_LOADER = String.raw `import { existsSync, readFileSync } from 'node:fs';
|
|
102
|
+
import { createRequire } from 'node:module';
|
|
103
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
104
|
+
const root = fileURLToPath(new URL('.', import.meta.url));
|
|
105
|
+
const original = ['ts','js','mts','mjs','cts','cjs'].map(ext => root + 'playwright.config.' + ext).find(existsSync);
|
|
106
|
+
const packageType = existsSync(root + 'package.json') ? JSON.parse(readFileSync(root + 'package.json', 'utf8')).type : undefined;
|
|
107
|
+
const commonjs = original && (/\.(cts|cjs)$/.test(original) || (!/\.(mts|mjs)$/.test(original) && packageType !== 'module'));
|
|
108
|
+
const imported = original ? (commonjs ? createRequire(import.meta.url)(original) : await import(pathToFileURL(original).href)) : {};
|
|
109
|
+
const base = imported.default?.default ?? imported.default ?? imported;
|
|
110
|
+
`;
|
package/dist/qa-runner.cjs
CHANGED
|
@@ -3,10 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.qaCaseGrep = void 0;
|
|
6
|
+
exports.runnerCommandScript = exports.qaCaseGrep = void 0;
|
|
7
7
|
exports.parseQaReport = parseQaReport;
|
|
8
8
|
exports.qaSelectionArgs = qaSelectionArgs;
|
|
9
|
-
exports.runnerCommandScript = runnerCommandScript;
|
|
10
9
|
exports.executeQaRunner = executeQaRunner;
|
|
11
10
|
const node_fs_1 = require("node:fs");
|
|
12
11
|
const node_path_1 = __importDefault(require("node:path"));
|
|
@@ -15,89 +14,29 @@ const sandbox_cjs_1 = require("./sandbox.cjs");
|
|
|
15
14
|
const playwright_server_cjs_1 = require("./playwright-server.cjs");
|
|
16
15
|
const lease_heartbeat_cjs_1 = require("./lease-heartbeat.cjs");
|
|
17
16
|
const api_cjs_1 = require("./api.cjs");
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
for (const spec of suite.specs ?? []) {
|
|
27
|
-
for (const test of spec.tests ?? []) {
|
|
28
|
-
const text = [...titles, spec.title ?? "", ...(spec.tags ?? []), ...(test.tags ?? [])].join(" ");
|
|
29
|
-
const ids = new Set([...text.matchAll(/@TC-[A-Z0-9]+(?:-[A-Z0-9]+)*(?:#[1-9][0-9]*)?(?![A-Za-z0-9_#-])/g)].map(match => match[0].slice(1)));
|
|
30
|
-
const attempts = test.results ?? [];
|
|
31
|
-
const last = attempts.at(-1);
|
|
32
|
-
// Expected failures are still product failures for case reporting.
|
|
33
|
-
const status = last?.status === "passed" ? "passed" : last?.status === "skipped" ? "skipped" : last?.status === "interrupted" && missingReason === "runner_timeout" ? "blocked" : "failed";
|
|
34
|
-
for (const id of ids) {
|
|
35
|
-
if (!selected.has(id) || !last)
|
|
36
|
-
continue;
|
|
37
|
-
const rows = found.get(id) ?? [];
|
|
38
|
-
rows.push({ run_id: assignment.run.id, case_id: id, attempt: 1, status,
|
|
39
|
-
flaky: status === "passed" && ((last.retry ?? 0) > 0 || attempts.some(result => ["failed", "timedOut", "interrupted"].includes(result.status ?? ""))),
|
|
40
|
-
duration_ms: Math.min(2147483647, attempts.reduce((sum, result) => sum + Math.max(0, result.duration ?? 0), 0)),
|
|
41
|
-
...(["failed", "blocked"].includes(status) ? { failure_summary: status === "blocked" ? missingReason : (last.error?.message ?? `Playwright: ${last.status ?? "unknown"}`).slice(0, 8000) } : {}),
|
|
42
|
-
traces: attempts.flatMap(result => (result.attachments ?? []).filter(a => a.name === "trace" && a.path).map(a => a.path)),
|
|
43
|
-
});
|
|
44
|
-
found.set(id, rows);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
for (const child of suite.suites ?? [])
|
|
49
|
-
walk(child, titles);
|
|
50
|
-
};
|
|
51
|
-
walk(raw, []);
|
|
52
|
-
return assignment.items.filter(item => ["queued", "running"].includes(item.status)).map(item => {
|
|
53
|
-
const rows = found.get(item.case_id) ?? [];
|
|
54
|
-
const failed = rows.find(row => row.status === "failed");
|
|
55
|
-
const blocked = rows.find(row => row.status === "blocked");
|
|
56
|
-
const skipped = rows.some(row => row.status === "skipped");
|
|
57
|
-
return { run_id: assignment.run.id, case_id: item.case_id, attempt: item.attempt ?? 1,
|
|
58
|
-
status: failed ? "failed" : blocked ? "blocked" : skipped ? "skipped" : rows.length ? "passed" : "blocked",
|
|
59
|
-
flaky: rows.some(row => row.flaky), duration_ms: Math.min(2147483647, rows.reduce((sum, row) => sum + (row.duration_ms ?? 0), 0)),
|
|
60
|
-
...(!rows.length ? { failure_summary: missingReason } : failed || blocked ? { failure_summary: (failed ?? blocked).failure_summary } : {}),
|
|
61
|
-
traces: [...new Set(rows.flatMap(row => row.traces))], };
|
|
62
|
-
});
|
|
17
|
+
const redact_cjs_1 = require("./redact.cjs");
|
|
18
|
+
// Keep BYO redaction at the boundary while both executors share report semantics.
|
|
19
|
+
const qa_report_js_1 = require("./qa-report.js");
|
|
20
|
+
var qa_report_js_2 = require("./qa-report.js");
|
|
21
|
+
Object.defineProperty(exports, "qaCaseGrep", { enumerable: true, get: function () { return qa_report_js_2.qaCaseGrep; } });
|
|
22
|
+
Object.defineProperty(exports, "runnerCommandScript", { enumerable: true, get: function () { return qa_report_js_2.runnerCommandScript; } });
|
|
23
|
+
function parseQaReport(raw, assignment, missingReason = "automation_missing", missingClass = "setup", sanitize = redact_cjs_1.redactText) {
|
|
24
|
+
return (0, qa_report_js_1.parseQaReport)(raw, assignment, missingReason, missingClass, sanitize);
|
|
63
25
|
}
|
|
64
|
-
const qaCaseGrep = (ids) => `@(?:${ids.map(id => id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})(?![A-Za-z0-9_#-])`;
|
|
65
|
-
exports.qaCaseGrep = qaCaseGrep;
|
|
66
26
|
/** Long selections live in config, never in argv or one oversized env value. */
|
|
67
27
|
async function qaSelectionArgs(repo, workDir, ids) {
|
|
68
|
-
const grep = (0,
|
|
28
|
+
const grep = (0, qa_report_js_1.qaCaseGrep)(ids);
|
|
69
29
|
if (Buffer.byteLength(grep) < 16_000)
|
|
70
30
|
return ["--grep", grep];
|
|
71
31
|
const selection = node_path_1.default.join(workDir, "qa-selection.txt");
|
|
72
32
|
const config = node_path_1.default.join(repo, ".navarch-qa-playwright.config.mts");
|
|
73
33
|
await node_fs_1.promises.writeFile(selection, grep);
|
|
74
|
-
|
|
75
|
-
for (const ext of ["ts", "js", "mts", "mjs", "cts", "cjs"]) {
|
|
76
|
-
const candidate = node_path_1.default.join(repo, `playwright.config.${ext}`);
|
|
77
|
-
if (await node_fs_1.promises.stat(candidate).then(s => s.isFile(), () => false)) {
|
|
78
|
-
original = candidate;
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
await node_fs_1.promises.writeFile(config, `${original ? `import base from ${JSON.stringify(original)};` : "const base = {};"}
|
|
83
|
-
import { readFileSync } from 'node:fs';
|
|
34
|
+
await node_fs_1.promises.writeFile(config, `${qa_report_js_1.QA_CONFIG_LOADER}
|
|
84
35
|
const grep = new RegExp(readFileSync(${JSON.stringify(selection)}, 'utf8'));
|
|
85
36
|
export default { ...base, grep, ...(base.projects ? { projects: base.projects.map(project => ({ ...project, grep })) } : {}) };
|
|
86
37
|
`);
|
|
87
38
|
return ["--config", config];
|
|
88
39
|
}
|
|
89
|
-
/** Forward explicit positional args, or append them to a final simple CLI.
|
|
90
|
-
* Reject ambiguous shell syntax before executing an unfiltered suite. */
|
|
91
|
-
function runnerCommandScript(run) {
|
|
92
|
-
const body = run.trimEnd();
|
|
93
|
-
const last = body.split("\n").at(-1) ?? "";
|
|
94
|
-
if (!last.includes("#") && /"\$(?:@|\{@\})"$/.test(last))
|
|
95
|
-
return body;
|
|
96
|
-
if (!last.trim() || /[#;{}|&<>`]/.test(last) || /^\s*(?:if|then|else|fi|do|done|esac|case|for|while|until)\b/.test(last)) {
|
|
97
|
-
throw new Error('Runner command must end in a simple CLI invocation or forward "$@" explicitly');
|
|
98
|
-
}
|
|
99
|
-
return `${body} "$@"`;
|
|
100
|
-
}
|
|
101
40
|
/** Repository commands receive recipe variables and their declared secrets only. */
|
|
102
41
|
function baseEnvironment() {
|
|
103
42
|
return Object.fromEntries(["PATH", "HOME", "TMPDIR", "TEMP", "TMP", "SystemRoot", "LANG"].flatMap(key => process.env[key] === undefined ? [] : [[key, process.env[key]]]));
|
|
@@ -142,6 +81,10 @@ async function executeQaRunner(deps) {
|
|
|
142
81
|
const htmlDir = node_path_1.default.join(workDir, "playwright-report");
|
|
143
82
|
const traceDir = node_path_1.default.join(workDir, "test-results");
|
|
144
83
|
let report = { suites: [] }, failure;
|
|
84
|
+
let phase = "setup";
|
|
85
|
+
let exitCode;
|
|
86
|
+
let attempted = false;
|
|
87
|
+
const secrets = [];
|
|
145
88
|
const run = async (bin, args, env, timeoutMs) => {
|
|
146
89
|
controller.signal.throwIfAborted();
|
|
147
90
|
const result = await runner.run(bin, args, { cwd: repo, env, timeoutMs, signal: controller.signal });
|
|
@@ -157,7 +100,7 @@ async function executeQaRunner(deps) {
|
|
|
157
100
|
if (!recipe || !commandName || !/^[a-z][a-z0-9_-]{0,31}$/.test(commandName) || !recipe.commands[commandName])
|
|
158
101
|
throw new Error("Runner requires a recipe e2e command");
|
|
159
102
|
const command = recipe.commands[commandName];
|
|
160
|
-
const commandScript = runnerCommandScript(command.run);
|
|
103
|
+
const commandScript = (0, qa_report_js_1.runnerCommandScript)(command.run);
|
|
161
104
|
const entryEnv = async (names) => {
|
|
162
105
|
const env = { ...baseEnvironment(), ...recipe.env.vars };
|
|
163
106
|
if (names.length) {
|
|
@@ -166,6 +109,7 @@ async function executeQaRunner(deps) {
|
|
|
166
109
|
const value = issued.secrets[name];
|
|
167
110
|
if (typeof value !== "string")
|
|
168
111
|
throw new Error("Runner recipe secret unavailable");
|
|
112
|
+
secrets.push(value);
|
|
169
113
|
const converted = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name) ? name : name.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
|
|
170
114
|
env[/^[0-9]/.test(converted) ? `_${converted}` : converted] = value;
|
|
171
115
|
}
|
|
@@ -184,6 +128,7 @@ async function executeQaRunner(deps) {
|
|
|
184
128
|
PLAYWRIGHT_JSON_OUTPUT_NAME: jsonFile, PLAYWRIGHT_HTML_OUTPUT_DIR: htmlDir, PLAYWRIGHT_HTML_OPEN: "never" };
|
|
185
129
|
// The runtime is outside the agent sandbox. On macOS the existing server
|
|
186
130
|
// gives loopback fixtures the same restricted browser used by agent suites.
|
|
131
|
+
phase = "resource";
|
|
187
132
|
if (process.platform === "darwin" && ["localhost", "127.0.0.1", "[::1]"].includes(new URL(assignment.target.url).hostname)) {
|
|
188
133
|
env.PW_TEST_CONNECT_WS_ENDPOINT = (await server.start({})).endpoint;
|
|
189
134
|
}
|
|
@@ -192,34 +137,65 @@ async function executeQaRunner(deps) {
|
|
|
192
137
|
const selection = await qaSelectionArgs(repo, workDir, assignment.items.filter(i => ["queued", "running"].includes(i.status)).map(i => i.case_id));
|
|
193
138
|
const executable = node_path_1.default.join(workDir, "navarch-run");
|
|
194
139
|
await node_fs_1.promises.writeFile(executable, `#!/bin/sh\nset -eu\n[ "$1" = ${JSON.stringify(commandName)} ] || exit 64\nshift\n[ "${"${1:-}"}" != -- ] || shift\n${commandScript}\n`, { mode: 0o700 });
|
|
195
|
-
|
|
140
|
+
phase = "runtime";
|
|
141
|
+
await node_fs_1.promises.rm(jsonFile, { force: true });
|
|
142
|
+
attempted = true;
|
|
143
|
+
exitCode = (await run(executable, [commandName, "--", ...selection, "--reporter=json,html", "--retries=1", "--trace=retain-on-failure", "--output", traceDir], env, command.timeout_s * 1000)).code;
|
|
196
144
|
}
|
|
197
|
-
catch {
|
|
145
|
+
catch (error) {
|
|
146
|
+
// Classify typed resource failures; do not infer a lock or timeout from prose.
|
|
147
|
+
const detail = error;
|
|
148
|
+
if (detail && (detail.failure_class === "resource" || ["EADDRINUSE", "ENOSPC", "EMFILE", "EAGAIN", "SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT"].includes(detail.code ?? "")))
|
|
149
|
+
phase = "resource";
|
|
198
150
|
failure = timedOut ? "runner_timeout" : "runner_error";
|
|
199
151
|
}
|
|
200
152
|
if (leaseLost)
|
|
201
153
|
return;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
154
|
+
if (attempted) {
|
|
155
|
+
try {
|
|
156
|
+
report = JSON.parse(await node_fs_1.promises.readFile(jsonFile, "utf8"));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
if (!timedOut)
|
|
160
|
+
failure ??= "runner_error";
|
|
161
|
+
}
|
|
208
162
|
}
|
|
209
163
|
let results;
|
|
210
164
|
try {
|
|
211
|
-
results = parseQaReport(report, assignment, timedOut ? "runner_timeout" : failure ?? "automation_missing");
|
|
165
|
+
results = parseQaReport(report, assignment, timedOut ? "runner_timeout" : failure ?? "automation_missing", timedOut ? "runtime" : failure ? phase : "setup", message => (0, redact_cjs_1.redactText)(message, secrets));
|
|
212
166
|
}
|
|
213
167
|
catch {
|
|
214
|
-
results = parseQaReport({ suites: [] }, assignment, timedOut ? "runner_timeout" : "runner_error");
|
|
168
|
+
results = parseQaReport({ suites: [] }, assignment, timedOut ? "runner_timeout" : "runner_error", "runtime");
|
|
169
|
+
}
|
|
170
|
+
const executionFailure = attempted && failure ? failure : exitCode !== undefined && exitCode !== 0 && !results.some(result => result.status === "failed") ? `Runner exited with code ${exitCode}` : undefined;
|
|
171
|
+
if (executionFailure && !report?.errors?.length) {
|
|
172
|
+
// A nonzero exit with no failed case is a runtime failure, even if every
|
|
173
|
+
// spec passed before a reporter or global teardown failed.
|
|
174
|
+
results = parseQaReport({ suites: Array.isArray(report?.suites) ? report.suites : [], errors: [{ message: executionFailure }] }, assignment, "runner_error", "runtime", message => (0, redact_cjs_1.redactText)(message, secrets));
|
|
175
|
+
}
|
|
176
|
+
// Summaries also use the parser sanitizer before applying size limits.
|
|
177
|
+
for (const result of results) {
|
|
178
|
+
if (result.failure_summary)
|
|
179
|
+
result.failure_summary = (0, redact_cjs_1.redactText)(result.failure_summary, secrets);
|
|
180
|
+
for (const attempt of result.failure_attempts ?? [])
|
|
181
|
+
attempt.summary = (0, redact_cjs_1.redactText)(attempt.summary, secrets);
|
|
215
182
|
}
|
|
216
183
|
const evidenceUrls = [];
|
|
184
|
+
const artifactRoots = async () => {
|
|
185
|
+
await node_fs_1.promises.mkdir(htmlDir, { recursive: true });
|
|
186
|
+
await node_fs_1.promises.mkdir(traceDir, { recursive: true });
|
|
187
|
+
const workspace = await node_fs_1.promises.realpath(workDir);
|
|
188
|
+
const roots = await Promise.all([htmlDir, traceDir].map(dir => node_fs_1.promises.realpath(dir)));
|
|
189
|
+
if (roots.some(root => !root.startsWith(workspace + node_path_1.default.sep)))
|
|
190
|
+
throw new Error("Artifact root outside runner workspace");
|
|
191
|
+
return roots;
|
|
192
|
+
};
|
|
217
193
|
const upload = async (file, mime) => {
|
|
218
194
|
if (leaseLost)
|
|
219
195
|
throw new Error("Runner lease lost");
|
|
220
196
|
const resolved = await node_fs_1.promises.realpath(file);
|
|
221
197
|
// Reports may contain arbitrary attachment paths; never upload host files.
|
|
222
|
-
const roots = await
|
|
198
|
+
const roots = await artifactRoots();
|
|
223
199
|
if (!roots.some(root => resolved.startsWith(root + node_path_1.default.sep)))
|
|
224
200
|
throw new Error("Artifact outside runner workspace");
|
|
225
201
|
const stat = await node_fs_1.promises.stat(resolved);
|
|
@@ -243,10 +219,22 @@ async function executeQaRunner(deps) {
|
|
|
243
219
|
return final.artifact_id;
|
|
244
220
|
};
|
|
245
221
|
let htmlId;
|
|
222
|
+
const diagnosticFile = node_path_1.default.join(htmlDir, `runner-diagnostics-${(0, node_crypto_1.randomUUID)()}.json`);
|
|
246
223
|
for (const result of results) {
|
|
247
|
-
if (result.status !== "failed")
|
|
224
|
+
if (result.status !== "failed" && !result.failure_attempts?.length)
|
|
248
225
|
continue;
|
|
249
|
-
|
|
226
|
+
if (!htmlId) {
|
|
227
|
+
const html = node_path_1.default.join(htmlDir, "index.html");
|
|
228
|
+
if (await node_fs_1.promises.stat(html).then(stat => stat.isFile(), () => false))
|
|
229
|
+
htmlId = await upload(html, "text/html");
|
|
230
|
+
else {
|
|
231
|
+
// Setup/report failures can have no HTML or traces. Persist safe
|
|
232
|
+
// diagnostics without inventing a product screenshot or test pass.
|
|
233
|
+
await artifactRoots();
|
|
234
|
+
await node_fs_1.promises.writeFile(diagnosticFile, JSON.stringify(results.map(({ traces: _traces, ...item }) => item)), { flag: "wx", mode: 0o600 });
|
|
235
|
+
htmlId = await upload(diagnosticFile, "text/plain");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
250
238
|
result.artifact_ids = [htmlId];
|
|
251
239
|
for (const trace of result.traces.slice(0, 49))
|
|
252
240
|
result.artifact_ids.push(await upload(node_path_1.default.resolve(repo, trace), "application/zip"));
|
|
@@ -260,7 +248,7 @@ async function executeQaRunner(deps) {
|
|
|
260
248
|
}
|
|
261
249
|
if (leaseLost)
|
|
262
250
|
return;
|
|
263
|
-
await api.completeLease(leaseId, { status: "completed", report: `QA runner (${assignment.target.commit_sha}):\n${results.map(item => `${item.case_id}: ${item.status}${item.flaky ? " (flaky)" : ""}${item.failure_summary ? ` — ${item.failure_summary}` : ""}`).join("\n")}`,
|
|
251
|
+
await api.completeLease(leaseId, { status: "completed", report: `QA runner (${assignment.target.commit_sha}):\n${results.map(item => `${item.case_id}: ${item.status}${item.failure_class ? ` [${item.failure_class}]` : ""}${item.flaky ? " (flaky)" : ""}${item.failure_summary ? ` — ${item.failure_summary}` : item.failure_attempts?.length ? ` — first failure: ${item.failure_attempts[0].summary}` : ""}`).join("\n")}`,
|
|
264
252
|
evidence_urls: evidenceUrls, cost: { tokens_in: 0, tokens_out: 0, cost_usd: 0 }, exit_status: "completed", sandbox_profile: "host" });
|
|
265
253
|
}
|
|
266
254
|
finally {
|
package/dist/session.cjs
CHANGED
|
@@ -371,6 +371,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
|
|
|
371
371
|
: undefined,
|
|
372
372
|
// Hosted runs skip checkpoints for verify tasks, which deliver a verdict.
|
|
373
373
|
restoreHostedCheckpoint: !deliveryBinding && !allowBranchRename && task.task_type !== "verify",
|
|
374
|
+
...(claimed.delivery_baseline_required ? { hostedCheckpointLeaseId: leaseId } : {}),
|
|
374
375
|
...(commitIdentity ? { ownershipCommitIdentity: commitIdentity.committer } : {}),
|
|
375
376
|
});
|
|
376
377
|
credentialConsumer.worktree = gitWorktree;
|
|
@@ -762,9 +763,14 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
|
|
|
762
763
|
// after a restart, so a retry cannot relabel inherited commits as output.
|
|
763
764
|
if (claimed.delivery_baseline_required) {
|
|
764
765
|
const initialHead = await (0, delivery_cjs_1.captureDeliveryBaseline)(gitWorktree.worktreePath);
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
766
|
+
if (!/^[0-9a-f]{40}$/.test(initialHead))
|
|
767
|
+
throw new Error("Delivery baseline capture returned an invalid SHA");
|
|
768
|
+
const baseline = await api.heartbeatLease(leaseId, { delivery_baseline_sha: initialHead }).catch((error) => {
|
|
769
|
+
throw new Error(`Delivery baseline registration failed: ${String(error)}`);
|
|
770
|
+
});
|
|
771
|
+
if (typeof baseline.delivery_baseline_sha !== "string" || !/^[0-9a-f]{40}$/.test(baseline.delivery_baseline_sha)) {
|
|
772
|
+
throw new Error("The control plane did not persist a valid required delivery baseline acknowledgement");
|
|
773
|
+
}
|
|
768
774
|
deliveryBaselineSha = baseline.delivery_baseline_sha;
|
|
769
775
|
}
|
|
770
776
|
const { browserUse, playwrightSuites } = (0, browser_evidence_cjs_1.navarchBrowserTools)({
|
package/package.json
CHANGED