Add AgentGit M1: agent-native git layer over a Forgejo backend

AgentGit is a thin, DID-gated source-collaboration layer over a backend
forge (default Forgejo at git.profullstack.com, BBS-members-only) — not a
new git host. M1 implements the contract and engines:

- forge/adapter.ts: ForgeAdapter interface (only forge-specific surface)
- forge/forgejo.ts: ForgejoAdapter over Forgejo/Gitea REST v1 (injectable
  fetch, typed errors), incl. ensureUser for member provisioning
- access.ts: gateAccess DID membership gate (owner/role/visibility)
- merge-policy.ts: evaluateMergePolicy pure engine (reviews, reputation
  floor, checks, escrow, merge method, agent-merge toggle)
- service.ts: AgentGitService ties gate + policy to the adapter; refuses
  policy-failing merges; provisionMember hook for AgentBBS
- schemas: logicsrc-repo + logicsrc-pull-request, registered in
  @logicsrc/validators with fixtures
- docs/agentgit.md spec; plugin wired into root build (default/disabled)

27 vitest tests pass; full monorepo build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-06-14 12:45:38 +00:00
parent 14fe9d608f
commit bf046ae280
25 changed files with 1776 additions and 3 deletions

View file

@ -0,0 +1,128 @@
import type { CheckStatus, MergeMethod, ReviewDecision } from "../domain.js";
// Forge-shaped types: what a backend forge actually returns, before mapping to
// LogicSRC domain objects (reviewers are forge logins, not DIDs). The service
// layer resolves logins -> DIDs and reputation.
export interface ForgeRepo {
owner: string;
name: string;
defaultBranch: string;
cloneUrl: string;
htmlUrl: string;
private: boolean;
archived: boolean;
}
export interface ForgeBranch {
name: string;
commitSha: string;
}
export interface ForgeReview {
reviewerLogin: string;
decision: ReviewDecision;
body?: string;
submittedAt?: string;
}
export interface ForgeCheck {
name: string;
status: CheckStatus;
url?: string;
}
export interface ForgePullRequest {
number: number;
title: string;
body?: string;
authorLogin: string;
sourceBranch: string;
targetBranch: string;
headSha: string;
state: "open" | "closed";
merged: boolean;
reviews: ForgeReview[];
checks: ForgeCheck[];
createdAt?: string;
updatedAt?: string;
}
export interface CreateRepoInput {
owner: string;
name: string;
description?: string;
private: boolean;
defaultBranch?: string;
}
export interface CreateBranchInput {
owner: string;
repo: string;
newBranch: string;
fromBranch: string;
}
export interface OpenPullRequestInput {
owner: string;
repo: string;
title: string;
body?: string;
sourceBranch: string;
targetBranch: string;
}
export interface AddReviewInput {
owner: string;
repo: string;
number: number;
decision: ReviewDecision;
body?: string;
}
export interface MergePullRequestInput {
owner: string;
repo: string;
number: number;
method: MergeMethod;
}
export interface MergeResult {
merged: boolean;
mergeSha?: string;
}
export interface EnsureUserInput {
username: string;
email: string;
/** Initial password; accounts are provisioned with must-change-password. */
password: string;
fullName?: string;
}
export interface ForgeUser {
username: string;
email: string;
created: boolean;
}
/**
* Backend-forge contract. The only forge-specific surface in AgentGit —
* swapping Forgejo for GitHub or bare git is an implementation of this
* interface, not a change to the AgentGit contract.
*/
export interface ForgeAdapter {
ensureUser(input: EnsureUserInput): Promise<ForgeUser>;
createRepo(input: CreateRepoInput): Promise<ForgeRepo>;
getRepo(owner: string, repo: string): Promise<ForgeRepo>;
listRepos(owner: string): Promise<ForgeRepo[]>;
archiveRepo(owner: string, repo: string): Promise<ForgeRepo>;
createBranch(input: CreateBranchInput): Promise<ForgeBranch>;
listBranches(owner: string, repo: string): Promise<ForgeBranch[]>;
openPullRequest(input: OpenPullRequestInput): Promise<ForgePullRequest>;
getPullRequest(owner: string, repo: string, number: number): Promise<ForgePullRequest>;
listPullRequests(owner: string, repo: string, state?: "open" | "closed" | "all"): Promise<ForgePullRequest[]>;
addReview(input: AddReviewInput): Promise<ForgeReview>;
mergePullRequest(input: MergePullRequestInput): Promise<MergeResult>;
closePullRequest(owner: string, repo: string, number: number): Promise<ForgePullRequest>;
}

View file

