The Open Framework for Building Agents
feat(self-modification): publish agent edits as draft pull requests (#2872)
prhab343096c3f26
diff --git a/packages/eve/src/self-modification/github-publisher.ts b/packages/eve/src/self-modification/github-publisher.tsnew file mode 100644index 000000000..0a045c60e--- /dev/null+++ b/packages/eve/src/self-modification/github-publisher.ts@@ -0,0 +1,373 @@+import { createHash } from "node:crypto";++import type { GitHubRepository } from "./config.js";+import type { GitHubCredentialProvider } from "./credentials.js";+import type { PreparedSelfModificationWorkspace } from "./git-workspace.js";+import { assertFullSha, assertGitRef, assertOperationId } from "./identifiers.js";+import {+ captureSelfModificationProposal,+ readProposalBlob,+ type SelfModificationProposal,+} from "./proposal.js";++const API = "https://api.github.com";+const TIMEOUT_MS = 30_000;+const DELETED_ENTRY_MODE = "100644";++export interface PublishedSelfModificationProposal {+ readonly changedPaths: readonly string[];+ readonly commitSha: string;+ readonly pullRequestUrl: string;+ readonly repository: string;+ readonly targetBranch: string;+ readonly branch: string;+ readonly draft: true;+ readonly merged: false;+ readonly deployed: false;+}++export interface GitHubDraftPublisherInput {+ readonly credentialProvider: GitHubCredentialProvider;+ readonly description: string;+ readonly fetch?: typeof fetch;+ /** Derived by the trusted parent/session lineage, never from model tool input. */+ readonly operationId: string;+ readonly sandbox: Parameters<typeof captureSelfModificationProposal>[0]["sandbox"];+ readonly title: string;+ readonly workspace: PreparedSelfModificationWorkspace;+}++/** Captures agent-only edits, then publishes one replay-safe draft pull request. */+export async function publishGitHubDraftPullRequest(+ input: GitHubDraftPublisherInput,+): Promise<PublishedSelfModificationProposal> {+ assertOperationId(input.operationId);+ validateText(input.title, "title", 256, false);+ validateText(input.description, "description", 65_536, true);+ const proposal = await captureSelfModificationProposal({+ sandbox: input.sandbox,+ workspace: input.workspace,+ });+ const branch = selfModificationBranchName(input.workspace.baseSha, input.operationId);+ // Deliberately after capture: a model can never obtain a publication credential by+ // submitting an invalid proposal.+ const token = await input.credentialProvider.resolve({+ capability: "publish",+ repository: repository(input.workspace),+ });+ if (token.trim().length === 0)+ throw new Error("Self-modification publication credential is empty.");+ const github = new GitHubClient(input.fetch ?? fetch, token.trim());+ await assertTargetAtBase(+ github,+ repository(input.workspace),+ input.workspace.targetBranch,+ proposal.baseSha,+ );+ const existing = await github.ref(repository(input.workspace), branch);+ if (existing !== null) return await reconcile(github, input, proposal, branch, existing);++ const commitSha = await upload(github, input, proposal);+ try {+ await github.createRef(repository(input.workspace), branch, commitSha);+ } catch (error) {+ const raced = await github.ref(repository(input.workspace), branch);+ if (raced === null) throw error;+ return await reconcile(github, input, proposal, branch, raced);+ }+ await assertTargetAtBase(+ github,+ repository(input.workspace),+ input.workspace.targetBranch,+ proposal.baseSha,+ );+ const pullRequest = await github.createPullRequest(+ repository(input.workspace),+ branch,+ input.workspace.targetBranch,+ input.title.trim(),+ body(input.description, proposal),+ );+ return receipt(input.workspace, proposal, branch, commitSha, pullRequest);+}++export function selfModificationBranchName(baseSha: string, operationId: string): string {+ assertFullSha(baseSha, "proposal base revision");+ assertOperationId(operationId);+ return `eve-self-modification/${baseSha.slice(0, 12)}/${createHash("sha256").update(operationId).digest("hex").slice(0, 24)}`;+}++async function reconcile(+ github: GitHubClient,+ input: GitHubDraftPublisherInput,+ proposal: SelfModificationProposal,+ branch: string,+ commitSha: string,+): Promise<PublishedSelfModificationProposal> {+ const commit = await github.commit(repository(input.workspace), commitSha);+ if (commit.parent !== proposal.baseSha)+ throw new Error("Self-modification operation conflict: existing branch has a different base.");+ if (commit.tree !== proposal.proposedTreeSha)+ throw new Error("Self-modification operation conflict: existing branch has different edits.");+ const pr = await github.pullRequest(+ repository(input.workspace),+ branch,+ input.workspace.targetBranch,+ );+ if (pr === null) {+ await assertTargetAtBase(+ github,+ repository(input.workspace),+ input.workspace.targetBranch,+ proposal.baseSha,+ );+ return receipt(+ input.workspace,+ proposal,+ branch,+ commitSha,+ await github.createPullRequest(+ repository(input.workspace),+ branch,+ input.workspace.targetBranch,+ input.title.trim(),+ body(input.description, proposal),+ ),+ );+ }+ if (!pr.draft)+ throw new Error("Self-modification operation conflict: its pull request is no longer a draft.");+ return receipt(input.workspace, proposal, branch, commitSha, pr);+}++async function upload(+ github: GitHubClient,+ input: GitHubDraftPublisherInput,+ proposal: SelfModificationProposal,+): Promise<string> {+ const entries = await Promise.all(+ proposal.changes.map(async (change) => {+ if (change.objectId === null)+ return { mode: DELETED_ENTRY_MODE, path: change.path, sha: null, type: "blob" as const };+ return {+ mode: change.mode!,+ path: change.path,+ sha: await github.blob(+ repository(input.workspace),+ await readProposalBlob({ change, sandbox: input.sandbox, workspace: input.workspace }),+ ),+ type: "blob" as const,+ };+ }),+ );+ const tree = await github.tree(repository(input.workspace), proposal.baseTreeSha, entries);+ if (tree !== proposal.proposedTreeSha)+ throw new Error("GitHub did not reassemble the validated proposal tree.");+ return await github.commitCreate(+ repository(input.workspace),+ proposal.baseSha,+ tree,+ `eve self-modification proposal\n\nOperation: ${createHash("sha256").update(input.operationId).digest("hex").slice(0, 24)}`,+ );+}++async function assertTargetAtBase(+ github: GitHubClient,+ repo: GitHubRepository,+ target: string,+ base: string,+): Promise<void> {+ assertGitRef(target);+ const ref = await github.ref(repo, target);+ if (ref === null)+ throw new Error(`Self-modification target branch ${JSON.stringify(target)} does not exist.`);+ if (ref !== base.toLowerCase())+ throw new Error(+ "Self-modification target branch changed while the proposal was being prepared.",+ );+}++function repository(workspace: PreparedSelfModificationWorkspace): GitHubRepository {+ return workspace.repository;+}++function receipt(+ workspace: PreparedSelfModificationWorkspace,+ proposal: SelfModificationProposal,+ branch: string,+ commitSha: string,+ pr: PullRequest,+): PublishedSelfModificationProposal {+ if (!pr.draft) throw new Error("GitHub did not create a draft self-modification pull request.");+ const repo = repository(workspace);+ return {+ branch,+ changedPaths: proposal.changes.map((change) => change.path),+ commitSha,+ deployed: false,+ draft: true,+ merged: false,+ pullRequestUrl: pr.url,+ repository: `github.com/${repo.owner}/${repo.repo}`,+ targetBranch: workspace.targetBranch,+ };+}++function body(description: string, proposal: SelfModificationProposal): string {+ return `${description}\n\n---\n\nThis is a draft proposal. Merge and deployment have not occurred.\n\n## Changed files\n${proposal.changes.map((change) => `- \`${change.path}\``).join("\n")}`;+}+function validateText(value: string, name: string, maximum: number, multiline: boolean): void {+ if (+ value.trim().length === 0 ||+ value.length > maximum ||+ (!multiline && /[\x00-\x1f\x7f]/u.test(value))+ )+ throw new Error(`Self-modification pull request ${name} is invalid.`);+}++interface PullRequest {+ readonly draft: boolean;+ readonly url: string;+}+class GitHubClient {+ readonly requestFetch: typeof fetch;+ readonly token: string;++ constructor(requestFetch: typeof fetch, token: string) {+ this.requestFetch = requestFetch;+ this.token = token;+ }+ async ref(repo: GitHubRepository, branch: string): Promise<string | null> {+ const value = await this.request(+ repo,+ "GET",+ `/git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`,+ undefined,+ true,+ );+ if (value === null || Array.isArray(value) || !record(value).object) return null;+ const sha = record(record(value).object).sha;+ if (typeof sha !== "string") throw new Error("GitHub returned an invalid ref.");+ assertFullSha(sha, "GitHub ref");+ return sha.toLowerCase();+ }+ async commit(repo: GitHubRepository, sha: string): Promise<{ parent: string; tree: string }> {+ const value = record(await this.request(repo, "GET", `/git/commits/${sha}`));+ const parents = value.parents;+ const tree = record(value.tree).sha;+ if (!Array.isArray(parents) || parents.length !== 1 || typeof tree !== "string")+ throw new Error("GitHub returned an invalid commit.");+ const parent = record(parents[0]).sha;+ if (typeof parent !== "string") throw new Error("GitHub returned an invalid commit.");+ assertFullSha(parent, "GitHub parent");+ assertFullSha(tree, "GitHub tree");+ return { parent: parent.toLowerCase(), tree: tree.toLowerCase() };+ }+ async blob(repo: GitHubRepository, content: string): Promise<string> {+ return this.sha(+ await this.request(repo, "POST", "/git/blobs", { content, encoding: "base64" }),+ );+ }+ async tree(repo: GitHubRepository, base: string, tree: unknown): Promise<string> {+ return this.sha(await this.request(repo, "POST", "/git/trees", { base_tree: base, tree }));+ }+ async commitCreate(+ repo: GitHubRepository,+ parent: string,+ tree: string,+ message: string,+ ): Promise<string> {+ return this.sha(+ await this.request(repo, "POST", "/git/commits", { message, parents: [parent], tree }),+ );+ }+ async createRef(repo: GitHubRepository, branch: string, sha: string): Promise<void> {+ await this.request(repo, "POST", "/git/refs", { ref: `refs/heads/${branch}`, sha });+ }+ async pullRequest(+ repo: GitHubRepository,+ branch: string,+ base: string,+ ): Promise<PullRequest | null> {+ // Do not filter by base: an operation-owned pull request retargeted elsewhere is+ // a conflict, not permission to create a second pull request from this branch.+ const query = new URLSearchParams({ head: `${repo.owner}:${branch}`, state: "all" });+ const values = await this.request(repo, "GET", `/pulls?${query}`);+ if (!Array.isArray(values)) throw new Error("GitHub returned an invalid pull request list.");+ return values[0] === undefined ? null : pullRequest(values[0], repo, branch, base);+ }+ async createPullRequest(+ repo: GitHubRepository,+ branch: string,+ base: string,+ title: string,+ body: string,+ ): Promise<PullRequest> {+ return pullRequest(+ await this.request(repo, "POST", "/pulls", { base, body, draft: true, head: branch, title }),+ repo,+ branch,+ base,+ );+ }+ private async sha(value: unknown): Promise<string> {+ const sha = record(value).sha;+ if (typeof sha !== "string") throw new Error("GitHub returned an invalid Git object.");+ assertFullSha(sha, "GitHub object");+ return sha.toLowerCase();+ }+ private async request(+ repo: GitHubRepository,+ method: string,+ path: string,+ body?: unknown,+ missing = false,+ ): Promise<unknown | null> {+ const headers: Record<string, string> = {+ accept: "application/vnd.github+json",+ authorization: `Bearer ${this.token}`,+ "user-agent": "eve-self-modification",+ "x-github-api-version": "2022-11-28",+ };+ if (body !== undefined) headers["content-type"] = "application/json";+ const response = await this.requestFetch(+ `${API}/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}${path}`,+ {+ body: body === undefined ? undefined : JSON.stringify(body),+ headers,+ method,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ },+ );+ if (missing && response.status === 404) return null;+ if (!response.ok)+ throw new Error(`GitHub ${method} ${path} failed with HTTP ${response.status}.`);+ return await response.json();+ }+}+function record(value: unknown): Record<string, unknown> {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ throw new Error("GitHub returned an invalid response.");+ return value as Record<string, unknown>;+}+function pullRequest(+ value: unknown,+ repo: GitHubRepository,+ branch: string,+ base: string,+): PullRequest {+ const result = record(value);+ const draft = result.draft;+ const state = result.state;+ const url = result.html_url;+ if (+ typeof draft !== "boolean" ||+ state !== "open" ||+ typeof url !== "string" ||+ record(result.head).ref !== branch ||+ record(result.base).ref !== base ||+ !url.startsWith(`https://github.com/${repo.owner}/${repo.repo}/pull/`)+ )+ throw new Error("GitHub returned an invalid pull request.");+ return { draft, url };+}diff --git a/packages/eve/src/self-modification/proposal.test.ts b/packages/eve/src/self-modification/proposal.test.tsnew file mode 100644index 000000000..dc9aed3d9--- /dev/null+++ b/packages/eve/src/self-modification/proposal.test.ts@@ -0,0 +1,203 @@+import { describe, expect, it } from "vitest";++import { publishGitHubDraftPullRequest, selfModificationBranchName } from "./github-publisher.js";+import { assertAllowedChange, parseRawDiff } from "./proposal.js";++describe("self-modification proposal capture", () => {+ it("parses only complete, safe raw Git diff records", () => {+ expect(+ parseRawDiff(`:100644 100644 ${"a".repeat(40)} ${"b".repeat(40)} M\0agent/instructions.md\0`),+ ).toEqual([+ {+ newMode: "100644",+ newObjectId: "b".repeat(40),+ path: "agent/instructions.md",+ status: "M",+ },+ ]);+ expect(() =>+ parseRawDiff(`:100644 100644 ${"a".repeat(40)} ${"b".repeat(40)} M\0../.env\0`),+ ).toThrow("malformed");+ });++ it("allows repository changes but protects publication controls and privileged paths", () => {+ expect(() =>+ assertAllowedChange({ mode: "100644", objectId: blob, path: "package.json" }, "."),+ ).not.toThrow();+ for (const path of [+ ".github/workflows/deploy.yml",+ ".env.production",+ ".envrc",+ ".turbo/cache/state.json",+ "node_modules/eve/index.js",+ "agent/subagents/self-modification/agent.ts",+ "agent/extensions/selfmod.ts",+ ]) {+ expect(() => assertAllowedChange({ mode: "100644", objectId: blob, path }, ".")).toThrow(+ "protected path",+ );+ }+ });++ it("derives a stable namespaced branch from trusted base and operation identifiers", () => {+ const branch = selfModificationBranchName("a".repeat(40), "parent-session:child-session");+ expect(branch).toMatch(/^eve-self-modification\/aaaaaaaaaaaa\/[a-f0-9]{24}$/u);+ expect(branch).toBe(selfModificationBranchName("a".repeat(40), "parent-session:child-session"));+ expect(() => selfModificationBranchName("a".repeat(40), "")).toThrow("operation id");+ });++ it("reports every changed path without registry provenance", async () => {+ const bodies: unknown[] = [];+ const result = await publish(successfulFetch(bodies));++ expect(result.changedPaths).toEqual(["agent/instructions.md"]);+ expect(JSON.stringify(bodies)).not.toContain("Registry items");+ });++ it("does not report a closed draft as a published proposal on retry", async () => {+ await expect(publish(closedDraftFetch())).rejects.toThrow("invalid pull request");+ });++ it("rechecks the target branch before creating the pull request", async () => {+ const calls: string[] = [];+ await expect(publish(targetMovesBeforePullRequestFetch(calls))).rejects.toThrow(+ "target branch changed",+ );+ expect(calls.filter((path) => path.endsWith("/git/ref/heads/main"))).toHaveLength(2);+ expect(calls).not.toContain("/repos/acme/agent/pulls");+ });++ it("rechecks the target branch before recovering a missing pull request", async () => {+ const calls: string[] = [];+ await expect(publish(targetMovesDuringReplayFetch(calls))).rejects.toThrow(+ "target branch changed",+ );+ expect(calls.filter((path) => path.endsWith("/git/ref/heads/main"))).toHaveLength(2);+ expect(calls.filter((path) => path === "/repos/acme/agent/pulls")).toHaveLength(1);+ });+});++const base = "a".repeat(40);+const baseTree = "b".repeat(40);+const proposedTree = "c".repeat(40);+const blob = "c1b0730e0133447badcfd47fd144e254807b06e1";++function publish(fetch: typeof globalThis.fetch) {+ return publishGitHubDraftPullRequest({+ credentialProvider: { resolve: async () => "token" },+ description: "Change the instructions.",+ fetch,+ operationId: "parent:child",+ sandbox: {+ run: async ({ command }) => {+ if (command.includes(" add -A")) return result("");+ if (command.includes("write-tree")) return result(proposedTree);+ if (command.includes("^{tree}")) return result(baseTree);+ if (command.includes("diff-tree"))+ return result(`:100644 100644 ${base} ${blob} M\0agent/instructions.md\0`);+ if (command.includes("cat-file -s")) return result("1");+ if (command.includes("cat-file blob")) return result("eA==");+ throw new Error(`Unexpected Git command: ${command}`);+ },+ },+ title: "Update instructions",+ workspace: {+ baseSha: base,+ directory: ".",+ repository: { owner: "acme", repo: "agent" },+ repositoryPath: "/workspace/repository",+ targetBranch: "main",+ },+ });+}++function successfulFetch(bodies: unknown[]): typeof globalThis.fetch {+ return (async (url, init) => {+ const request = new URL(String(url));+ const path = request.pathname;+ if (init?.body !== undefined) bodies.push(JSON.parse(String(init.body)));+ if (path === "/repos/acme/agent/git/ref/heads/main") return response({ object: { sha: base } });+ if (path.includes("eve-self-modification")) return response({}, 404);+ if (path === "/repos/acme/agent/git/blobs") return response({ sha: blob });+ if (path === "/repos/acme/agent/git/trees") return response({ sha: proposedTree });+ if (path === "/repos/acme/agent/git/commits") return response({ sha: "d".repeat(40) });+ if (path === "/repos/acme/agent/git/refs") return response({});+ if (path === "/repos/acme/agent/pulls") {+ const body = JSON.parse(String(init?.body));+ return response({+ base: { ref: body.base },+ draft: true,+ head: { ref: body.head },+ html_url: "https://github.com/acme/agent/pull/1",+ state: "open",+ });+ }+ throw new Error(`Unexpected GitHub request: ${path}`);+ }) as typeof globalThis.fetch;+}++function closedDraftFetch(): typeof globalThis.fetch {+ return (async (url) => {+ const request = new URL(String(url));+ const path = request.pathname;+ if (path === "/repos/acme/agent/git/ref/heads/main") return response({ object: { sha: base } });+ if (path.includes("eve-self-modification"))+ return response({ object: { sha: "d".repeat(40) } });+ if (path === `/repos/acme/agent/git/commits/${"d".repeat(40)}`)+ return response({ parents: [{ sha: base }], tree: { sha: proposedTree } });+ if (path === "/repos/acme/agent/pulls")+ return response([+ {+ base: { ref: "main" },+ draft: true,+ head: { ref: request.searchParams.get("head")!.split(":")[1] },+ html_url: "https://github.com/acme/agent/pull/1",+ state: "closed",+ },+ ]);+ throw new Error(`Unexpected GitHub request: ${path}`);+ }) as typeof globalThis.fetch;+}++function targetMovesBeforePullRequestFetch(calls: string[]): typeof globalThis.fetch {+ let targetReads = 0;+ return (async (url) => {+ const path = new URL(String(url)).pathname;+ calls.push(path);+ if (path === "/repos/acme/agent/git/ref/heads/main") {+ targetReads += 1;+ return response({ object: { sha: targetReads === 1 ? base : "e".repeat(40) } });+ }+ if (path.includes("eve-self-modification")) return response({}, 404);+ if (path === "/repos/acme/agent/git/blobs") return response({ sha: blob });+ if (path === "/repos/acme/agent/git/trees") return response({ sha: proposedTree });+ if (path === "/repos/acme/agent/git/commits") return response({ sha: "d".repeat(40) });+ if (path === "/repos/acme/agent/git/refs") return response({});+ throw new Error(`Unexpected GitHub request: ${path}`);+ }) as typeof globalThis.fetch;+}++function targetMovesDuringReplayFetch(calls: string[]): typeof globalThis.fetch {+ let targetReads = 0;+ return (async (url) => {+ const path = new URL(String(url)).pathname;+ calls.push(path);+ if (path === "/repos/acme/agent/git/ref/heads/main") {+ targetReads += 1;+ return response({ object: { sha: targetReads === 1 ? base : "e".repeat(40) } });+ }+ if (path.includes("eve-self-modification"))+ return response({ object: { sha: "d".repeat(40) } });+ if (path === `/repos/acme/agent/git/commits/${"d".repeat(40)}`)+ return response({ parents: [{ sha: base }], tree: { sha: proposedTree } });+ if (path === "/repos/acme/agent/pulls") return response([]);+ throw new Error(`Unexpected GitHub request: ${path}`);+ }) as typeof globalThis.fetch;+}++function response(value: unknown, status = 200): Response {+ return new Response(JSON.stringify(value), { status });+}+function result(stdout: string) {+ return { exitCode: 0, stderr: "", stdout };+}diff --git a/packages/eve/src/self-modification/proposal.ts b/packages/eve/src/self-modification/proposal.tsnew file mode 100644index 000000000..9c2be222a--- /dev/null+++ b/packages/eve/src/self-modification/proposal.ts@@ -0,0 +1,217 @@+import { createHash } from "node:crypto";++import type { SandboxSession } from "eve/sandbox";++import { shellQuote } from "#shared/shell-quote.js";++import type { PreparedSelfModificationWorkspace } from "./git-workspace.js";+import { gitOutput, runGitCommand } from "./git.js";+import { assertFullSha } from "./identifiers.js";++export const MAX_PROPOSAL_CHANGED_BYTES = 1_000_000;+export const MAX_PROPOSAL_CHANGED_FILES = 100;++export interface ProposalChange {+ readonly bytes: number;+ readonly kind: "add" | "delete" | "modify";+ readonly mode: "100644" | "100755" | null;+ readonly objectId: string | null;+ readonly path: string;+}++export interface SelfModificationProposal {+ readonly baseSha: string;+ readonly baseTreeSha: string;+ readonly changedBytes: number;+ readonly changes: readonly ProposalChange[];+ readonly proposedTreeSha: string;+}++type ProposalSandbox = Pick<SandboxSession, "run">;++/** Captures and validates the worktree before any publication credential is resolved. */+export async function captureSelfModificationProposal(input: {+ readonly sandbox: ProposalSandbox;+ readonly workspace: PreparedSelfModificationWorkspace;+}): Promise<SelfModificationProposal> {+ const repository = quote(input.workspace.repositoryPath);+ assertFullSha(input.workspace.baseSha, "proposal base revision");+ await runGitCommand(input.sandbox, `git -C ${repository} add -A -- .`);+ const proposedTreeSha = await gitOutput(input.sandbox, `git -C ${repository} write-tree`);+ const baseTreeSha = await gitOutput(+ input.sandbox,+ `git -C ${repository} rev-parse ${quote(`${input.workspace.baseSha}^{tree}`)}`,+ );+ assertFullSha(proposedTreeSha, "proposal tree");+ assertFullSha(baseTreeSha, "proposal base tree");+ const raw = await gitOutput(+ input.sandbox,+ `git -C ${repository} diff-tree -r --no-commit-id --raw -z --no-renames ${quote(input.workspace.baseSha)} ${quote(proposedTreeSha)}`,+ false,+ );+ const records = parseRawDiff(raw);+ if (records.length === 0) throw new Error("Self-modification proposal contains no changes.");+ if (records.length > MAX_PROPOSAL_CHANGED_FILES) {+ throw new Error(+ `Self-modification proposal changes ${records.length} files; limit is ${MAX_PROPOSAL_CHANGED_FILES}.`,+ );+ }++ const changes: ProposalChange[] = [];+ let changedBytes = 0;+ for (const record of records) {+ const mode = record.status === "D" ? null : proposalMode(record.newMode, record.path);+ const objectId = record.status === "D" ? null : record.newObjectId;+ assertAllowedChange({ mode, objectId, path: record.path }, input.workspace.directory);+ const bytes =+ objectId === null+ ? 0+ : await blobSize(input.sandbox, input.workspace.repositoryPath, objectId);+ changedBytes += bytes;+ if (changedBytes > MAX_PROPOSAL_CHANGED_BYTES) {+ throw new Error(+ `Self-modification proposal changes more than ${MAX_PROPOSAL_CHANGED_BYTES} bytes.`,+ );+ }+ changes.push({+ bytes,+ kind: record.status === "A" ? "add" : record.status === "D" ? "delete" : "modify",+ mode,+ objectId,+ path: record.path,+ });+ }+ return { baseSha: input.workspace.baseSha, baseTreeSha, changedBytes, changes, proposedTreeSha };+}++/** Reads an already captured blob and verifies its Git object id before upload. */+export async function readProposalBlob(input: {+ readonly change: ProposalChange;+ readonly sandbox: ProposalSandbox;+ readonly workspace: PreparedSelfModificationWorkspace;+}): Promise<string> {+ if (input.change.objectId === null) throw new Error("Cannot read a deleted proposal blob.");+ const base64 = await gitOutput(+ input.sandbox,+ `git -C ${quote(input.workspace.repositoryPath)} cat-file blob ${quote(input.change.objectId)} | base64 | tr -d '\\n'`,+ );+ const bytes = Buffer.from(base64, "base64");+ const objectId = createHash("sha1")+ .update(`blob ${bytes.byteLength}\0`)+ .update(bytes)+ .digest("hex");+ if (bytes.byteLength !== input.change.bytes || objectId !== input.change.objectId.toLowerCase()) {+ throw new Error(+ `Self-modification proposal blob changed after validation: ${JSON.stringify(input.change.path)}.`,+ );+ }+ return base64;+}++interface RawChange {+ readonly newMode: string;+ readonly newObjectId: string;+ readonly path: string;+ readonly status: "A" | "D" | "M";+}++export function parseRawDiff(raw: string): readonly RawChange[] {+ if (raw.length === 0) return [];+ const fields = raw.split("\0");+ if (fields.at(-1) === "") fields.pop();+ if (fields.length % 2 !== 0) throw new Error("Git returned malformed raw diff output.");+ const changes: RawChange[] = [];+ for (let index = 0; index < fields.length; index += 2) {+ const metadata = fields[index];+ const path = fields[index + 1];+ const match =+ metadata === undefined+ ? null+ : /^:[0-7]{6} ([0-7]{6}) [a-f0-9]{40} ([a-f0-9]{40}) ([ADM])$/u.exec(metadata);+ if (match === null || path === undefined || !isSafePath(path))+ throw new Error("Git returned malformed raw diff output.");+ changes.push({+ newMode: match[1]!,+ newObjectId: match[2]!,+ path,+ status: match[3]! as RawChange["status"],+ });+ }+ return changes;+}++export function assertAllowedChange(+ change: Pick<ProposalChange, "mode" | "objectId" | "path">,+ directory: string,+): void {+ const path = change.path;+ const appRoot = directory === "." ? "" : `${directory}/`;+ const agentRoot = `${appRoot}agent/`;+ const parts = path.split("/");+ const basename = parts.at(-1) ?? "";+ if (+ !isSafePath(path) ||+ parts.includes(".git") ||+ basename === ".env" ||+ basename === ".envrc" ||+ basename.startsWith(".env.") ||+ parts.some((part) =>+ [+ "node_modules",+ "dist",+ "build",+ ".next",+ ".output",+ ".turbo",+ ".vercel",+ "coverage",+ "out",+ ].includes(part),+ ) ||+ path.startsWith(".github/workflows/") ||+ path.startsWith(`${agentRoot}subagents/self-modification/`) ||+ path === `${appRoot}agent/extensions/selfmod.ts` ||+ path === `${appRoot}agent/self-modification.config.ts`+ ) {+ throw new Error(+ `Self-modification proposal changes a protected path: ${JSON.stringify(path)}.`,+ );+ }+}++function isSafePath(path: string): boolean {+ return (+ path.length > 0 &&+ !path.startsWith("/") &&+ !path.includes("\\") &&+ !path.includes("\n") &&+ !path.includes("\r") &&+ !path.split("/").some((part) => part === "" || part === "." || part === "..")+ );+}++function proposalMode(mode: string, path: string): "100644" | "100755" {+ if (mode === "100644" || mode === "100755") return mode;+ throw new Error(+ `Self-modification proposal uses unsafe Git mode ${mode}: ${JSON.stringify(path)}.`,+ );+}++async function blobSize(+ sandbox: ProposalSandbox,+ repository: string,+ objectId: string,+): Promise<number> {+ assertFullSha(objectId, "proposal blob");+ const size = await gitOutput(+ sandbox,+ `git -C ${quote(repository)} cat-file -s ${quote(objectId)}`,+ );+ if (!/^\d+$/u.test(size) || !Number.isSafeInteger(Number(size)))+ throw new Error("Git returned an invalid blob size.");+ return Number(size);+}++function quote(value: string): string {+ return shellQuote(value);+}