@loucompanion/forge-bridge 0.2.1-dev.573a8a5fa582 → 0.2.1-dev.7171bf414613
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/README.md +38 -2
- package/dist/bridge/bridge-state-io.d.ts +6 -2
- package/dist/bridge/bridge-state-io.js +22 -4
- package/dist/bridge/bridge.service.d.ts +10 -0
- package/dist/bridge/bridge.service.js +62 -92
- package/dist/bridge/bridge.types.d.ts +6 -0
- package/dist/bridge/default-session-service.d.ts +13 -0
- package/dist/bridge/default-session-service.js +22 -0
- package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
- package/dist/bridge/dispatch-offer-policy.js +58 -0
- package/dist/cleanup/cleanup-wip.js +3 -3
- package/dist/cleanup/forge-owned-paths.d.ts +2 -0
- package/dist/cleanup/forge-owned-paths.js +9 -0
- package/dist/cli/cli.help.js +1 -1
- package/dist/cli/cli.service.js +3 -3
- package/dist/cli/local-config.d.ts +2 -0
- package/dist/cli/local-config.js +3 -0
- package/dist/runtime/host-load-capacity.d.ts +198 -0
- package/dist/runtime/host-load-capacity.js +353 -0
- package/dist/runtime/host-load-child-environment.d.ts +13 -0
- package/dist/runtime/host-load-child-environment.js +35 -1
- package/dist/runtime/host-load-governor-config.d.ts +23 -2
- package/dist/runtime/host-load-governor-config.js +20 -2
- package/dist/runtime/host-load-governor.d.ts +81 -1
- package/dist/runtime/host-load-governor.js +184 -15
- package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
- package/dist/runtime/host-load-live-test-slots.js +193 -0
- package/dist/runtime/host-load-sampler.d.ts +17 -0
- package/dist/runtime/host-load-sampler.js +24 -0
- package/dist/runtime/host-load-step-run.d.ts +37 -3
- package/dist/runtime/host-load-step-run.js +63 -7
- package/dist/runtime/host-load-test-slot.d.ts +3 -0
- package/dist/runtime/host-load-test-slot.js +19 -7
- package/dist/sandbox/runtime.d.ts +1 -2
- package/dist/sandbox/runtime.js +7 -13
- package/dist/sandbox/sandbox-input.d.ts +22 -0
- package/dist/sandbox/sandbox-input.js +49 -0
- package/dist/sandbox/workspace.service.js +15 -2
- package/dist/session/managed-attempt-tools.js +6 -29
- package/dist/session/managed-build-receipt.d.ts +3 -1
- package/dist/session/managed-build-receipt.js +5 -2
- package/dist/session/managed-command-environment.d.ts +8 -0
- package/dist/session/managed-command-environment.js +28 -0
- package/dist/session/managed-command-host-load.d.ts +10 -5
- package/dist/session/managed-command-host-load.js +18 -14
- package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
- package/dist/session/phase-completion.artifact-bundle.js +167 -0
- package/dist/session/phase-completion.artifacts.d.ts +2 -17
- package/dist/session/phase-completion.artifacts.js +63 -165
- package/dist/session/phase-completion.d.ts +25 -2
- package/dist/session/phase-completion.helpers.js +5 -53
- package/dist/session/phase-completion.js +15 -32
- package/dist/session/phase-completion.mcp-args.js +69 -2
- package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
- package/dist/session/phase-completion.phase-aliases.js +43 -0
- package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
- package/dist/session/phase-completion.pr-review-schema.js +75 -0
- package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
- package/dist/session/phase-completion.pr-review-threads.js +90 -0
- package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
- package/dist/session/phase-completion.pr-review-validation.js +215 -0
- package/dist/session/phase-completion.pr-review.d.ts +36 -0
- package/dist/session/phase-completion.pr-review.js +294 -0
- package/dist/session/phase-completion.prompts.d.ts +1 -1
- package/dist/session/phase-completion.prompts.js +14 -0
- package/dist/session/phase-completion.runtime.js +9 -3
- package/dist/session/phase-completion.schemas.js +12 -2
- package/dist/session/phase-completion.validation.d.ts +1 -0
- package/dist/session/phase-completion.validation.js +9 -1
- package/dist/session/pr-review-diff-base.d.ts +18 -0
- package/dist/session/pr-review-diff-base.js +45 -0
- package/dist/session/pr-review-placement.d.ts +50 -0
- package/dist/session/pr-review-placement.js +91 -0
- package/dist/session/pre-publication-change-set.d.ts +62 -0
- package/dist/session/pre-publication-change-set.js +166 -0
- package/dist/session/pre-publication-host-load.js +6 -5
- package/dist/session/pre-publication-process.js +3 -2
- package/dist/session/pre-publication-validation.d.ts +2 -1
- package/dist/session/pre-publication-validation.js +31 -36
- package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
- package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
- package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
- package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
- package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
- package/dist/session/provider-cli/pr-review-prompt.js +132 -0
- package/dist/session/provider-cli/pre-publication-repair.js +7 -3
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
- package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -13
- package/dist/session/provider-cli/provider-cli.prompts.js +123 -107
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
- package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
- package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
- package/dist/session/provider-cli/provider-cli.service.js +24 -139
- package/dist/session/sandbox-host-capacity-gate.js +28 -6
- package/dist/session/session.parse-helpers.d.ts +10 -0
- package/dist/session/session.parse-helpers.js +84 -0
- package/dist/session/session.runtime-refresh.d.ts +46 -0
- package/dist/session/session.runtime-refresh.js +116 -0
- package/dist/session/session.service.d.ts +2 -1
- package/dist/session/session.service.js +40 -95
- package/dist/session/session.types.d.ts +4 -0
- package/dist/session/session.types.js +7 -77
- package/dist/session/session.types.pr-review.d.ts +59 -0
- package/dist/session/session.types.pr-review.js +53 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.js +24 -0
- package/dist/worktree/worktree.service.d.ts +22 -0
- package/dist/worktree/worktree.service.js +116 -12
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
5
|
+
/** The failure code of every review session that changed or published something it must not. */
|
|
6
|
+
export const prReviewGuardrailViolationCode = "guardrail_violation";
|
|
7
|
+
/** A push URL no git transport handles, so a push fails before any network or credential lookup. */
|
|
8
|
+
export const prReviewDisabledPushUrl = "forge-review-push-disabled://publication-is-not-allowed";
|
|
9
|
+
/** The git and gh environment for a review session whose isolation directory is `directory`. */
|
|
10
|
+
export function prReviewIsolatedGitEnvironment(directory, options = {}) {
|
|
11
|
+
const entries = [
|
|
12
|
+
["credential.helper", ""],
|
|
13
|
+
["credential.interactive", "false"],
|
|
14
|
+
["protocol.allow", "never"],
|
|
15
|
+
["http.extraHeader", ""],
|
|
16
|
+
["core.askPass", ""],
|
|
17
|
+
...(options.remotes ?? ["origin"]).map((remote) => [`remote.${remote}.pushurl`, prReviewDisabledPushUrl]),
|
|
18
|
+
...(options.safeDirectories ?? []).map((directory) => ["safe.directory", directory.replaceAll("\\", "/")]),
|
|
19
|
+
];
|
|
20
|
+
const env = {
|
|
21
|
+
GIT_CONFIG_GLOBAL: path.join(directory, "gitconfig"),
|
|
22
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
23
|
+
GIT_CONFIG_COUNT: String(entries.length),
|
|
24
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
25
|
+
GIT_ASKPASS: "",
|
|
26
|
+
SSH_ASKPASS: "",
|
|
27
|
+
GCM_INTERACTIVE: "never",
|
|
28
|
+
GH_CONFIG_DIR: path.join(directory, "gh"),
|
|
29
|
+
GH_PROMPT_DISABLED: "1",
|
|
30
|
+
GH_NO_UPDATE_NOTIFIER: "1",
|
|
31
|
+
};
|
|
32
|
+
entries.forEach(([key, value], index) => {
|
|
33
|
+
env[`GIT_CONFIG_KEY_${index}`] = key;
|
|
34
|
+
env[`GIT_CONFIG_VALUE_${index}`] = value;
|
|
35
|
+
});
|
|
36
|
+
return env;
|
|
37
|
+
}
|
|
38
|
+
/** Creates the empty global git configuration and gh configuration directory for one session. */
|
|
39
|
+
export async function preparePrReviewCredentialIsolation(options = {}) {
|
|
40
|
+
const directory = await fs.mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "forge-pr-review-git-"));
|
|
41
|
+
try {
|
|
42
|
+
await fs.writeFile(path.join(directory, "gitconfig"), "", "utf8");
|
|
43
|
+
await fs.mkdir(path.join(directory, "gh"));
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
directory,
|
|
51
|
+
env: prReviewIsolatedGitEnvironment(directory, options),
|
|
52
|
+
cleanup: async () => {
|
|
53
|
+
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** The repository's remote names, read before the session starts. */
|
|
58
|
+
export async function listRemotes(git, worktreePath) {
|
|
59
|
+
const output = await git.run(worktreePath, ["remote"]).catch(() => "");
|
|
60
|
+
const remotes = output.split(/\r?\n/u).map((line) => line.trim()).filter((line) => /^[A-Za-z0-9._/-]+$/u.test(line));
|
|
61
|
+
return remotes.length > 0 ? remotes : ["origin"];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The refs a review session could move: the pull request's source branch (local and every
|
|
65
|
+
* remote-tracking copy) and the namespaces only history-rewriting or bookkeeping commands write
|
|
66
|
+
* (notes, replace, stash, bisect, per-worktree refs, filter-branch backups). Other branches and tags
|
|
67
|
+
* are left out on purpose: the repository is shared with Forge's other sessions, whose fetches move
|
|
68
|
+
* them while this review runs.
|
|
69
|
+
*/
|
|
70
|
+
export function reviewRefPatterns(sourceBranch, remotes) {
|
|
71
|
+
const branch = sourceBranch?.trim();
|
|
72
|
+
return [
|
|
73
|
+
...(branch ? [`refs/heads/${branch}`, ...remotes.map((remote) => `refs/remotes/${remote}/${branch}`)] : []),
|
|
74
|
+
"refs/notes",
|
|
75
|
+
"refs/replace",
|
|
76
|
+
"refs/stash",
|
|
77
|
+
"refs/bisect",
|
|
78
|
+
"refs/worktree",
|
|
79
|
+
"refs/original",
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
export async function snapshotReviewRefs(git, worktreePath, patterns) {
|
|
83
|
+
const output = await git.run(worktreePath, ["for-each-ref", "--format=%(refname) %(objectname)", ...patterns]);
|
|
84
|
+
const refs = new Map();
|
|
85
|
+
for (const line of output.split(/\r?\n/u)) {
|
|
86
|
+
const separator = line.lastIndexOf(" ");
|
|
87
|
+
if (separator > 0) {
|
|
88
|
+
refs.set(line.slice(0, separator), line.slice(separator + 1).trim().toLowerCase());
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return { refs };
|
|
92
|
+
}
|
|
93
|
+
/** Throws `guardrail_violation` when a ref in the review's scope was created, moved or deleted. */
|
|
94
|
+
export async function assertReviewRefsUnchanged(git, worktreePath, patterns, baseline) {
|
|
95
|
+
const after = await snapshotReviewRefs(git, worktreePath, patterns);
|
|
96
|
+
const problems = [];
|
|
97
|
+
for (const [ref, sha] of after.refs) {
|
|
98
|
+
const before = baseline.refs.get(ref);
|
|
99
|
+
if (before === undefined)
|
|
100
|
+
problems.push(`${ref} was created`);
|
|
101
|
+
else if (before !== sha)
|
|
102
|
+
problems.push(`${ref} moved from ${before.slice(0, 12)} to ${sha.slice(0, 12)}`);
|
|
103
|
+
}
|
|
104
|
+
for (const ref of baseline.refs.keys()) {
|
|
105
|
+
if (!after.refs.has(ref))
|
|
106
|
+
problems.push(`${ref} was deleted`);
|
|
107
|
+
}
|
|
108
|
+
if (problems.length > 0) {
|
|
109
|
+
throw new ForgeFailureError(prReviewGuardrailViolationCode, `guardrail_violation: the review-only session changed git refs (${problems.slice(0, 10).join("; ")}). Forge discards the review and publishes nothing.`, "bridge");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Reads the pull request branch's head on origin with the bridge's own git environment, never the
|
|
114
|
+
* session's. In the Docker sandbox there is nothing to read: the container's workspace has no remote
|
|
115
|
+
* and no credential, so the session has nowhere to push. On a host placement a read that fails, or a
|
|
116
|
+
* dispatch without the branch, fails closed: a moved branch could not be detected.
|
|
117
|
+
*/
|
|
118
|
+
export async function readReviewRemoteHead(git, worktreePath, dispatch) {
|
|
119
|
+
if (dispatch.sandbox?.executionMode === "docker") {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
const branch = dispatch.pullRequest?.sourceBranch?.trim() ?? "";
|
|
123
|
+
const unreadable = (detail, cause) => new ForgeFailureError("pr_review_remote_head_unreadable", `pr_review_remote_head_unreadable: ${detail}, so a push from the review could not be detected. Forge did not record the review.`, "bridge", cause === undefined ? undefined : { cause });
|
|
124
|
+
if (!branch) {
|
|
125
|
+
throw unreadable("the review dispatch did not name the pull request branch");
|
|
126
|
+
}
|
|
127
|
+
const output = await git.run(worktreePath, ["ls-remote", "--heads", "origin", `refs/heads/${branch}`])
|
|
128
|
+
.catch((error) => { throw unreadable(`origin could not be read for ${branch}`, error); });
|
|
129
|
+
const sha = output.split(/\r?\n/u)
|
|
130
|
+
.map((line) => line.trim().split(/\s+/u))
|
|
131
|
+
.find(([, ref]) => ref === `refs/heads/${branch}`)?.[0]?.toLowerCase() ?? "";
|
|
132
|
+
return { branch, sha };
|
|
133
|
+
}
|
|
134
|
+
/** Throws `guardrail_violation` when the pull request branch on origin moved, appeared or vanished during the session. */
|
|
135
|
+
export async function assertReviewRemoteHeadUnchanged(git, worktreePath, before) {
|
|
136
|
+
if (!before) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const after = await readReviewRemoteHead(git, worktreePath, { pullRequest: { sourceBranch: before.branch } });
|
|
140
|
+
if (after?.sha !== before.sha) {
|
|
141
|
+
const describe = (sha) => (sha ? sha.slice(0, 12) : "absent");
|
|
142
|
+
throw new ForgeFailureError(prReviewGuardrailViolationCode, `guardrail_violation: the pull request branch ${before.branch} on origin moved from ${describe(before.sha)} to ${describe(after?.sha)} while the review-only session ran. Forge discards the review and publishes nothing.`, "bridge");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { GitClient } from "../../shared/git/git.js";
|
|
2
|
+
/**
|
|
3
|
+
* Guardrails for the review-only pr_review provider session. The session reads a pull request
|
|
4
|
+
* at a pinned head and hands Forge one review through the completion tool; it never changes the
|
|
5
|
+
* checkout, never publishes, and never talks to GitHub. The isolation is the Docker sandbox; a host
|
|
6
|
+
* review runs only where its owner opted in (pr-review-placement.ts), and there everything below is
|
|
7
|
+
* defence in depth. The environment, the same for every provider (pr-review-credential-isolation.ts),
|
|
8
|
+
* carries no credential Forge controls and points git and gh at empty configuration. On top of it: a
|
|
9
|
+
* provider tool deny list (Claude), `git`/`gh` command shims on PATH (POSIX), and post-run worktree,
|
|
10
|
+
* ref and (on a host) remote-head comparisons that fail the session when anything changed.
|
|
11
|
+
*/
|
|
12
|
+
export { assertReviewRefsUnchanged, assertReviewRemoteHeadUnchanged, listRemotes, preparePrReviewCredentialIsolation, prReviewGuardrailViolationCode, readReviewRemoteHead, reviewRefPatterns, snapshotReviewRefs, type PrReviewCredentialIsolation, type ReviewRefSnapshot, type ReviewRemoteHead, } from "./pr-review-credential-isolation.js";
|
|
13
|
+
/**
|
|
14
|
+
* Git subcommands that move HEAD, rewrite history, change refs, configuration or the checkout,
|
|
15
|
+
* create other worktrees, or publish. A review only reads (log, diff, show, blame, grep, ...).
|
|
16
|
+
*/
|
|
17
|
+
export declare const prReviewDeniedGitSubcommands: readonly string[];
|
|
18
|
+
/**
|
|
19
|
+
* Provider tool rules (Claude Code syntax) the review session is launched without. Deny rules apply
|
|
20
|
+
* even under `--permission-mode bypassPermissions`, which every Forge provider run (reviews included)
|
|
21
|
+
* uses. They are a second layer over the environment (pr-review-credential-isolation.ts), and neither is
|
|
22
|
+
* a boundary on a host: only the Docker sandbox is. The file tools are denied outright, because a
|
|
23
|
+
* review changes nothing and hands its result over only through the completion tool.
|
|
24
|
+
*/
|
|
25
|
+
export declare function prReviewDisallowedTools(): readonly string[];
|
|
26
|
+
/**
|
|
27
|
+
* Removes GitHub and publication credentials from a provider environment and disables
|
|
28
|
+
* interactive credential prompts. The provider's own model API key is kept.
|
|
29
|
+
*/
|
|
30
|
+
export declare function stripPublicationCredentials(env: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
|
|
31
|
+
export interface PrReviewCommandShims {
|
|
32
|
+
readonly directory: string;
|
|
33
|
+
cleanup(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Writes `git` and `gh` wrappers that refuse the denied commands and otherwise run the real
|
|
37
|
+
* binary. POSIX only. Windows has no shim, so command-level enforcement there comes from the
|
|
38
|
+
* provider launch itself: Claude's deny rules (prReviewDisallowedTools) and Codex's read-only
|
|
39
|
+
* sandbox, which has no write or network access. Other providers are refused before launch.
|
|
40
|
+
*/
|
|
41
|
+
export declare function installPrReviewCommandShims(parentPath?: string | undefined, platform?: NodeJS.Platform): Promise<PrReviewCommandShims | null>;
|
|
42
|
+
/** `PATH` with the shim directory first. */
|
|
43
|
+
export declare function pathWithShims(shimDirectory: string, parentPath?: string | undefined): string;
|
|
44
|
+
export interface WorktreeSnapshot {
|
|
45
|
+
readonly head: string;
|
|
46
|
+
readonly entries: ReadonlyMap<string, string>;
|
|
47
|
+
}
|
|
48
|
+
export interface WorktreeSnapshotOptions {
|
|
49
|
+
/** Absolute directories whose contents are not part of the checkout (for example test output). */
|
|
50
|
+
readonly ignoredDirectories?: readonly string[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Records HEAD plus every tracked-modified, untracked or git-ignored path with a content hash
|
|
54
|
+
* (ignored files, which can hold `.env` or build output, use a size and mtime fingerprint). Comparing a
|
|
55
|
+
* before and an after snapshot catches commits, branch moves, edits and new files, including
|
|
56
|
+
* edits to files that were already dirty before the provider started (injected `.forge` files).
|
|
57
|
+
*/
|
|
58
|
+
export declare function snapshotWorktree(git: GitClient, worktreePath: string, options?: WorktreeSnapshotOptions): Promise<WorktreeSnapshot>;
|
|
59
|
+
/** Throws `guardrail_violation` when the worktree differs from the pre-session snapshot. */
|
|
60
|
+
export declare function assertWorktreeUnchanged(git: GitClient, worktreePath: string, baseline: WorktreeSnapshot, options?: WorktreeSnapshotOptions): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Codex's sandbox for a review-only session. On a host it is `read-only`. In the Docker sandbox it is
|
|
63
|
+
* `danger-full-access`, as for every other Docker lane: Codex's Linux sandbox needs kernel facilities
|
|
64
|
+
* (Landlock and seccomp filters, or bubblewrap's user namespaces) that the hardened container
|
|
65
|
+
* (`--cap-drop ALL`, `no-new-privileges`, read-only root, Docker's seccomp profile) does not reliably grant,
|
|
66
|
+
* and where it cannot start, every shell command fails and the review can only end blocked. The container
|
|
67
|
+
* (no git credential, no remote, no host home) is the isolation, and the review stays read-only through its
|
|
68
|
+
* guardrails: the git and gh shims, the worktree, ref and artifact checks, and no publication grant.
|
|
69
|
+
*/
|
|
70
|
+
export declare function codexReviewSandboxMode(executionMode?: string): "read-only" | "danger-full-access";
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
6
|
+
import { prReviewGuardrailViolationCode } from "./pr-review-credential-isolation.js";
|
|
7
|
+
/**
|
|
8
|
+
* Guardrails for the review-only pr_review provider session. The session reads a pull request
|
|
9
|
+
* at a pinned head and hands Forge one review through the completion tool; it never changes the
|
|
10
|
+
* checkout, never publishes, and never talks to GitHub. The isolation is the Docker sandbox; a host
|
|
11
|
+
* review runs only where its owner opted in (pr-review-placement.ts), and there everything below is
|
|
12
|
+
* defence in depth. The environment, the same for every provider (pr-review-credential-isolation.ts),
|
|
13
|
+
* carries no credential Forge controls and points git and gh at empty configuration. On top of it: a
|
|
14
|
+
* provider tool deny list (Claude), `git`/`gh` command shims on PATH (POSIX), and post-run worktree,
|
|
15
|
+
* ref and (on a host) remote-head comparisons that fail the session when anything changed.
|
|
16
|
+
*/
|
|
17
|
+
// The review's guardrail surface: the credential isolation and ref checks are re-exported from here.
|
|
18
|
+
export { assertReviewRefsUnchanged, assertReviewRemoteHeadUnchanged, listRemotes, preparePrReviewCredentialIsolation, prReviewGuardrailViolationCode, readReviewRemoteHead, reviewRefPatterns, snapshotReviewRefs, } from "./pr-review-credential-isolation.js";
|
|
19
|
+
/**
|
|
20
|
+
* Git subcommands that move HEAD, rewrite history, change refs, configuration or the checkout,
|
|
21
|
+
* create other worktrees, or publish. A review only reads (log, diff, show, blame, grep, ...).
|
|
22
|
+
*/
|
|
23
|
+
export const prReviewDeniedGitSubcommands = [
|
|
24
|
+
"push",
|
|
25
|
+
"commit",
|
|
26
|
+
"rebase",
|
|
27
|
+
"reset",
|
|
28
|
+
"checkout",
|
|
29
|
+
"switch",
|
|
30
|
+
"merge",
|
|
31
|
+
"cherry-pick",
|
|
32
|
+
"revert",
|
|
33
|
+
"am",
|
|
34
|
+
"update-ref",
|
|
35
|
+
"symbolic-ref",
|
|
36
|
+
"branch",
|
|
37
|
+
"tag",
|
|
38
|
+
"worktree",
|
|
39
|
+
"config",
|
|
40
|
+
"stash",
|
|
41
|
+
"clean",
|
|
42
|
+
"restore",
|
|
43
|
+
"apply",
|
|
44
|
+
"add",
|
|
45
|
+
"rm",
|
|
46
|
+
"mv",
|
|
47
|
+
"fetch",
|
|
48
|
+
"pull",
|
|
49
|
+
"remote",
|
|
50
|
+
"submodule",
|
|
51
|
+
"init",
|
|
52
|
+
"clone",
|
|
53
|
+
"gc",
|
|
54
|
+
"replace",
|
|
55
|
+
"notes",
|
|
56
|
+
"filter-branch",
|
|
57
|
+
"fast-import",
|
|
58
|
+
];
|
|
59
|
+
/**
|
|
60
|
+
* Git subcommands that publish, move refs or read stored credentials. These are also denied when a
|
|
61
|
+
* global option comes first (`git -C <dir> push`), where a broader rule would refuse ordinary reads
|
|
62
|
+
* such as `git log --grep commit`; edits and commits by other subcommands are caught by the post-run
|
|
63
|
+
* worktree and ref checks instead.
|
|
64
|
+
*/
|
|
65
|
+
const prReviewPublishingGitSubcommands = [
|
|
66
|
+
"push",
|
|
67
|
+
"send-pack",
|
|
68
|
+
"http-push",
|
|
69
|
+
"update-ref",
|
|
70
|
+
"symbolic-ref",
|
|
71
|
+
"credential",
|
|
72
|
+
"credential-store",
|
|
73
|
+
"credential-cache",
|
|
74
|
+
"credential-manager",
|
|
75
|
+
"credential-manager-core",
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* Command patterns (Claude Code permission-rule syntax: `*` matches anything, including spaces) a
|
|
79
|
+
* review session may not run, applied to both the Bash and PowerShell tools. Claude matches every
|
|
80
|
+
* subcommand of a compound command and skips leading `VAR=value` assignments, so these cover
|
|
81
|
+
* `cd x && git push` too.
|
|
82
|
+
*/
|
|
83
|
+
function prReviewDeniedCommandPatterns() {
|
|
84
|
+
const gitRules = new Set();
|
|
85
|
+
for (const subcommand of [...prReviewDeniedGitSubcommands, ...prReviewPublishingGitSubcommands]) {
|
|
86
|
+
gitRules.add(`git ${subcommand}`);
|
|
87
|
+
gitRules.add(`git ${subcommand} *`);
|
|
88
|
+
}
|
|
89
|
+
for (const subcommand of prReviewPublishingGitSubcommands) {
|
|
90
|
+
gitRules.add(`git * ${subcommand}`);
|
|
91
|
+
gitRules.add(`git * ${subcommand} *`);
|
|
92
|
+
// Through a wrapper (env, command, exec, xargs, sudo) or an absolute or .exe path to git.
|
|
93
|
+
gitRules.add(`* git ${subcommand}*`);
|
|
94
|
+
gitRules.add(`* git * ${subcommand}*`);
|
|
95
|
+
gitRules.add(`*/git *${subcommand}*`);
|
|
96
|
+
gitRules.add(`*git.exe *${subcommand}*`);
|
|
97
|
+
}
|
|
98
|
+
return [
|
|
99
|
+
...gitRules,
|
|
100
|
+
// Configuration overrides on the command line could bring back a credential helper or a transport.
|
|
101
|
+
"git -c *",
|
|
102
|
+
"git * -c *",
|
|
103
|
+
"* git -c *",
|
|
104
|
+
"git *--config-env*",
|
|
105
|
+
"*/git *-c *",
|
|
106
|
+
"*git.exe *-c *",
|
|
107
|
+
// Dashed forms: git-push, git-send-pack, git-credential-manager, ...
|
|
108
|
+
"git-*",
|
|
109
|
+
"*/git-push*",
|
|
110
|
+
"*/git-send-pack*",
|
|
111
|
+
"*/git-http-push*",
|
|
112
|
+
"*git-credential*",
|
|
113
|
+
"*credential-manager*",
|
|
114
|
+
// The GitHub CLI in any form.
|
|
115
|
+
"gh",
|
|
116
|
+
"gh *",
|
|
117
|
+
"* gh *",
|
|
118
|
+
"*/gh *",
|
|
119
|
+
"*gh.exe*",
|
|
120
|
+
// Indirection a literal git rule misses: git named through a variable or PowerShell's call operator
|
|
121
|
+
// (`$g push`, `& $g ('pu'+'sh')`), string evaluation, and nested shells, whose own command line
|
|
122
|
+
// these rules never see. A review needs none of them.
|
|
123
|
+
"$* push*",
|
|
124
|
+
"\"$*\" push*",
|
|
125
|
+
"& *",
|
|
126
|
+
"* & *",
|
|
127
|
+
"*Invoke-Expression*",
|
|
128
|
+
"iex *",
|
|
129
|
+
"* iex *",
|
|
130
|
+
"*Start-Process*",
|
|
131
|
+
"saps *",
|
|
132
|
+
"* saps *",
|
|
133
|
+
"cmd *",
|
|
134
|
+
"* cmd *",
|
|
135
|
+
"*cmd.exe*",
|
|
136
|
+
"powershell *",
|
|
137
|
+
"* powershell *",
|
|
138
|
+
"*powershell.exe*",
|
|
139
|
+
"pwsh *",
|
|
140
|
+
"* pwsh *",
|
|
141
|
+
"*pwsh.exe*",
|
|
142
|
+
// HTTP clients aimed at GitHub.
|
|
143
|
+
"curl *github*",
|
|
144
|
+
"* curl *github*",
|
|
145
|
+
"wget *github*",
|
|
146
|
+
"* wget *github*",
|
|
147
|
+
"*Invoke-WebRequest*",
|
|
148
|
+
"*Invoke-RestMethod*",
|
|
149
|
+
"iwr *",
|
|
150
|
+
"* iwr *",
|
|
151
|
+
"irm *",
|
|
152
|
+
"* irm *",
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Provider tool rules (Claude Code syntax) the review session is launched without. Deny rules apply
|
|
157
|
+
* even under `--permission-mode bypassPermissions`, which every Forge provider run (reviews included)
|
|
158
|
+
* uses. They are a second layer over the environment (pr-review-credential-isolation.ts), and neither is
|
|
159
|
+
* a boundary on a host: only the Docker sandbox is. The file tools are denied outright, because a
|
|
160
|
+
* review changes nothing and hands its result over only through the completion tool.
|
|
161
|
+
*/
|
|
162
|
+
export function prReviewDisallowedTools() {
|
|
163
|
+
const commands = prReviewDeniedCommandPatterns();
|
|
164
|
+
return [
|
|
165
|
+
...commands.map((pattern) => `Bash(${pattern})`),
|
|
166
|
+
...commands.map((pattern) => `PowerShell(${pattern})`),
|
|
167
|
+
"Write",
|
|
168
|
+
"Edit",
|
|
169
|
+
"MultiEdit",
|
|
170
|
+
"NotebookEdit",
|
|
171
|
+
"Read(~/.git-credentials)",
|
|
172
|
+
"Read(~/.config/git/credentials)",
|
|
173
|
+
"Read(~/.config/gh/**)",
|
|
174
|
+
"Read(~/.ssh/**)",
|
|
175
|
+
"WebFetch(domain:github.com)",
|
|
176
|
+
"WebFetch(domain:api.github.com)",
|
|
177
|
+
"WebFetch(domain:uploads.github.com)",
|
|
178
|
+
];
|
|
179
|
+
}
|
|
180
|
+
const credentialEnvironmentPattern = /(^|_)(TOKEN|SECRET|PASSWORD|PASSPHRASE|CREDENTIALS?|PAT|APIKEY|API_KEY|PRIVATE_KEY)(_|$)/iu;
|
|
181
|
+
const gitHubEnvironmentPattern = /^(GH|GITHUB)_/iu;
|
|
182
|
+
/**
|
|
183
|
+
* Inherited git, Git Credential Manager and SSH plumbing a review session never receives: any git
|
|
184
|
+
* configuration variable (GIT_CONFIG_GLOBAL, _SYSTEM, _NOSYSTEM, _PARAMETERS, _COUNT, _KEY_n, _VALUE_n),
|
|
185
|
+
* askpass programs, agent sockets, transport overrides and an XDG configuration home that could
|
|
186
|
+
* hold another git or gh configuration. The isolated values (pr-review-credential-isolation.ts) replace them.
|
|
187
|
+
*/
|
|
188
|
+
const gitCredentialEnvironmentPattern = /^(GIT_CONFIG.*|GCM_.*|GIT_ASKPASS|SSH_ASKPASS.*|SSH_AUTH_SOCK|GIT_SSH|GIT_SSH_COMMAND|GIT_SSH_VARIANT|GIT_EXEC_PATH|GIT_PROXY_COMMAND|GIT_ALLOW_PROTOCOL|GIT_PROTOCOL_FROM_USER|XDG_CONFIG_HOME)$/u;
|
|
189
|
+
/** Variables a review session must keep even though their names look like credentials: the provider's own model key. */
|
|
190
|
+
const providerCredentialAllowList = new Set(["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "CODEX_API_KEY"]);
|
|
191
|
+
/**
|
|
192
|
+
* Removes GitHub and publication credentials from a provider environment and disables
|
|
193
|
+
* interactive credential prompts. The provider's own model API key is kept.
|
|
194
|
+
*/
|
|
195
|
+
export function stripPublicationCredentials(env) {
|
|
196
|
+
const result = {};
|
|
197
|
+
for (const [name, value] of Object.entries(env)) {
|
|
198
|
+
const upper = name.trim().toUpperCase();
|
|
199
|
+
if (providerCredentialAllowList.has(upper)) {
|
|
200
|
+
result[name] = value;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (gitHubEnvironmentPattern.test(upper)
|
|
204
|
+
|| gitCredentialEnvironmentPattern.test(upper)
|
|
205
|
+
|| credentialEnvironmentPattern.test(upper)) {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
result[name] = value;
|
|
209
|
+
}
|
|
210
|
+
result.GIT_TERMINAL_PROMPT = "0";
|
|
211
|
+
result.GH_PROMPT_DISABLED = "1";
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Writes `git` and `gh` wrappers that refuse the denied commands and otherwise run the real
|
|
216
|
+
* binary. POSIX only. Windows has no shim, so command-level enforcement there comes from the
|
|
217
|
+
* provider launch itself: Claude's deny rules (prReviewDisallowedTools) and Codex's read-only
|
|
218
|
+
* sandbox, which has no write or network access. Other providers are refused before launch.
|
|
219
|
+
*/
|
|
220
|
+
export async function installPrReviewCommandShims(parentPath = process.env.PATH, platform = process.platform) {
|
|
221
|
+
if (platform === "win32") {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
const realGit = await findExecutable("git", parentPath);
|
|
225
|
+
if (!realGit) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "forge-pr-review-shims-"));
|
|
229
|
+
const denied = [...prReviewDeniedGitSubcommands, ...prReviewPublishingGitSubcommands].join("|");
|
|
230
|
+
const gitShim = `#!/bin/sh
|
|
231
|
+
# Forge pr_review guardrail: review sessions never change or publish the checkout.
|
|
232
|
+
skip=0
|
|
233
|
+
for arg in "$@"; do
|
|
234
|
+
if [ "$skip" = "1" ]; then skip=0; continue; fi
|
|
235
|
+
case "$arg" in
|
|
236
|
+
-C|-c|--git-dir|--work-tree|--namespace|--exec-path|--super-prefix|--config-env) skip=1; continue ;;
|
|
237
|
+
-*) continue ;;
|
|
238
|
+
${denied}) echo "forge guardrail_violation: 'git $arg' is not allowed in a review-only session." >&2; exit 126 ;;
|
|
239
|
+
*) break ;;
|
|
240
|
+
esac
|
|
241
|
+
done
|
|
242
|
+
exec ${shellQuote(realGit)} "$@"
|
|
243
|
+
`;
|
|
244
|
+
const ghShim = `#!/bin/sh
|
|
245
|
+
echo "forge guardrail_violation: the GitHub CLI is not available in a review-only session." >&2
|
|
246
|
+
exit 126
|
|
247
|
+
`;
|
|
248
|
+
await fs.writeFile(path.join(directory, "git"), gitShim, { mode: 0o755 });
|
|
249
|
+
await fs.writeFile(path.join(directory, "gh"), ghShim, { mode: 0o755 });
|
|
250
|
+
return {
|
|
251
|
+
directory,
|
|
252
|
+
cleanup: async () => {
|
|
253
|
+
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
async function findExecutable(name, searchPath) {
|
|
258
|
+
for (const directory of (searchPath ?? "").split(path.delimiter)) {
|
|
259
|
+
if (!directory)
|
|
260
|
+
continue;
|
|
261
|
+
const candidate = path.join(directory, name);
|
|
262
|
+
const stat = await fs.stat(candidate).catch(() => null);
|
|
263
|
+
if (stat?.isFile()) {
|
|
264
|
+
try {
|
|
265
|
+
await fs.access(candidate, fs.constants.X_OK);
|
|
266
|
+
return candidate;
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// Not executable; keep searching.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
function shellQuote(value) {
|
|
276
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
277
|
+
}
|
|
278
|
+
/** `PATH` with the shim directory first. */
|
|
279
|
+
export function pathWithShims(shimDirectory, parentPath = process.env.PATH) {
|
|
280
|
+
return parentPath ? `${shimDirectory}${path.delimiter}${parentPath}` : shimDirectory;
|
|
281
|
+
}
|
|
282
|
+
/** Completion artifacts the Forge tool server writes under `.forge/<owner>/<id>/artifacts/`. */
|
|
283
|
+
const completionArtifactPath = /^\.forge\/[^/]+\/[^/]+\/artifacts\//u;
|
|
284
|
+
/**
|
|
285
|
+
* Records HEAD plus every tracked-modified, untracked or git-ignored path with a content hash
|
|
286
|
+
* (ignored files, which can hold `.env` or build output, use a size and mtime fingerprint). Comparing a
|
|
287
|
+
* before and an after snapshot catches commits, branch moves, edits and new files, including
|
|
288
|
+
* edits to files that were already dirty before the provider started (injected `.forge` files).
|
|
289
|
+
*/
|
|
290
|
+
export async function snapshotWorktree(git, worktreePath, options = {}) {
|
|
291
|
+
const head = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
292
|
+
const status = await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=traditional"]);
|
|
293
|
+
const ignored = (options.ignoredDirectories ?? []).map((directory) => path.resolve(directory));
|
|
294
|
+
const entries = new Map();
|
|
295
|
+
const fields = status.split("\0");
|
|
296
|
+
for (let index = 0; index < fields.length; index += 1) {
|
|
297
|
+
const field = fields[index];
|
|
298
|
+
if (!field)
|
|
299
|
+
continue;
|
|
300
|
+
const code = field.slice(0, 2);
|
|
301
|
+
const relativePath = field.slice(3);
|
|
302
|
+
// A rename or copy lists its source path as the next field.
|
|
303
|
+
const source = code.includes("R") || code.includes("C") ? fields[++index] ?? "" : "";
|
|
304
|
+
const absolutePath = path.resolve(worktreePath, relativePath);
|
|
305
|
+
if (completionArtifactPath.test(relativePath.replaceAll("\\", "/")))
|
|
306
|
+
continue;
|
|
307
|
+
if (ignored.some((directory) => absolutePath === directory || absolutePath.startsWith(`${directory}${path.sep}`))) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
// Dependency trees are installed before the session and are too large to fingerprint.
|
|
311
|
+
if (/(^|\/)node_modules(\/|$)/u.test(relativePath.replaceAll("\\", "/")))
|
|
312
|
+
continue;
|
|
313
|
+
const fingerprint = code === "!!" ? await statFingerprint(absolutePath) : await hashFile(absolutePath);
|
|
314
|
+
entries.set(relativePath, `${code}:${source}:${fingerprint}`);
|
|
315
|
+
}
|
|
316
|
+
return { head, entries };
|
|
317
|
+
}
|
|
318
|
+
async function statFingerprint(filePath) {
|
|
319
|
+
const stat = await fs.stat(filePath).catch(() => null);
|
|
320
|
+
return stat ? `${stat.size}:${Math.trunc(stat.mtimeMs)}` : "absent";
|
|
321
|
+
}
|
|
322
|
+
async function hashFile(filePath) {
|
|
323
|
+
const content = await fs.readFile(filePath).catch(() => null);
|
|
324
|
+
return content ? createHash("sha256").update(content).digest("hex") : "absent";
|
|
325
|
+
}
|
|
326
|
+
/** Throws `guardrail_violation` when the worktree differs from the pre-session snapshot. */
|
|
327
|
+
export async function assertWorktreeUnchanged(git, worktreePath, baseline, options = {}) {
|
|
328
|
+
const after = await snapshotWorktree(git, worktreePath, options);
|
|
329
|
+
const problems = [];
|
|
330
|
+
if (after.head.toLowerCase() !== baseline.head.toLowerCase()) {
|
|
331
|
+
problems.push(`HEAD moved from ${baseline.head} to ${after.head}`);
|
|
332
|
+
}
|
|
333
|
+
for (const [entryPath, fingerprint] of after.entries) {
|
|
334
|
+
if (baseline.entries.get(entryPath) !== fingerprint) {
|
|
335
|
+
problems.push(`${entryPath} was ${baseline.entries.has(entryPath) ? "changed" : "added or modified"}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
for (const entryPath of baseline.entries.keys()) {
|
|
339
|
+
if (!after.entries.has(entryPath)) {
|
|
340
|
+
problems.push(`${entryPath} was removed or reverted`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (problems.length > 0) {
|
|
344
|
+
const shown = problems.slice(0, 10).join("; ");
|
|
345
|
+
const more = problems.length > 10 ? `; and ${problems.length - 10} more` : "";
|
|
346
|
+
throw new ForgeFailureError(prReviewGuardrailViolationCode, `guardrail_violation: the review-only session left changes in the worktree (${shown}${more}). Forge discards the review and publishes nothing.`, "bridge");
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Codex's sandbox for a review-only session. On a host it is `read-only`. In the Docker sandbox it is
|
|
351
|
+
* `danger-full-access`, as for every other Docker lane: Codex's Linux sandbox needs kernel facilities
|
|
352
|
+
* (Landlock and seccomp filters, or bubblewrap's user namespaces) that the hardened container
|
|
353
|
+
* (`--cap-drop ALL`, `no-new-privileges`, read-only root, Docker's seccomp profile) does not reliably grant,
|
|
354
|
+
* and where it cannot start, every shell command fails and the review can only end blocked. The container
|
|
355
|
+
* (no git credential, no remote, no host home) is the isolation, and the review stays read-only through its
|
|
356
|
+
* guardrails: the git and gh shims, the worktree, ref and artifact checks, and no publication grant.
|
|
357
|
+
*/
|
|
358
|
+
export function codexReviewSandboxMode(executionMode) {
|
|
359
|
+
return executionMode === "docker" ? "danger-full-access" : "read-only";
|
|
360
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RunOnceDispatchPacket } from "../session.types.js";
|
|
2
|
+
import type { DispatchPrReviewThread } from "../session.types.pr-review.js";
|
|
3
|
+
/**
|
|
4
|
+
* The prior threads the prompt shows the reviewer, in dispatch order, each with its rendered block: at most 50,
|
|
5
|
+
* and after the first, only while the section budget lasts. The completion tool holds the reviewer to these.
|
|
6
|
+
*/
|
|
7
|
+
export declare function renderedPrReviewThreads(prReview: NonNullable<RunOnceDispatchPacket["prReview"]>): readonly {
|
|
8
|
+
readonly thread: DispatchPrReviewThread;
|
|
9
|
+
readonly block: readonly string[];
|
|
10
|
+
}[];
|
|
11
|
+
export declare function buildPrReviewPrompt(dispatch: RunOnceDispatchPacket, laneCommandBody: string, headSha: string): string;
|