@ -0,0 +1,106 @@
import { describe, expect, it, vi } from "vitest";
import { ForgejoAdapter, type FetchLike } from "./forgejo.js";
interface Call {
method: string;
path: string;
body?: unknown;
}
function makeFetch(routes: Record<string, { status?: number; json?: unknown }>): { fetch: FetchLike; calls: Call[] } {
const calls: Call[] = [];
const fetch: FetchLike = async (url, init) => {
const method = init?.method ?? "GET";
const path = url.replace("https://git.example.com/api/v1", "");
calls.push({ method, path, body: init?.body ? JSON.parse(init.body) : undefined });
const route = routes[`${method} ${path}`] ?? routes[path];
const status = route?.status ?? 200;
return {
ok: status >= 200 && status < 300,
status,
text: async () => (route?.json === undefined ? "" : JSON.stringify(route.json))
};
};
return { fetch, calls };
}
function adapterWith(routes: Record<string, { status?: number; json?: unknown }>) {
const { fetch, calls } = makeFetch(routes);
const adapter = new ForgejoAdapter({ baseUrl: "https://git.example.com", token: "t", fetch });
return { adapter, calls };
}
describe("ForgejoAdapter", () => {
it("creates a user only when missing", async () => {
const { adapter, calls } = adapterWith({
"GET /users/alice": { status: 404 },
"POST /admin/users": { json: { id: 1 } }
});
const result = await adapter.ensureUser({ username: "alice", email: "alice@x.com", password: "pw" });
expect(result.created).toBe(true);
expect(calls.map((c) => `${c.method} ${c.path}`)).toEqual(["GET /users/alice", "POST /admin/users"]);
const createBody = calls[1].body as Record<string, unknown>;
expect(createBody.must_change_password).toBe(true);
});
it("is a no-op when the user already exists", async () => {
const { adapter, calls } = adapterWith({ "GET /users/alice": { json: { id: 1 } } });
const result = await adapter.ensureUser({ username: "alice", email: "alice@x.com", password: "pw" });
expect(result.created).toBe(false);
expect(calls).toHaveLength(1);
});
it("creates a repo for a user via the admin endpoint", async () => {
const { adapter, calls } = adapterWith({
"POST /admin/users/alice/repos": {
json: { name: "demo", default_branch: "main", clone_url: "c", html_url: "h", private: true, owner: { login: "alice" } }
}
});
const repo = await adapter.createRepo({ owner: "alice", name: "demo", private: true });
expect(repo).toMatchObject({ owner: "alice", name: "demo", private: true });
expect((calls[0].body as Record<string, unknown>).auto_init).toBe(true);
});
it("assembles a pull request from pulls + reviews + status", async () => {
const { adapter } = adapterWith({
"GET /repos/alice/demo/pulls/7": {
json: {
number: 7,
title: "Add feature",
user: { login: "bob" },
head: { ref: "feature", sha: "abc1234" },
base: { ref: "main" },
state: "open",
merged: false
}
},
"GET /repos/alice/demo/pulls/7/reviews": {
json: [
{ state: "APPROVED", user: { login: "carol" } },
{ state: "PENDING", user: { login: "dave" } }
]
},
"GET /repos/alice/demo/commits/abc1234/status": {
json: { statuses: [{ context: "ci", status: "success", target_url: "u" }] }
}
});
const pr = await adapter.getPullRequest("alice", "demo", 7);
expect(pr.number).toBe(7);
expect(pr.authorLogin).toBe("bob");
expect(pr.reviews).toEqual([{ reviewerLogin: "carol", decision: "approve", body: undefined, submittedAt: undefined }]);
expect(pr.checks).toEqual([{ name: "ci", status: "passing", url: "u" }]);
});
it("throws a typed error on non-2xx", async () => {
const { adapter } = adapterWith({ "GET /repos/alice/demo": { status: 500, json: { message: "boom" } } });
await expect(adapter.getRepo("alice", "demo")).rejects.toThrow(/Forgejo GET .* 500/);
});
it("uses the injected fetch, never a real network", async () => {
const fetch = vi.fn<FetchLike>(async () => ({ ok: true, status: 200, text: async () => "[]" }));
const adapter = new ForgejoAdapter({ baseUrl: "https://git.example.com/", token: "t", fetch });
await adapter.listBranches("alice", "demo");
expect(fetch).toHaveBeenCalledOnce();
});
});

View file

