Skip to content

An open-source, faster Devin alternative

TypeScript

Work index: GitHub client, projection and Durable Object (work tracking 3.6)

Igor Zalutski via Computer18bb6f2a0232
diff --git a/services/managed-agents/src/computer/work/github.ts b/services/managed-agents/src/computer/work/github.ts
new file mode 100644
index 00000000..0007e9b1
--- /dev/null
+++ b/services/managed-agents/src/computer/work/github.ts
@@ -0,0 +1,399 @@
+// The Work index's GitHub client (tech design 3.6, "GitHub access"): the few REST calls an advance,
+// a build and the history need, and one GraphQL query for pull request state.
+//
+// - Tokens come from the Account object's `mintGitHubInstallationToken`. Contents are read with a
+// token narrowed to the knowledge repository and `contents: read`; pull request state, which
+// lives in other repositories, with `pull_requests: read` across the installation. Each is held
+// in memory until five minutes before it expires.
+// - Quota: the installation's limit is shared with the organization's agents. Every response's
+// rate-limit headers are kept per resource (`core`, `graphql`); `spare()` is false under a fifth
+// of the limit, and background work stops. A 403 or 429 with `retry-after` (or no requests
+// left) is a pause (`GitHubPaused`), not an error: nothing more is asked until it ends.
+// - Permanent failures (installation removed, repository deleted or no longer granted, branch
+// gone, a permission the installation lacks) are `GitHubGone` with the problem the screens show.
+
+import type { GitHubTokenMint } from "../../protocol.js";
+
+const GITHUB_API = "https://api.github.com";
+const GITHUB_API_VERSION = "2026-03-10";
+const USER_AGENT = "opencomputer-managed-agents";
+/** A token is minted again this long before it expires. */
+const TOKEN_MARGIN_MS = 5 * 60_000;
+/** Background work stops under this share of the limit remaining. */
+const SPARE_SHARE = 0.2;
+const DEFAULT_PAUSE_MS = 60_000;
+const MAX_PAUSE_MS = 60 * 60_000;
+
+/** Why the repository cannot be read; shown as `repository.problem`. */
+export type RepositoryProblem =
+ | "installation_removed"
+ | "installation_suspended"
+ | "repository_not_found"
+ | "branch_not_found"
+ | "access_denied"
+ | "github_app_not_configured";
+
+/** A permanent failure: the repository setting needs a person. */
+export class GitHubGone extends Error {
+ constructor(readonly problem: RepositoryProblem, message: string = problem) {
+ super(message);
+ }
+}
+
+/** GitHub asked us to wait (rate limit or abuse limit); retry after `until`. */
+export class GitHubPaused extends Error {
+ constructor(readonly until: number) {
+ super(`GitHub paused requests until ${new Date(until).toISOString()}`);
+ }
+}
+
+/** A temporary failure: GitHub unreachable, 5xx, a malformed answer. */
+export class GitHubUnavailable extends Error {}
+
+/** What the client needs of the Account object. */
+export interface TokenMinter {
+ mintGitHubInstallationToken(input: {
+ installationId: string;
+ permissions?: Record<string, "read" | "write">;
+ repositories?: string[];
+ }): Promise<GitHubTokenMint>;
+}
+
+export interface WorkRepo {
+ installationId: string;
+ owner: string;
+ name: string;
+ branch: string;
+}
+
+export interface CommitInfo {
+ sha: string;
+ message: string;
+ authorName: string;
+ authorEmail: string | null;
+ /** The author date, ISO. */
+ at: string;
+}
+
+export interface FileChange {
+ filename: string;
+ status: "added" | "removed" | "modified" | "renamed" | "copied" | "changed" | "unchanged";
+ previousFilename: string | null;
+ /** The blob sha at the head side (absent for a removal). */
+ sha: string | null;
+}
+
+export interface Comparison {
+ status: "ahead" | "behind" | "diverged" | "identical";
+ totalCommits: number;
+ commits: CommitInfo[];
+ files: FileChange[];
+}
+
+export interface TreeEntry {
+ name: string;
+ type: "blob" | "tree" | "commit";
+ sha: string;
+}
+
+export type PullState = "open" | "draft" | "merged" | "closed";
+
+interface Quota {
+ limit: number;
+ remaining: number;
+ /** ms epoch. */
+ reset: number;
+}
+
+interface HeldToken {
+ token: string;
+ expiresAt: number;
+}
+
+export interface WorkGitHubOptions {
+ repo: WorkRepo;
+ account: TokenMinter;
+ fetch?: typeof fetch;
+ now?: () => number;
+}
+
+/** One knowledge repository's GitHub access. */
+export class WorkGitHub {
+ readonly repo: WorkRepo;
+ private readonly account: TokenMinter;
+ private readonly fetcher: typeof fetch;
+ private readonly now: () => number;
+ private readonly tokens = new Map<"contents" | "pulls", HeldToken>();
+ private readonly quota = new Map<string, Quota>();
+ private pausedUntil = 0;
+ /** Calls made, for tests and telemetry. */
+ calls = 0;
+
+ constructor(options: WorkGitHubOptions) {
+ this.repo = options.repo;
+ this.account = options.account;
+ this.fetcher = options.fetch ?? ((input, init) => fetch(input, init));
+ this.now = options.now ?? Date.now;
+ }
+
+ /** Until when GitHub asked us to wait; 0 when it did not. */
+ paused(): number {
+ return this.pausedUntil > this.now() ? this.pausedUntil : 0;
+ }
+
+ /** Whether background work may spend quota: not paused, and more than a fifth of the limit left. */
+ spare(resource: "core" | "graphql" = "core"): boolean {
+ if (this.paused()) return false;
+ const q = this.quota.get(resource);
+ if (!q || q.reset <= this.now()) return true;
+ return q.remaining >= q.limit * SPARE_SHARE;
+ }
+
+ // ---------------------------------------------------------------- tokens
+
+ private async token(kind: "contents" | "pulls"): Promise<string> {
+ const held = this.tokens.get(kind);
+ if (held && held.expiresAt - TOKEN_MARGIN_MS > this.now()) return held.token;
+ const minted = await this.account.mintGitHubInstallationToken({
+ installationId: this.repo.installationId,
+ ...(kind === "contents"
+ ? { permissions: { contents: "read" }, repositories: [this.repo.name] }
+ : { permissions: { pull_requests: "read" } }),
+ });
+ if (minted.outcome === "not_connected") throw new GitHubGone("installation_removed", "The GitHub connection is gone.");
+ if (minted.outcome === "app_not_configured") throw new GitHubGone("github_app_not_configured", "The GitHub App is not configured.");
+ if (minted.outcome === "failed") {
+ if (minted.code === "installation_not_found") throw new GitHubGone("installation_removed", minted.message);
+ if (minted.code === "installation_suspended") throw new GitHubGone("installation_suspended", minted.message);
+ // A narrowed mint for a repository the installation no longer grants is refused with 422.
+ if (minted.code === "github_permission_missing") throw new GitHubGone(kind === "contents" ? "repository_not_found" : "access_denied", minted.message);
+ if (minted.code === "mint_rate_limited") throw this.pause((minted.retryAfterSeconds ?? 60) * 1000);
+ throw new GitHubUnavailable(minted.message);
+ }
+ const expiresAt = Date.parse(minted.expiresAt);
+ this.tokens.set(kind, { token: minted.token, expiresAt: Number.isFinite(expiresAt) ? expiresAt : this.now() + 30 * 60_000 });
+ return minted.token;
+ }
+
+ private pause(ms: number): GitHubPaused {
+ this.pausedUntil = Math.max(this.pausedUntil, this.now() + Math.min(Math.max(ms, 1000), MAX_PAUSE_MS));
+ return new GitHubPaused(this.pausedUntil);
+ }
+
+ // ---------------------------------------------------------------- transport
+
+ /**
+ * One request. Answers 2xx, 304 and 404 to the caller; a rate limit is a pause, 401 drops the
+ * token, other 403s are `access_denied`, the rest temporary.
+ */
+ private async request(
+ path: string,
+ init: { kind?: "contents" | "pulls"; accept?: string; etag?: string; method?: string; body?: unknown } = {},
+ ): Promise<Response> {
+ const paused = this.paused();
+ if (paused) throw new GitHubPaused(paused);
+ const kind = init.kind ?? "contents";
+ const token = await this.token(kind);
+ const headers: Record<string, string> = {
+ authorization: `Bearer ${token}`,
+ accept: init.accept ?? "application/vnd.github+json",
+ "user-agent": USER_AGENT,
+ "x-github-api-version": GITHUB_API_VERSION,
+ };
+ if (init.etag) headers["if-none-match"] = init.etag;
+ if (init.body !== undefined) headers["content-type"] = "application/json";
+ let response: Response;
+ this.calls += 1;
+ try {
+ response = await this.fetcher(`${GITHUB_API}${path}`, {
+ method: init.method ?? "GET",
+ headers,
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ });
+ } catch {
+ throw new GitHubUnavailable("GitHub is unreachable.");
+ }
+ this.noteQuota(response);
+ if (response.ok || response.status === 304 || response.status === 404) return response;
+ const retryAfter = Number.parseInt(response.headers.get("retry-after") ?? "", 10);
+ const limited = response.headers.get("x-ratelimit-remaining") === "0";
+ if (response.status === 429 || (response.status === 403 && (Number.isFinite(retryAfter) || limited))) {
+ if (Number.isFinite(retryAfter)) throw this.pause(retryAfter * 1000);
+ const reset = Number.parseInt(response.headers.get("x-ratelimit-reset") ?? "", 10);
+ throw this.pause(Number.isFinite(reset) ? reset * 1000 - this.now() : DEFAULT_PAUSE_MS);
+ }
+ if (response.status === 401) {
+ this.tokens.delete(kind);
+ throw new GitHubUnavailable("GitHub refused the token.");
+ }
+ if (response.status === 403) throw new GitHubGone("access_denied", "GitHub refused access to the repository.");
+ throw new GitHubUnavailable(`GitHub answered ${response.status}.`);
+ }
+
+ private noteQuota(response: Response): void {
+ const limit = Number.parseInt(response.headers.get("x-ratelimit-limit") ?? "", 10);
+ const remaining = Number.parseInt(response.headers.get("x-ratelimit-remaining") ?? "", 10);
+ const reset = Number.parseInt(response.headers.get("x-ratelimit-reset") ?? "", 10);
+ if (!Number.isFinite(limit) || !Number.isFinite(remaining)) return;
+ const resource = response.headers.get("x-ratelimit-resource") ?? "core";
+ this.quota.set(resource, { limit, remaining, reset: Number.isFinite(reset) ? reset * 1000 : this.now() + 3_600_000 });
+ }
+
+ private async json<T>(response: Response): Promise<T> {
+ try {
+ return (await response.json()) as T;
+ } catch {
+ throw new GitHubUnavailable("GitHub returned a malformed response.");
+ }
+ }
+
+ private repoPath(rest: string): string {
+ return `/repos/${encodeURIComponent(this.repo.owner)}/${encodeURIComponent(this.repo.name)}${rest}`;
+ }
+
+ /** A 404 on the repository's resources: the repository itself, or only the thing asked for. */
+ private async gone(): Promise<GitHubGone> {
+ const response = await this.request(this.repoPath(""));
+ if (response.status === 404) return new GitHubGone("repository_not_found", "The repository is gone or no longer granted.");
+ return new GitHubGone("branch_not_found", `The branch ${this.repo.branch} is gone.`);
+ }
+
+ // ---------------------------------------------------------------- calls
+
+ /** The repository as GitHub names it, and its default branch (setRepository's check). */
+ async repository(): Promise<{ owner: string; name: string; defaultBranch: string }> {
+ const response = await this.request(this.repoPath(""));
+ if (response.status === 404) throw new GitHubGone("repository_not_found", "The repository is gone or no longer granted.");
+ const body = await this.json<{ name?: unknown; owner?: { login?: unknown }; default_branch?: unknown }>(response);
+ if (typeof body.name !== "string" || typeof body.owner?.login !== "string") throw new GitHubUnavailable("GitHub returned an invalid repository.");
+ return { owner: body.owner.login, name: body.name, defaultBranch: typeof body.default_branch === "string" ? body.default_branch : "main" };
+ }
+
+ /** The branch's head commit; "unchanged" when `etag` still matches (a 304 costs no quota). */
+ async head(etag?: string): Promise<{ sha: string; etag: string | null } | "unchanged"> {
+ const response = await this.request(this.repoPath(`/git/ref/heads/${this.repo.branch.split("/").map(encodeURIComponent).join("/")}`), etag ? { etag } : {});
+ if (response.status === 304) return "unchanged";
+ if (response.status === 404) throw await this.gone();
+ const body = await this.json<{ object?: { sha?: unknown; type?: unknown } }>(response);
+ if (typeof body.object?.sha !== "string") throw new GitHubUnavailable("GitHub returned an invalid ref.");
+ return { sha: body.object.sha, etag: response.headers.get("etag") };
+ }
+
+ /** `base...head`; null when GitHub no longer knows `base` (a rewritten history). */
+ async compare(base: string, head: string): Promise<Comparison | null> {
+ const response = await this.request(this.repoPath(`/compare/${base}...${head}?per_page=250`));
+ if (response.status === 404) return null;
+ const body = await this.json<{ status?: unknown; total_commits?: unknown; commits?: unknown; files?: unknown }>(response);
+ const status = body.status;
+ if (status !== "ahead" && status !== "behind" && status !== "diverged" && status !== "identical") throw new GitHubUnavailable("GitHub returned an invalid comparison.");
+ return {
+ status,
+ totalCommits: typeof body.total_commits === "number" ? body.total_commits : 0,
+ commits: Array.isArray(body.commits) ? body.commits.map(commitOf).filter((c): c is CommitInfo => c !== null) : [],
+ files: Array.isArray(body.files) ? body.files.map(fileOf).filter((f): f is FileChange => f !== null) : [],
+ };
+ }
+
+ /** One commit with its files. */
+ async commit(sha: string): Promise<CommitInfo & { files: FileChange[] }> {
+ const response = await this.request(this.repoPath(`/commits/${sha}`));
+ if (response.status === 404) throw new GitHubUnavailable(`GitHub has no commit ${sha}.`);
+ const body = await this.json<{ files?: unknown }>(response);
+ const commit = commitOf(body);
+ if (!commit) throw new GitHubUnavailable("GitHub returned an invalid commit.");
+ return { ...commit, files: Array.isArray(body.files) ? body.files.map(fileOf).filter((f): f is FileChange => f !== null) : [] };
+ }
+
+ /** A tree's entries, not recursive; null when there is no such tree. */
+ async tree(sha: string): Promise<{ entries: TreeEntry[]; truncated: boolean } | null> {
+ const response = await this.request(this.repoPath(`/git/trees/${sha}`));
+ if (response.status === 404) return null;
+ const body = await this.json<{ tree?: unknown; truncated?: unknown }>(response);
+ const entries: TreeEntry[] = [];
+ for (const raw of Array.isArray(body.tree) ? body.tree : []) {
+ const e = raw as { path?: unknown; type?: unknown; sha?: unknown };
+ if (typeof e.path === "string" && typeof e.sha === "string" && (e.type === "blob" || e.type === "tree" || e.type === "commit")) {
+ entries.push({ name: e.path, type: e.type, sha: e.sha });
+ }
+ }
+ return { entries, truncated: body.truncated === true };
+ }
+
+ /** A blob's text (UTF-8). */
+ async blob(sha: string): Promise<string> {
+ const response = await this.request(this.repoPath(`/git/blobs/${sha}`));
+ if (response.status === 404) throw new GitHubUnavailable(`GitHub has no blob ${sha}.`);
+ const body = await this.json<{ content?: unknown; encoding?: unknown }>(response);
+ if (typeof body.content !== "string") throw new GitHubUnavailable("GitHub returned an invalid blob.");
+ if (body.encoding !== "base64") return body.content;
+ const bytes = Uint8Array.from(atob(body.content.replace(/\s/g, "")), (c) => c.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+ }
+
+ /** Commits that touched `path` (a file or a directory), newest first, from `sha`. */
+ async commits(input: { sha: string; path: string; page: number; perPage: number }): Promise<CommitInfo[]> {
+ const query = new URLSearchParams({ sha: input.sha, path: input.path, per_page: String(input.perPage), page: String(input.page) });
+ const response = await this.request(this.repoPath(`/commits?${query}`));
+ if (response.status === 404) return [];
+ const body = await this.json<unknown>(response);
+ return Array.isArray(body) ? body.map(commitOf).filter((c): c is CommitInfo => c !== null) : [];
+ }
+
+ /**
+ * Pull request state for GitHub pull request URLs, in one GraphQL query (at most 50 per call).
+ * A URL the installation cannot read is `unreadable`; a URL that is not a GitHub pull request is
+ * left out.
+ */
+ async pulls(urls: string[]): Promise<Map<string, { state: PullState; title: string } | "unreadable">> {
+ const out = new Map<string, { state: PullState; title: string } | "unreadable">();
+ const targets = urls.map((url) => ({ url, pr: pullOf(url) })).filter((t): t is { url: string; pr: { owner: string; name: string; number: number } } => t.pr !== null);
+ if (!targets.length) return out;
+ const fields = targets.map(
+ (t, i) => `p${i}: repository(owner: ${JSON.stringify(t.pr.owner)}, name: ${JSON.stringify(t.pr.name)}) { pullRequest(number: ${t.pr.number}) { state isDraft title } }`,
+ );
+ const response = await this.request("/graphql", { kind: "pulls", method: "POST", body: { query: `query {\n${fields.join("\n")}\n}` } });
+ if (response.status === 404) throw new GitHubUnavailable("GitHub has no GraphQL endpoint.");
+ const body = await this.json<{ data?: Record<string, { pullRequest?: { state?: unknown; isDraft?: unknown; title?: unknown } | null } | null> | null; errors?: unknown }>(response);
+ if (!body.data && body.errors) throw new GitHubUnavailable("GitHub refused the pull request query.");
+ targets.forEach((t, i) => {
+ const pr = body.data?.[`p${i}`]?.pullRequest;
+ if (!pr || typeof pr.state !== "string") {
+ out.set(t.url, "unreadable");
+ return;
+ }
+ const state: PullState = pr.state === "MERGED" ? "merged" : pr.state === "CLOSED" ? "closed" : pr.isDraft === true ? "draft" : "open";
+ out.set(t.url, { state, title: typeof pr.title === "string" ? pr.title : "" });
+ });
+ return out;
+ }
+}
+
+/** `https://github.com/{owner}/{name}/pull/{n}`, or null. */
+export function pullOf(url: string): { owner: string; name: string; number: number } | null {
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100})\/pull\/(\d{1,9})(?:[/?#].*)?$/.exec(url);
+ return m ? { owner: m[1]!, name: m[2]!, number: Number(m[3]) } : null;
+}
+
+function commitOf(raw: unknown): CommitInfo | null {
+ const c = raw as { sha?: unknown; commit?: { message?: unknown; author?: { name?: unknown; email?: unknown; date?: unknown } } };
+ if (typeof c?.sha !== "string" || typeof c.commit?.message !== "string") return null;
+ const author = c.commit.author;
+ return {
+ sha: c.sha,
+ message: c.commit.message,
+ authorName: typeof author?.name === "string" ? author.name : "",
+ authorEmail: typeof author?.email === "string" ? author.email : null,
+ at: typeof author?.date === "string" ? author.date : new Date(0).toISOString(),
+ };
+}
+
+function fileOf(raw: unknown): FileChange | null {
+ const f = raw as { filename?: unknown; status?: unknown; previous_filename?: unknown; sha?: unknown };
+ if (typeof f?.filename !== "string" || typeof f.status !== "string") return null;
+ return {
+ filename: f.filename,
+ status: f.status as FileChange["status"],
+ previousFilename: typeof f.previous_filename === "string" ? f.previous_filename : null,
+ sha: typeof f.sha === "string" && f.status !== "removed" ? f.sha : null,
+ };
+}
diff --git a/services/managed-agents/src/computer/work/index-contract.ts b/services/managed-agents/src/computer/work/index-contract.ts
new file mode 100644
index 00000000..3bc906f8
--- /dev/null
+++ b/services/managed-agents/src/computer/work/index-contract.ts
@@ -0,0 +1,115 @@
+// The Work index's RPC surface (tech design 3.6, "Interface"), called only by the Work API in the
+// stateless Worker (work/api.ts) and by the Computer object (`knowledgeRepository`). Every call
+// names the organization (the object is addressed by its account id, like COMPUTERS); every read
+// result carries `{ head, asOf, building, problem }`.
+//
+// Close and Reopen (3.9, build step 5) slot in beside `setRepository`: writes that run inside the
+// index's one-at-a-time chain and answer a `WorkWrite`.
+
+import type { RepositoryProblem } from "./github.js";
+import type { Stage } from "./item.js";
+
+export type { RepositoryProblem } from "./github.js";
+
+/** The knowledge repository setting, as the API shows it. */
+export interface Repository {
+ /** The organization's GitHub installation (the Account object's id for it). */
+ installationId: string;
+ owner: string;
+ name: string;
+ branch: string;
+ /** Set when the repository can no longer be read; the screens send the person to settings. */
+ problem: RepositoryProblem | null;
+}
+
+/** What `PUT /work/repository` asks for; the branch defaults to the repository's default branch. */
+export interface RepositoryChoice {
+ installationId: string;
+ owner: string;
+ name: string;
+ branch?: string;
+}
+
+/** Who made a write, from the identity the edge asserted. */
+export interface WorkActor {
+ member: string;
+ name: string | null;
+ email: string | null;
+}
+
+/** On every read: where the projection is and whether it is still being built. */
+export interface ReadState {
+ /** The commit the projection is at; null before the first build has listed the repository. */
+ head: string | null;
+ /** When the head was last confirmed against GitHub, ISO; null before. */
+ asOf: string | null;
+ /** True while the open items of a build are still being read. */
+ building: boolean;
+ problem: RepositoryProblem | null;
+}
+
+/** An item as the index holds it, before the Worker joins sessions and people. */
+export interface IndexedItem {
+ number: number;
+ stage: Stage;
+ path: string;
+ /** The file on GitHub. */
+ url: string;
+ title: string;
+ stateLine: string | null;
+ tags: string[];
+ /** The frontmatter owner email, lowercased. */
+ owner: string | null;
+ /** The author of the commit that added the file; null until the index has seen that commit. */
+ author: { name: string; email: string | null } | null;
+ left: number | null;
+ readyToClose: boolean;
+ warnings: string[];
+ pullRequests: { url: string; state: "open" | "draft" | "merged" | "closed" | null; title: string | null }[];
+ /** Sessions with a commit that touched the file, most recent first. */
+ sessionIds: string[];
+ updatedAt: string | null;
+ createdAt: string | null;
+ closedAt: string | null;
+ /** The name of the person who closed it; null when unknown or closed in a session. */
+ closedBy: string | null;
+ /** False while the body has not been read yet (a closed item before its page was asked for). */
+ parsed: boolean;
+}
+
+export interface ItemsQuery {
+ stage: "open" | "closed";
+ cursor?: string;
+ limit?: number;
+}
+
+export type ItemsResult =
+ | (ReadState & { ok: true; repository: Repository | null; items: IndexedItem[]; nextCursor: string | null })
+ | { ok: false; error: "invalid_cursor" };
+
+export type ItemResult = ReadState & { repository: Repository | null; item: IndexedItem | null; body: string | null };
+
+export interface Revision {
+ sha: string;
+ url: string;
+ at: string;
+ authorName: string;
+ summary: string;
+ sessionId: string | null;
+}
+
+export type HistoryResult =
+ | (ReadState & { ok: true; revisions: Revision[]; nextCursor: string | null })
+ | { ok: false; error: "item_not_found" | "invalid_cursor" | "unavailable"; retryAfterMs?: number };
+
+/** A write's answer: the result, or an API error the Worker forwards. */
+export type WorkWrite<T> = { ok: true; value: T } | { ok: false; status: number; code: string; message: string; field?: string; reason?: string; retryAfterMs?: number };
+
+export interface WorkIndexRpc {
+ repository(accountId: string): Promise<Repository | null>;
+ setRepository(accountId: string, choice: RepositoryChoice, by: WorkActor): Promise<WorkWrite<Repository>>;
+ items(accountId: string, query: ItemsQuery): Promise<ItemsResult>;
+ item(accountId: string, number: number): Promise<ItemResult>;
+ history(accountId: string, number: number, cursor?: string): Promise<HistoryResult>;
+ poke(accountId: string): Promise<void>;
+}
diff --git a/services/managed-agents/src/computer/work/index-do.ts b/services/managed-agents/src/computer/work/index-do.ts
new file mode 100644
index 00000000..a6fcf270
--- /dev/null
+++ b/services/managed-agents/src/computer/work/index-do.ts
@@ -0,0 +1,74 @@
+// The Work index's Durable Object (tech design 3.6): binding `WORK_INDEX`, one per organization,
+// addressed by account id like `COMPUTERS`. The logic is `WorkIndex` (index.ts); this is storage,
+// the alarm and the Account object.
+
+import { DurableObject } from "cloudflare:workers";
+
+import type { TokenMinter } from "./github.js";
+import { WorkIndex } from "./index.js";
+import type { ItemsQuery, RepositoryChoice, WorkActor, WorkIndexRpc } from "./index-contract.js";
+
+export interface WorkIndexEnv {
+ /** The edge's AccountDurableObject, addressed by account id. */
+ ACCOUNTS: DurableObjectNamespace;
+}
+
+export class WorkIndexDurableObject extends DurableObject<WorkIndexEnv> implements WorkIndexRpc {
+ private index!: WorkIndex;
+
+ constructor(ctx: DurableObjectState, env: WorkIndexEnv) {
+ super(ctx, env);
+ void ctx.blockConcurrencyWhile(async () => {
+ this.index = new WorkIndex({
+ sql: ctx.storage.sql,
+ transaction: (fn) => ctx.storage.transactionSync(fn),
+ account: (accountId) => env.ACCOUNTS.getByName(accountId) as unknown as TokenMinter,
+ arm: (at) => this.arm(at),
+ waitUntil: (promise) => ctx.waitUntil(promise),
+ });
+ });
+ }
+
+ private async arm(at: number): Promise<void> {
+ const current = await this.ctx.storage.getAlarm();
+ if (current === null || at < current) await this.ctx.storage.setAlarm(at);
+ }
+
+ repository(accountId: string) {
+ return this.index.getRepository(accountId);
+ }
+
+ setRepository(accountId: string, choice: RepositoryChoice, by: WorkActor) {
+ return this.index.setRepository(accountId, choice, by);
+ }
+
+ items(accountId: string, query: ItemsQuery) {
+ return this.index.items(accountId, query);
+ }
+
+ item(accountId: string, number: number) {
+ return this.index.item(accountId, number);
+ }
+
+ history(accountId: string, number: number, cursor?: string) {
+ return this.index.history(accountId, number, cursor);
+ }
+
+ poke(accountId: string) {
+ return this.index.poke(accountId);
+ }
+
+ override async alarm(): Promise<void> {
+ const next = await this.index.alarm();
+ if (next !== null) await this.arm(Math.max(next, Date.now() + 1));
+ }
+}
+
+/**
+ * The organization's knowledge repository, or null when none is set (or the index is not bound).
+ * The one call the knowledge-repository work (build step 2) makes of the Work index.
+ */
+export async function knowledgeRepository(env: { WORK_INDEX?: DurableObjectNamespace }, orgId: string) {
+ if (!env.WORK_INDEX) return null;
+ return (env.WORK_INDEX.getByName(orgId) as unknown as WorkIndexRpc).repository(orgId);
+}
diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.ts
new file mode 100644
index 00000000..a4c0a6d2
--- /dev/null
+++ b/services/managed-agents/src/computer/work/index.ts
@@ -0,0 +1,959 @@
+// The Work index (work tracking, tech design 3.6): one organization's projection of its knowledge
+// repository's `work/` and `done/` folders, kept in SQLite and moved forward from a cursor commit.
+// The repository is the record; this is a cache that can always be rebuilt from it.
+//
+// - Advance (the only way the projection changes, besides a build): compare `cursor...head`, fetch
+// the blobs of the changed item files, then write rows, links and the cursor in one transaction.
+// A crash before the transaction repeats the work with the same result.
+// - Build (no cursor, or the head is not ahead of it): list the two folders at the head; open items
+// are read in batches of 50 continued by the alarm, and the cursor is set when they are done.
+// Closed items get a row from the listing and are read when a page of them is asked for. Then a
+// background walk of the commits recovers links, authors and close dates within the quota.
+// - Duplicate numbers: `files` holds every item file at the cursor; the row of a number is its open
+// file before a closed one, then the first path. The others show as a warning on the row.
+// - One GitHub task at a time (`exclusive`): look, build, fill, walk, pull state, setRepository.
+// Reads are SQL and never wait on GitHub, except a page of closed items not read yet (bounded).
+//
+// Close and Reopen (3.9, build step 5) are writes in the same chain: a commit through the
+// contents API, then an advance to it.
+
+import {
+ GitHubGone,
+ GitHubPaused,
+ GitHubUnavailable,
+ pullOf,
+ WorkGitHub,
+ type CommitInfo,
+ type FileChange,
+ type RepositoryProblem,
+ type TokenMinter,
+ type WorkRepo,
+} from "./github.js";
+import type {
+ HistoryResult,
+ IndexedItem,
+ ItemResult,
+ ItemsQuery,
+ ItemsResult,
+ ReadState,
+ Repository,
+ RepositoryChoice,
+ Revision,
+ WorkActor,
+ WorkWrite,
+} from "./index-contract.js";
+import { itemPath, PARSER_VERSION, parseItem, readyToClose, sessionTrailers, slugTitle, type ItemPath, type ParsedItem } from "./item.js";
+
+/** A read finding the head older than this looks behind its response. */
+export const LOOK_AFTER_MS = 10_000;
+/** The alarm looks this often while there have been reads in the last READS_WINDOW_MS. */
+export const ALARM_EVERY_MS = 60_000;
+export const READS_WINDOW_MS = 10 * 60_000;
+/** Between two batches of a build. */
+const BUILD_STEP_MS = 1_000;
+export const FILL_BATCH = 50;
+/** Pull request state is asked at most this often. */
+export const PULLS_EVERY_MS = 5 * 60_000;
+const PULLS_PER_QUERY = 50;
+/** An advance asks per-commit files for at most this many commits. */
+const DETAIL_CAP = 20;
+/** Compare lists at most 300 files; at that many, the listing may be cut: rebuild. */
+const COMPARE_FILES_MAX = 300;
+/** A page of closed items waits this long for bodies not read yet, then answers with what it has. */
+const LAZY_WAIT_MS = 5_000;
+const WALK_PAGE = 30;
+const WALK_COMMITS_PER_TICK = 10;
+const HISTORY_PAGE = 30;
+const CLOSED_LIMIT_DEFAULT = 50;
+const CLOSED_LIMIT_MAX = 100;
+const FETCH_PARALLEL = 6;
+
+const SCHEMA = `
+CREATE TABLE IF NOT EXISTS items (
+ number INTEGER PRIMARY KEY,
+ path TEXT NOT NULL,
+ blob TEXT NOT NULL,
+ body TEXT NOT NULL,
+ parsed TEXT NOT NULL,
+ parser INTEGER NOT NULL,
+ author_name TEXT, author_email TEXT, created_at TEXT,
+ updated_at TEXT, closed_at TEXT, closed_by TEXT
+);
+CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, number INTEGER NOT NULL, blob TEXT NOT NULL);
+CREATE INDEX IF NOT EXISTS files_number ON files (number);
+CREATE TABLE IF NOT EXISTS links (number INTEGER NOT NULL, session_id TEXT NOT NULL, last_at TEXT NOT NULL, PRIMARY KEY (number, session_id));
+CREATE TABLE IF NOT EXISTS pulls (url TEXT PRIMARY KEY, state TEXT, title TEXT, checked_at TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);
+`;
+
+/** What the index needs of its Durable Object. */
+export interface WorkIndexDeps {
+ sql: SqlStorage;
+ transaction<T>(fn: () => T): T;
+ /** The organization's Account object. */
+ account(accountId: string): TokenMinter;
+ /** Makes sure the alarm fires at `at` or sooner. */
+ arm(at: number): Promise<void>;
+ waitUntil(promise: Promise<unknown>): void;
+ fetch?: typeof fetch;
+ now?: () => number;
+}
+
+interface ItemRow {
+ number: number;
+ path: string;
+ blob: string;
+ body: string;
+ parsed: string;
+ parser: number;
+ author_name: string | null;
+ author_email: string | null;
+ created_at: string | null;
+ updated_at: string | null;
+ closed_at: string | null;
+ closed_by: string | null;
+}
+
+type Row = Record<string, SqlStorageValue>;
+
+interface StoredRepo extends WorkRepo {}
+
+interface WalkState {
+ head: string;
+ dir: "work" | "done";
+ page: number;
+ index: number;
+}
+
+/** One organization's Work index. */
+export class WorkIndex {
+ private readonly now: () => number;
+ private github: WorkGitHub | null = null;
+ private tail: Promise<unknown> = Promise.resolve();
+ private looking: Promise<void> | null = null;
+ private readonly filling = new Set<number>();
+
+ constructor(private readonly deps: WorkIndexDeps) {
+ this.now = deps.now ?? Date.now;
+ deps.sql.exec(SCHEMA);
+ this.reparse();
+ }
+
+ // ------------------------------------------------------------------ meta
+
+ private meta(k: string): string | null {
+ const row = this.deps.sql.exec<{ v: string }>("SELECT v FROM meta WHERE k = ?", k).toArray()[0];
+ return row ? row.v : null;
+ }
+
+ private setMeta(k: string, v: string | number | null): void {
+ if (v === null) this.deps.sql.exec("DELETE FROM meta WHERE k = ?", k);
+ else this.deps.sql.exec("INSERT INTO meta (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v", k, String(v));
+ }
+
+ private metaJson<T>(k: string): T | null {
+ const v = this.meta(k);
+ if (v === null) return null;
+ try {
+ return JSON.parse(v) as T;
+ } catch {
+ return null;
+ }
+ }
+
+ private metaNumber(k: string): number {
+ const v = Number(this.meta(k));
+ return Number.isFinite(v) ? v : 0;
+ }
+
+ /** The organization the object serves; recorded on the first call so the alarm knows it. */
+ private bind(accountId: string): void {
+ if (this.meta("account_id") !== accountId) this.setMeta("account_id", accountId);
+ }
+
+ private repo(): StoredRepo | null {
+ return this.metaJson<StoredRepo>("repo");
+ }
+
+ private client(): WorkGitHub | null {
+ const repo = this.repo();
+ const accountId = this.meta("account_id");
+ if (!repo || !accountId) return null;
+ const g = this.github;
+ if (g && g.repo.installationId === repo.installationId && g.repo.owner === repo.owner && g.repo.name === repo.name && g.repo.branch === repo.branch) return g;
+ this.github = new WorkGitHub({ repo, account: this.deps.account(accountId), now: this.now, ...(this.deps.fetch ? { fetch: this.deps.fetch } : {}) });
+ return this.github;
+ }
+
+ private repository(): Repository | null {
+ const repo = this.repo();
+ if (!repo) return null;
+ return { installationId: repo.installationId, owner: repo.owner, name: repo.name, branch: repo.branch, problem: (this.meta("problem") as RepositoryProblem | null) ?? null };
+ }
+
+ private readState(): ReadState {
+ const asOf = this.metaNumber("as_of");
+ const build = this.metaJson<{ head: string }>("build");
+ return {
+ head: this.meta("cursor") ?? build?.head ?? null,
+ asOf: asOf ? new Date(asOf).toISOString() : null,
+ building: build !== null,
+ problem: (this.meta("problem") as RepositoryProblem | null) ?? null,
+ };
+ }
+
+ // ------------------------------------------------------------------ one at a time
+
+ private exclusive<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.tail.then(fn, fn);
+ this.tail = run.catch(() => undefined);
+ return run;
+ }
+
+ /** Looks once, joining a look already queued. */
+ private kick(): Promise<void> {
+ if (!this.looking) {
+ this.looking = this.exclusive(() => this.look()).finally(() => {
+ this.looking = null;
+ });
+ }
+ return this.looking;
+ }
+
+ /** A read: note it, and look behind the response when the head is older than 10 s. */
+ private noteRead(): void {
+ const now = this.now();
+ this.setMeta("read_at", now);
+ if (!this.repo()) return;
+ const seen = Math.max(this.metaNumber("as_of"), this.metaNumber("tried_at"));
+ if (now - seen > LOOK_AFTER_MS) this.deps.waitUntil(this.kick());
+ this.deps.waitUntil(this.deps.arm(now + ALARM_EVERY_MS));
+ }
+
+ // ------------------------------------------------------------------ RPC
+
+ async getRepository(accountId: string): Promise<Repository | null> {
+ this.bind(accountId);
+ return this.repository();
+ }
+
+ async poke(accountId: string): Promise<void> {
+ this.bind(accountId);
+ if (!this.repo()) return;
+ this.deps.waitUntil(this.kick());
+ }
+
+ async setRepository(accountId: string, choice: RepositoryChoice, _by: WorkActor): Promise<WorkWrite<Repository>> {
+ this.bind(accountId);
+ return this.exclusive(async () => {
+ const trial = new WorkGitHub({
+ repo: { installationId: choice.installationId, owner: choice.owner, name: choice.name, branch: choice.branch ?? "main" },
+ account: this.deps.account(accountId),
+ now: this.now,
+ ...(this.deps.fetch ? { fetch: this.deps.fetch } : {}),
+ });
+ let repo: StoredRepo;
+ try {
+ const found = await trial.repository();
+ repo = { installationId: choice.installationId, owner: found.owner, name: found.name, branch: choice.branch ?? found.defaultBranch };
+ const checked = new WorkGitHub({ repo, account: this.deps.account(accountId), now: this.now, ...(this.deps.fetch ? { fetch: this.deps.fetch } : {}) });
+ await checked.head();
+ } catch (error) {
+ if (error instanceof GitHubGone) {
+ const field = error.problem === "branch_not_found" ? "branch" : error.problem === "repository_not_found" ? "name" : "installationId";
+ return { ok: false, status: 400, code: "invalid_request", message: refusal(error.problem), field, reason: error.problem };
+ }
+ const retryAfterMs = error instanceof GitHubPaused ? Math.max(1000, error.until - this.now()) : 5_000;
+ return { ok: false, status: 503, code: "unavailable", message: "GitHub could not be reached. Try again shortly.", retryAfterMs };
+ }
+ const current = this.repo();
+ const same =
+ current !== null &&
+ current.installationId === repo.installationId &&
+ current.owner.toLowerCase() === repo.owner.toLowerCase() &&
+ current.name.toLowerCase() === repo.name.toLowerCase() &&
+ current.branch === repo.branch;
+ this.deps.transaction(() => {
+ if (!same) {
+ for (const table of ["items", "files", "links", "pulls"]) this.deps.sql.exec(`DELETE FROM ${table}`);
+ for (const k of ["cursor", "build", "walk", "head_etag", "as_of", "tried_at", "pulls_at", "pause_until"]) this.setMeta(k, null);
+ }
+ this.setMeta("repo", JSON.stringify(repo));
+ this.setMeta("problem", null);
+ });
+ this.github = null;
+ this.deps.waitUntil(this.kick());
+ return { ok: true, value: this.repository()! };
+ });
+ }
+
+ async items(accountId: string, query: ItemsQuery): Promise<ItemsResult> {
+ this.bind(accountId);
+ this.noteRead();
+ const repository = this.repository();
+ if (query.stage === "open") {
+ const rows = this.deps.sql.exec<ItemRow & Row>("SELECT * FROM items WHERE path LIKE 'work/%' ORDER BY number").toArray();
+ return { ok: true, ...this.readState(), repository, items: this.indexed(rows), nextCursor: null };
+ }
+ let before = Number.MAX_SAFE_INTEGER;
+ if (query.cursor !== undefined) {
+ const n = decodeCursor(query.cursor, "n");
+ if (n === null) return { ok: false, error: "invalid_cursor" };
+ before = n;
+ }
+ const limit = Math.min(Math.max(query.limit ?? CLOSED_LIMIT_DEFAULT, 1), CLOSED_LIMIT_MAX);
+ const select = () =>
+ this.deps.sql.exec<ItemRow & Row>("SELECT * FROM items WHERE path LIKE 'done/%' AND number < ? ORDER BY number DESC LIMIT ?", before, limit + 1).toArray();
+ let rows = select();
+ const pending = rows.slice(0, limit).filter((r) => r.parser === 0);
+ if (pending.length) {
+ await this.fillLater(pending);
+ rows = select();
+ }
+ const page = rows.slice(0, limit);
+ const nextCursor = rows.length > limit ? encodeCursor({ n: page[page.length - 1]!.number }) : null;
+ return { ok: true, ...this.readState(), repository, items: this.indexed(page), nextCursor };
+ }
+
+ async item(accountId: string, number: number): Promise<ItemResult> {
+ this.bind(accountId);
+ this.noteRead();
+ const select = () => this.deps.sql.exec<ItemRow & Row>("SELECT * FROM items WHERE number = ?", number).toArray()[0];
+ let row = select();
+ if (row && row.parser === 0) {
+ await this.fillLater([row]);
+ row = select();
+ }
+ return { ...this.readState(), repository: this.repository(), item: row ? this.indexed([row])[0]! : null, body: row && row.parser > 0 ? row.body : null };
+ }
+
+ async history(accountId: string, number: number, cursor?: string): Promise<HistoryResult> {
+ this.bind(accountId);
+ this.noteRead();
+ const row = this.deps.sql.exec<{ path: string }>("SELECT path FROM items WHERE number = ?", number).toArray()[0];
+ if (!row) return { ok: false, error: "item_not_found" };
+ let page = 1;
+ if (cursor !== undefined) {
+ const p = decodeCursor(cursor, "p");
+ if (p === null || p < 1) return { ok: false, error: "invalid_cursor" };
+ page = p;
+ }
+ const gh = this.client();
+ const head = this.readState().head;
+ const repo = this.repo();
+ if (!gh || !head || !repo) return { ok: false, error: "unavailable", retryAfterMs: 5_000 };
+ const file = row.path.slice(row.path.indexOf("/") + 1);
+ try {
+ const lists = await Promise.all(["work", "done"].map((dir) => gh.commits({ sha: head, path: `${dir}/${file}`, page, perPage: HISTORY_PAGE })));
+ const seen = new Set<string>();
+ const revisions: Revision[] = [];
+ for (const c of lists.flat().sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0))) {
+ if (seen.has(c.sha)) continue;
+ seen.add(c.sha);
+ revisions.push({
+ sha: c.sha,
+ url: `https://github.com/${repo.owner}/${repo.name}/commit/${c.sha}`,
+ at: c.at,
+ authorName: c.authorName,
+ summary: c.message.split(/\r?\n/, 1)[0]!.slice(0, 200),
+ sessionId: sessionTrailers(c.message)[0] ?? null,
+ });
+ }
+ const more = lists.some((l) => l.length >= HISTORY_PAGE);
+ return { ok: true, ...this.readState(), revisions, nextCursor: more ? encodeCursor({ p: page + 1 }) : null };
+ } catch (error) {
+ if (error instanceof GitHubGone) this.problem(error.problem);
+ const retryAfterMs = error instanceof GitHubPaused ? Math.max(1000, error.until - this.now()) : 5_000;
+ return { ok: false, error: "unavailable", retryAfterMs };
+ }
+ }
+
+ /** The alarm: continue a build, look while there are readers, walk. Returns when to come back. */
+ async alarm(): Promise<number | null> {
+ if (!this.repo()) return null;
+ await this.exclusive(async () => {
+ const now = this.now();
+ if (this.meta("build") !== null) {
+ if (now - this.metaNumber("as_of") >= ALARM_EVERY_MS) await this.look();
+ else await this.guard(() => this.fillOpen());
+ return;
+ }
+ if (now - this.metaNumber("read_at") < READS_WINDOW_MS) await this.look();
+ else await this.guard(() => this.walkTick());
+ });
+ const now = this.now();
+ const pausedUntil = this.metaNumber("pause_until");
+ let next: number | null = null;
+ if (this.meta("build") !== null) next = now + BUILD_STEP_MS;
+ else if (now - this.metaNumber("read_at") < READS_WINDOW_MS || this.meta("walk") !== null) next = now + ALARM_EVERY_MS;
+ if (next !== null && this.meta("problem") !== null && now - this.metaNumber("read_at") >= READS_WINDOW_MS) next = null;
+ if (next !== null && pausedUntil > next) next = pausedUntil;
+ return next;
+ }
+
+ // ------------------------------------------------------------------ looking
+
+ /** Runs `fn` with GitHub failures recorded: a pause until it ends, a permanent failure as the problem. */
+ private async guard(fn: () => Promise<void>): Promise<void> {
+ try {
+ await fn();
+ } catch (error) {
+ if (error instanceof GitHubGone) this.problem(error.problem);
+ else if (error instanceof GitHubPaused) this.setMeta("pause_until", error.until);
+ else if (!(error instanceof GitHubUnavailable)) throw error;
+ }
+ }
+
+ private problem(problem: RepositoryProblem): void {
+ this.setMeta("problem", problem);
+ }
+
+ /** Checks the head and moves the projection to it; then one step of background work. */
+ private async look(): Promise<void> {
+ const gh = this.client();
+ if (!gh) return;
+ if (this.metaNumber("pause_until") > this.now()) return;
+ this.setMeta("tried_at", this.now());
+ await this.guard(async () => {
+ const etag = this.meta("head_etag") ?? undefined;
+ const head = await gh.head(etag);
+ this.setMeta("problem", null);
+ if (head !== "unchanged") {
+ const cursor = this.meta("cursor");
+ const build = this.metaJson<{ head: string }>("build");
+ if (build) {
+ // A build in progress finishes at its head; the next look advances from there.
+ } else if (cursor === null) {
+ await this.build(gh, head.sha);
+ } else if (cursor !== head.sha) {
+ const result = await this.advance(gh, cursor, head.sha);
+ if (result === "rebuild") await this.build(gh, head.sha);
+ }
+ if (this.meta("cursor") === head.sha && head.etag) this.setMeta("head_etag", head.etag);
+ }
+ this.setMeta("as_of", this.now());
+ if (this.meta("build") !== null) {
+ await this.fillOpen();
+ if (this.meta("build") !== null) this.deps.waitUntil(this.deps.arm(this.now() + BUILD_STEP_MS));
+ } else if (this.meta("walk") !== null) {
+ await this.walkTick();
+ }
+ await this.refreshPulls(gh);
+ });
+ }
+
+ // ------------------------------------------------------------------ build
+
+ /** Lists `work/` and `done/` at `head`; open items are read by `fillOpen`, closed ones on demand. */
+ private async build(gh: WorkGitHub, head: string): Promise<void> {
+ const root = await gh.tree(head);
+ if (!root) throw new GitHubUnavailable(`GitHub has no tree for ${head}.`);
+ const listing = new Map<string, { number: number; blob: string }>();
+ for (const dir of ["work", "done"] as const) {
+ const entry = root.entries.find((e) => e.name === dir && e.type === "tree");
+ if (!entry) continue;
+ const tree = await gh.tree(entry.sha);
+ for (const e of tree?.entries ?? []) {
+ const path = `${dir}/${e.name}`;
+ const ip = e.type === "blob" ? itemPath(path) : null;
+ if (ip) listing.set(path, { number: ip.number, blob: e.sha });
+ }
+ }
+ const winners = pickWinners([...listing].map(([path, f]) => ({ path, ...f })));
+ const sql = this.deps.sql;
+ this.deps.transaction(() => {
+ sql.exec("DELETE FROM files");
+ for (const [path, f] of listing) sql.exec("INSERT INTO files (path, number, blob) VALUES (?, ?, ?)", path, f.number, f.blob);
+ const old = new Map(sql.exec<ItemRow & Row>("SELECT * FROM items").toArray().map((r) => [r.number, r]));
+ for (const [number] of old) {
+ if (!winners.has(number)) {
+ sql.exec("DELETE FROM items WHERE number = ?", number);
+ sql.exec("DELETE FROM links WHERE number = ?", number);
+ }
+ }
+ for (const [number, w] of winners) {
+ const ip = itemPath(w.path)!;
+ const prev = old.get(number);
+ if (prev && prev.blob === w.blob) {
+ if (prev.path !== w.path) {
+ const moved = stageOf(prev.path) !== ip.stage;
+ sql.exec(
+ "UPDATE items SET path = ?, parsed = ?, closed_at = ?, closed_by = ? WHERE number = ?",
+ w.path,
+ prev.parser > 0 ? JSON.stringify(parseItem(ip, prev.body)) : JSON.stringify(pendingParse(ip)),
+ moved ? null : prev.closed_at,
+ moved ? null : prev.closed_by,
+ number,
+ );
+ }
+ continue;
+ }
+ if (prev) {
+ const moved = stageOf(prev.path) !== ip.stage;
+ sql.exec(
+ "UPDATE items SET path = ?, blob = ?, body = '', parsed = ?, parser = 0, updated_at = NULL, closed_at = ?, closed_by = ? WHERE number = ?",
+ w.path,
+ w.blob,
+ JSON.stringify(pendingParse(ip)),
+ moved ? null : prev.closed_at,
+ moved ? null : prev.closed_by,
+ number,
+ );
+ } else {
+ sql.exec("INSERT INTO items (number, path, blob, body, parsed, parser) VALUES (?, ?, ?, '', ?, 0)", number, w.path, w.blob, JSON.stringify(pendingParse(ip)));
+ }
+ }
+ this.setMeta("cursor", null);
+ this.setMeta("head_etag", null);
+ this.setMeta("walk", null);
+ this.setMeta("build", JSON.stringify({ head }));
+ });
+ }
+
+ /** One batch of open items not read yet; the cursor is set when none is left. */
+ private async fillOpen(): Promise<void> {
+ const build = this.metaJson<{ head: string }>("build");
+ const gh = this.client();
+ if (!build || !gh) return;
+ const rows = this.deps.sql.exec<ItemRow & Row>("SELECT * FROM items WHERE parser = 0 AND path LIKE 'work/%' ORDER BY number LIMIT ?", FILL_BATCH).toArray();
+ await parallel(rows, (row) => this.fill(gh, row, build.head));
+ const left = this.deps.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM items WHERE parser = 0 AND path LIKE 'work/%'").toArray()[0]!.n;
+ if (left > 0) return;
+ this.deps.transaction(() => {
+ this.setMeta("cursor", build.head);
+ this.setMeta("build", null);
+ this.setMeta("walk", JSON.stringify({ head: build.head, dir: "work", page: 1, index: 0 } satisfies WalkState));
+ });
+ }
+
+ /** Reads one row's body; written only if the row still has that blob. */
+ private async fill(gh: WorkGitHub, row: ItemRow, head: string | null): Promise<void> {
+ const ip = itemPath(row.path);
+ if (!ip) return;
+ const body = await gh.blob(row.blob);
+ let updatedAt = row.updated_at;
+ if (updatedAt === null && head !== null && stageOf(row.path) === "open") {
+ updatedAt = (await gh.commits({ sha: head, path: row.path, page: 1, perPage: 1 }))[0]?.at ?? null;
+ }
+ this.deps.sql.exec(
+ "UPDATE items SET body = ?, parsed = ?, parser = ?, updated_at = COALESCE(updated_at, ?) WHERE number = ? AND blob = ? AND path = ?",
+ body,
+ JSON.stringify(parseItem(ip, body)),
+ PARSER_VERSION,
+ updatedAt,
+ row.number,
+ row.blob,
+ row.path,
+ );
+ }
+
+ /** Closed items asked for before they were read: read them, waiting at most LAZY_WAIT_MS. */
+ private async fillLater(rows: ItemRow[]): Promise<void> {
+ const gh = this.client();
+ if (!gh || gh.paused()) return;
+ const todo = rows.filter((r) => !this.filling.has(r.number));
+ if (!todo.length) return;
+ for (const r of todo) this.filling.add(r.number);
+ const work = parallel(todo, (row) => this.guard(() => this.fill(gh, row, null))).finally(() => {
+ for (const r of todo) this.filling.delete(r.number);
+ });
+ this.deps.waitUntil(work);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([work, new Promise<void>((resolve) => (timer = setTimeout(resolve, LAZY_WAIT_MS)))]);
+ clearTimeout(timer);
+ }
+
+ // ------------------------------------------------------------------ advance
+
+ /** `base...head` applied in one transaction; "rebuild" when the head is not ahead of the cursor. */
+ async advance(gh: WorkGitHub, base: string, head: string): Promise<"done" | "rebuild"> {
+ const cmp = await gh.compare(base, head);
+ if (!cmp || cmp.status !== "ahead" || cmp.files.length >= COMPARE_FILES_MAX || cmp.totalCommits > cmp.commits.length) return "rebuild";
+ const commits = cmp.commits;
+ const newest = commits[commits.length - 1];
+ const isItemChange = (f: FileChange) => itemPath(f.filename) !== null || (f.previousFilename !== null && itemPath(f.previousFilename) !== null);
+ const changes = cmp.files.filter(isItemChange);
+
+ // Which commit touched which file: the range's files for one commit; else per commit, for the
+ // commits with a trailer, and for all of them when an item was added or moved (authors, close dates).
+ const perCommit = new Map<string, FileChange[]>();
+ if (changes.length) {
+ if (commits.length === 1) perCommit.set(commits[0]!.sha, cmp.files);
+ else {
+ const moved = changes.some((f) => f.status === "added" || f.status === "renamed");
+ const wanted = commits.filter((c) => (moved && commits.length <= DETAIL_CAP) || sessionTrailers(c.message).length > 0).slice(-DETAIL_CAP);
+ for (const c of wanted) perCommit.set(c.sha, (await gh.commit(c.sha)).files);
+ }
+ }
+ const complete = perCommit.size === commits.length;
+
+ // Per new path: the newest commit that touched it, the one that added it, the one that closed it.
+ const touch = new Map<string, { last?: CommitInfo; added?: CommitInfo; closed?: CommitInfo }>();
+ for (const c of commits) {
+ for (const f of perCommit.get(c.sha) ?? []) {
+ const t = touch.get(f.filename) ?? {};
+ t.last = c;
+ const from = f.previousFilename ? itemPath(f.previousFilename) : null;
+ if (f.status === "added" || (f.status === "renamed" && !from)) t.added ??= c;
+ if (f.filename.startsWith("done/") && (f.status === "added" || (f.status === "renamed" && from?.stage !== "closed"))) t.closed = c;
+ touch.set(f.filename, t);
+ }
+ }
+
+ // The files of the affected numbers after the range, and the row each number gets.
+ const numbers = new Set<number>();
+ for (const f of changes) {
+ for (const p of [f.filename, f.previousFilename]) {
+ const ip = p ? itemPath(p) : null;
+ if (ip) numbers.add(ip.number);
+ }
+ }
+ const files = new Map<string, { number: number; blob: string }>();
+ for (const n of numbers) {
+ for (const r of this.deps.sql.exec<{ path: string; blob: string } & Row>("SELECT path, blob FROM files WHERE number = ?", n).toArray()) files.set(r.path, { number: n, blob: r.blob });
+ }
+ const removed = new Set<string>();
+ for (const f of changes) {
+ if (f.status === "removed" || f.status === "renamed") {
+ const gone = f.status === "removed" ? f.filename : f.previousFilename!;
+ files.delete(gone);
+ removed.add(gone);
+ }
+ if (f.status !== "removed") {
+ const ip = itemPath(f.filename);
+ if (ip && f.sha) {
+ files.set(f.filename, { number: ip.number, blob: f.sha });
+ removed.delete(f.filename);
+ }
+ }
+ }
+ const winners = pickWinners([...files].map(([path, f]) => ({ path, ...f })));
+ const old = new Map<number, ItemRow>();
+ for (const n of numbers) {
+ const r = this.deps.sql.exec<ItemRow & Row>("SELECT * FROM items WHERE number = ?", n).toArray()[0];
+ if (r) old.set(n, r);
+ }
+
+ // Bodies to read, before the transaction.
+ const needed = [...winners.values()].filter((w) => {
+ const prev = old.get(w.number);
+ return !prev || prev.blob !== w.blob || prev.parser === 0;
+ });
+ const readNow = needed.filter((w) => stageOf(w.path) === "open" || needed.length <= FILL_BATCH);
+ const bodies = new Map<string, string>();
+ await parallel(readNow, async (w) => {
+ bodies.set(w.blob, await gh.blob(w.blob));
+ });
+
+ // Links: each trailer commit's item files.
+ const links: { number: number; sessionId: string; at: string }[] = [];
+ for (const c of commits) {
+ const trailers = sessionTrailers(c.message);
+ if (!trailers.length) continue;
+ for (const f of perCommit.get(c.sha) ?? []) {
+ const ip = itemPath(f.filename) ?? (f.previousFilename ? itemPath(f.previousFilename) : null);
+ if (!ip || !winners.has(ip.number)) continue;
+ for (const sessionId of trailers) links.push({ number: ip.number, sessionId, at: c.at });
+ }
+ }
+
+ const sql = this.deps.sql;
+ this.deps.transaction(() => {
+ for (const p of removed) sql.exec("DELETE FROM files WHERE path = ?", p);
+ for (const f of changes) {
+ const entry = files.get(f.filename);
+ if (entry) sql.exec("INSERT INTO files (path, number, blob) VALUES (?, ?, ?) ON CONFLICT (path) DO UPDATE SET number = excluded.number, blob = excluded.blob", f.filename, entry.number, entry.blob);
+ }
+ for (const n of numbers) {
+ const w = winners.get(n);
+ const prev = old.get(n);
+ if (!w) {
+ sql.exec("DELETE FROM items WHERE number = ?", n);
+ sql.exec("DELETE FROM links WHERE number = ?", n);
+ continue;
+ }
+ const ip = itemPath(w.path)!;
+ const t = touch.get(w.path) ?? {};
+ const changed = !prev || prev.blob !== w.blob || prev.path !== w.path;
+ const body = bodies.get(w.blob) ?? (prev && prev.blob === w.blob && prev.parser > 0 ? prev.body : null);
+ const parsed = body !== null ? parseItem(ip, body) : pendingParse(ip);
+ const last = t.last ?? (complete ? undefined : newest);
+ const updatedAt = changed ? (last?.at ?? prev?.updated_at ?? null) : (prev?.updated_at ?? null);
+ let authorName = prev?.author_name ?? null;
+ let authorEmail = prev?.author_email ?? null;
+ let createdAt = prev?.created_at ?? null;
+ if (!prev && t.added) {
+ authorName = t.added.authorName;
+ authorEmail = t.added.authorEmail;
+ createdAt = t.added.at;
+ }
+ let closedAt = prev?.closed_at ?? null;
+ let closedBy = prev?.closed_by ?? null;
+ const wasOpen = !prev || stageOf(prev.path) === "open";
+ if (ip.stage === "open") {
+ closedAt = null;
+ closedBy = null;
+ } else if (wasOpen) {
+ const closer = t.closed ?? (complete ? t.last : newest);
+ closedAt = closer?.at ?? null;
+ closedBy = closer ? closerName(closer) : null;
+ }
+ sql.exec(
+ `INSERT INTO items (number, path, blob, body, parsed, parser, author_name, author_email, created_at, updated_at, closed_at, closed_by)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (number) DO UPDATE SET path = excluded.path, blob = excluded.blob, body = excluded.body, parsed = excluded.parsed,
+ parser = excluded.parser, author_name = excluded.author_name, author_email = excluded.author_email, created_at = excluded.created_at,
+ updated_at = excluded.updated_at, closed_at = excluded.closed_at, closed_by = excluded.closed_by`,
+ n,
+ w.path,
+ w.blob,
+ body ?? "",
+ JSON.stringify(parsed),
+ body !== null ? PARSER_VERSION : 0,
+ authorName,
+ authorEmail,
+ createdAt,
+ updatedAt,
+ closedAt,
+ closedBy,
+ );
+ }
+ for (const l of links) this.link(l.number, l.sessionId, l.at);
+ this.setMeta("cursor", head);
+ this.setMeta("as_of", this.now());
+ });
+ return "done";
+ }
+
+ private link(number: number, sessionId: string, at: string): void {
+ this.deps.sql.exec(
+ "INSERT INTO links (number, session_id, last_at) VALUES (?, ?, ?) ON CONFLICT (number, session_id) DO UPDATE SET last_at = MAX(last_at, excluded.last_at)",
+ number,
+ sessionId,
+ at,
+ );
+ }
+
+ // ------------------------------------------------------------------ walk
+
+ /**
+ * A few commits of the walk over `work/` then `done/`, newest first, within the quota: links,
+ * authors (the commit that added the file), close dates and update dates the build could not know.
+ */
+ private async walkTick(): Promise<void> {
+ const walk = this.metaJson<WalkState>("walk");
+ const gh = this.client();
+ if (!walk || !gh || !gh.spare()) return;
+ const page = await gh.commits({ sha: walk.head, path: walk.dir, page: walk.page, perPage: WALK_PAGE });
+ const slice = page.slice(walk.index, walk.index + WALK_COMMITS_PER_TICK);
+ const details: { commit: CommitInfo; files: FileChange[] }[] = [];
+ for (const c of slice) {
+ if (!gh.spare()) break;
+ details.push({ commit: c, files: (await gh.commit(c.sha)).files });
+ }
+ const sql = this.deps.sql;
+ this.deps.transaction(() => {
+ for (const { commit, files } of details) {
+ const trailers = sessionTrailers(commit.message);
+ for (const f of files) {
+ const ip = itemPath(f.filename);
+ const from = f.previousFilename ? itemPath(f.previousFilename) : null;
+ const number = ip?.number ?? from?.number;
+ if (number === undefined) continue;
+ const row = sql.exec<ItemRow & Row>("SELECT * FROM items WHERE number = ?", number).toArray()[0];
+ if (!row) continue;
+ for (const sessionId of trailers) this.link(number, sessionId, commit.at);
+ if (ip && (f.status === "added" || (f.status === "renamed" && !from)) && (row.created_at === null || commit.at < row.created_at)) {
+ sql.exec("UPDATE items SET created_at = ?, author_name = ?, author_email = ? WHERE number = ?", commit.at, commit.authorName, commit.authorEmail, number);
+ }
+ if (ip?.stage === "closed" && row.closed_at === null && stageOf(row.path) === "closed" && (f.status === "added" || (f.status === "renamed" && from?.stage !== "closed"))) {
+ sql.exec("UPDATE items SET closed_at = ?, closed_by = ? WHERE number = ?", commit.at, closerName(commit), number);
+ }
+ if (row.updated_at === null && f.filename === row.path) sql.exec("UPDATE items SET updated_at = ? WHERE number = ?", commit.at, number);
+ }
+ }
+ let next: WalkState | null = { ...walk, index: walk.index + details.length };
+ if (next.index >= page.length) {
+ if (page.length >= WALK_PAGE) next = { ...walk, page: walk.page + 1, index: 0 };
+ else next = walk.dir === "work" ? { head: walk.head, dir: "done", page: 1, index: 0 } : null;
+ }
+ this.setMeta("walk", next ? JSON.stringify(next) : null);
+ });
+ }
+
+ // ------------------------------------------------------------------ pull requests
+
+ /** At most every 5 minutes while read: the state of open items' pull requests not final yet. */
+ private async refreshPulls(gh: WorkGitHub): Promise<void> {
+ const now = this.now();
+ if (now - this.metaNumber("read_at") >= READS_WINDOW_MS) return;
+ if (now - this.metaNumber("pulls_at") < PULLS_EVERY_MS) return;
+ if (!gh.spare("graphql")) return;
+ const final = new Set(
+ this.deps.sql.exec<{ url: string }>("SELECT url FROM pulls WHERE state IN ('merged', 'closed', 'unreadable')").toArray().map((r) => r.url),
+ );
+ const urls = new Set<string>();
+ for (const r of this.deps.sql.exec<{ parsed: string }>("SELECT parsed FROM items WHERE path LIKE 'work/%' AND parser > 0").toArray()) {
+ for (const url of (JSON.parse(r.parsed) as ParsedItem).pullRequests) if (pullOf(url) && !final.has(url)) urls.add(url);
+ }
+ if (!urls.size) return;
+ this.setMeta("pulls_at", now);
+ let states: Awaited<ReturnType<WorkGitHub["pulls"]>>;
+ try {
+ states = await gh.pulls([...urls].slice(0, PULLS_PER_QUERY));
+ } catch (error) {
+ // No pull request permission is not a problem with the repository: the links stay plain.
+ if (error instanceof GitHubGone) return;
+ throw error;
+ }
+ const at = new Date(now).toISOString();
+ this.deps.transaction(() => {
+ for (const [url, s] of states) {
+ const state = s === "unreadable" ? "unreadable" : s.state;
+ const title = s === "unreadable" ? null : s.title;
+ this.deps.sql.exec(
+ "INSERT INTO pulls (url, state, title, checked_at) VALUES (?, ?, ?, ?) ON CONFLICT (url) DO UPDATE SET state = excluded.state, title = excluded.title, checked_at = excluded.checked_at",
+ url,
+ state,
+ title,
+ at,
+ );
+ }
+ });
+ }
+
+ // ------------------------------------------------------------------ parser version
+
+ /** A new parser version re-parses every stored body, with no GitHub call. */
+ private reparse(): void {
+ if (this.meta("parser_version") === String(PARSER_VERSION)) return;
+ this.deps.transaction(() => {
+ for (const r of this.deps.sql.exec<{ number: number; path: string; body: string } & Row>("SELECT number, path, body FROM items WHERE parser > 0").toArray()) {
+ const ip = itemPath(r.path);
+ if (ip) this.deps.sql.exec("UPDATE items SET parsed = ?, parser = ? WHERE number = ?", JSON.stringify(parseItem(ip, r.body)), PARSER_VERSION, r.number);
+ }
+ this.setMeta("parser_version", PARSER_VERSION);
+ });
+ }
+
+ // ------------------------------------------------------------------ rows to items
+
+ private indexed(rows: ItemRow[]): IndexedItem[] {
+ const repo = this.repo();
+ if (!rows.length || !repo) return [];
+ const sql = this.deps.sql;
+ const numbers = rows.map((r) => r.number);
+ const marks = numbers.map(() => "?").join(",");
+ const others = new Map<number, string[]>();
+ for (const f of sql.exec<{ number: number; path: string } & Row>(`SELECT number, path FROM files WHERE number IN (${marks}) ORDER BY path`, ...numbers).toArray()) {
+ others.set(f.number, [...(others.get(f.number) ?? []), f.path]);
+ }
+ const links = new Map<number, string[]>();
+ for (const l of sql.exec<{ number: number; session_id: string } & Row>(`SELECT number, session_id FROM links WHERE number IN (${marks}) ORDER BY last_at DESC, session_id`, ...numbers).toArray()) {
+ links.set(l.number, [...(links.get(l.number) ?? []), l.session_id]);
+ }
+ const pulls = new Map<string, { state: string | null; title: string | null }>();
+ for (const p of sql.exec<{ url: string; state: string | null; title: string | null } & Row>("SELECT url, state, title FROM pulls").toArray()) pulls.set(p.url, p);
+ return rows.map((r) => {
+ const stage = stageOf(r.path);
+ const parsed = JSON.parse(r.parsed) as ParsedItem;
+ const duplicates = (others.get(r.number) ?? []).filter((p) => p !== r.path).map((p) => `Another file has number ${r.number}: ${p}`);
+ return {
+ number: r.number,
+ stage,
+ path: r.path,
+ url: `https://github.com/${repo.owner}/${repo.name}/blob/${repo.branch.split("/").map(encodeURIComponent).join("/")}/${r.path.split("/").map(encodeURIComponent).join("/")}`,
+ title: parsed.title,
+ stateLine: parsed.stateLine,
+ tags: parsed.tags,
+ owner: parsed.owner,
+ author: r.author_name !== null ? { name: r.author_name, email: r.author_email } : null,
+ left: parsed.left,
+ readyToClose: readyToClose(stage, parsed),
+ warnings: [...parsed.warnings, ...duplicates],
+ pullRequests: parsed.pullRequests.map((url) => {
+ const p = pulls.get(url);
+ const state = p && p.state !== "unreadable" ? (p.state as IndexedItem["pullRequests"][number]["state"]) : null;
+ return { url, state, title: p && p.state !== "unreadable" ? p.title : null };
+ }),
+ sessionIds: links.get(r.number) ?? [],
+ updatedAt: r.updated_at,
+ createdAt: r.created_at,
+ closedAt: stage === "closed" ? r.closed_at : null,
+ closedBy: stage === "closed" ? r.closed_by : null,
+ parsed: r.parser > 0,
+ };
+ });
+ }
+}
+
+// -------------------------------------------------------------------- helpers
+
+function stageOf(path: string): "open" | "closed" {
+ return path.startsWith("done/") ? "closed" : "open";
+}
+
+/** The row of each number: its open file before a closed one, then the first path. */
+function pickWinners(files: { path: string; number: number; blob: string }[]): Map<number, { path: string; number: number; blob: string }> {
+ const out = new Map<number, { path: string; number: number; blob: string }>();
+ for (const f of files) {
+ const cur = out.get(f.number);
+ if (!cur) {
+ out.set(f.number, f);
+ continue;
+ }
+ const rank = (p: string) => (stageOf(p) === "open" ? 0 : 1);
+ if (rank(f.path) < rank(cur.path) || (rank(f.path) === rank(cur.path) && f.path < cur.path)) out.set(f.number, f);
+ }
+ return out;
+}
+
+/** The fields of a row whose body is not read yet: the slug as title. */
+function pendingParse(ip: ItemPath): ParsedItem {
+ return { title: slugTitle(ip.slug), stateLine: null, tags: [], owner: null, left: null, boxes: 0, pullRequests: [], warnings: [] };
+}
+
+/** Who closed: the commit's author, or null when a session made the commit (it says "closed in a session"). */
+function closerName(c: CommitInfo): string | null {
+ if (sessionTrailers(c.message).length) return null;
+ return c.authorName.replace(/\s+via Computer$/i, "").trim() || null;
+}
+
+function refusal(problem: RepositoryProblem): string {
+ switch (problem) {
+ case "installation_removed":
+ return "The GitHub installation is not connected to this organization.";
+ case "installation_suspended":
+ return "The GitHub installation is suspended.";
+ case "repository_not_found":
+ return "The repository does not exist or the installation does not grant it.";
+ case "branch_not_found":
+ return "The repository has no such branch.";
+ case "access_denied":
+ return "The installation cannot read the repository's contents.";
+ case "github_app_not_configured":
+ return "The GitHub App is not configured.";
+ }
+}
+
+function encodeCursor(value: Record<string, number>): string {
+ return btoa(JSON.stringify(value)).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
+}
+
+function decodeCursor(cursor: string, key: string): number | null {
+ try {
+ const text = atob(cursor.replace(/-/g, "+").replace(/_/g, "/"));
+ const value = (JSON.parse(text) as Record<string, unknown>)[key];
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+async function parallel<T>(items: T[], fn: (item: T) => Promise<void>): Promise<void> {
+ let next = 0;
+ const lanes = Array.from({ length: Math.min(FETCH_PARALLEL, items.length) }, async () => {
+ while (next < items.length) await fn(items[next++]!);
+ });
+ await Promise.all(lanes);
+}
diff --git a/services/managed-agents/test/fixtures/fake-github-repo.ts b/services/managed-agents/test/fixtures/fake-github-repo.ts
new file mode 100644
index 00000000..b56470d7
--- /dev/null
+++ b/services/managed-agents/test/fixtures/fake-github-repo.ts
@@ -0,0 +1,214 @@
+import { createHash } from "node:crypto";
+
+/**
+ * A knowledge repository on a fake GitHub, as much of the REST API as the Work index uses: the
+ * branch ref (with ETag), compare (with rename detection), commits (one, and filtered by path),
+ * trees (a commit's root, then one directory), blobs, the repository, and the pull request
+ * GraphQL query. History is a list of commits with whole-tree snapshots; `forcePush` rewrites it.
+ */
+
+export interface FakeCommit {
+ sha: string;
+ parent: string | null;
+ message: string;
+ author: { name: string; email: string };
+ at: string;
+ files: Map<string, string>;
+}
+
+export interface FakePull {
+ state: "OPEN" | "MERGED" | "CLOSED";
+ isDraft?: boolean;
+ title: string;
+}
+
+const sha1 = (text: string) => createHash("sha1").update(text).digest("hex");
+
+export class FakeRepo {
+ owner = "acme";
+ name = "knowledge";
+ defaultBranch = "main";
+ commits = new Map<string, FakeCommit>();
+ head: string | null = null;
+ /** Every request, as `METHOD path`. */
+ log: string[] = [];
+ /** The next requests answer this (then normal service resumes). */
+ failNext: { status: number; headers?: Record<string, string> }[] = [];
+ remaining = 5000;
+ limit = 5000;
+ deleted = false;
+ pulls = new Map<string, FakePull>();
+ private clock = Date.parse("2026-11-01T00:00:00Z");
+
+ constructor(initial: Record<string, string> = {}) {
+ this.commit(initial, "Initial", { name: "Ana", email: "[email protected]" });
+ }
+
+ /** A commit on the branch: `changes` maps a path to its new text, or null to remove it. */
+ commit(changes: Record<string, string | null>, message = "Update", author = { name: "Ana", email: "[email protected]" }, renames: Record<string, string> = {}): string {
+ const files = new Map(this.head ? this.commits.get(this.head)!.files : []);
+ for (const [from, to] of Object.entries(renames)) {
+ files.set(to, files.get(from)!);
+ files.delete(from);
+ }
+ for (const [path, text] of Object.entries(changes)) {
+ if (text === null) files.delete(path);
+ else files.set(path, text);
+ }
+ this.clock += 60_000;
+ const sha = sha1(`${this.head}\n${message}\n${this.clock}\n${[...files].join("\n")}`);
+ this.commits.set(sha, { sha, parent: this.head, message, author, at: new Date(this.clock).toISOString(), files });
+ this.head = sha;
+ return sha;
+ }
+
+ /** Rewrites history: a new root commit with these files; the old commits are forgotten. */
+ forcePush(files: Record<string, string>, message = "Rewritten"): string {
+ this.commits.clear();
+ this.head = null;
+ return this.commit(files, message);
+ }
+
+ blobSha(text: string): string {
+ return sha1(`blob\n${text}`);
+ }
+
+ private ancestors(sha: string): string[] {
+ const out: string[] = [];
+ for (let c: string | null = sha; c; c = this.commits.get(c)?.parent ?? null) out.push(c);
+ return out;
+ }
+
+ /** The files a commit changed against its parent, GitHub style (renames by equal content). */
+ diff(from: Map<string, string>, to: Map<string, string>) {
+ const out: { filename: string; status: string; previous_filename?: string; sha?: string }[] = [];
+ const removed = [...from.keys()].filter((p) => !to.has(p));
+ const added = [...to.keys()].filter((p) => !from.has(p));
+ const renamedFrom = new Set<string>();
+ for (const p of added) {
+ const source = removed.find((r) => !renamedFrom.has(r) && from.get(r) === to.get(p));
+ if (source) {
+ renamedFrom.add(source);
+ out.push({ filename: p, status: "renamed", previous_filename: source, sha: this.blobSha(to.get(p)!) });
+ } else out.push({ filename: p, status: "added", sha: this.blobSha(to.get(p)!) });
+ }
+ for (const p of removed) if (!renamedFrom.has(p)) out.push({ filename: p, status: "removed", sha: this.blobSha(from.get(p)!) });
+ for (const [p, text] of to) if (from.has(p) && from.get(p) !== text) out.push({ filename: p, status: "modified", sha: this.blobSha(text) });
+ return out;
+ }
+
+ private commitJson(c: FakeCommit) {
+ return { sha: c.sha, commit: { message: c.message, author: { name: c.author.name, email: c.author.email, date: c.at } } };
+ }
+
+ private changed(c: FakeCommit) {
+ return this.diff(c.parent ? this.commits.get(c.parent)!.files : new Map(), c.files);
+ }
+
+ private blobs(): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const c of this.commits.values()) for (const text of c.files.values()) out.set(this.blobSha(text), text);
+ return out;
+ }
+
+ /** The `fetch` the client is given. */
+ fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const url = new URL(String(input));
+ const method = init?.method ?? "GET";
+ this.log.push(`${method} ${url.pathname}${url.search}`);
+ const headers = new Headers(init?.headers);
+ const quota = () => ({
+ "x-ratelimit-limit": String(this.limit),
+ "x-ratelimit-remaining": String(Math.max(0, --this.remaining)),
+ "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 3600),
+ "x-ratelimit-resource": url.pathname === "/graphql" ? "graphql" : "core",
+ });
+ const json = (status: number, body: unknown, extra: Record<string, string> = {}) =>
+ new Response(status === 304 ? null : JSON.stringify(body), { status, headers: { "content-type": "application/json", ...quota(), ...extra } });
+ const fail = this.failNext.shift();
+ if (fail) return json(fail.status, { message: "failed" }, fail.headers);
+ if (!headers.get("authorization")?.startsWith("Bearer ")) return json(401, { message: "no token" });
+
+ if (url.pathname === "/graphql") {
+ const query = JSON.parse(String(init?.body)).query as string;
+ const data: Record<string, unknown> = {};
+ for (const m of query.matchAll(/(p\d+): repository\(owner: "([^"]+)", name: "([^"]+)"\) \{ pullRequest\(number: (\d+)\)/g)) {
+ const pr = this.pulls.get(`https://github.com/${m[2]}/${m[3]}/pull/${m[4]}`);
+ data[m[1]!] = pr ? { pullRequest: { state: pr.state, isDraft: pr.isDraft ?? false, title: pr.title } } : null;
+ }
+ return json(200, { data });
+ }
+ const base = `/repos/${this.owner}/${this.name}`;
+ // GitHub's owner and repository names are case-insensitive.
+ if (this.deleted || !url.pathname.toLowerCase().startsWith(base.toLowerCase())) return json(404, { message: "Not Found" });
+ const rest = url.pathname.slice(base.length);
+ if (rest === "") return json(200, { name: this.name, owner: { login: this.owner }, default_branch: this.defaultBranch });
+ if (rest === `/git/ref/heads/${this.defaultBranch}`) {
+ const etag = `"${this.head}"`;
+ if (headers.get("if-none-match") === etag) return json(304, null, { etag });
+ return json(200, { object: { sha: this.head, type: "commit" } }, { etag });
+ }
+ if (rest.startsWith("/git/ref/heads/")) return json(404, { message: "Not Found" });
+ let m = /^\/compare\/([0-9a-f]+)\.\.\.([0-9a-f]+)$/.exec(rest);
+ if (m) {
+ const [baseSha, headSha] = [m[1]!, m[2]!];
+ if (!this.commits.has(baseSha) || !this.commits.has(headSha)) return json(404, { message: "Not Found" });
+ const line = this.ancestors(headSha);
+ const at = line.indexOf(baseSha);
+ if (at === -1) return json(200, { status: "diverged", total_commits: 0, commits: [], files: [] });
+ if (at === 0) return json(200, { status: "identical", total_commits: 0, commits: [], files: [] });
+ const range = line.slice(0, at).reverse().map((s) => this.commits.get(s)!);
+ return json(200, {
+ status: "ahead",
+ total_commits: range.length,
+ commits: range.map((c) => this.commitJson(c)),
+ files: this.diff(this.commits.get(baseSha)!.files, this.commits.get(headSha)!.files),
+ });
+ }
+ m = /^\/commits\/([0-9a-f]+)$/.exec(rest);
+ if (m) {
+ const c = this.commits.get(m[1]!);
+ return c ? json(200, { ...this.commitJson(c), files: this.changed(c) }) : json(404, { message: "Not Found" });
+ }
+ if (rest === "/commits") {
+ const from = url.searchParams.get("sha")!;
+ const path = url.searchParams.get("path")!;
+ const page = Number(url.searchParams.get("page") ?? "1");
+ const perPage = Number(url.searchParams.get("per_page") ?? "30");
+ const touching = this.ancestors(from)
+ .map((s) => this.commits.get(s)!)
+ .filter((c) => this.changed(c).some((f) => f.filename === path || f.filename.startsWith(`${path}/`) || f.previous_filename === path || f.previous_filename?.startsWith(`${path}/`)));
+ return json(200, touching.slice((page - 1) * perPage, page * perPage).map((c) => this.commitJson(c)));
+ }
+ m = /^\/git\/trees\/(.+)$/.exec(rest);
+ if (m) {
+ const id = decodeURIComponent(m[1]!);
+ const dir = /^tree-([0-9a-f]+)-(.+)$/.exec(id);
+ const commit = this.commits.get(dir ? dir[1]! : id);
+ if (!commit) return json(404, { message: "Not Found" });
+ const prefix = dir ? `${dir[2]}/` : "";
+ const entries = new Map<string, { path: string; type: string; sha: string }>();
+ for (const [path, text] of commit.files) {
+ if (!path.startsWith(prefix)) continue;
+ const name = path.slice(prefix.length);
+ const slash = name.indexOf("/");
+ if (slash === -1) entries.set(name, { path: name, type: "blob", sha: this.blobSha(text) });
+ else entries.set(name.slice(0, slash), { path: name.slice(0, slash), type: "tree", sha: `tree-${commit.sha}-${prefix}${name.slice(0, slash)}` });
+ }
+ return json(200, { sha: id, tree: [...entries.values()], truncated: false });
+ }
+ m = /^\/git\/blobs\/([0-9a-f]+)$/.exec(rest);
+ if (m) {
+ const text = this.blobs().get(m[1]!);
+ return text === undefined ? json(404, { message: "Not Found" }) : json(200, { sha: m[1], encoding: "base64", content: Buffer.from(text).toString("base64") });
+ }
+ return json(404, { message: "Not Found" });
+ };
+
+ /** Requests made since the last call, then forgets them. */
+ take(): string[] {
+ const out = this.log;
+ this.log = [];
+ return out;
+ }
+}
diff --git a/services/managed-agents/test/work-index.test.ts b/services/managed-agents/test/work-index.test.ts
new file mode 100644
index 00000000..45565e49
--- /dev/null
+++ b/services/managed-agents/test/work-index.test.ts
@@ -0,0 +1,476 @@
+import { describe, expect, it } from "vitest";
+
+import type { TokenMinter } from "../src/computer/work/github.js";
+import { ALARM_EVERY_MS, FILL_BATCH, LOOK_AFTER_MS, PULLS_EVERY_MS, WorkIndex } from "../src/computer/work/index.js";
+import type { IndexedItem, ItemsResult } from "../src/computer/work/index-contract.js";
+import { sqlStorage } from "./fixtures/computer-sql.js";
+import { FakeRepo } from "./fixtures/fake-github-repo.js";
+
+/** Work tracking 3.6: the Work index against a fake GitHub. */
+
+const ORG = "acct_1";
+const by = { member: "m_1", name: "Ana", email: "[email protected]" };
+
+function setup(repo: FakeRepo, options: { sql?: SqlStorage; mint?: TokenMinter } = {}) {
+ let t = Date.parse("2026-11-19T10:00:00Z");
+ const pending: Promise<unknown>[] = [];
+ const mints: unknown[] = [];
+ let alarmAt: number | null = null;
+ const sql = options.sql ?? sqlStorage();
+ const account: TokenMinter = options.mint ?? {
+ async mintGitHubInstallationToken(input) {
+ mints.push(input);
+ return { outcome: "minted", token: "ghs_test", expiresAt: new Date(t + 3_600_000).toISOString() };
+ },
+ };
+ const index = new WorkIndex({
+ sql,
+ transaction: (fn) => fn(),
+ account: () => account,
+ arm: async (at) => {
+ if (alarmAt === null || at < alarmAt) alarmAt = at;
+ },
+ waitUntil: (p) => void pending.push(p),
+ fetch: repo.fetch,
+ now: () => t,
+ });
+ const settle = async () => {
+ while (pending.length) await Promise.allSettled(pending.splice(0));
+ };
+ return {
+ index,
+ sql,
+ mints,
+ settle,
+ tick: (ms: number) => (t += ms),
+ now: () => t,
+ alarmAt: () => alarmAt,
+ /** Runs alarms until there is nothing more to do (or `max` runs). */
+ async drain(max = 50) {
+ for (let i = 0; i < max; i++) {
+ const next = await index.alarm();
+ await settle();
+ if (next === null) return;
+ t = Math.max(t, next);
+ if (index["meta"]("build") === null && index["meta"]("walk") === null && t - Number(index["meta"]("read_at")) > 10 * 60_000) return;
+ }
+ },
+ };
+}
+
+const item = (n: number, title: string, extra = "") => `# ${n}. ${title}\n\nState of ${title}.\n${extra}`;
+
+async function connect(repo: FakeRepo) {
+ const s = setup(repo);
+ const r = await s.index.setRepository(ORG, { installationId: "inst_1", owner: "ACME", name: "Knowledge" }, by);
+ expect(r).toMatchObject({ ok: true, value: { installationId: "inst_1", owner: "acme", name: "knowledge", branch: "main", problem: null } });
+ await s.settle();
+ await s.drain();
+ return s;
+}
+
+const open = async (s: ReturnType<typeof setup>) => {
+ const r = await s.index.items(ORG, { stage: "open" });
+ if (!r.ok) throw new Error("not ok");
+ return r;
+};
+const byNumber = (r: ItemsResult & { ok: true }) => new Map<number, IndexedItem>(r.items.map((i) => [i.number, i]));
+
+describe("build", () => {
+ it("reads open items, gives closed ones a row from the listing, and reads those on demand", async () => {
+ const repo = new FakeRepo({
+ "work/1-board.md": item(1, "Board", "## Left\n- [x] a\n"),
+ "work/2-api.md": item(2, "API"),
+ "work/README.md": "not an item",
+ "done/3-old-thing.md": item(3, "Old thing"),
+ "notes/4-x.md": item(4, "Not tracked"),
+ });
+ const s = setup(repo);
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ await s.settle();
+ const r = await open(s);
+ expect(r.head).toBe(repo.head);
+ expect(r.building).toBe(false);
+ expect(r.items.map((i) => [i.number, i.title, i.stateLine, i.readyToClose])).toEqual([
+ [1, "Board", "State of Board.", true],
+ [2, "API", "State of API.", false],
+ ]);
+ expect(r.items[0]!.url).toBe("https://github.com/acme/knowledge/blob/main/work/1-board.md");
+ expect(r.items[0]!.updatedAt).toBe(repo.commits.get(repo.head!)!.at);
+ // The token is narrowed to the repository, contents read.
+ expect(s.mints[0]).toEqual({ installationId: "inst_1", permissions: { contents: "read" }, repositories: ["knowledge"] });
+
+ // The build read the two open bodies only.
+ expect(repo.take().filter((l) => l.includes("/git/blobs/"))).toHaveLength(2);
+ const closed = await s.index.items(ORG, { stage: "closed" });
+ expect(closed.ok && closed.items.map((i) => [i.number, i.title, i.parsed])).toEqual([[3, "Old thing", true]]);
+ expect(repo.take().filter((l) => l.includes("/git/blobs/"))).toHaveLength(1);
+ });
+
+ it("reads open items in batches of 50 continued by the alarm, building until the last", async () => {
+ const files: Record<string, string> = {};
+ for (let n = 1; n <= FILL_BATCH + 5; n++) files[`work/${n}-item.md`] = item(n, `Item ${n}`);
+ const repo = new FakeRepo(files);
+ const s = setup(repo);
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ await s.settle();
+ let r = await open(s);
+ expect(r.building).toBe(true);
+ expect(r.items.filter((i) => i.parsed)).toHaveLength(FILL_BATCH);
+ expect(r.items.find((i) => !i.parsed)!.title).toBe("item");
+ expect(s.alarmAt()).not.toBeNull();
+ s.tick(1000);
+ await s.index.alarm();
+ r = await open(s);
+ expect(r.building).toBe(false);
+ expect(r.items.every((i) => i.parsed)).toBe(true);
+ });
+
+ it("the walk recovers authors, created dates, links and close dates after a build", async () => {
+ const repo = new FakeRepo({});
+ repo.commit({ "work/1-a.md": item(1, "A") }, "Add 1\n\nSession: cs_one", { name: "Bob", email: "[email protected]" });
+ repo.commit({ "work/2-b.md": item(2, "B") }, "Add 2", { name: "Cy via Computer", email: "[email protected]" });
+ repo.commit({}, "Close 2", { name: "Cy via Computer", email: "[email protected]" }, { "work/2-b.md": "done/2-b.md" });
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ const one = (await s.index.item(ORG, 1)).item!;
+ expect(one.author).toEqual({ name: "Bob", email: "[email protected]" });
+ expect(one.createdAt).toBe([...repo.commits.values()][1]!.at);
+ expect(one.sessionIds).toEqual(["cs_one"]);
+ const two = (await s.index.item(ORG, 2)).item!;
+ expect(two.stage).toBe("closed");
+ expect(two.closedBy).toBe("Cy");
+ expect(two.closedAt).toBe(repo.commits.get(repo.head!)!.at);
+ expect(s.index["meta"]("walk")).toBeNull();
+ });
+});
+
+describe("advance", () => {
+ it("a push costs a head check, one compare and one blob", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.take();
+ repo.commit({ "work/1-a.md": item(1, "A renamed") }, "Edit 1", { name: "Bob", email: "[email protected]" });
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect(repo.take().map((l) => l.split("?")[0]!.replace(/[0-9a-f]{40}/g, "SHA"))).toEqual([
+ "GET /repos/acme/knowledge/git/ref/heads/main",
+ "GET /repos/acme/knowledge/compare/SHA...SHA",
+ "GET /repos/acme/knowledge/git/blobs/SHA",
+ ]);
+ const r = await open(s);
+ expect(r.head).toBe(repo.head);
+ expect(r.items[0]!.title).toBe("A renamed");
+ expect(r.items[0]!.updatedAt).toBe(repo.commits.get(repo.head!)!.at);
+ });
+
+ it("an unchanged head is a 304 and nothing else; a fresh read does not look", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ repo.take();
+ s.tick(LOOK_AFTER_MS + 1);
+ const before = (await open(s)).asOf;
+ await s.settle();
+ expect(repo.take()).toEqual(["GET /repos/acme/knowledge/git/ref/heads/main"]);
+ const after = (await open(s)).asOf;
+ expect(Date.parse(after!)).toBeGreaterThan(Date.parse(before!));
+ await open(s);
+ await s.settle();
+ expect(repo.take()).toEqual([]);
+ });
+
+ it("a move to done/ sets closedAt and closedBy from that commit, a move back clears them", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B") });
+ const s = await connect(repo);
+ repo.commit({}, "Close 1", { name: "Bob via Computer", email: "[email protected]" }, { "work/1-a.md": "done/1-a.md" });
+ await s.index.poke(ORG);
+ await s.settle();
+ let one = (await s.index.item(ORG, 1)).item!;
+ expect(one).toMatchObject({ stage: "closed", path: "done/1-a.md", closedBy: "Bob", closedAt: repo.commits.get(repo.head!)!.at, readyToClose: false });
+ expect((await open(s)).items.map((i) => i.number)).toEqual([2]);
+ // Two commits: a session closes 2 (no closer name), then 1 is reopened.
+ repo.commit({}, "Close 2\n\nSession: cs_x", { name: "Cy", email: "[email protected]" }, { "work/2-b.md": "done/2-b.md" });
+ repo.commit({}, "Reopen 1", { name: "Ana", email: "[email protected]" }, { "done/1-a.md": "work/1-a.md" });
+ await s.index.poke(ORG);
+ await s.settle();
+ one = (await s.index.item(ORG, 1)).item!;
+ expect(one).toMatchObject({ stage: "open", closedAt: null, closedBy: null });
+ const two = (await s.index.item(ORG, 2)).item!;
+ expect(two).toMatchObject({ stage: "closed", closedBy: null, sessionIds: ["cs_x"] });
+ expect(two.closedAt).toBe([...repo.commits.values()].at(-2)!.at);
+ });
+
+ it("Session: trailers link: one commit uses the range's files, more ask only the trailer commits", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B") });
+ const s = await connect(repo);
+ repo.take();
+ repo.commit({ "work/1-a.md": item(1, "A", "more") }, "Edit\n\nSession: cs_1");
+ await s.index.poke(ORG);
+ await s.settle();
+ expect(repo.take().some((l) => /\/commits\/[0-9a-f]{40}$/.test(l))).toBe(false);
+ expect((await s.index.item(ORG, 1)).item!.sessionIds).toEqual(["cs_1"]);
+
+ repo.commit({ "work/2-b.md": item(2, "B", "x") }, "Edit 2\n\nSession: cs_2");
+ repo.commit({ "work/1-a.md": item(1, "A", "y") }, "Edit 1 by hand");
+ repo.take();
+ await s.index.poke(ORG);
+ await s.settle();
+ expect(repo.take().filter((l) => /\/commits\/[0-9a-f]{40}$/.test(l))).toHaveLength(1);
+ expect((await s.index.item(ORG, 2)).item!.sessionIds).toEqual(["cs_2"]);
+ expect((await s.index.item(ORG, 1)).item!.sessionIds).toEqual(["cs_1"]);
+ });
+
+ it("an added item takes its author from the commit; a removed one loses its row and links", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.commit({ "work/2-b.md": item(2, "B") }, "Add 2\n\nSession: cs_2", { name: "Bob", email: "[email protected]" });
+ await s.index.poke(ORG);
+ await s.settle();
+ expect((await s.index.item(ORG, 2)).item).toMatchObject({ author: { name: "Bob", email: "[email protected]" }, sessionIds: ["cs_2"] });
+ repo.commit({ "work/2-b.md": null }, "Remove 2");
+ await s.index.poke(ORG);
+ await s.settle();
+ expect((await s.index.item(ORG, 2)).item).toBeNull();
+ expect(s.sql.exec("SELECT * FROM links WHERE number = 2").toArray()).toEqual([]);
+ });
+
+ it("a rewritten history rebuilds, keeping links of the items that remain", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B") });
+ const s = await connect(repo);
+ repo.commit({ "work/1-a.md": item(1, "A", "z") }, "Edit\n\nSession: cs_1");
+ await s.index.poke(ORG);
+ await s.settle();
+ repo.forcePush({ "work/1-a.md": item(1, "A", "z"), "work/3-c.md": item(3, "C") });
+ await s.index.poke(ORG);
+ await s.settle();
+ const r = await open(s);
+ expect(r.head).toBe(repo.head);
+ expect(r.items.map((i) => i.number)).toEqual([1, 3]);
+ expect(byNumber(r).get(1)!.sessionIds).toEqual(["cs_1"]);
+ });
+
+ it("duplicate numbers: the open file wins, the other is a warning, and is promoted when the winner goes", async () => {
+ const repo = new FakeRepo({ "work/5-new.md": item(5, "New"), "done/5-old.md": item(5, "Old") });
+ const s = await connect(repo);
+ let five = (await s.index.item(ORG, 5)).item!;
+ expect(five).toMatchObject({ path: "work/5-new.md", title: "New", warnings: ["Another file has number 5: done/5-old.md"] });
+ repo.commit({ "work/5-a-second.md": item(5, "Second") });
+ await s.index.poke(ORG);
+ await s.settle();
+ five = (await s.index.item(ORG, 5)).item!;
+ expect(five.path).toBe("work/5-a-second.md");
+ expect(five.warnings).toHaveLength(2);
+ repo.commit({ "work/5-a-second.md": null, "work/5-new.md": null });
+ await s.index.poke(ORG);
+ await s.settle();
+ five = (await s.index.item(ORG, 5)).item!;
+ expect(five).toMatchObject({ path: "done/5-old.md", stage: "closed", title: "Old", warnings: [] });
+ });
+});
+
+describe("GitHub trouble", () => {
+ it("a 429 with retry-after pauses: nothing is asked until it ends, and the read still answers", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.commit({ "work/1-a.md": item(1, "A2") });
+ repo.failNext.push({ status: 429, headers: { "retry-after": "120" } });
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ repo.take();
+ s.tick(LOOK_AFTER_MS + 1);
+ expect((await open(s)).items[0]!.title).toBe("A");
+ await s.settle();
+ expect(repo.take()).toEqual([]);
+ s.tick(120_000);
+ await open(s);
+ await s.settle();
+ expect((await open(s)).items[0]!.title).toBe("A2");
+ });
+
+ it("a 403 rate limit (remaining 0) is a pause, not a problem", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.failNext.push({ status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(s.now() / 1000) + 60) } });
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect((await open(s)).problem).toBeNull();
+ expect(Number(s.index["meta"]("pause_until"))).toBeGreaterThan(s.now());
+ });
+
+ it("under a fifth of the quota left, the walk stops", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = setup(repo);
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ await s.settle();
+ repo.remaining = 900;
+ repo.take();
+ s.tick(11 * 60_000);
+ await s.index.alarm();
+ // One call to learn the quota is low, then nothing more.
+ expect(repo.take().length).toBeLessThanOrEqual(1);
+ expect(s.index["meta"]("walk")).not.toBeNull();
+ });
+
+ it("a deleted repository sets problem; it clears when the repository is back", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.deleted = true;
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ const r = await open(s);
+ expect(r.problem).toBe("repository_not_found");
+ expect(r.repository!.problem).toBe("repository_not_found");
+ expect(r.items).toHaveLength(1);
+ repo.deleted = false;
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect((await open(s)).problem).toBeNull();
+ });
+
+ it("a removed installation is installation_removed", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ let connected = true;
+ const s = setup(repo, {
+ mint: {
+ async mintGitHubInstallationToken() {
+ return connected ? { outcome: "minted", token: "t", expiresAt: new Date(Date.now() + 3_600_000).toISOString() } : { outcome: "not_connected" };
+ },
+ },
+ });
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ await s.settle();
+ connected = false;
+ s.index["github"] = null;
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect((await open(s)).problem).toBe("installation_removed");
+ });
+});
+
+describe("pull requests", () => {
+ it("one query at most every 5 minutes; merged is never asked again; unreadable is a plain link", async () => {
+ const pr = (n: number) => `https://github.com/acme/app/pull/${n}`;
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A", `PR: ${pr(1)} ${pr(2)} ${pr(3)} https://example.com/x\n`) });
+ repo.pulls.set(pr(1), { state: "OPEN", title: "One" });
+ repo.pulls.set(pr(2), { state: "MERGED", title: "Two" });
+ const s = await connect(repo);
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ let prs = (await open(s)).items[0]!.pullRequests;
+ expect(prs).toEqual([
+ { url: pr(1), state: "open", title: "One" },
+ { url: pr(2), state: "merged", title: "Two" },
+ { url: pr(3), state: null, title: null },
+ { url: "https://example.com/x", state: null, title: null },
+ ]);
+ expect(s.mints).toContainEqual({ installationId: "inst_1", permissions: { pull_requests: "read" } });
+ repo.take();
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect(repo.take().filter((l) => l.includes("graphql"))).toEqual([]);
+ repo.pulls.set(pr(1), { state: "OPEN", isDraft: true, title: "One" });
+ s.tick(PULLS_EVERY_MS);
+ await open(s);
+ await s.settle();
+ const queries = repo.take().filter((l) => l.includes("graphql"));
+ expect(queries).toHaveLength(1);
+ prs = (await open(s)).items[0]!.pullRequests;
+ expect(prs[0]!.state).toBe("draft");
+ });
+});
+
+describe("history", () => {
+ it("merges the work/ and done/ paths, newest first, with session trailers", async () => {
+ const repo = new FakeRepo({});
+ repo.commit({ "work/1-a.md": item(1, "A") }, "Add 1\n\nbody", { name: "Ana", email: "a@x" });
+ repo.commit({ "work/1-a.md": item(1, "A", "x") }, "Edit 1\n\nSession: cs_9", { name: "Bob", email: "b@x" });
+ repo.commit({}, "Close 1", { name: "Cy", email: "c@x" }, { "work/1-a.md": "done/1-a.md" });
+ const s = await connect(repo);
+ const h = await s.index.history(ORG, 1);
+ expect(h.ok).toBe(true);
+ if (!h.ok) return;
+ expect(h.revisions.map((r) => [r.summary, r.authorName, r.sessionId])).toEqual([
+ ["Close 1", "Cy", null],
+ ["Edit 1", "Bob", "cs_9"],
+ ["Add 1", "Ana", null],
+ ]);
+ expect(h.revisions[0]!.url).toBe(`https://github.com/acme/knowledge/commit/${repo.head}`);
+ expect(h.nextCursor).toBeNull();
+ expect(await s.index.history(ORG, 99)).toEqual({ ok: false, error: "item_not_found" });
+ expect(await s.index.history(ORG, 1, "garbage!")).toEqual({ ok: false, error: "invalid_cursor" });
+ });
+});
+
+describe("setRepository", () => {
+ it("refuses what cannot be read, with the reason", async () => {
+ const repo = new FakeRepo({});
+ const s = setup(repo);
+ expect(await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "nope" }, by)).toMatchObject({
+ ok: false,
+ status: 400,
+ code: "invalid_request",
+ reason: "repository_not_found",
+ });
+ expect(await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge", branch: "gone" }, by)).toMatchObject({
+ ok: false,
+ reason: "branch_not_found",
+ field: "branch",
+ });
+ expect(await s.index.getRepository(ORG)).toBeNull();
+ });
+
+ it("wipes the projection when the repository changes, keeps it when it is the same", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge", branch: "main" }, by);
+ expect(s.sql.exec("SELECT number FROM items").toArray()).toHaveLength(1);
+ repo.defaultBranch = "trunk";
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge", branch: "trunk" }, by);
+ expect(s.sql.exec("SELECT number FROM items").toArray()).toHaveLength(0);
+ await s.settle();
+ expect((await open(s)).items.map((i) => i.number)).toEqual([1]);
+ });
+});
+
+describe("parser version", () => {
+ it("re-parses stored bodies with no GitHub call", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ s.sql.exec("UPDATE items SET parsed = ?", JSON.stringify({ title: "stale", stateLine: null, tags: [], owner: null, left: null, boxes: 0, pullRequests: [], warnings: [] }));
+ s.sql.exec("UPDATE meta SET v = '0' WHERE k = 'parser_version'");
+ repo.take();
+ const again = setup(repo, { sql: s.sql });
+ const r = await again.index.items(ORG, { stage: "open" });
+ expect(r.ok && r.items[0]!.title).toBe("A");
+ expect(repo.take()).toEqual([]);
+ });
+});
+
+describe("the alarm", () => {
+ it("looks once a minute while there have been reads in the last ten, then stops", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ await open(s);
+ await s.settle();
+ repo.take();
+ s.tick(ALARM_EVERY_MS);
+ expect(await s.index.alarm()).toBe(s.now() + ALARM_EVERY_MS);
+ expect(repo.take()).toEqual(["GET /repos/acme/knowledge/git/ref/heads/main"]);
+ s.tick(11 * 60_000);
+ expect(await s.index.alarm()).toBeNull();
+ });
+});
diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.ts
index 58f6c7ee..d9046e6f 100644
--- a/services/managed-agents/vitest.config.ts
+++ b/services/managed-agents/vitest.config.ts
@@ -495,6 +495,7 @@ export default defineConfig({
"test/computer-token-check.test.ts",
"test/computer-secrets.test.ts", "test/computer-secrets-scopes.test.ts",
"test/work-item.test.ts",
+ "test/work-index.test.ts",
"test/computer-connections.test.ts",
"test/computer-model-subscriptions.test.ts",
"test/computer-codex-subscriptions.test.ts",