@superfunctions/reviewfn-cli 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/config.d.ts +14 -0
- package/dist/config.js +71 -0
- package/dist/execution.d.ts +10 -0
- package/dist/execution.js +123 -0
- package/dist/expected-cli.d.ts +11 -0
- package/dist/expected-cli.js +17 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +151 -0
- package/dist/panel.d.ts +145 -0
- package/dist/panel.js +404 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 21n
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @superfunctions/reviewfn-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Installs the `reviewfn` binary. Commands: `init` (`--panel` writes a panel policy template), `preflight`, `review`, `panel`, `report` (`--panel` re-renders a stored panel report), `publish`, `render`, and `evaluate`. See [panel review](../docs/panel.md) for `reviewfn panel` and its exit codes. The Codex harness adapter is a direct dependency; the `claude-code` and `cli` adapter packages are not published yet and will resolve once installed next to the CLI. Run from a Git worktree with Node.js 22 or newer.
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type PanelPolicy, type ReviewFnConfig, type ReviewPolicy } from "@superfunctions/reviewfn-core";
|
|
2
|
+
export declare function loadConfig(file: string): Promise<ReviewFnConfig>;
|
|
3
|
+
export declare function loadPolicy(file: string): Promise<ReviewPolicy>;
|
|
4
|
+
export declare function loadTrustedConfigFromBase(root: string, base: string, relative?: string): Promise<ReviewFnConfig>;
|
|
5
|
+
export declare function loadTrustedPolicyFromBase(root: string, base: string, relative?: string): Promise<ReviewPolicy>;
|
|
6
|
+
export declare function initializeConfiguration(root: string): Promise<string[]>;
|
|
7
|
+
/**
|
|
8
|
+
* The `reviewfn init --panel` template: one general stage-1 slot that also extracts requirements, and one general
|
|
9
|
+
* stage-2 slot, both on the Codex harness with the default inference. `harness.version` is the exact version the
|
|
10
|
+
* harness reports (`codex --version`) and must be updated to the installed Codex before a run can complete.
|
|
11
|
+
*/
|
|
12
|
+
export declare const PANEL_POLICY_TEMPLATE: PanelPolicy;
|
|
13
|
+
/** Write the panel policy template to `.reviewfn/panel.json`, refusing to overwrite an existing file. */
|
|
14
|
+
export declare function initializePanelPolicy(root: string): Promise<string>;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { safeDirectory, DEFAULT_CONFIG, DEFAULT_POLICY, PANEL_POLICY_PATH, parsePanelPolicy, validateConfig, validatePolicy } from "@superfunctions/reviewfn-core";
|
|
6
|
+
const execFileAsync = promisify(execFile);
|
|
7
|
+
export async function loadConfig(file) {
|
|
8
|
+
return validateConfig(JSON.parse(await readFile(file, "utf8")));
|
|
9
|
+
}
|
|
10
|
+
export async function loadPolicy(file) {
|
|
11
|
+
return validatePolicy(JSON.parse(await readFile(file, "utf8")));
|
|
12
|
+
}
|
|
13
|
+
export async function loadTrustedConfigFromBase(root, base, relative = ".reviewfn/config.json") {
|
|
14
|
+
if (relative.startsWith("/") || relative.split(/[\\/]/).includes(".."))
|
|
15
|
+
throw new Error("Trusted configuration path must be repository-relative.");
|
|
16
|
+
const commit = (await execFileAsync("git", ["rev-parse", "--verify", "--end-of-options", `${base}^{commit}`], { cwd: root })).stdout.trim();
|
|
17
|
+
const { stdout } = await execFileAsync("git", ["show", `${commit}:${relative}`], { cwd: root, maxBuffer: 5_000_000 });
|
|
18
|
+
return validateConfig(JSON.parse(stdout));
|
|
19
|
+
}
|
|
20
|
+
export async function loadTrustedPolicyFromBase(root, base, relative = ".reviewfn/policy.json") {
|
|
21
|
+
if (relative.startsWith("/") || relative.split(/[\\/]/).includes(".."))
|
|
22
|
+
throw new Error("Trusted policy path must be repository-relative.");
|
|
23
|
+
const commit = (await execFileAsync("git", ["rev-parse", "--verify", "--end-of-options", `${base}^{commit}`], { cwd: root })).stdout.trim();
|
|
24
|
+
const { stdout } = await execFileAsync("git", ["show", `${commit}:${relative}`], { cwd: root, maxBuffer: 5_000_000 });
|
|
25
|
+
return validatePolicy(JSON.parse(stdout));
|
|
26
|
+
}
|
|
27
|
+
async function refuseExisting(root, files) {
|
|
28
|
+
for (const file of files) {
|
|
29
|
+
try {
|
|
30
|
+
await readFile(file);
|
|
31
|
+
throw new Error(`Refusing to overwrite ${path.relative(root, file)}.`);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "ENOENT")
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function initializeConfiguration(root) {
|
|
40
|
+
const directory = path.join(root, ".reviewfn");
|
|
41
|
+
await safeDirectory(directory);
|
|
42
|
+
const files = [path.join(directory, "config.json"), path.join(directory, "policy.json")];
|
|
43
|
+
await refuseExisting(root, files);
|
|
44
|
+
await writeFile(files[0], `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
45
|
+
await writeFile(files[1], `${JSON.stringify(DEFAULT_POLICY, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
46
|
+
return files;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The `reviewfn init --panel` template: one general stage-1 slot that also extracts requirements, and one general
|
|
50
|
+
* stage-2 slot, both on the Codex harness with the default inference. `harness.version` is the exact version the
|
|
51
|
+
* harness reports (`codex --version`) and must be updated to the installed Codex before a run can complete.
|
|
52
|
+
*/
|
|
53
|
+
export const PANEL_POLICY_TEMPLATE = parsePanelPolicy({
|
|
54
|
+
version: 1,
|
|
55
|
+
slots: [
|
|
56
|
+
{ id: "codex-general", stage: 1, harness: { adapter: "codex", version: "codex-cli 0.154.0" }, inference: { ...DEFAULT_CONFIG.inference }, lens: "general", budget: { timeoutMs: 20 * 60_000, maxOutputBytes: 10_000_000 } },
|
|
57
|
+
{ id: "codex-second-pass", stage: 2, harness: { adapter: "codex", version: "codex-cli 0.154.0" }, inference: { ...DEFAULT_CONFIG.inference }, lens: "general", budget: { timeoutMs: 20 * 60_000, maxOutputBytes: 10_000_000 } },
|
|
58
|
+
],
|
|
59
|
+
quorum: { stage1: 1, stage2: 1 },
|
|
60
|
+
requirementsSlot: "codex-general",
|
|
61
|
+
maxConcurrentSlots: 2,
|
|
62
|
+
incremental: "full",
|
|
63
|
+
});
|
|
64
|
+
/** Write the panel policy template to `.reviewfn/panel.json`, refusing to overwrite an existing file. */
|
|
65
|
+
export async function initializePanelPolicy(root) {
|
|
66
|
+
await safeDirectory(path.join(root, ".reviewfn"));
|
|
67
|
+
const file = path.join(root, PANEL_POLICY_PATH);
|
|
68
|
+
await refuseExisting(root, [file]);
|
|
69
|
+
await writeFile(file, `${JSON.stringify(PANEL_POLICY_TEMPLATE, null, 2)}\n`, { flag: "wx", mode: 0o600 });
|
|
70
|
+
return file;
|
|
71
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type ArtifactStore, type ExecutionAdapter, type PreflightResult, type ReviewPolicy, type TestReceipt } from "@superfunctions/reviewfn-core";
|
|
2
|
+
export declare const TEST_IMAGE = "node:22-bookworm-slim@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5";
|
|
3
|
+
/** Docker is mandatory. No fallback to same-user host execution is permitted. */
|
|
4
|
+
export declare class LocalIsolatedExecutionAdapter implements ExecutionAdapter {
|
|
5
|
+
private readonly artifacts?;
|
|
6
|
+
readonly id = "local-isolated";
|
|
7
|
+
constructor(artifacts?: ArtifactStore | undefined);
|
|
8
|
+
preflight(root: string): Promise<PreflightResult>;
|
|
9
|
+
run(root: string, headCommit: string, commands: string[][], policy: ReviewPolicy, signal?: AbortSignal): Promise<TestReceipt[]>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { mkdtemp, rm, mkdir, writeFile, stat, chmod } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { isolatedGitEnvironment, sha256, redactText } from "@superfunctions/reviewfn-core";
|
|
7
|
+
// This image is resolved to a digest before executing any repository command.
|
|
8
|
+
export const TEST_IMAGE = "node:22-bookworm-slim@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5";
|
|
9
|
+
/** Docker is mandatory. No fallback to same-user host execution is permitted. */
|
|
10
|
+
export class LocalIsolatedExecutionAdapter {
|
|
11
|
+
artifacts;
|
|
12
|
+
id = "local-isolated";
|
|
13
|
+
constructor(artifacts) {
|
|
14
|
+
this.artifacts = artifacts;
|
|
15
|
+
}
|
|
16
|
+
async preflight(root) {
|
|
17
|
+
const diagnostics = [];
|
|
18
|
+
if (Number(process.versions.node.split(".")[0]) < 22)
|
|
19
|
+
diagnostics.push({ code: "REVIEWFN_NODE_VERSION", level: "error", message: "Node 22 or newer is required." });
|
|
20
|
+
for (const [command, args] of [["git", ["rev-parse", "--is-inside-work-tree"]], ["docker", ["info", "--format", "{{.ServerVersion}}"]], ["docker", ["image", "inspect", TEST_IMAGE, "--format", "{{.Id}}"]]]) {
|
|
21
|
+
const result = await runProcess(command, [...args], root, 10_000, 64_000).catch(() => undefined);
|
|
22
|
+
if (result?.exitCode !== 0)
|
|
23
|
+
diagnostics.push({ code: "REVIEWFN_ISOLATION_UNAVAILABLE", level: "error", message: `Required ${command} capability unavailable: ${args.join(" ")}. Install Docker and pull ${TEST_IMAGE} before review.` });
|
|
24
|
+
}
|
|
25
|
+
return { ok: !diagnostics.some(item => item.level === "error"), diagnostics };
|
|
26
|
+
}
|
|
27
|
+
async run(root, headCommit, commands, policy, signal) {
|
|
28
|
+
if (!commands.length || signal?.aborted)
|
|
29
|
+
return [];
|
|
30
|
+
if (!/^[a-f0-9]{40,64}$/i.test(headCommit))
|
|
31
|
+
throw new Error("Execution requires an immutable commit hash.");
|
|
32
|
+
const owned = await mkdtemp(path.join(tmpdir(), "reviewfn-execution-"));
|
|
33
|
+
const archive = path.join(owned, "source.tar");
|
|
34
|
+
const receipts = [];
|
|
35
|
+
try {
|
|
36
|
+
const inventory = await runProcess("git", ["ls-tree", "-r", "-l", headCommit], root, 30_000, 5_000_000, signal);
|
|
37
|
+
const totalSize = inventory.stdout.split("\n").reduce((sum, line) => sum + Number(line.match(/^\d+ blob [a-f0-9]+\s+(\d+)\t/)?.[1] ?? 0), 0);
|
|
38
|
+
if (inventory.exitCode !== 0 || inventory.outputLimited || totalSize > 256 * 1024 * 1024)
|
|
39
|
+
throw new Error("Repository archive exceeds the 256 MiB input budget.");
|
|
40
|
+
const archiveRepo = path.join(owned, "archive.git");
|
|
41
|
+
const cloned = await runProcess("git", ["clone", "--template=", "--bare", "--shared", "--", root, archiveRepo], root, 60_000, 64_000, signal);
|
|
42
|
+
if (cloned.exitCode !== 0)
|
|
43
|
+
throw new Error("Unable to prepare archive repository.");
|
|
44
|
+
await mkdir(path.join(archiveRepo, "info"), { recursive: true });
|
|
45
|
+
await writeFile(path.join(archiveRepo, "info", "attributes"), "* -export-ignore -export-subst\n");
|
|
46
|
+
const archived = await runProcess("git", ["--git-dir", archiveRepo, "archive", "--format=tar", `--output=${archive}`, headCommit], root, 60_000, 64_000, signal);
|
|
47
|
+
if (archived.exitCode !== 0 || archived.canceled)
|
|
48
|
+
throw new Error("Unable to archive reviewed commit.");
|
|
49
|
+
if ((await stat(archive)).size > 256 * 1024 * 1024)
|
|
50
|
+
throw new Error("Generated archive exceeds the 256 MiB input budget.");
|
|
51
|
+
await chmod(archive, 0o444);
|
|
52
|
+
const image = await runProcess("docker", ["image", "inspect", TEST_IMAGE, "--format", "{{.Id}}"], root, 10_000, 64_000, signal);
|
|
53
|
+
if (image.exitCode !== 0 || !/^sha256:[a-f0-9]{64}$/.test(image.stdout.trim()))
|
|
54
|
+
throw new Error("Required isolated test image is unavailable.");
|
|
55
|
+
const deadline = Date.now() + policy.limits.testTimeoutMs;
|
|
56
|
+
for (const [index, command] of commands.entries()) {
|
|
57
|
+
if (signal?.aborted)
|
|
58
|
+
break;
|
|
59
|
+
if (!command.length || command.some(part => !part || part.includes("\0")))
|
|
60
|
+
throw new Error(`Invalid command ${index}.`);
|
|
61
|
+
const name = `reviewfn-${sha256(path.resolve(root)).slice(0, 16)}-${randomUUID()}`;
|
|
62
|
+
const startedAt = new Date();
|
|
63
|
+
let result;
|
|
64
|
+
try {
|
|
65
|
+
result = await runProcess("docker", ["run", "--name", name, "--rm", "--network=none", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--pids-limit=128", "--memory=512m", "--memory-swap=512m", "--cpus=1", "--user=65534:65534", "--tmpfs=/workspace:rw,nosuid,nodev,size=268435456,mode=1777", "--tmpfs=/tmp:rw,nosuid,nodev,size=67108864,mode=1777", "--mount", `type=bind,source=${archive},target=/input/source.tar,readonly`, "--workdir=/workspace", image.stdout.trim(), "sh", "-c", 'tar --no-same-owner -xf /input/source.tar -C /workspace && exec "$@"', "reviewfn-test", ...command], root, Math.max(1, deadline - Date.now()), policy.limits.maxOutputBytes, signal);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
// Container teardown kills all descendants even after their parent exits or detaches.
|
|
69
|
+
await runProcess("docker", ["rm", "--force", name], root, 10_000, 64_000).catch(() => undefined);
|
|
70
|
+
}
|
|
71
|
+
const stdout = redactText(result.stdout, []);
|
|
72
|
+
const stderr = redactText(result.stderr, []);
|
|
73
|
+
const stdoutArtifact = await this.artifacts?.put("test-stdout", stdout, policy.retention.testLogDays);
|
|
74
|
+
const stderrArtifact = await this.artifacts?.put("test-stderr", stderr, policy.retention.testLogDays);
|
|
75
|
+
receipts.push({ stdoutArtifact: stdoutArtifact?.id, stderrArtifact: stderrArtifact?.id, id: `test-${index}-${sha256(JSON.stringify(command)).slice(0, 12)}`, command, cwd: ".", commit: headCommit, startedAt: startedAt.toISOString(), finishedAt: new Date().toISOString(), runtimeMs: result.runtimeMs, exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, canceled: result.canceled, stdoutDigest: sha256(stdout), stderrDigest: sha256(stderr), limitations: [`Docker image ${image.stdout.trim()}; network disabled; 1 CPU, 512 MiB memory, 128 PIDs, 256 MiB workspace, 64 MiB temporary disk.`, ...(result.outputLimited ? ["Command exceeded output budget."] : []), ...(result.timedOut ? ["Test batch deadline exhausted."] : [])] });
|
|
76
|
+
if (result.timedOut || result.canceled || result.outputLimited)
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
return receipts;
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
await rm(owned, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function runProcess(command, args, cwd, timeoutMs, maxOutputBytes, signal) {
|
|
87
|
+
if (signal?.aborted)
|
|
88
|
+
return { exitCode: null, signal: null, stdout: "", stderr: "", timedOut: false, canceled: true, runtimeMs: 0, outputLimited: false };
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const started = Date.now();
|
|
91
|
+
const env = command === "git" ? isolatedGitEnvironment() : Object.fromEntries(["PATH", "HOME", "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "TMPDIR"].flatMap(key => process.env[key] ? [[key, process.env[key]]] : []));
|
|
92
|
+
const child = spawn(command, args, { cwd, env, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
|
|
93
|
+
let stdout = "", stderr = "", bytes = 0;
|
|
94
|
+
let timedOut = false, canceled = false, outputLimited = false;
|
|
95
|
+
const kill = () => { try {
|
|
96
|
+
process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL");
|
|
97
|
+
}
|
|
98
|
+
catch { /* process group already gone */ } };
|
|
99
|
+
const timer = setTimeout(() => { timedOut = true; kill(); }, timeoutMs);
|
|
100
|
+
const abort = () => { canceled = true; kill(); };
|
|
101
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
102
|
+
if (signal?.aborted)
|
|
103
|
+
abort();
|
|
104
|
+
const append = (target, chunk) => {
|
|
105
|
+
bytes += chunk.length;
|
|
106
|
+
if (bytes > maxOutputBytes) {
|
|
107
|
+
outputLimited = true;
|
|
108
|
+
kill();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (target === "stdout")
|
|
112
|
+
stdout += chunk.toString("utf8");
|
|
113
|
+
else
|
|
114
|
+
stderr += chunk.toString("utf8");
|
|
115
|
+
};
|
|
116
|
+
child.stdout.on("data", (chunk) => append("stdout", chunk));
|
|
117
|
+
child.stderr.on("data", (chunk) => append("stderr", chunk));
|
|
118
|
+
const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); kill(); };
|
|
119
|
+
child.once("error", error => { cleanup(); reject(error); });
|
|
120
|
+
child.once("exit", kill);
|
|
121
|
+
child.once("close", (exitCode, exitSignal) => { cleanup(); resolve({ exitCode: outputLimited ? null : exitCode, signal: exitSignal, stdout, stderr, timedOut, canceled, outputLimited, runtimeMs: Date.now() - started }); });
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bare `reviewfn` package runs this CLI with BARE_EXPECTED_CLI set to "<package>@<version>", the exact version it
|
|
3
|
+
* pins. npm exec can reach another installed version under the same bin name, so the CLI refuses to run as any
|
|
4
|
+
* version but that one. A matching expectation is removed, so commands the CLI starts do not inherit it.
|
|
5
|
+
*
|
|
6
|
+
* @returns the message to print when this CLI is not the expected version, or undefined
|
|
7
|
+
*/
|
|
8
|
+
export declare function expectedCliMismatch(pkg: {
|
|
9
|
+
name: string;
|
|
10
|
+
version: string;
|
|
11
|
+
}, env?: NodeJS.ProcessEnv): string | undefined;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bare `reviewfn` package runs this CLI with BARE_EXPECTED_CLI set to "<package>@<version>", the exact version it
|
|
3
|
+
* pins. npm exec can reach another installed version under the same bin name, so the CLI refuses to run as any
|
|
4
|
+
* version but that one. A matching expectation is removed, so commands the CLI starts do not inherit it.
|
|
5
|
+
*
|
|
6
|
+
* @returns the message to print when this CLI is not the expected version, or undefined
|
|
7
|
+
*/
|
|
8
|
+
export function expectedCliMismatch(pkg, env = process.env) {
|
|
9
|
+
const expected = env.BARE_EXPECTED_CLI;
|
|
10
|
+
if (!expected?.startsWith(`${pkg.name}@`))
|
|
11
|
+
return undefined;
|
|
12
|
+
if (expected === `${pkg.name}@${pkg.version}`) {
|
|
13
|
+
delete env.BARE_EXPECTED_CLI;
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
return `expected ${pkg.name} ${expected.slice(pkg.name.length + 1)}, found ${pkg.version}; run npx ${expected}`;
|
|
17
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { safeRead, FileArtifactStore, ReviewCoordinator, ReviewFnError, renderMarkdownReport } from "@superfunctions/reviewfn-core";
|
|
7
|
+
import { githubRepositoryIdentity, GitHubAdvisoryPublisher, GitHubApi, GitSourceControlAdapter } from "@superfunctions/reviewfn-github";
|
|
8
|
+
import { CodexHarnessAdapter } from "@superfunctions/reviewfn-harness-codex";
|
|
9
|
+
import { evaluate } from "@superfunctions/reviewfn-testing";
|
|
10
|
+
import { initializeConfiguration, initializePanelPolicy } from "./config.js";
|
|
11
|
+
import { expectedCliMismatch } from "./expected-cli.js";
|
|
12
|
+
import { LocalIsolatedExecutionAdapter } from "./execution.js";
|
|
13
|
+
import { contextAdapters, createReviewSnapshot, loadRunConfiguration, optional, parseArguments, publication, renderStoredReport, required, runPanelCommand } from "./panel.js";
|
|
14
|
+
async function createCoordinator(root, config, pullRequest, targetBranch) {
|
|
15
|
+
if (process.env.GITHUB_TOKEN)
|
|
16
|
+
throw new Error("Review execution must not receive GITHUB_TOKEN; use the separate publish command in a credentialed job.");
|
|
17
|
+
const sourceControl = new GitSourceControlAdapter({ targetBranch });
|
|
18
|
+
const artifacts = new FileArtifactStore(path.resolve(root, "../artifacts"));
|
|
19
|
+
return new ReviewCoordinator({
|
|
20
|
+
sourceControl,
|
|
21
|
+
contexts: contextAdapters(config),
|
|
22
|
+
harness: new CodexHarnessAdapter({ executable: config.harness.executable }),
|
|
23
|
+
execution: new LocalIsolatedExecutionAdapter(artifacts),
|
|
24
|
+
artifacts,
|
|
25
|
+
publishers: [],
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
async function run() {
|
|
29
|
+
const args = parseArguments(process.argv.slice(2));
|
|
30
|
+
const root = path.resolve(optional(args.flags, "root") ?? process.cwd());
|
|
31
|
+
if (args.command === "--version") {
|
|
32
|
+
process.stdout.write(`${createRequire(import.meta.url)("../package.json").version}\n`);
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
if (!args.command || args.command === "help" || args.flags.has("help")) {
|
|
36
|
+
process.stdout.write(help());
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
if (args.command === "init") {
|
|
40
|
+
if (typeof args.flags.get("panel") === "string")
|
|
41
|
+
throw new Error("--panel takes no value.");
|
|
42
|
+
const files = args.flags.has("panel") ? [await initializePanelPolicy(root)] : await initializeConfiguration(root);
|
|
43
|
+
process.stdout.write(`${files.map((file) => path.relative(root, file)).join("\n")}\n`);
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
if (args.command === "render") {
|
|
47
|
+
const input = path.resolve(root, required(args.flags, "input"));
|
|
48
|
+
process.stdout.write(renderMarkdownReport(JSON.parse(await readFile(input, "utf8"))));
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (args.command === "report") {
|
|
52
|
+
process.stdout.write(await renderStoredReport(args.flags, root));
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
if (args.command === "panel") {
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
const abort = () => controller.abort();
|
|
58
|
+
process.once("SIGINT", abort);
|
|
59
|
+
process.once("SIGTERM", abort);
|
|
60
|
+
try {
|
|
61
|
+
return await runPanelCommand(args.flags, { signal: controller.signal });
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
process.removeListener("SIGINT", abort);
|
|
65
|
+
process.removeListener("SIGTERM", abort);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (args.command === "publish") {
|
|
69
|
+
const value = JSON.parse((await safeRead(path.resolve(root, required(args.flags, "input")))).toString("utf8"));
|
|
70
|
+
const repository = required(args.flags, "repository").split("/");
|
|
71
|
+
const pullRequest = Number(required(args.flags, "pull-request"));
|
|
72
|
+
const expectedHead = required(args.flags, "head");
|
|
73
|
+
if (repository.length !== 2 || !process.env.GITHUB_TOKEN || !Number.isInteger(pullRequest) || pullRequest <= 0)
|
|
74
|
+
throw new Error("Publication requires repository, PR number and GITHUB_TOKEN.");
|
|
75
|
+
const { report, rendered, profile } = publication(value, args.flags);
|
|
76
|
+
if (report.change.headCommit !== expectedHead || report.change.pullRequest !== pullRequest)
|
|
77
|
+
throw new Error("Artifact does not match trusted publication identity or is not completed.");
|
|
78
|
+
if (githubRepositoryIdentity(report.change.repositoryId) !== repository.join("/").toLowerCase())
|
|
79
|
+
throw new Error("Artifact repository does not match the trusted publication target.");
|
|
80
|
+
const publisher = new GitHubAdvisoryPublisher({ api: new GitHubApi({ owner: repository[0], repository: repository[1], token: process.env.GITHUB_TOKEN }), pullRequest, publisherLogin: optional(args.flags, "publisher-login") });
|
|
81
|
+
const result = await publisher.publish({ report, rendered, expectedHead, profile });
|
|
82
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
83
|
+
return result.status === "failed" || result.status === "stale" ? 1 : 0;
|
|
84
|
+
}
|
|
85
|
+
if (args.command === "evaluate") {
|
|
86
|
+
const input = JSON.parse(await readFile(path.resolve(root, required(args.flags, "input")), "utf8"));
|
|
87
|
+
process.stdout.write(`${JSON.stringify(evaluate(input.cases, input.outcomes), null, 2)}\n`);
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
if (!["preflight", "review"].includes(args.command))
|
|
91
|
+
throw new Error(`Unknown command ${args.command}.`);
|
|
92
|
+
const base = required(args.flags, "base");
|
|
93
|
+
const head = required(args.flags, "head");
|
|
94
|
+
const pullRequestText = optional(args.flags, "pull-request") ?? process.env.GITHUB_EVENT_PULL_REQUEST_NUMBER;
|
|
95
|
+
const pullRequest = pullRequestText === undefined ? undefined : Number(pullRequestText);
|
|
96
|
+
if (pullRequestText !== undefined && (!Number.isInteger(pullRequest) || pullRequest <= 0))
|
|
97
|
+
throw new Error("--pull-request must be a positive integer.");
|
|
98
|
+
const { config, policy } = await loadRunConfiguration(root, base, args.flags);
|
|
99
|
+
const owned = await mkdtemp(path.join(tmpdir(), "reviewfn-run-"));
|
|
100
|
+
try {
|
|
101
|
+
const snapshot = await createReviewSnapshot(root, owned, base, head, optional(args.flags, "target-branch"));
|
|
102
|
+
const coordinator = await createCoordinator(snapshot.root, config, pullRequest, snapshot.targetBranch);
|
|
103
|
+
const request = { root: snapshot.root, base: snapshot.base, head: snapshot.head, pullRequest, config, policy, issue: optional(args.flags, "issue") };
|
|
104
|
+
if (args.command === "preflight") {
|
|
105
|
+
const diagnostics = await coordinator.preflight(request);
|
|
106
|
+
process.stdout.write(`${JSON.stringify({ ok: !diagnostics.some((item) => item.level === "error"), diagnostics }, null, 2)}\n`);
|
|
107
|
+
return diagnostics.some((item) => item.level === "error") ? 1 : 0;
|
|
108
|
+
}
|
|
109
|
+
const controller = new AbortController();
|
|
110
|
+
const abort = () => controller.abort();
|
|
111
|
+
process.once("SIGINT", abort);
|
|
112
|
+
process.once("SIGTERM", abort);
|
|
113
|
+
try {
|
|
114
|
+
const result = await coordinator.run({ ...request, signal: controller.signal });
|
|
115
|
+
const outputDirectory = path.resolve(root, optional(args.flags, "output") ?? ".reviewfn/output");
|
|
116
|
+
const store = new FileArtifactStore(path.join(outputDirectory, "artifacts"), outputDirectory);
|
|
117
|
+
// Merge retained artifacts without shortening expiration for prior references.
|
|
118
|
+
await store.importFrom(path.join(owned, "artifacts"));
|
|
119
|
+
const cleanup = await store.deleteExpired();
|
|
120
|
+
await store.writeReportCopies(`${JSON.stringify(result.report, null, 2)}\n`, result.rendered, Math.min(config.retention.reportDays, policy.retention.reportDays));
|
|
121
|
+
process.stdout.write(`${result.rendered}\n`);
|
|
122
|
+
if (cleanup.errors.length) {
|
|
123
|
+
process.stderr.write(`${JSON.stringify({ error: "REVIEWFN_RETENTION_CLEANUP_FAILED", message: "Review outputs were saved, but retention cleanup failed; inspect the output store and retry cleanup.", details: cleanup.errors })}\n`);
|
|
124
|
+
return 1;
|
|
125
|
+
}
|
|
126
|
+
return result.report.execution === "completed" ? 0 : 1;
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
process.removeListener("SIGINT", abort);
|
|
130
|
+
process.removeListener("SIGTERM", abort);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
await rm(owned, { recursive: true, force: true });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function help() {
|
|
138
|
+
return `ReviewFn — evidence-backed pull request review\n\nUsage:\n reviewfn --version\n reviewfn init [--root PATH] [--panel]\n reviewfn preflight --base REF --head REF [--issue ID] [--trusted-config-from-base]\n reviewfn review --base REF --head REF [--pull-request N] [--issue ID] [--output DIR]\n reviewfn publish --input report.json --repository OWNER/REPO --pull-request N --head SHA --profile NAME\n reviewfn panel --base REF --head REF [--since SHA] [--issue ID] [--pull-request N] [--panel FILE] [--output DIR] [--trusted-config-from-base] [--json]\n reviewfn report [--panel] [--input FILE]\n reviewfn publish --input panel-report.json --repository OWNER/REPO --pull-request N --head SHA [--profile panel]\n reviewfn render --input report.json\n reviewfn evaluate --input evaluation.json\n\nReview is advisory by default. Configuration and policy are loaded from .reviewfn/, and the panel policy from .reviewfn/panel.json.\nreviewfn panel exits 0 (complete), 2 (incomplete coverage or quorum not met), 3 (preflight failed), 4 (canceled) or 1 (other error).\n`;
|
|
139
|
+
}
|
|
140
|
+
const mismatch = expectedCliMismatch(createRequire(import.meta.url)("../package.json"));
|
|
141
|
+
if (mismatch) {
|
|
142
|
+
process.stderr.write(`reviewfn: ${mismatch}\n`);
|
|
143
|
+
process.exitCode = 1;
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
run().then((code) => { process.exitCode = code; }).catch((error) => {
|
|
147
|
+
const payload = error instanceof ReviewFnError ? { error: error.code, message: error.message, details: error.details } : { error: "REVIEWFN_UNEXPECTED", message: error instanceof Error ? error.message : String(error) };
|
|
148
|
+
process.stderr.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
149
|
+
process.exitCode = 1;
|
|
150
|
+
});
|
|
151
|
+
}
|
package/dist/panel.d.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { FileArtifactStore, type ArtifactStore, type ContextAdapter, type ExecutionAdapter, type PanelHarnessAdapter, type PanelPolicy, type PanelReport, type ReviewFnConfig, type ReviewPolicy, type ReviewReport } from "@superfunctions/reviewfn-core";
|
|
2
|
+
export type Flags = Map<string, string | true>;
|
|
3
|
+
export interface Arguments {
|
|
4
|
+
command?: string;
|
|
5
|
+
flags: Flags;
|
|
6
|
+
positionals: string[];
|
|
7
|
+
}
|
|
8
|
+
export declare function parseArguments(argv: string[]): Arguments;
|
|
9
|
+
export declare function required(flags: Flags, name: string): string;
|
|
10
|
+
export declare function optional(flags: Flags, name: string): string | undefined;
|
|
11
|
+
/** Whether configuration is trusted only from the base revision: in GitHub Actions, or when asked. */
|
|
12
|
+
export declare function trustedFromBase(flags: Flags, environment?: NodeJS.ProcessEnv): boolean;
|
|
13
|
+
/** The run configuration and review policy, from the base revision when trusted, otherwise from the working tree. */
|
|
14
|
+
export declare function loadRunConfiguration(root: string, base: string, flags: Flags, environment?: NodeJS.ProcessEnv): Promise<{
|
|
15
|
+
config: ReviewFnConfig;
|
|
16
|
+
policy: ReviewPolicy;
|
|
17
|
+
}>;
|
|
18
|
+
/**
|
|
19
|
+
* The context adapters a configuration names. `code-references` takes its pairs and exclusions from the loaded panel
|
|
20
|
+
* policy, and its defaults (no pairs, the default exclusions) without one.
|
|
21
|
+
*/
|
|
22
|
+
export declare function contextAdapters(config: ReviewFnConfig, panelPolicy?: PanelPolicy): ContextAdapter[];
|
|
23
|
+
export interface ReviewSnapshot {
|
|
24
|
+
/** A private clone checked out at `head`, without hooks, attribute filters or the original remote's credentials. */
|
|
25
|
+
root: string;
|
|
26
|
+
base: string;
|
|
27
|
+
head: string;
|
|
28
|
+
/** The target branch name, from `--target-branch`, the symbolic base, or `GITHUB_BASE_REF`. */
|
|
29
|
+
targetBranch: string;
|
|
30
|
+
}
|
|
31
|
+
/** Resolve `ref` in `root` to a full commit ID. */
|
|
32
|
+
export declare function resolveCommit(root: string, ref: string): Promise<string>;
|
|
33
|
+
/**
|
|
34
|
+
* Clone `root` into `<owned>/checkout` at the immutable head, as the review commands read it: no hooks, no attribute
|
|
35
|
+
* filters, and a redacted remote.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createReviewSnapshot(root: string, owned: string, base: string, head: string, targetBranchFlag?: string, environment?: NodeJS.ProcessEnv): Promise<ReviewSnapshot>;
|
|
38
|
+
/** The closed set of `reviewfn panel` exit codes. The verdict never changes the exit code: panel output is advisory. */
|
|
39
|
+
export declare const PANEL_EXIT_CODES: Readonly<{
|
|
40
|
+
/** The run completed and its coverage is complete. */
|
|
41
|
+
complete: 0;
|
|
42
|
+
/** Any error not listed below. */
|
|
43
|
+
error: 1;
|
|
44
|
+
/** The run completed with incomplete coverage, or a stage's quorum was not met. */
|
|
45
|
+
incomplete: 2;
|
|
46
|
+
/** Preflight failed: configuration, panel policy, harness resolution or a component's preflight. */
|
|
47
|
+
preflight: 3;
|
|
48
|
+
/** The run was canceled. */
|
|
49
|
+
canceled: 4;
|
|
50
|
+
}>;
|
|
51
|
+
/**
|
|
52
|
+
* Supported harness adapters, by the `harness.adapter` a slot names: the package that provides it and the adapter class
|
|
53
|
+
* it exports. Adapters are optional peer installs and are only ever loaded from this table, never from a module path.
|
|
54
|
+
*/
|
|
55
|
+
export declare const PANEL_HARNESS_PACKAGES: Readonly<Record<string, {
|
|
56
|
+
packageName: string;
|
|
57
|
+
exportName: string;
|
|
58
|
+
}>>;
|
|
59
|
+
/** Loads one package from `PANEL_HARNESS_PACKAGES` by name; the dynamic `import()` by default. */
|
|
60
|
+
export type HarnessModuleImporter = (packageName: string) => Promise<unknown>;
|
|
61
|
+
/** Options every harness adapter class receives from the CLI. */
|
|
62
|
+
export interface PanelHarnessConstructorOptions {
|
|
63
|
+
/** The configured executable, for the adapter the run configuration names; the adapter's default otherwise. */
|
|
64
|
+
executable?: string;
|
|
65
|
+
environment?: NodeJS.ProcessEnv;
|
|
66
|
+
}
|
|
67
|
+
export interface ResolvedPanelHarnesses {
|
|
68
|
+
harnesses: PanelHarnessAdapter[];
|
|
69
|
+
/** The adapter contract version of each adapter other than the configured one, read before any preflight. */
|
|
70
|
+
contractVersions: Record<string, string>;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Load and construct one adapter for each harness the panel's review slots name, through the fixed package table.
|
|
74
|
+
* Fails with `REVIEWFN_HARNESS_NOT_INSTALLED` when an adapter's package is not installed, `REVIEWFN_HARNESS_UNSUPPORTED`
|
|
75
|
+
* for an adapter the table does not name, and `REVIEWFN_HARNESS_LOAD_FAILED` for a package that does not provide a
|
|
76
|
+
* usable adapter. Verifier slots are not run by this release, so their adapters are not loaded.
|
|
77
|
+
*/
|
|
78
|
+
export declare function resolvePanelHarnesses(policy: PanelPolicy, config: ReviewFnConfig, importModule?: HarnessModuleImporter, environment?: NodeJS.ProcessEnv): Promise<ResolvedPanelHarnesses>;
|
|
79
|
+
/** Injection points for the panel command; the CLI uses the defaults. */
|
|
80
|
+
export interface PanelCommandDependencies {
|
|
81
|
+
/** Loads harness packages named by `PANEL_HARNESS_PACKAGES`. */
|
|
82
|
+
importHarnessModule?: HarnessModuleImporter;
|
|
83
|
+
/** The trusted test execution; Docker-isolated execution by default. */
|
|
84
|
+
execution?: (artifacts: ArtifactStore) => ExecutionAdapter;
|
|
85
|
+
/** Aborting it cancels the run (exit 4). */
|
|
86
|
+
signal?: AbortSignal;
|
|
87
|
+
environment?: NodeJS.ProcessEnv;
|
|
88
|
+
stdout?: (text: string) => void;
|
|
89
|
+
stderr?: (text: string) => void;
|
|
90
|
+
/** Removes the run's private snapshot directory; a retried recursive `rm` by default. */
|
|
91
|
+
removeSnapshot?: (directory: string) => Promise<void>;
|
|
92
|
+
/** Clones the private snapshot; `createReviewSnapshot` by default. */
|
|
93
|
+
createSnapshot?: typeof createReviewSnapshot;
|
|
94
|
+
/** The store that checks, writes and expires the panel report copies; the panel `FileArtifactStore` by default. */
|
|
95
|
+
reportCopiesStore?: (locations: Pick<PanelOutputLocations, "artifactsDirectory" | "outputDirectory">) => FileArtifactStore;
|
|
96
|
+
}
|
|
97
|
+
/** The single JSON error line every command writes to stderr. */
|
|
98
|
+
export declare function errorPayload(error: unknown): Record<string, unknown>;
|
|
99
|
+
/** Where a finished panel run saves its outputs, and the retention of the report copies. */
|
|
100
|
+
export interface PanelOutputLocations {
|
|
101
|
+
/** The run's private artifact store, imported into `artifactsDirectory`. */
|
|
102
|
+
ownedArtifacts: string;
|
|
103
|
+
artifactsDirectory: string;
|
|
104
|
+
outputDirectory: string;
|
|
105
|
+
/** Retention of `panel-report.json` and `panel-report.md`, as of the stored report: the smaller of config and policy `reportDays`. */
|
|
106
|
+
reportDays: number;
|
|
107
|
+
}
|
|
108
|
+
export interface SavedPanelRun {
|
|
109
|
+
/** Undefined when the invocation was canceled before the report copies were written: nothing was written to the output directory. */
|
|
110
|
+
reportPath?: string;
|
|
111
|
+
rendered?: string;
|
|
112
|
+
exitCode: number;
|
|
113
|
+
/** The error that sets a nonzero exit code other than incomplete coverage, if any. */
|
|
114
|
+
error?: unknown;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Save a finished panel run: expire old artifacts and report copies, import the run's evidence into the artifact store,
|
|
118
|
+
* then write `panel-report.json` and `panel-report.md` as a pair under report-copy retention. Cancellation is checked
|
|
119
|
+
* once, after cleanup and before saving begins; nothing of the run is saved before that point. A cancellation before it,
|
|
120
|
+
* or a failure while canceled before it, saves nothing and exits 4. Once saving begins it is not interrupted: the
|
|
121
|
+
* saved report decides the exit code, and any failure exits 1 (4 only when the report records the cancellation), so an
|
|
122
|
+
* exit 4 never leaves an uncanceled report of the run. `store` is a test seam.
|
|
123
|
+
*/
|
|
124
|
+
export declare function savePanelRun(report: PanelReport, quorumMet: boolean, locations: PanelOutputLocations, signal?: AbortSignal, store?: FileArtifactStore): Promise<SavedPanelRun>;
|
|
125
|
+
/**
|
|
126
|
+
* `reviewfn panel`: run the panel over base..head and write `panel-report.json` and `panel-report.md` to the output
|
|
127
|
+
* directory, with the run's evidence under `.reviewfn/artifacts`. Returns an exit code from `PANEL_EXIT_CODES`. Any
|
|
128
|
+
* failure while the signal is aborted, before the report copies are written, exits 4.
|
|
129
|
+
*/
|
|
130
|
+
export declare function runPanelCommand(flags: Flags, dependencies?: PanelCommandDependencies): Promise<number>;
|
|
131
|
+
/**
|
|
132
|
+
* Check a stored report for publication and render it. A 0.1 report must be completed and match `--profile`. A panel
|
|
133
|
+
* report must be structurally valid and not canceled, and publishes only under the `panel` profile, so it maintains
|
|
134
|
+
* one summary comment and one neutral `ReviewFn / panel` check.
|
|
135
|
+
*/
|
|
136
|
+
export declare function publication(value: unknown, flags: Flags): {
|
|
137
|
+
report: ReviewReport | PanelReport;
|
|
138
|
+
rendered: string;
|
|
139
|
+
profile: string;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* `reviewfn report [--panel] [--input FILE]`: re-render a stored report as Markdown on stdout. With `--panel` the input
|
|
143
|
+
* (`.reviewfn/output/panel-report.json` by default) must be a structurally valid panel report.
|
|
144
|
+
*/
|
|
145
|
+
export declare function renderStoredReport(flags: Flags, root: string): Promise<string>;
|
package/dist/panel.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { devNull, tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { ComposioLinearContextAdapter } from "@superfunctions/reviewfn-context-composio";
|
|
7
|
+
import { CODE_REFERENCES_ADAPTER_ID, CodeReferencesContextAdapter, codeReferencesOptions, effectiveRetention, FileArtifactStore, isPanelReport, isolatedGitEnvironment, loadPanelPolicy, PANEL_REPORT_COPY_NAMES, panelReportCanceled, panelStructureIssues, PanelCoordinator, RepositoryMarkdownContextAdapter, renderMarkdownReport, renderPanelMarkdownReport, ReviewFnError, safeDirectory, safeRead, validateConfig, validatePolicy, } from "@superfunctions/reviewfn-core";
|
|
8
|
+
import { GitSourceControlAdapter, redactRepositoryRemote } from "@superfunctions/reviewfn-github";
|
|
9
|
+
import { loadConfig, loadPolicy, loadTrustedConfigFromBase, loadTrustedPolicyFromBase } from "./config.js";
|
|
10
|
+
import { LocalIsolatedExecutionAdapter } from "./execution.js";
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
export function parseArguments(argv) {
|
|
13
|
+
const [command, ...rest] = argv;
|
|
14
|
+
const flags = new Map();
|
|
15
|
+
const positionals = [];
|
|
16
|
+
for (let index = 0; index < rest.length; index += 1) {
|
|
17
|
+
const value = rest[index];
|
|
18
|
+
if (!value.startsWith("--")) {
|
|
19
|
+
positionals.push(value);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const separator = value.indexOf("=");
|
|
23
|
+
const name = value.slice(2, separator < 0 ? undefined : separator);
|
|
24
|
+
const inline = separator < 0 ? undefined : value.slice(separator + 1);
|
|
25
|
+
if (inline !== undefined)
|
|
26
|
+
flags.set(name, inline);
|
|
27
|
+
else if (rest[index + 1] && !rest[index + 1].startsWith("--"))
|
|
28
|
+
flags.set(name, rest[++index]);
|
|
29
|
+
else
|
|
30
|
+
flags.set(name, true);
|
|
31
|
+
}
|
|
32
|
+
return { command, flags, positionals };
|
|
33
|
+
}
|
|
34
|
+
export function required(flags, name) {
|
|
35
|
+
const value = flags.get(name);
|
|
36
|
+
if (typeof value !== "string" || value.length === 0)
|
|
37
|
+
throw new Error(`--${name} is required.`);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
export function optional(flags, name) {
|
|
41
|
+
const value = flags.get(name);
|
|
42
|
+
return typeof value === "string" ? value : undefined;
|
|
43
|
+
}
|
|
44
|
+
/** Whether configuration is trusted only from the base revision: in GitHub Actions, or when asked. */
|
|
45
|
+
export function trustedFromBase(flags, environment = process.env) {
|
|
46
|
+
return flags.has("trusted-config-from-base") || environment.GITHUB_ACTIONS === "true";
|
|
47
|
+
}
|
|
48
|
+
/** The run configuration and review policy, from the base revision when trusted, otherwise from the working tree. */
|
|
49
|
+
export async function loadRunConfiguration(root, base, flags, environment = process.env) {
|
|
50
|
+
const trusted = trustedFromBase(flags, environment);
|
|
51
|
+
const configRelative = optional(flags, "config") ?? ".reviewfn/config.json";
|
|
52
|
+
const policyRelative = optional(flags, "policy") ?? ".reviewfn/policy.json";
|
|
53
|
+
const config = trusted ? await loadTrustedConfigFromBase(root, base, configRelative) : await loadConfig(path.resolve(root, configRelative));
|
|
54
|
+
const policy = trusted ? await loadTrustedPolicyFromBase(root, base, policyRelative) : await loadPolicy(path.resolve(root, policyRelative));
|
|
55
|
+
if (config.output.mode !== policy.mode)
|
|
56
|
+
throw new Error(`Configuration output mode ${config.output.mode} does not match trusted policy mode ${policy.mode}.`);
|
|
57
|
+
return { config: validateConfig(config), policy: validatePolicy(policy) };
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The context adapters a configuration names. `code-references` takes its pairs and exclusions from the loaded panel
|
|
61
|
+
* policy, and its defaults (no pairs, the default exclusions) without one.
|
|
62
|
+
*/
|
|
63
|
+
export function contextAdapters(config, panelPolicy) {
|
|
64
|
+
const adapters = new Map();
|
|
65
|
+
for (const item of config.context) {
|
|
66
|
+
if (item.adapter === "repository-markdown")
|
|
67
|
+
adapters.set(item.adapter, new RepositoryMarkdownContextAdapter());
|
|
68
|
+
else if (item.adapter === CODE_REFERENCES_ADAPTER_ID)
|
|
69
|
+
adapters.set(item.adapter, new CodeReferencesContextAdapter(panelPolicy ? codeReferencesOptions(panelPolicy) : {}));
|
|
70
|
+
else if (item.adapter === "composio-linear")
|
|
71
|
+
adapters.set(item.adapter, new ComposioLinearContextAdapter());
|
|
72
|
+
}
|
|
73
|
+
return [...adapters.values()];
|
|
74
|
+
}
|
|
75
|
+
/** Resolve `ref` in `root` to a full commit ID. */
|
|
76
|
+
export async function resolveCommit(root, ref) {
|
|
77
|
+
return (await execFileAsync("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { cwd: root })).stdout.trim();
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Clone `root` into `<owned>/checkout` at the immutable head, as the review commands read it: no hooks, no attribute
|
|
81
|
+
* filters, and a redacted remote.
|
|
82
|
+
*/
|
|
83
|
+
export async function createReviewSnapshot(root, owned, base, head, targetBranchFlag, environment = process.env) {
|
|
84
|
+
const snapshot = path.join(owned, "checkout");
|
|
85
|
+
const snapshotEnvironment = isolatedGitEnvironment();
|
|
86
|
+
const immutableHead = await resolveCommit(root, head);
|
|
87
|
+
const immutableBase = await resolveCommit(root, base);
|
|
88
|
+
await execFileAsync("git", ["-c", `core.hooksPath=${devNull}`, "clone", "--template=", "--no-local", "--no-checkout", root, snapshot], { env: snapshotEnvironment, maxBuffer: 1_000_000 });
|
|
89
|
+
// info/attributes outranks every committed .gitattributes, including nested files.
|
|
90
|
+
await mkdir(path.join(snapshot, ".git", "info"), { recursive: true, mode: 0o700 });
|
|
91
|
+
await writeFile(path.join(snapshot, ".git", "info", "attributes"), "* -text -eol -working-tree-encoding -filter -ident\n", { mode: 0o600 });
|
|
92
|
+
await execFileAsync("git", ["-c", `core.hooksPath=${devNull}`, "-c", `core.attributesFile=${devNull}`, "-c", "core.autocrlf=false", "checkout", "--detach", immutableHead], { cwd: snapshot, env: snapshotEnvironment, maxBuffer: 1_000_000 });
|
|
93
|
+
const remote = (await execFileAsync("git", ["config", "--get", "remote.origin.url"], { cwd: root }).catch(() => ({ stdout: "local" }))).stdout.trim();
|
|
94
|
+
await execFileAsync("git", ["remote", "set-url", "origin", redactRepositoryRemote(remote)], { cwd: snapshot });
|
|
95
|
+
const symbolicBase = (await execFileAsync("git", ["rev-parse", "--symbolic-full-name", "--verify", "--end-of-options", base], { cwd: root })).stdout.trim();
|
|
96
|
+
const targetBranch = targetBranchFlag ?? (symbolicBase.startsWith("refs/") ? symbolicBase.replace(/^refs\/(heads|remotes)\//, "") : environment.GITHUB_BASE_REF ?? "unknown");
|
|
97
|
+
return { root: snapshot, base: immutableBase, head: immutableHead, targetBranch };
|
|
98
|
+
}
|
|
99
|
+
/** The closed set of `reviewfn panel` exit codes. The verdict never changes the exit code: panel output is advisory. */
|
|
100
|
+
export const PANEL_EXIT_CODES = Object.freeze({
|
|
101
|
+
/** The run completed and its coverage is complete. */
|
|
102
|
+
complete: 0,
|
|
103
|
+
/** Any error not listed below. */
|
|
104
|
+
error: 1,
|
|
105
|
+
/** The run completed with incomplete coverage, or a stage's quorum was not met. */
|
|
106
|
+
incomplete: 2,
|
|
107
|
+
/** Preflight failed: configuration, panel policy, harness resolution or a component's preflight. */
|
|
108
|
+
preflight: 3,
|
|
109
|
+
/** The run was canceled. */
|
|
110
|
+
canceled: 4,
|
|
111
|
+
});
|
|
112
|
+
/**
|
|
113
|
+
* Supported harness adapters, by the `harness.adapter` a slot names: the package that provides it and the adapter class
|
|
114
|
+
* it exports. Adapters are optional peer installs and are only ever loaded from this table, never from a module path.
|
|
115
|
+
*/
|
|
116
|
+
export const PANEL_HARNESS_PACKAGES = Object.freeze({
|
|
117
|
+
codex: Object.freeze({ packageName: "@superfunctions/reviewfn-harness-codex", exportName: "CodexHarnessAdapter" }),
|
|
118
|
+
"claude-code": Object.freeze({ packageName: "@superfunctions/reviewfn-harness-claude-code", exportName: "ClaudeCodeHarnessAdapter" }),
|
|
119
|
+
cli: Object.freeze({ packageName: "@superfunctions/reviewfn-harness-cli", exportName: "CliHarnessAdapter" }),
|
|
120
|
+
});
|
|
121
|
+
function moduleNotFound(error, packageName) {
|
|
122
|
+
const failure = error;
|
|
123
|
+
// A missing dependency of an installed adapter is a broken install, not a missing adapter.
|
|
124
|
+
return (failure?.code === "ERR_MODULE_NOT_FOUND" || failure?.code === "MODULE_NOT_FOUND") && typeof failure.message === "string" && failure.message.includes(`'${packageName}'`);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Load and construct one adapter for each harness the panel's review slots name, through the fixed package table.
|
|
128
|
+
* Fails with `REVIEWFN_HARNESS_NOT_INSTALLED` when an adapter's package is not installed, `REVIEWFN_HARNESS_UNSUPPORTED`
|
|
129
|
+
* for an adapter the table does not name, and `REVIEWFN_HARNESS_LOAD_FAILED` for a package that does not provide a
|
|
130
|
+
* usable adapter. Verifier slots are not run by this release, so their adapters are not loaded.
|
|
131
|
+
*/
|
|
132
|
+
export async function resolvePanelHarnesses(policy, config, importModule = specifier => import(specifier), environment = process.env) {
|
|
133
|
+
const bySlot = new Map();
|
|
134
|
+
for (const slot of policy.slots)
|
|
135
|
+
if (slot.stage !== "verifier")
|
|
136
|
+
bySlot.set(slot.harness.adapter, [...(bySlot.get(slot.harness.adapter) ?? []), slot.id]);
|
|
137
|
+
const harnesses = [];
|
|
138
|
+
const contractVersions = {};
|
|
139
|
+
for (const [adapter, slots] of bySlot) {
|
|
140
|
+
const entry = Object.hasOwn(PANEL_HARNESS_PACKAGES, adapter) ? PANEL_HARNESS_PACKAGES[adapter] : undefined;
|
|
141
|
+
if (!entry)
|
|
142
|
+
throw new ReviewFnError("REVIEWFN_HARNESS_UNSUPPORTED", `Slot(s) ${slots.join(", ")} name harness adapter ${JSON.stringify(adapter)}, which ReviewFn does not support. Supported adapters: ${Object.keys(PANEL_HARNESS_PACKAGES).join(", ")}.`, { adapter, slots });
|
|
143
|
+
let loaded;
|
|
144
|
+
try {
|
|
145
|
+
loaded = await importModule(entry.packageName);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
if (moduleNotFound(error, entry.packageName))
|
|
149
|
+
throw new ReviewFnError("REVIEWFN_HARNESS_NOT_INSTALLED", `Slot(s) ${slots.join(", ")} use the ${adapter} harness, but ${entry.packageName} is not installed. Install it next to @superfunctions/reviewfn-cli.`, { adapter, packageName: entry.packageName, slots });
|
|
150
|
+
throw new ReviewFnError("REVIEWFN_HARNESS_LOAD_FAILED", `${entry.packageName} could not be loaded: ${error instanceof Error ? error.message : String(error)}`, { adapter, packageName: entry.packageName });
|
|
151
|
+
}
|
|
152
|
+
const constructor = loaded?.[entry.exportName];
|
|
153
|
+
if (typeof constructor !== "function")
|
|
154
|
+
throw new ReviewFnError("REVIEWFN_HARNESS_LOAD_FAILED", `${entry.packageName} does not export the adapter class ${entry.exportName}.`, { adapter, packageName: entry.packageName });
|
|
155
|
+
const options = { environment, ...(adapter === config.harness.adapter && config.harness.executable ? { executable: config.harness.executable } : {}) };
|
|
156
|
+
const harness = new constructor(options);
|
|
157
|
+
if (harness?.capabilities?.id !== adapter)
|
|
158
|
+
throw new ReviewFnError("REVIEWFN_HARNESS_LOAD_FAILED", `${entry.packageName} provides harness ${String(harness?.capabilities?.id)}, not ${adapter}.`, { adapter, packageName: entry.packageName });
|
|
159
|
+
// Read now: adapters such as Codex overwrite capabilities.version with the executable's version during preflight.
|
|
160
|
+
if (adapter !== config.harness.adapter && typeof harness.capabilities.version === "string")
|
|
161
|
+
contractVersions[adapter] = harness.capabilities.version;
|
|
162
|
+
harnesses.push(harness);
|
|
163
|
+
}
|
|
164
|
+
return { harnesses, contractVersions };
|
|
165
|
+
}
|
|
166
|
+
/** The single JSON error line every command writes to stderr. */
|
|
167
|
+
export function errorPayload(error) {
|
|
168
|
+
return error instanceof ReviewFnError ? { error: error.code, message: error.message, ...(error.details === undefined ? {} : { details: error.details }) } : { error: "REVIEWFN_UNEXPECTED", message: error instanceof Error ? error.message : String(error) };
|
|
169
|
+
}
|
|
170
|
+
/** Every `reviewfn panel` flag that takes a value; given bare or empty (`--output=`), it is an invalid argument (exit 1). */
|
|
171
|
+
const PANEL_VALUE_FLAGS = ["base", "head", "since", "issue", "pull-request", "panel", "output", "root", "config", "policy", "target-branch"];
|
|
172
|
+
function requireValues(flags, names) {
|
|
173
|
+
for (const name of names)
|
|
174
|
+
if (flags.get(name) === true || flags.get(name) === "")
|
|
175
|
+
throw new Error(`--${name} requires a value.`);
|
|
176
|
+
}
|
|
177
|
+
function panelInvocation(flags, environment) {
|
|
178
|
+
requireValues(flags, PANEL_VALUE_FLAGS);
|
|
179
|
+
const root = path.resolve(optional(flags, "root") ?? process.cwd());
|
|
180
|
+
const pullRequestText = optional(flags, "pull-request") ?? environment.GITHUB_EVENT_PULL_REQUEST_NUMBER;
|
|
181
|
+
const pullRequest = pullRequestText === undefined ? undefined : Number(pullRequestText);
|
|
182
|
+
if (pullRequestText !== undefined && (!/^[0-9]+$/.test(pullRequestText) || !Number.isSafeInteger(pullRequest) || pullRequest <= 0))
|
|
183
|
+
throw new Error("--pull-request must be a positive integer.");
|
|
184
|
+
return {
|
|
185
|
+
root, base: required(flags, "base"), head: required(flags, "head"), since: optional(flags, "since"), issue: optional(flags, "issue"), pullRequest, json: flags.has("json"),
|
|
186
|
+
outputDirectory: path.resolve(root, optional(flags, "output") ?? ".reviewfn/output"),
|
|
187
|
+
artifactsDirectory: path.resolve(root, ".reviewfn/artifacts"),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
async function readArtifactJson(store, id) {
|
|
191
|
+
const bytes = await store.get(id);
|
|
192
|
+
if (!bytes)
|
|
193
|
+
throw new ReviewFnError("REVIEWFN_ARTIFACT_UNSAFE", `Artifact ${id} is missing.`);
|
|
194
|
+
return JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Save a finished panel run: expire old artifacts and report copies, import the run's evidence into the artifact store,
|
|
198
|
+
* then write `panel-report.json` and `panel-report.md` as a pair under report-copy retention. Cancellation is checked
|
|
199
|
+
* once, after cleanup and before saving begins; nothing of the run is saved before that point. A cancellation before it,
|
|
200
|
+
* or a failure while canceled before it, saves nothing and exits 4. Once saving begins it is not interrupted: the
|
|
201
|
+
* saved report decides the exit code, and any failure exits 1 (4 only when the report records the cancellation), so an
|
|
202
|
+
* exit 4 never leaves an uncanceled report of the run. `store` is a test seam.
|
|
203
|
+
*/
|
|
204
|
+
export async function savePanelRun(report, quorumMet, locations, signal, store = new FileArtifactStore(locations.artifactsDirectory, locations.outputDirectory, PANEL_REPORT_COPY_NAMES)) {
|
|
205
|
+
const recordsCancellation = panelReportCanceled(report);
|
|
206
|
+
let saving = false;
|
|
207
|
+
try {
|
|
208
|
+
const cleanup = await store.deleteExpired();
|
|
209
|
+
const rendered = renderPanelMarkdownReport(report);
|
|
210
|
+
if (signal?.aborted && !recordsCancellation)
|
|
211
|
+
return { exitCode: PANEL_EXIT_CODES.canceled, error: new ReviewFnError("REVIEWFN_CANCELED", "The panel run was canceled before its report was saved; nothing of the run was saved.", { runId: report.runId }) };
|
|
212
|
+
saving = true;
|
|
213
|
+
// Merge retained artifacts without shortening expiration for prior references.
|
|
214
|
+
await store.importFrom(locations.ownedArtifacts);
|
|
215
|
+
await safeDirectory(locations.outputDirectory);
|
|
216
|
+
await store.writeReportCopies(`${JSON.stringify(report, null, 2)}\n`, rendered, locations.reportDays);
|
|
217
|
+
const reportPath = path.join(locations.outputDirectory, PANEL_REPORT_COPY_NAMES.json);
|
|
218
|
+
if (recordsCancellation)
|
|
219
|
+
return { reportPath, rendered, exitCode: PANEL_EXIT_CODES.canceled, error: new ReviewFnError("REVIEWFN_CANCELED", "The panel run was canceled; the saved report records the cancellation.", { runId: report.runId }) };
|
|
220
|
+
if (cleanup.errors.length)
|
|
221
|
+
return { reportPath, rendered, exitCode: PANEL_EXIT_CODES.error, error: new ReviewFnError("REVIEWFN_RETENTION_CLEANUP_FAILED", "Panel outputs were saved, but retention cleanup failed; inspect the artifact store and retry cleanup.", { errors: cleanup.errors }) };
|
|
222
|
+
return { reportPath, rendered, exitCode: report.coverage !== "complete" || !quorumMet ? PANEL_EXIT_CODES.incomplete : PANEL_EXIT_CODES.complete };
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
// Before saving begins, a failure of a canceled run exits 4; once it has begun, only a report that records the
|
|
226
|
+
// cancellation does.
|
|
227
|
+
if (recordsCancellation || (!saving && signal?.aborted))
|
|
228
|
+
return { exitCode: PANEL_EXIT_CODES.canceled, error: new ReviewFnError("REVIEWFN_CANCELED", saving ? "The panel run was canceled, and saving its report, which records the cancellation, failed." : "The panel run was canceled before its report was saved; nothing of the run was saved.", { runId: report.runId, cause: errorPayload(error) }) };
|
|
229
|
+
return { exitCode: PANEL_EXIT_CODES.error, error };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function removeSnapshot(directory) { return rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
233
|
+
/**
|
|
234
|
+
* `reviewfn panel`: run the panel over base..head and write `panel-report.json` and `panel-report.md` to the output
|
|
235
|
+
* directory, with the run's evidence under `.reviewfn/artifacts`. Returns an exit code from `PANEL_EXIT_CODES`. Any
|
|
236
|
+
* failure while the signal is aborted, before the report copies are written, exits 4.
|
|
237
|
+
*/
|
|
238
|
+
export async function runPanelCommand(flags, dependencies = {}) {
|
|
239
|
+
const stdout = dependencies.stdout ?? (text => void process.stdout.write(text));
|
|
240
|
+
const stderr = dependencies.stderr ?? (text => void process.stderr.write(text));
|
|
241
|
+
const environment = dependencies.environment ?? process.env;
|
|
242
|
+
const signal = dependencies.signal;
|
|
243
|
+
const fail = (code, error) => { stderr(`${JSON.stringify(errorPayload(error))}\n`); return code; };
|
|
244
|
+
const canceled = (error, stage) => fail(PANEL_EXIT_CODES.canceled, error instanceof ReviewFnError && error.code === "REVIEWFN_CANCELED" ? error : new ReviewFnError("REVIEWFN_CANCELED", `The panel run was canceled ${stage}.`, { cause: errorPayload(error) }));
|
|
245
|
+
let invocation;
|
|
246
|
+
try {
|
|
247
|
+
invocation = panelInvocation(flags, environment);
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
return fail(PANEL_EXIT_CODES.error, error);
|
|
251
|
+
}
|
|
252
|
+
let owned;
|
|
253
|
+
// The saved report's stdout line, printed only after the private snapshot is removed and the exit code is final.
|
|
254
|
+
let output;
|
|
255
|
+
const reportCopiesStore = () => dependencies.reportCopiesStore?.(invocation) ?? new FileArtifactStore(invocation.artifactsDirectory, invocation.outputDirectory, PANEL_REPORT_COPY_NAMES);
|
|
256
|
+
const code = await (async () => {
|
|
257
|
+
try {
|
|
258
|
+
let coordinator;
|
|
259
|
+
let request;
|
|
260
|
+
let reportDays;
|
|
261
|
+
let setup;
|
|
262
|
+
// Preflight (exit 3): configuration, panel policy, harness resolution, refs that must name commits, and an output
|
|
263
|
+
// directory whose lock is still held (such as one a killed run left behind).
|
|
264
|
+
try {
|
|
265
|
+
if (environment.GITHUB_TOKEN)
|
|
266
|
+
throw new ReviewFnError("REVIEWFN_PREFLIGHT_FAILED", "Review execution must not receive GITHUB_TOKEN; use the separate publish command in a credentialed job.");
|
|
267
|
+
const { root } = invocation;
|
|
268
|
+
const { config, policy } = await loadRunConfiguration(root, invocation.base, flags, environment);
|
|
269
|
+
reportDays = effectiveRetention(config, policy).reportDays;
|
|
270
|
+
const { policy: panelPolicy } = await loadPanelPolicy({ root, base: invocation.base, head: invocation.head, trustedFromBase: trustedFromBase(flags, environment), path: optional(flags, "panel"), signal });
|
|
271
|
+
const { harnesses, contractVersions } = await resolvePanelHarnesses(panelPolicy, config, dependencies.importHarnessModule, environment);
|
|
272
|
+
for (const ref of [invocation.base, invocation.head])
|
|
273
|
+
await resolveCommit(root, ref);
|
|
274
|
+
const since = invocation.since === undefined ? undefined : await resolveCommit(root, invocation.since);
|
|
275
|
+
await reportCopiesStore().checkReportCopiesLock(signal);
|
|
276
|
+
setup = { config, policy, panelPolicy, harnesses, contractVersions, since };
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
if (signal?.aborted)
|
|
280
|
+
return canceled(error, "during preflight");
|
|
281
|
+
return fail(PANEL_EXIT_CODES.preflight, error);
|
|
282
|
+
}
|
|
283
|
+
// Setup I/O (exit 1): the private snapshot and the run's artifact store.
|
|
284
|
+
let ownedStore;
|
|
285
|
+
let ownedArtifacts;
|
|
286
|
+
try {
|
|
287
|
+
const { config, policy, panelPolicy, harnesses, contractVersions, since } = setup;
|
|
288
|
+
owned = await mkdtemp(path.join(tmpdir(), "reviewfn-panel-cli-"));
|
|
289
|
+
ownedArtifacts = path.join(owned, "artifacts");
|
|
290
|
+
ownedStore = new FileArtifactStore(ownedArtifacts);
|
|
291
|
+
const snapshot = await (dependencies.createSnapshot ?? createReviewSnapshot)(invocation.root, owned, invocation.base, invocation.head, optional(flags, "target-branch"), environment);
|
|
292
|
+
await mkdir(ownedArtifacts, { recursive: true, mode: 0o700 });
|
|
293
|
+
coordinator = new PanelCoordinator({
|
|
294
|
+
sourceControl: new GitSourceControlAdapter({ targetBranch: snapshot.targetBranch }),
|
|
295
|
+
contexts: contextAdapters(config, panelPolicy),
|
|
296
|
+
harnesses,
|
|
297
|
+
harnessContractVersions: contractVersions,
|
|
298
|
+
execution: dependencies.execution?.(ownedStore) ?? new LocalIsolatedExecutionAdapter(ownedStore),
|
|
299
|
+
artifacts: ownedStore,
|
|
300
|
+
environment,
|
|
301
|
+
});
|
|
302
|
+
request = { root: snapshot.root, base: snapshot.base, head: snapshot.head, pullRequest: invocation.pullRequest, config, policy, issue: invocation.issue, panelPolicy, signal, ...(since === undefined ? {} : { since }) };
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
if (signal?.aborted)
|
|
306
|
+
return canceled(error, "while the run was set up");
|
|
307
|
+
return fail(PANEL_EXIT_CODES.error, error);
|
|
308
|
+
}
|
|
309
|
+
let report;
|
|
310
|
+
let quorumMet;
|
|
311
|
+
try {
|
|
312
|
+
const result = await coordinator.run(request);
|
|
313
|
+
report = result.report;
|
|
314
|
+
quorumMet = result.quorum.every(item => item.met);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
// Canceled while the report was stored: the superseding report records the cancellation; keep it as the output.
|
|
318
|
+
const artifact = error instanceof ReviewFnError && error.code === "REVIEWFN_CANCELED" ? error.details?.reportArtifact : undefined;
|
|
319
|
+
if (typeof artifact === "string") {
|
|
320
|
+
report = await readArtifactJson(ownedStore, artifact);
|
|
321
|
+
quorumMet = false;
|
|
322
|
+
}
|
|
323
|
+
else if (signal?.aborted)
|
|
324
|
+
return canceled(error, "while the panel ran");
|
|
325
|
+
else if (error instanceof ReviewFnError && error.code === "REVIEWFN_PREFLIGHT_FAILED")
|
|
326
|
+
return fail(PANEL_EXIT_CODES.preflight, error);
|
|
327
|
+
else
|
|
328
|
+
return fail(PANEL_EXIT_CODES.error, error);
|
|
329
|
+
}
|
|
330
|
+
const saved = await savePanelRun(report, quorumMet, { ownedArtifacts, artifactsDirectory: invocation.artifactsDirectory, outputDirectory: invocation.outputDirectory, reportDays }, signal, reportCopiesStore());
|
|
331
|
+
// Exit 1 prints nothing on stdout, even when the report was saved (a retention cleanup failure).
|
|
332
|
+
if (saved.reportPath !== undefined && saved.exitCode !== PANEL_EXIT_CODES.error)
|
|
333
|
+
output = invocation.json ? `${JSON.stringify({ report: saved.reportPath, runId: report.runId })}\n` : `${saved.rendered}\n`;
|
|
334
|
+
return saved.error === undefined ? saved.exitCode : fail(saved.exitCode, saved.error);
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
// Only reading a stored canceled report reaches here; nothing was written to the output directory.
|
|
338
|
+
if (signal?.aborted)
|
|
339
|
+
return canceled(error, "while its report was read");
|
|
340
|
+
return fail(PANEL_EXIT_CODES.error, error);
|
|
341
|
+
}
|
|
342
|
+
})();
|
|
343
|
+
// The private snapshot holds a copy of the repository. A run that cannot remove it always names it on stderr, prints
|
|
344
|
+
// no report on stdout, and exits 1 instead of 0 or 2; exits 1, 3 and 4 keep their code.
|
|
345
|
+
// stdout carries the report (Markdown or the `--json` line) only for exit 0, 2, or 4 with a saved report that records
|
|
346
|
+
// the cancellation, and only once the snapshot is removed.
|
|
347
|
+
if (owned !== undefined) {
|
|
348
|
+
try {
|
|
349
|
+
await (dependencies.removeSnapshot ?? removeSnapshot)(owned);
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
const leftover = fail(PANEL_EXIT_CODES.error, new ReviewFnError("REVIEWFN_SNAPSHOT_CLEANUP_FAILED", `The panel run's private snapshot ${owned} was not removed; delete it: ${error instanceof Error ? error.message : String(error)}`, { snapshot: owned }));
|
|
353
|
+
return code === PANEL_EXIT_CODES.complete || code === PANEL_EXIT_CODES.incomplete ? leftover : code;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (output !== undefined)
|
|
357
|
+
stdout(output);
|
|
358
|
+
return code;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Check a stored report for publication and render it. A 0.1 report must be completed and match `--profile`. A panel
|
|
362
|
+
* report must be structurally valid and not canceled, and publishes only under the `panel` profile, so it maintains
|
|
363
|
+
* one summary comment and one neutral `ReviewFn / panel` check.
|
|
364
|
+
*/
|
|
365
|
+
export function publication(value, flags) {
|
|
366
|
+
if (isPanelReport(value)) {
|
|
367
|
+
const issues = panelStructureIssues("panelReport", value);
|
|
368
|
+
if (issues.length)
|
|
369
|
+
throw new Error(`Artifact is not a valid panel report: ${issues.slice(0, 5).map(issue => `${issue.path || "/"} ${issue.message}`).join("; ")}`);
|
|
370
|
+
const profile = optional(flags, "profile") ?? "panel";
|
|
371
|
+
if (profile !== "panel")
|
|
372
|
+
throw new Error("A panel report publishes only under the panel profile.");
|
|
373
|
+
if (panelReportCanceled(value))
|
|
374
|
+
throw new Error("The panel run was canceled; a canceled panel report is never published.");
|
|
375
|
+
return { report: value, rendered: renderPanelMarkdownReport(value), profile };
|
|
376
|
+
}
|
|
377
|
+
const report = value;
|
|
378
|
+
if (report.execution !== "completed" || report.configuration.profile !== required(flags, "profile"))
|
|
379
|
+
throw new Error("Artifact does not match trusted publication identity or is not completed.");
|
|
380
|
+
return { report, rendered: renderMarkdownReport(report), profile: report.configuration.profile };
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* `reviewfn report [--panel] [--input FILE]`: re-render a stored report as Markdown on stdout. With `--panel` the input
|
|
384
|
+
* (`.reviewfn/output/panel-report.json` by default) must be a structurally valid panel report.
|
|
385
|
+
*/
|
|
386
|
+
export async function renderStoredReport(flags, root) {
|
|
387
|
+
requireValues(flags, ["input", "root"]);
|
|
388
|
+
const panelValue = flags.get("panel");
|
|
389
|
+
if (typeof panelValue === "string")
|
|
390
|
+
throw new Error(`--panel takes no value; use --input ${panelValue} to choose the report.`);
|
|
391
|
+
const panel = flags.has("panel");
|
|
392
|
+
const input = path.resolve(root, optional(flags, "input") ?? (panel ? ".reviewfn/output/panel-report.json" : ".reviewfn/output/report.json"));
|
|
393
|
+
const value = JSON.parse((await safeRead(input)).toString("utf8"));
|
|
394
|
+
const kind = typeof value === "object" && value !== null ? value.kind : undefined;
|
|
395
|
+
if (!panel) {
|
|
396
|
+
if (kind === "reviewfn-panel")
|
|
397
|
+
throw new ReviewFnError("REVIEWFN_REPORT_INVALID", `${path.relative(root, input)} is a panel report; use reviewfn report --panel.`);
|
|
398
|
+
return renderMarkdownReport(value);
|
|
399
|
+
}
|
|
400
|
+
const issues = panelStructureIssues("panelReport", value);
|
|
401
|
+
if (issues.length)
|
|
402
|
+
throw new ReviewFnError("REVIEWFN_REPORT_INVALID", `${path.relative(root, input)} is not a valid panel report: ${issues.slice(0, 5).map(issue => `${issue.path || "/"} ${issue.message}`).join("; ")}`, { issues });
|
|
403
|
+
return renderPanelMarkdownReport(value);
|
|
404
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superfunctions/reviewfn-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Portable evidence-backed pull request review CLI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"reviewfn": "./dist/main.js"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.json",
|
|
24
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
25
|
+
"test": "vitest run",
|
|
26
|
+
"lint": "tsc --noEmit -p tsconfig.json",
|
|
27
|
+
"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\""
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@superfunctions/reviewfn-context-composio": "0.1.2",
|
|
31
|
+
"@superfunctions/reviewfn-core": "0.1.2",
|
|
32
|
+
"@superfunctions/reviewfn-github": "0.1.2",
|
|
33
|
+
"@superfunctions/reviewfn-harness-codex": "0.1.2",
|
|
34
|
+
"@superfunctions/reviewfn-testing": "0.1.2"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@superfunctions/reviewfn-harness-claude-code": "0.1.2",
|
|
38
|
+
"@superfunctions/reviewfn-harness-cli": "0.1.2",
|
|
39
|
+
"@types/node": "^22.0.0",
|
|
40
|
+
"typescript": "^5.6.0",
|
|
41
|
+
"vitest": "^3.2.4"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22"
|
|
45
|
+
},
|
|
46
|
+
"license": "MIT",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/21nCo/superfunctions.git",
|
|
50
|
+
"directory": "reviewfn/cli"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/21nCo/super-functions/issues"
|
|
54
|
+
},
|
|
55
|
+
"sideEffects": false,
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
},
|
|
59
|
+
"frontDoorCli": {
|
|
60
|
+
"checksExpectedVersion": true
|
|
61
|
+
},
|
|
62
|
+
"gitHead": "9ea7d0b20b729018bd283f2892ac1156cd4f5610"
|
|
63
|
+
}
|