@ -0,0 +1,300 @@
import type { CheckStatus, MergeMethod, ReviewDecision } from "../domain.js";
import type {
AddReviewInput,
CreateBranchInput,
CreateRepoInput,
EnsureUserInput,
ForgeAdapter,
ForgeBranch,
ForgePullRequest,
ForgeRepo,
ForgeReview,
ForgeUser,
MergePullRequestInput,
MergeResult,
OpenPullRequestInput
} from "./adapter.js";
export type FetchLike = (
input: string,
init?: {
method?: string;
headers?: Record<string, string>;
body?: string;
}
) => Promise<{
ok: boolean;
status: number;
text(): Promise<string>;
}>;
export interface ForgejoAdapterOptions {
/** Base URL of the Forgejo instance, e.g. https://git.profullstack.com */
baseUrl: string;
/** Admin/personal access token used for server-side operations. */
token: string;
fetch?: FetchLike;
}
export class ForgejoApiError extends Error {
constructor(
readonly status: number,
readonly method: string,
readonly path: string,
body: string
) {
super(`Forgejo ${method} ${path} -> ${status}: ${body.slice(0, 300)}`);
this.name = "ForgejoApiError";
}
}
const REVIEW_EVENT: Record<ReviewDecision, string> = {
approve: "APPROVED",
request_changes: "REQUEST_CHANGES",
comment: "COMMENT"
};
const MERGE_DO: Record<MergeMethod, string> = {
merge: "merge",
squash: "squash",
rebase: "rebase"
};
/** Maps a Forgejo combined-status state to our check status vocabulary. */
function mapCheckStatus(state: string): CheckStatus {
switch (state) {
case "success":
return "passing";
case "pending":
return "pending";
default:
// failure, error, warning
return "failing";
}
}
function mapReviewDecision(state: string): ReviewDecision {
switch (state) {
case "APPROVED":
return "approve";
case "REQUEST_CHANGES":
return "request_changes";
default:
return "comment";
}
}
/** Forgejo / Gitea REST API (v1) implementation of the ForgeAdapter. */
export class ForgejoAdapter implements ForgeAdapter {
private readonly baseUrl: string;
private readonly token: string;
private readonly fetchImpl: FetchLike;
constructor(options: ForgejoAdapterOptions) {
this.baseUrl = options.baseUrl.replace(/\/+$/, "");
this.token = options.token;
const injected = options.fetch;
if (injected) {
this.fetchImpl = injected;
} else if (typeof globalThis.fetch === "function") {
this.fetchImpl = globalThis.fetch.bind(globalThis) as unknown as FetchLike;
} else {
throw new Error("No fetch implementation available; pass options.fetch");
}
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const response = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
method,
headers: {
Authorization: `token ${this.token}`,
Accept: "application/json",
...(body === undefined ? {} : { "Content-Type": "application/json" })
},
body: body === undefined ? undefined : JSON.stringify(body)
});
const text = await response.text();
if (!response.ok) {
throw new ForgejoApiError(response.status, method, path, text);
}
return (text ? JSON.parse(text) : undefined) as T;
}
private mapRepo(raw: Record<string, unknown>): ForgeRepo {
const owner = (raw.owner as Record<string, unknown> | undefined)?.login as string;
return {
owner,
name: raw.name as string,
defaultBranch: (raw.default_branch as string) ?? "main",
cloneUrl: raw.clone_url as string,
htmlUrl: raw.html_url as string,
private: Boolean(raw.private),
archived: Boolean(raw.archived)
};
}
async ensureUser(input: EnsureUserInput): Promise<ForgeUser> {
try {
await this.request<unknown>("GET", `/users/${encodeURIComponent(input.username)}`);
return { username: input.username, email: input.email, created: false };
} catch (error) {
if (!(error instanceof ForgejoApiError) || error.status !== 404) {
throw error;
}
}
await this.request<unknown>("POST", "/admin/users", {
username: input.username,
email: input.email,
password: input.password,
full_name: input.fullName,
must_change_password: true
});
return { username: input.username, email: input.email, created: true };
}
async createRepo(input: CreateRepoInput): Promise<ForgeRepo> {
const raw = await this.request<Record<string, unknown>>("POST", `/admin/users/${encodeURIComponent(input.owner)}/repos`, {
name: input.name,
description: input.description,
private: input.private,
default_branch: input.defaultBranch ?? "main",
auto_init: true
});
return this.mapRepo(raw);
}
async getRepo(owner: string, repo: string): Promise<ForgeRepo> {
const raw = await this.request<Record<string, unknown>>("GET", `/repos/${owner}/${repo}`);
return this.mapRepo(raw);
}
async listRepos(owner: string): Promise<ForgeRepo[]> {
const raw = await this.request<Array<Record<string, unknown>>>("GET", `/users/${encodeURIComponent(owner)}/repos`);
return raw.map((entry) => this.mapRepo(entry));
}
async archiveRepo(owner: string, repo: string): Promise<ForgeRepo> {
const raw = await this.request<Record<string, unknown>>("PATCH", `/repos/${owner}/${repo}`, { archived: true });
return this.mapRepo(raw);
}
async createBranch(input: CreateBranchInput): Promise<ForgeBranch> {
const raw = await this.request<Record<string, unknown>>("POST", `/repos/${input.owner}/${input.repo}/branches`, {
new_branch_name: input.newBranch,
old_branch_name: input.fromBranch
});
return {
name: raw.name as string,
commitSha: ((raw.commit as Record<string, unknown> | undefined)?.id as string) ?? ""
};
}
async listBranches(owner: string, repo: string): Promise<ForgeBranch[]> {
const raw = await this.request<Array<Record<string, unknown>>>("GET", `/repos/${owner}/${repo}/branches`);
return raw.map((entry) => ({
name: entry.name as string,
commitSha: ((entry.commit as Record<string, unknown> | undefined)?.id as string) ?? ""
}));
}
private async fetchReviews(owner: string, repo: string, number: number): Promise<ForgeReview[]> {
const raw = await this.request<Array<Record<string, unknown>>>("GET", `/repos/${owner}/${repo}/pulls/${number}/reviews`);
return raw
.filter((entry) => entry.state !== "PENDING")
.map((entry) => ({
reviewerLogin: (entry.user as Record<string, unknown> | undefined)?.login as string,
decision: mapReviewDecision(entry.state as string),
body: entry.body as string | undefined,
submittedAt: entry.submitted_at as string | undefined
}));
}
private async fetchChecks(owner: string, repo: string, sha: string): Promise<ForgePullRequest["checks"]> {
if (!sha) {
return [];
}
const raw = await this.request<{ statuses?: Array<Record<string, unknown>> }>(
"GET",
`/repos/${owner}/${repo}/commits/${sha}/status`
);
return (raw.statuses ?? []).map((entry) => ({
name: (entry.context as string) ?? "status",
status: mapCheckStatus(entry.status as string),
url: entry.target_url as string | undefined
}));
}
private async mapPullRequest(owner: string, repo: string, raw: Record<string, unknown>): Promise<ForgePullRequest> {
const number = raw.number as number;
const headSha = ((raw.head as Record<string, unknown> | undefined)?.sha as string) ?? "";
const [reviews, checks] = await Promise.all([
this.fetchReviews(owner, repo, number),
this.fetchChecks(owner, repo, headSha)
]);
return {
number,
title: raw.title as string,
body: raw.body as string | undefined,
authorLogin: (raw.user as Record<string, unknown> | undefined)?.login as string,
sourceBranch: (raw.head as Record<string, unknown> | undefined)?.ref as string,
targetBranch: (raw.base as Record<string, unknown> | undefined)?.ref as string,
headSha,
state: (raw.state as "open" | "closed") ?? "open",
merged: Boolean(raw.merged),
reviews,
checks,
createdAt: raw.created_at as string | undefined,
updatedAt: raw.updated_at as string | undefined
};
}
async openPullRequest(input: OpenPullRequestInput): Promise<ForgePullRequest> {
const raw = await this.request<Record<string, unknown>>("POST", `/repos/${input.owner}/${input.repo}/pulls`, {
title: input.title,
body: input.body,
head: input.sourceBranch,
base: input.targetBranch
});
return this.mapPullRequest(input.owner, input.repo, raw);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<ForgePullRequest> {
const raw = await this.request<Record<string, unknown>>("GET", `/repos/${owner}/${repo}/pulls/${number}`);
return this.mapPullRequest(owner, repo, raw);
}
async listPullRequests(owner: string, repo: string, state: "open" | "closed" | "all" = "open"): Promise<ForgePullRequest[]> {
const raw = await this.request<Array<Record<string, unknown>>>("GET", `/repos/${owner}/${repo}/pulls?state=${state}`);
return Promise.all(raw.map((entry) => this.mapPullRequest(owner, repo, entry)));
}
async addReview(input: AddReviewInput): Promise<ForgeReview> {
const raw = await this.request<Record<string, unknown>>("POST", `/repos/${input.owner}/${input.repo}/pulls/${input.number}/reviews`, {
event: REVIEW_EVENT[input.decision],
body: input.body
});
return {
reviewerLogin: (raw.user as Record<string, unknown> | undefined)?.login as string,
decision: input.decision,
body: input.body,
submittedAt: raw.submitted_at as string | undefined
};
}
async mergePullRequest(input: MergePullRequestInput): Promise<MergeResult> {
await this.request<unknown>("POST", `/repos/${input.owner}/${input.repo}/pulls/${input.number}/merge`, {
Do: MERGE_DO[input.method]
});
const merged = await this.getPullRequest(input.owner, input.repo, input.number);
return { merged: merged.merged, mergeSha: merged.headSha };
}
async closePullRequest(owner: string, repo: string, number: number): Promise<ForgePullRequest> {
const raw = await this.request<Record<string, unknown>>("PATCH", `/repos/${owner}/${repo}/pulls/${number}`, {
state: "closed"
});
return this.mapPullRequest(owner, repo, raw);
}
}