Skip to content

An open-source, faster Devin alternative

TypeScript

Work index: portable core, bounded GitHub, cheap advance and a resumable walk (work tracking 3.2, 3.6, 3.10)

Igor Zalutski via Computerd77694a56ecf
diff --git a/services/managed-agents/src/computer/api-http.ts b/services/managed-agents/src/computer/api-http.ts
index b50ad35a..abe7183d 100644
--- a/services/managed-agents/src/computer/api-http.ts
+++ b/services/managed-agents/src/computer/api-http.ts
@@ -25,14 +25,14 @@ import type { LogReadRefusal, SessionLogRpc } from "./session-log-contract.js";
import { isSessionId, memberId } from "./session-ids.js";
import type { ApiCaller, ApiOp, ApiReply, WriteMethod } from "./sessions-api.js";
import type { SecretsApiOp } from "./secrets-store.js";
-import type { WorkContextOp } from "./work/briefs.js";
+import type { WorkContextOp, WorkStampOp } from "./work/briefs.js";
import { type WorkRoute, workApi } from "./work/api.js";
import type { WorkIndexRpc } from "./work/index-contract.js";
import { gatewayTelemetry } from "./telemetry/gateway.js";
/** What api-http needs of the Computer DO stub. */
export interface ComputerApiStub {
- computerApi(accountId: string, caller: ApiCaller, op: ApiOp | SecretsApiOp | WorkContextOp): Promise<ApiReply>;
+ computerApi(accountId: string, caller: ApiCaller, op: ApiOp | SecretsApiOp | WorkContextOp | WorkStampOp): Promise<ApiReply>;
}
const BODY_MAX_BYTES = 512 * 1024;
@@ -398,6 +398,7 @@ async function routeApi(
);
const response = out.of(reply);
if (reply.etag) response.headers.set("etag", reply.etag);
+ if (reply.asOf) response.headers.set("work-as-of", reply.asOf);
return response;
}
if (route.op === "secrets") return out.error(409, "feature_unavailable", "Only organization secrets can be set over this API for now.", { feature: "secrets" });
diff --git a/services/managed-agents/src/computer/work/api.ts b/services/managed-agents/src/computer/work/api.ts
index d35f792d..f186408e 100644
--- a/services/managed-agents/src/computer/work/api.ts
+++ b/services/managed-agents/src/computer/work/api.ts
@@ -3,9 +3,15 @@
// object calls the other; this is the only place their answers meet.
//
// api-http.ts matches the routes, checks scopes and turns the `WorkReply` into a response.
+//
+// The open list is polled. Its ETag is `"{head}-{stamp}"`: the index's head and version (rows,
+// pull request state, the problem), the Computer object's session stamp (`work.stamp`, any write
+// to sessions or people), and the caller (attention, `mine` and visibility are the caller's). Both
+// stamps are read first, two small calls, and a match answers 304 before anything is composed.
+// Every read answers `Work-As-Of`, when the head was last confirmed against GitHub.
import type { ApiCaller, ApiReply } from "../sessions-api.js";
-import type { SessionBrief, WorkContext, WorkContextOp } from "./briefs.js";
+import type { SessionBrief, WorkContext, WorkContextOp, WorkStampOp } from "./briefs.js";
import type { IndexedItem, ItemsResult, Revision, WorkIndexRpc } from "./index-contract.js";
export interface Person {
@@ -40,7 +46,8 @@ export interface Item {
/** 3.10's `{id, title, ownerName}`, plus the session's lifecycle `status` (the board shows it). */
sessions: { id: string; title: string | null; ownerName: string | null; status: SessionBrief["status"] }[];
unpublished: boolean;
- updatedAt: string;
+ /** The last commit that changed the file; null until the index has dated it. */
+ updatedAt: string | null;
createdAt: string | null;
closedAt: string | null;
closedBy: string | null;
@@ -54,16 +61,16 @@ export interface WorkRoute {
sub?: string;
}
-/** An ApiReply, with the open list's ETag; status 304 has no body. */
-export type WorkReply = ApiReply & { etag?: string };
+/** An ApiReply, with the open list's ETag and the reads' `Work-As-Of`; status 304 has no body. */
+export type WorkReply = ApiReply & { etag?: string; asOf?: string | null };
export interface WorkDeps {
accountId: string;
caller: ApiCaller;
/** The Work index, or null when the binding is missing. */
index: WorkIndexRpc | null;
- /** The Computer object's `work.context`. */
- context(op: WorkContextOp): Promise<ApiReply>;
+ /** The Computer object's `work.context` and `work.stamp`. */
+ context(op: WorkContextOp | WorkStampOp): Promise<ApiReply>;
}
/** The query parameters each route takes; any other is refused. */
@@ -79,7 +86,6 @@ const CLOSED_LIMIT_MAX = 100;
const NUMBER = /^[1-9]\d{0,8}$/;
const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
const REPO_NAME = /^[A-Za-z0-9._-]{1,100}$/;
-const BRANCH = /^[^\s~^:?*[\\]{1,255}$/;
const UNAVAILABLE: WorkReply = { status: 503, error: { code: "unavailable", message: "Work is unavailable. Try again shortly.", retryAfterMs: 5_000 } };
const invalid = (message: string, field: string): WorkReply => ({ status: 400, error: { code: "invalid_request", message, field } });
@@ -119,6 +125,15 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearch
if (rawLimit !== null && (!/^\d{1,3}$/.test(rawLimit) || Number(rawLimit) < 1 || Number(rawLimit) > CLOSED_LIMIT_MAX)) {
return invalid(`limit is 1 to ${CLOSED_LIMIT_MAX}.`, "limit");
}
+ let stamp: string | null = null;
+ if (stage === "open") {
+ // The stamps first: an unchanged poll is answered without reading or composing the list.
+ const [open, sessions] = await Promise.all([index.stamp(deps.accountId), deps.context({ op: "work.stamp" })]);
+ if (sessions.error) return sessions;
+ stamp = String((sessions.body as { stamp: number }).stamp);
+ const etag = await etagOf(open.head, open.version, stamp, deps.caller);
+ if (ifNoneMatch !== null && matches(ifNoneMatch, etag)) return { status: 304, etag, asOf: open.asOf };
+ }
const cursor = query.get("cursor");
const result: ItemsResult = await index.items(deps.accountId, {
stage,
@@ -126,24 +141,23 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearch
...(rawLimit !== null ? { limit: Number(rawLimit) } : {}),
});
if (!result.ok) return { status: 400, error: { code: "invalid_cursor", message: "The cursor is not valid for this list." } };
- const composed = await compose(deps, result.items, result.asOf);
+ const composed = await compose(deps, result.items);
if ("status" in composed) return composed;
- if (stage === "closed") return { status: 200, body: { items: composed.items, nextCursor: result.nextCursor } };
+ if (stage === "closed") return { status: 200, body: { items: composed.items, nextCursor: result.nextCursor }, asOf: result.asOf };
const page = { repository: result.repository, head: result.head, asOf: result.asOf, building: result.building, items: composed.items };
- const etag = await etagOf(page);
- if (ifNoneMatch !== null && matches(ifNoneMatch, etag)) return { status: 304, etag };
- return { status: 200, body: page, etag };
+ // The list's own head and version: the ETag never names content newer than the page.
+ return { status: 200, body: page, etag: await etagOf(result.head, result.version, stamp!, deps.caller), asOf: result.asOf };
}
case "work.item": {
if (!NUMBER.test(route.sub ?? "")) return notFound();
const result = await index.item(deps.accountId, Number(route.sub));
- if (!result.item) return notFound();
- // A closed item's body is read on first view; GitHub could not be reached.
- if (result.body === null) return UNAVAILABLE;
- const composed = await compose(deps, [result.item], result.asOf);
+ // A closed item's body is read on first view; GitHub did not give it in time.
+ if (!result.ok) return { ...UNAVAILABLE, error: { ...UNAVAILABLE.error!, retryAfterMs: result.retryAfterMs } };
+ if (!result.item || result.body === null) return notFound();
+ const composed = await compose(deps, [result.item]);
if ("status" in composed) return composed;
- return { status: 200, body: { item: composed.items[0]!, body: result.body } };
+ return { status: 200, body: { item: composed.items[0]!, body: result.body }, asOf: result.asOf };
}
case "work.history": {
@@ -161,7 +175,7 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearch
// A trailer names a session id or a Slack session's key: shown as the session's id, and only
// when the caller may see it.
const revisions: Revision[] = result.revisions.map((r) => ({ ...r, sessionId: r.sessionId ? (context.sessions[r.sessionId]?.id ?? null) : null }));
- return { status: 200, body: { revisions, nextCursor: result.nextCursor } };
+ return { status: 200, body: { revisions, nextCursor: result.nextCursor }, asOf: result.asOf };
}
}
}
@@ -182,7 +196,7 @@ function repositoryChoice(body: unknown): { value: { installationId: string; own
if (installation === null) return { error: invalid("installationId is the GitHub installation's id.", "installationId") };
if (typeof owner !== "string" || !OWNER.test(owner)) return { error: invalid("owner is a GitHub account login.", "owner") };
if (typeof name !== "string" || !REPO_NAME.test(name) || name === "." || name === "..") return { error: invalid("name is a GitHub repository name.", "name") };
- if (branch !== undefined && branch !== null && (typeof branch !== "string" || !BRANCH.test(branch))) return { error: invalid("branch is a branch name.", "branch") };
+ if (branch !== undefined && branch !== null && (typeof branch !== "string" || !branchName(branch))) return { error: invalid("branch is a branch name.", "branch") };
return { value: { installationId: installation, owner, name, ...(typeof branch === "string" ? { branch } : {}) } };
}
@@ -192,8 +206,24 @@ async function workContext(deps: WorkDeps, sessionIds: string[], emails: string[
return reply.body as WorkContext;
}
+/**
+ * A name `git check-ref-format --branch` accepts: no `.` or `..` segment, no segment starting with
+ * `.` or ending with `.lock`, no `..`, `@{`, `//`, control characters, space or `~^:?*[\`, not `@`,
+ * not starting with `-` or `/`, not ending with `/` or `.`. At most 255 characters.
+ */
+export function branchName(name: string): boolean {
+ if (name.length < 1 || name.length > 255 || name === "@") return false;
+ if (name.startsWith("-") || name.startsWith("/") || name.endsWith("/") || name.endsWith(".")) return false;
+ if (name.includes("..") || name.includes("@{") || name.includes("//")) return false;
+ for (let i = 0; i < name.length; i++) {
+ const c = name.charCodeAt(i);
+ if (c < 0x21 || c === 0x7f || "~^:?*[\\".includes(name[i]!)) return false;
+ }
+ return name.split("/").every((segment) => !segment.startsWith(".") && !segment.endsWith(".lock"));
+}
+
/** The index's items joined with the caller's sessions and the members behind emails. */
-async function compose(deps: WorkDeps, items: IndexedItem[], asOf: string | null): Promise<{ items: Item[] } | WorkReply> {
+async function compose(deps: WorkDeps, items: IndexedItem[]): Promise<{ items: Item[] } | WorkReply> {
const sessionIds = [...new Set(items.flatMap((i) => i.sessionIds))];
const emails = [...new Set(items.flatMap((i) => [i.owner, i.author?.email ?? null]).filter((e): e is string => !!e).map((e) => e.toLowerCase()))];
const context = items.length ? await workContext(deps, sessionIds, emails) : { sessions: {}, people: {}, callerEmails: [] };
@@ -224,7 +254,7 @@ async function compose(deps: WorkDeps, items: IndexedItem[], asOf: string | null
attention: itemAttention(briefs, deps.caller.member),
sessions: briefs.map((b) => ({ id: b.id, title: b.title, ownerName: b.ownerName, status: b.status })),
unpublished: false,
- updatedAt: i.updatedAt ?? i.closedAt ?? i.createdAt ?? asOf ?? new Date(0).toISOString(),
+ updatedAt: i.updatedAt ?? i.closedAt ?? i.createdAt,
createdAt: i.createdAt,
closedAt: i.closedAt,
closedBy: i.closedBy,
@@ -270,14 +300,14 @@ export function itemAttention(briefs: SessionBrief[], member: string): ItemAtten
}
/**
- * The open list's ETag: the head, and a stamp of everything else the page says except `asOf`
- * (attention, sessions, people and pull request states change without a commit).
+ * The open list's ETag: the head, then a digest of the index's version, the Computer object's
+ * session stamp and the caller (attention, sessions, people and pull request states change without
+ * a commit; `mine` and visibility are the caller's).
*/
-export async function etagOf(page: { head: string | null; asOf: string | null }): Promise<string> {
- const { asOf: _asOf, ...rest } = page;
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(rest)));
+export async function etagOf(head: string | null, version: number, sessions: string, caller: Pick<ApiCaller, "member" | "email">): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([version, sessions, caller.member, caller.email])));
const stamp = [...new Uint8Array(digest).slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");
- return `"${page.head ?? "none"}-${stamp}"`;
+ return `"${head ?? "none"}-${stamp}"`;
}
function matches(ifNoneMatch: string, etag: string): boolean {
diff --git a/services/managed-agents/src/computer/work/github.ts b/services/managed-agents/src/computer/work/github.ts
index 0007e9b1..2d56decb 100644
--- a/services/managed-agents/src/computer/work/github.ts
+++ b/services/managed-agents/src/computer/work/github.ts
@@ -2,17 +2,26 @@
// 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.
+// token narrowed to the knowledge repository and `contents: read`. Pull request state is read
+// with `pull_requests: read` narrowed to the repositories of the batch asked, and only for
+// repositories of the installation's own account (other links are `unreadable`). Finding a
+// renamed repository by its id uses `metadata: read`. Each token is held in memory until five
+// minutes before it expires.
+// - Every request is aborted after REQUEST_TIMEOUT_MS, the body included.
// - 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.
+// of the limit, and background work stops. A rate limit is a pause of that resource only
+// (`GitHubPaused`), not an error: nothing more is asked of it until the pause ends. A 403 is a
+// rate limit when it has `retry-after`, no requests left, or a body naming a rate, abuse or
+// secondary limit (at least DEFAULT_PAUSE_MS then); it is permanent only when the body says the
+// integration cannot reach the resource. Any other 403 is temporary.
// - 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.
+// The index retries them slowly, so a fixed setting heals by itself.
+// - A request GitHub answered through a redirect (a renamed repository) sets `moved`.
import type { GitHubTokenMint } from "../../protocol.js";
+import type { Clock, Fetch } from "./platform.js";
const GITHUB_API = "https://api.github.com";
const GITHUB_API_VERSION = "2026-03-10";
@@ -21,10 +30,17 @@ const USER_AGENT = "opencomputer-managed-agents";
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;
+export const DEFAULT_PAUSE_MS = 60_000;
const MAX_PAUSE_MS = 60 * 60_000;
-
-/** Why the repository cannot be read; shown as `repository.problem`. */
+/** Every GitHub request, its body included, is aborted after this. */
+export const REQUEST_TIMEOUT_MS = 10_000;
+/** GitHub's largest page for lists. */
+export const PER_PAGE_MAX = 100;
+/** A commit's files: 300 a page, ten pages at most. */
+export const COMMIT_FILES_PAGE = 300;
+const COMMIT_FILE_PAGES = 10;
+
+/** Why the repository cannot be read; shown as `repository.problem`. A stable code. */
export type RepositoryProblem =
| "installation_removed"
| "installation_suspended"
@@ -33,21 +49,23 @@ export type RepositoryProblem =
| "access_denied"
| "github_app_not_configured";
-/** A permanent failure: the repository setting needs a person. */
+export type RateResource = "core" | "graphql";
+
+/** A permanent failure: the repository setting needs a person. `message` is for people. */
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`. */
+/** GitHub asked us to wait (rate limit or abuse limit) on one resource; retry after `until`. */
export class GitHubPaused extends Error {
- constructor(readonly until: number) {
- super(`GitHub paused requests until ${new Date(until).toISOString()}`);
+ constructor(readonly until: number, readonly resource: RateResource = "core") {
+ super(`GitHub paused ${resource} requests until ${new Date(until).toISOString()}`);
}
}
-/** A temporary failure: GitHub unreachable, 5xx, a malformed answer. */
+/** A temporary failure: GitHub unreachable or slow, 5xx, an unexplained 403, a malformed answer. */
export class GitHubUnavailable extends Error {}
/** What the client needs of the Account object. */
@@ -57,6 +75,8 @@ export interface TokenMinter {
permissions?: Record<string, "read" | "write">;
repositories?: string[];
}): Promise<GitHubTokenMint>;
+ /** The installation's GitHub account (`accountLogin`), or null when it is not connected. */
+ getGitHubInstallation(installationId: string): Promise<{ accountLogin: string } | null> | { accountLogin: string } | null;
}
export interface WorkRepo {
@@ -64,6 +84,8 @@ export interface WorkRepo {
owner: string;
name: string;
branch: string;
+ /** GitHub's id for the repository, which survives renames; absent in settings stored before it. */
+ id?: number;
}
export interface CommitInfo {
@@ -71,8 +93,8 @@ export interface CommitInfo {
message: string;
authorName: string;
authorEmail: string | null;
- /** The author date, ISO. */
- at: string;
+ /** The author date, ISO; null when GitHub gave none. */
+ at: string | null;
}
export interface FileChange {
@@ -86,7 +108,9 @@ export interface FileChange {
export interface Comparison {
status: "ahead" | "behind" | "diverged" | "identical";
totalCommits: number;
+ /** Oldest first; at most a page of them. */
commits: CommitInfo[];
+ /** At most COMPARE_FILES_MAX; check `files.length` before trusting it as complete. */
files: FileChange[];
}
@@ -110,90 +134,120 @@ interface HeldToken {
expiresAt: number;
}
+interface Answer {
+ status: number;
+ headers: Headers;
+ body: string;
+}
+
+type TokenKind = { kind: "contents" } | { kind: "metadata" } | { kind: "pulls"; repositories: string[] };
+
export interface WorkGitHubOptions {
repo: WorkRepo;
account: TokenMinter;
- fetch?: typeof fetch;
- now?: () => number;
+ fetch: Fetch;
+ clock: Clock;
}
/** 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 fetcher: Fetch;
+ private readonly clock: Clock;
+ private readonly tokens = new Map<string, HeldToken>();
private readonly quota = new Map<string, Quota>();
- private pausedUntil = 0;
+ private readonly pausedUntil = new Map<RateResource, number>();
+ private login: string | null = null;
/** Calls made, for tests and telemetry. */
calls = 0;
+ /** Set when GitHub answered through a redirect: the repository was renamed or moved. */
+ moved = false;
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;
+ this.fetcher = options.fetch;
+ this.clock = options.clock;
}
- /** Until when GitHub asked us to wait; 0 when it did not. */
- paused(): number {
- return this.pausedUntil > this.now() ? this.pausedUntil : 0;
+ /** Until when GitHub asked us to wait on `resource`; 0 when it did not. */
+ paused(resource: RateResource = "core"): number {
+ const until = this.pausedUntil.get(resource) ?? 0;
+ return until > this.clock.now() ? until : 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;
+ spare(resource: RateResource = "core"): boolean {
+ if (this.paused(resource)) return false;
const q = this.quota.get(resource);
- if (!q || q.reset <= this.now()) return true;
+ if (!q || q.reset <= this.clock.now()) return true;
return q.remaining >= q.limit * SPARE_SHARE;
}
+ /** The installation's account login (the owner a knowledge repository and a readable PR must have). */
+ async accountLogin(): Promise<string> {
+ if (this.login !== null) return this.login;
+ const installation = await this.account.getGitHubInstallation(this.repo.installationId);
+ if (!installation) throw new GitHubGone("installation_removed", "The GitHub installation is not connected to this organization.");
+ this.login = installation.accountLogin;
+ return this.login;
+ }
+
// ---------------------------------------------------------------- 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;
+ private async token(want: TokenKind): Promise<string> {
+ const key = want.kind === "pulls" ? `pulls:${want.repositories.join(",")}` : want.kind;
+ const held = this.tokens.get(key);
+ if (held && held.expiresAt - TOKEN_MARGIN_MS > this.clock.now()) return held.token;
+ const resource: RateResource = want.kind === "pulls" ? "graphql" : "core";
const minted = await this.account.mintGitHubInstallationToken({
installationId: this.repo.installationId,
- ...(kind === "contents"
+ ...(want.kind === "contents"
? { permissions: { contents: "read" }, repositories: [this.repo.name] }
- : { permissions: { pull_requests: "read" } }),
+ : want.kind === "metadata"
+ ? { permissions: { metadata: "read" } }
+ : { permissions: { pull_requests: "read" }, repositories: want.repositories }),
});
- if (minted.outcome === "not_connected") throw new GitHubGone("installation_removed", "The GitHub connection is gone.");
+ if (minted.outcome === "not_connected") throw new GitHubGone("installation_removed", "The GitHub installation is not connected to this organization.");
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);
+ if (minted.code === "github_permission_missing") {
+ throw new GitHubGone(want.kind === "contents" ? "repository_not_found" : "access_denied", minted.message);
+ }
+ if (minted.code === "mint_rate_limited") throw this.pause(resource, (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 });
+ this.tokens.set(key, { token: minted.token, expiresAt: Number.isFinite(expiresAt) ? expiresAt : this.clock.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);
+ private pause(resource: RateResource, ms: number): GitHubPaused {
+ const until = Math.max(this.pausedUntil.get(resource) ?? 0, this.clock.now() + Math.min(Math.max(ms, 1000), MAX_PAUSE_MS));
+ this.pausedUntil.set(resource, until);
+ return new GitHubPaused(until, resource);
}
// ---------------------------------------------------------------- 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.
+ * One request, its body read, within REQUEST_TIMEOUT_MS. Answers 2xx, 304 and 404 to the caller;
+ * a rate limit is a pause, 401 drops the token, a 403 the integration may not see is
+ * `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);
+ init: { token?: TokenKind; accept?: string; etag?: string; method?: string; body?: unknown } = {},
+ ): Promise<Answer> {
+ const resource: RateResource = path === "/graphql" ? "graphql" : "core";
+ const paused = this.paused(resource);
+ if (paused) throw new GitHubPaused(paused, resource);
+ const want = init.token ?? { kind: "contents" };
+ const token = await this.token(want);
const headers: Record<string, string> = {
authorization: `Bearer ${token}`,
accept: init.accept ?? "application/vnd.github+json",
@@ -202,46 +256,67 @@ export class WorkGitHub {
};
if (init.etag) headers["if-none-match"] = init.etag;
if (init.body !== undefined) headers["content-type"] = "application/json";
- let response: Response;
this.calls += 1;
+ const controller = new AbortController();
+ const late = new GitHubUnavailable(`GitHub did not answer within ${REQUEST_TIMEOUT_MS / 1000} s.`);
+ let answer: Answer;
+ const cancel = this.clock.timeout(REQUEST_TIMEOUT_MS, () => controller.abort(late));
try {
- response = await this.fetcher(`${GITHUB_API}${path}`, {
- method: init.method ?? "GET",
- headers,
- ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ answer = await new Promise<Answer>((resolve, reject) => {
+ controller.signal.addEventListener("abort", () => reject(late), { once: true });
+ this.fetcher(`${GITHUB_API}${path}`, {
+ method: init.method ?? "GET",
+ headers,
+ signal: controller.signal,
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ })
+ .then(async (response) => {
+ if (response.redirected) this.moved = true;
+ resolve({ status: response.status, headers: response.headers, body: await response.text() });
+ })
+ .catch(reject);
});
- } catch {
+ } catch (error) {
+ if (error === late) throw late;
throw new GitHubUnavailable("GitHub is unreachable.");
+ } finally {
+ cancel();
}
- 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);
+ this.noteQuota(answer.headers);
+ const { status } = answer;
+ if ((status >= 200 && status < 300) || status === 304 || status === 404) return answer;
+ const retryAfter = Number.parseInt(answer.headers.get("retry-after") ?? "", 10);
+ const exhausted = answer.headers.get("x-ratelimit-remaining") === "0";
+ const message = messageOf(answer.body);
+ const limited = /rate limit|abuse|secondary/i.test(message);
+ if (status === 429 || (status === 403 && (Number.isFinite(retryAfter) || exhausted || limited))) {
+ if (Number.isFinite(retryAfter)) throw this.pause(resource, Math.max(retryAfter * 1000, limited ? DEFAULT_PAUSE_MS : 0));
+ const reset = Number.parseInt(answer.headers.get("x-ratelimit-reset") ?? "", 10);
+ if (exhausted && Number.isFinite(reset)) throw this.pause(resource, Math.max(reset * 1000 - this.clock.now(), limited ? DEFAULT_PAUSE_MS : 0));
+ throw this.pause(resource, DEFAULT_PAUSE_MS);
}
- if (response.status === 401) {
- this.tokens.delete(kind);
+ if (status === 401) {
+ this.tokens.clear();
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}.`);
+ if (status === 403 && /resource not accessible by integration/i.test(message)) {
+ throw new GitHubGone("access_denied", "The GitHub App installation cannot read the repository's contents.");
+ }
+ throw new GitHubUnavailable(`GitHub answered ${status}${message ? `: ${message.slice(0, 200)}` : ""}.`);
}
- 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);
+ private noteQuota(headers: Headers): void {
+ const limit = Number.parseInt(headers.get("x-ratelimit-limit") ?? "", 10);
+ const remaining = Number.parseInt(headers.get("x-ratelimit-remaining") ?? "", 10);
+ const reset = Number.parseInt(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 });
+ const resource = headers.get("x-ratelimit-resource") ?? "core";
+ this.quota.set(resource, { limit, remaining, reset: Number.isFinite(reset) ? reset * 1000 : this.clock.now() + 3_600_000 });
}
- private async json<T>(response: Response): Promise<T> {
+ private json<T>(answer: Answer): T {
try {
- return (await response.json()) as T;
+ return JSON.parse(answer.body) as T;
} catch {
throw new GitHubUnavailable("GitHub returned a malformed response.");
}
@@ -253,37 +328,45 @@ export class WorkGitHub {
/** 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.`);
+ const answer = await this.request(this.repoPath(""));
+ if (answer.status === 404) return new GitHubGone("repository_not_found", "The repository does not exist or the installation does not grant it.");
+ return new GitHubGone("branch_not_found", `The repository has no branch ${this.repo.branch}.`);
}
// ---------------------------------------------------------------- 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 repository as GitHub names it now, its id and default branch (setRepository's check). */
+ async repository(): Promise<{ id: number | null; owner: string; name: string; defaultBranch: string }> {
+ const answer = await this.request(this.repoPath(""));
+ if (answer.status === 404) throw new GitHubGone("repository_not_found", "The repository does not exist or the installation does not grant it.");
+ return repositoryOf(this.json(answer));
+ }
+
+ /** A repository by its id, wherever it is now (after a rename); null when the installation cannot see it. */
+ async locate(id: number): Promise<{ id: number | null; owner: string; name: string; defaultBranch: string } | null> {
+ const answer = await this.request(`/repositories/${id}`, { token: { kind: "metadata" } });
+ if (answer.status === 404) return null;
+ return repositoryOf(this.json(answer));
}
/** 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);
+ const answer = await this.request(this.repoPath(`/git/ref/heads/${this.repo.branch.split("/").map(encodeURIComponent).join("/")}`), etag ? { etag } : {});
+ if (answer.status === 304) return "unchanged";
+ if (answer.status === 404) throw await this.gone();
+ const body = this.json<{ object?: { sha?: unknown; type?: unknown } }>(answer);
if (typeof body.object?.sha !== "string") throw new GitHubUnavailable("GitHub returned an invalid ref.");
- return { sha: body.object.sha, etag: response.headers.get("etag") };
+ return { sha: body.object.sha, etag: answer.headers.get("etag") };
}
- /** `base...head`; null when GitHub no longer knows `base` (a rewritten history). */
+ /**
+ * `base...head`, one page of PER_PAGE_MAX commits (the oldest) and at most 300 files; 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 answer = await this.request(this.repoPath(`/compare/${base}...${head}?per_page=${PER_PAGE_MAX}`));
+ if (answer.status === 404) return null;
+ const body = this.json<{ status?: unknown; total_commits?: unknown; commits?: unknown; files?: unknown }>(answer);
const status = body.status;
if (status !== "ahead" && status !== "behind" && status !== "diverged" && status !== "identical") throw new GitHubUnavailable("GitHub returned an invalid comparison.");
return {
@@ -294,21 +377,31 @@ export class WorkGitHub {
};
}
- /** One commit with its files. */
+ /**
+ * One commit with its files. GitHub lists 300 files a page, up to 3000: a larger commit (an
+ * import) takes a call per 300 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) : [] };
+ let commit: CommitInfo | null = null;
+ const files: FileChange[] = [];
+ for (let page = 1; page <= COMMIT_FILE_PAGES; page++) {
+ const answer = await this.request(this.repoPath(`/commits/${sha}${page > 1 ? `?page=${page}` : ""}`));
+ if (answer.status === 404) throw new GitHubUnavailable(`GitHub has no commit ${sha}.`);
+ const body = this.json<{ files?: unknown }>(answer);
+ commit ??= commitOf(body);
+ if (!commit) throw new GitHubUnavailable("GitHub returned an invalid commit.");
+ const list = Array.isArray(body.files) ? body.files : [];
+ files.push(...list.map(fileOf).filter((f): f is FileChange => f !== null));
+ if (list.length < COMMIT_FILES_PAGE) break;
+ }
+ return { ...commit!, files };
}
- /** 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);
+ /** A tree's entries, not recursive (a commit sha names its root tree); null when there is no such tree. */
+ async tree(sha: string): Promise<{ sha: string; entries: TreeEntry[]; truncated: boolean } | null> {
+ const answer = await this.request(this.repoPath(`/git/trees/${sha}`));
+ if (answer.status === 404) return null;
+ const body = this.json<{ sha?: unknown; tree?: unknown; truncated?: unknown }>(answer);
const entries: TreeEntry[] = [];
for (const raw of Array.isArray(body.tree) ? body.tree : []) {
const e = raw as { path?: unknown; type?: unknown; sha?: unknown };
@@ -316,44 +409,63 @@ export class WorkGitHub {
entries.push({ name: e.path, type: e.type, sha: e.sha });
}
}
- return { entries, truncated: body.truncated === true };
+ return { sha: typeof body.sha === "string" ? body.sha : sha, 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);
+ const answer = await this.request(this.repoPath(`/git/blobs/${sha}`));
+ if (answer.status === 404) throw new GitHubUnavailable(`GitHub has no blob ${sha}.`);
+ const body = this.json<{ content?: unknown; encoding?: unknown }>(answer);
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);
+ /** Commits that touched `path` (a file or a directory), newest first, from `sha`, dated `until` or before; one page. */
+ async commits(input: { sha: string; path: string; page: number; perPage: number; until?: string }): Promise<CommitInfo[]> {
+ const query = new URLSearchParams({ sha: input.sha, path: input.path, per_page: String(Math.min(input.perPage, PER_PAGE_MAX)), page: String(input.page) });
+ if (input.until) query.set("until", input.until);
+ const answer = await this.request(this.repoPath(`/commits?${query}`));
+ if (answer.status === 404) return [];
+ const body = this.json<unknown>(answer);
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.
+ * Pull request state for GitHub pull request URLs, in one GraphQL query (at most 50 per call),
+ * with a token narrowed to their repositories. A URL outside the installation's account, or one
+ * the token 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);
+ const login = (await this.accountLogin()).toLowerCase();
+ const targets: { url: string; pr: { owner: string; name: string; number: number } }[] = [];
+ for (const url of urls) {
+ const pr = pullOf(url);
+ if (!pr) continue;
+ if (pr.owner.toLowerCase() === login) targets.push({ url, pr });
+ else out.set(url, "unreadable");
+ }
if (!targets.length) return out;
+ const repositories = [...new Set(targets.map((t) => t.pr.name.toLowerCase()))].sort();
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);
+ let answer: Answer;
+ try {
+ answer = await this.request("/graphql", { token: { kind: "pulls", repositories }, method: "POST", body: { query: `query {\n${fields.join("\n")}\n}` } });
+ } catch (error) {
+ // The installation lacks the permission, or no longer grants one of the repositories.
+ if (error instanceof GitHubGone && error.problem === "access_denied") {
+ for (const t of targets) out.set(t.url, "unreadable");
+ return out;
+ }
+ throw error;
+ }
+ if (answer.status === 404) throw new GitHubUnavailable("GitHub has no GraphQL endpoint.");
+ const body = this.json<{ data?: Record<string, { pullRequest?: { state?: unknown; isDraft?: unknown; title?: unknown } | null } | null> | null; errors?: unknown }>(answer);
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;
@@ -368,22 +480,44 @@ export class WorkGitHub {
}
}
-/** `https://github.com/{owner}/{name}/pull/{n}`, or null. */
+/** `https://github.com/{owner}/{name}/pull/{n}`, or null. Linear: no nested quantifiers. */
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;
}
+/** GitHub's `message` in an error body, or "". */
+function messageOf(body: string): string {
+ try {
+ const parsed = JSON.parse(body) as { message?: unknown };
+ return typeof parsed?.message === "string" ? parsed.message : "";
+ } catch {
+ return body.slice(0, 500);
+ }
+}
+
+function repositoryOf(raw: unknown): { id: number | null; owner: string; name: string; defaultBranch: string } {
+ const body = raw as { id?: unknown; name?: unknown; owner?: { login?: unknown }; default_branch?: unknown };
+ if (typeof body?.name !== "string" || typeof body.owner?.login !== "string") throw new GitHubUnavailable("GitHub returned an invalid repository.");
+ return {
+ id: typeof body.id === "number" ? body.id : null,
+ owner: body.owner.login,
+ name: body.name,
+ defaultBranch: typeof body.default_branch === "string" ? body.default_branch : "main",
+ };
+}
+
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;
+ const at = typeof author?.date === "string" && Number.isFinite(Date.parse(author.date)) ? author.date : null;
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(),
+ at,
};
}
diff --git a/services/managed-agents/src/computer/work/index-contract.ts b/services/managed-agents/src/computer/work/index-contract.ts
index 3bc906f8..2361f74f 100644
--- a/services/managed-agents/src/computer/work/index-contract.ts
+++ b/services/managed-agents/src/computer/work/index-contract.ts
@@ -1,7 +1,7 @@
// 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 }`.
+// result carries `{ head, asOf, building, version, problem, problemMessage }`.
//
// 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`.
@@ -18,8 +18,10 @@ export interface Repository {
owner: string;
name: string;
branch: string;
- /** Set when the repository can no longer be read; the screens send the person to settings. */
+ /** Set when the repository can no longer be read; the screens send the person to settings. A stable code. */
problem: RepositoryProblem | null;
+ /** The problem in words, for people; null without a problem. */
+ problemMessage: string | null;
}
/** What `PUT /work/repository` asks for; the branch defaults to the repository's default branch. */
@@ -45,7 +47,17 @@ export interface ReadState {
asOf: string | null;
/** True while the open items of a build are still being read. */
building: boolean;
+ /** Moves whenever anything a list shows changes (rows, pull request state, the problem). */
+ version: number;
problem: RepositoryProblem | null;
+ problemMessage: string | null;
+}
+
+/** What the open list's ETag is made of, read without composing the list. */
+export interface OpenStamp {
+ head: string | null;
+ asOf: string | null;
+ version: number;
}
/** An item as the index holds it, before the Worker joins sessions and people. */
@@ -87,7 +99,10 @@ 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 type ItemResult =
+ | (ReadState & { ok: true; repository: Repository | null; item: IndexedItem | null; body: string | null })
+ /** The body is not read yet and GitHub did not give it within the read's wait. */
+ | { ok: false; error: "unavailable"; retryAfterMs: number };
export interface Revision {
sha: string;
@@ -112,4 +127,5 @@ export interface WorkIndexRpc {
item(accountId: string, number: number): Promise<ItemResult>;
history(accountId: string, number: number, cursor?: string): Promise<HistoryResult>;
poke(accountId: string): Promise<void>;
+ stamp(accountId: string): Promise<OpenStamp>;
}
diff --git a/services/managed-agents/src/computer/work/index-do.ts b/services/managed-agents/src/computer/work/index-do.ts
index a6fcf270..341ac6ce 100644
--- a/services/managed-agents/src/computer/work/index-do.ts
+++ b/services/managed-agents/src/computer/work/index-do.ts
@@ -1,12 +1,14 @@
// 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.
+// addressed by account id like `COMPUTERS`. The logic is `WorkIndex` (index.ts), which holds no
+// platform; this file adapts the Durable Object to it (platform.ts): SQLite storage, the clock, the
+// alarm, fetch and the Account object. It is the only Work index file that names Cloudflare.
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";
+import type { IndexStore, StoreValue } from "./platform.js";
export interface WorkIndexEnv {
/** The edge's AccountDurableObject, addressed by account id. */
@@ -19,12 +21,22 @@ export class WorkIndexDurableObject extends DurableObject<WorkIndexEnv> implemen
constructor(ctx: DurableObjectState, env: WorkIndexEnv) {
super(ctx, env);
void ctx.blockConcurrencyWhile(async () => {
- this.index = new WorkIndex({
- sql: ctx.storage.sql,
+ const store: IndexStore = {
+ exec: <T extends Record<string, StoreValue>>(sql: string, ...params: StoreValue[]) => ctx.storage.sql.exec<T>(sql, ...params).toArray(),
transaction: (fn) => ctx.storage.transactionSync(fn),
+ };
+ this.index = new WorkIndex({
+ store,
+ clock: {
+ now: () => Date.now(),
+ timeout: (ms, fn) => {
+ const timer = setTimeout(fn, ms);
+ return () => clearTimeout(timer);
+ },
+ },
+ scheduler: { arm: (at) => this.arm(at), waitUntil: (promise) => ctx.waitUntil(promise) },
account: (accountId) => env.ACCOUNTS.getByName(accountId) as unknown as TokenMinter,
- arm: (at) => this.arm(at),
- waitUntil: (promise) => ctx.waitUntil(promise),
+ fetch: (url, init) => fetch(url, init),
});
});
}
@@ -58,6 +70,10 @@ export class WorkIndexDurableObject extends DurableObject<WorkIndexEnv> implemen
return this.index.poke(accountId);
}
+ stamp(accountId: string) {
+ return this.index.stamp(accountId);
+ }
+
override async alarm(): Promise<void> {
const next = await this.index.alarm();
if (next !== null) await this.arm(Math.max(next, Date.now() + 1));
diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.ts
index a88d7cc6..0c9c5c25 100644
--- a/services/managed-agents/src/computer/work/index.ts
+++ b/services/managed-agents/src/computer/work/index.ts
@@ -2,17 +2,34 @@
// 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.
+// - Advance (the only way the projection changes, besides a build), from the cursor to the head:
+// 1. compare `cursor...head` (one call): not ahead means a rewritten history, so rebuild. When
+// it lists fewer than 300 files, that list is the change.
+// 2. Otherwise the trees: the head's root tree, and each of `work/` and `done/` whose tree sha
+// differs from the one stored at the cursor (2-3 calls), diffed against the `files` table.
+// 3. The blobs of the changed items only, then rows, files and the cursor in one transaction.
+// Changed rows lose `updatedAt`, a new close loses `closedAt`/`closedBy`: null until the walk
+// fills them, never a guess. A range of one commit fills them at once from compare's files.
+// 4. The walk (below) gets the range: a page of each changed folder's commits and up to
+// ADVANCE_DETAILS commit details now, the rest from the alarm.
+// Whatever the range's size, an advance never rebuilds and stays within those calls.
+// - Build (no cursor, or a rewritten history): 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. Dates,
+// authors and links come from the walk.
+// - The walk: `commits?path=work` and `commits?path=done` from a head, back to the newest commit of
+// that folder already listed (a page of 100 at a time); then each listed commit's files (one call
+// each, newest first, within the quota). A commit's files give its items' revisions (history),
+// links (`Session:` trailers), the add (author, created), the move into done/ (closed) and the
+// latest change (updated).
// - 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.
+// file before a closed one, then the first path. The others show as a warning naming them.
// - 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).
+// Reads never wait on it: they are SQL, and the two that may need GitHub (an item or a page of
+// closed items not read yet, history while the walk is not done) wait at most READ_WAIT_MS. Every
+// GitHub request is aborted after 10 s, so a hung one holds the chain no longer than that.
+// - A permanent failure is stored as `problem` (a code) and `problemMessage`; it is retried from
+// the alarm with a backoff from PROBLEM_RETRY_MS to PROBLEM_RETRY_MAX_MS and cleared on success.
//
// 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.
@@ -21,6 +38,7 @@ import {
GitHubGone,
GitHubPaused,
GitHubUnavailable,
+ PER_PAGE_MAX,
pullOf,
WorkGitHub,
type CommitInfo,
@@ -35,6 +53,7 @@ import type {
ItemResult,
ItemsQuery,
ItemsResult,
+ OpenStamp,
ReadState,
Repository,
RepositoryChoice,
@@ -43,6 +62,7 @@ import type {
WorkWrite,
} from "./index-contract.js";
import { itemPath, PARSER_VERSION, parseItem, readyToClose, sessionTrailers, slugTitle, type ItemPath, type ParsedItem } from "./item.js";
+import { within, type Clock, type Fetch, type IndexStore, type Scheduler, type StoreValue } from "./platform.js";
/** A read finding the head older than this looks behind its response. */
export const LOOK_AFTER_MS = 10_000;
@@ -54,26 +74,37 @@ 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;
+export const PULLS_PER_QUERY = 50;
+/** A pull request GitHub would not show is asked again after this. */
+export const UNREADABLE_RECHECK_MS = 24 * 60 * 60_000;
+/** Compare lists at most this many files; at that many, the list may be cut. */
+export const COMPARE_FILES_MAX = 300;
+/** Commit details an advance asks itself; the alarm asks the rest. */
+export const ADVANCE_DETAILS = 10;
+/** Per alarm without readers: pages of folder commits, and commit details. */
+export const WALK_PAGES_PER_TICK = 2;
+export const WALK_DETAILS_PER_TICK = 10;
+/** A read that needs GitHub answers within this, or 503 `unavailable`. */
+export const READ_WAIT_MS = 5_000;
+/** A stored problem is retried after this, doubling each time up to the maximum. */
+export const PROBLEM_RETRY_MS = 60_000;
+export const PROBLEM_RETRY_MAX_MS = 60 * 60_000;
const HISTORY_PAGE = 30;
const CLOSED_LIMIT_DEFAULT = 50;
const CLOSED_LIMIT_MAX = 100;
const FETCH_PARALLEL = 6;
+/** Durable Object SQL binds at most 100 parameters per statement. */
+const BIND_MAX = 90;
/** Stored bodies re-parsed per step after PARSER_VERSION changes. */
export const REPARSE_BATCH = 100;
+/** The tables' shape; another stored version drops them (the repository is the record). */
+const SCHEMA_VERSION = 2;
const SCHEMA = `
CREATE TABLE IF NOT EXISTS items (
number INTEGER PRIMARY KEY,
path TEXT NOT NULL,
+ stage TEXT NOT NULL,
blob TEXT NOT NULL,
body TEXT NOT NULL,
parsed TEXT NOT NULL,
@@ -81,31 +112,43 @@ CREATE TABLE IF NOT EXISTS items (
author_name TEXT, author_email TEXT, created_at TEXT,
updated_at TEXT, closed_at TEXT, closed_by TEXT
);
+CREATE INDEX IF NOT EXISTS items_stage ON items (stage, number);
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 commits (
+ sha TEXT PRIMARY KEY, at TEXT, author_name TEXT NOT NULL, author_email TEXT, message TEXT NOT NULL, detailed INTEGER NOT NULL,
+ listed TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS commits_todo ON commits (detailed, at);
+CREATE TABLE IF NOT EXISTS revisions (
+ number INTEGER NOT NULL, sha TEXT NOT NULL, path TEXT NOT NULL, at TEXT NOT NULL, author_name TEXT NOT NULL, summary TEXT NOT NULL, session_id TEXT,
+ PRIMARY KEY (number, sha, path)
+);
+CREATE INDEX IF NOT EXISTS revisions_order ON revisions (number, at, sha);
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);
`;
+const TABLES = ["items", "files", "links", "commits", "revisions", "pulls"];
-/** What the index needs of its Durable Object. */
+/** What the index needs of where it runs. */
export interface WorkIndexDeps {
- sql: SqlStorage;
- transaction<T>(fn: () => T): T;
+ store: IndexStore;
+ clock: Clock;
+ scheduler: Scheduler;
/** 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;
+ fetch: Fetch;
}
+/** The columns a list shows (no body). */
+const ROW_COLUMNS = "number, path, stage, blob, parsed, parser, author_name, author_email, created_at, updated_at, closed_at, closed_by";
+
interface ItemRow {
number: number;
path: string;
+ stage: string;
blob: string;
- body: string;
parsed: string;
parser: number;
author_name: string | null;
@@ -116,40 +159,68 @@ interface ItemRow {
closed_by: string | null;
}
-type Row = Record<string, SqlStorageValue>;
+type Row = Record<string, StoreValue>;
+type Dir = "work" | "done";
+const DIRS: Dir[] = ["work", "done"];
interface StoredRepo extends WorkRepo {}
-interface WalkState {
+/**
+ * The walk's listing of one folder's commits: from `head` back to the first commit already listed
+ * for that folder (everything older is listed, or is the range of a task still running).
+ */
+interface WalkTask {
+ dir: Dir;
head: string;
- dir: "work" | "done";
+ /** The next page to ask. */
page: number;
- index: number;
}
+interface WalkState {
+ tasks: WalkTask[];
+}
+
+type DirShas = Record<Dir, string | null>;
+
/** One organization's Work index. */
export class WorkIndex {
- private readonly now: () => number;
+ private readonly store: IndexStore;
+ private readonly clock: Clock;
private github: WorkGitHub | null = null;
private tail: Promise<unknown> = Promise.resolve();
private looking: Promise<void> | null = null;
- private readonly filling = new Set<number>();
+ private readonly filling = new Map<number, Promise<void>>();
constructor(private readonly deps: WorkIndexDeps) {
- this.now = deps.now ?? Date.now;
- deps.sql.exec(SCHEMA);
+ this.store = deps.store;
+ this.clock = deps.clock;
+ this.store.exec("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)");
+ if (this.meta("schema_version") !== String(SCHEMA_VERSION)) {
+ // An earlier shape: drop the projection and keep the setting; the next look rebuilds it.
+ this.store.transaction(() => {
+ for (const table of TABLES) this.store.exec(`DROP TABLE IF EXISTS ${table}`);
+ this.store.exec("DELETE FROM meta WHERE k NOT IN ('repo', 'account_id')");
+ this.setMeta("schema_version", SCHEMA_VERSION);
+ this.setMeta("parser_version", PARSER_VERSION);
+ });
+ }
+ this.store.exec(SCHEMA);
+ }
+
+ private now(): number {
+ return this.clock.now();
}
// ------------------------------------------------------------------ meta
private meta(k: string): string | null {
- const row = this.deps.sql.exec<{ v: string }>("SELECT v FROM meta WHERE k = ?", k).toArray()[0];
+ const row = this.store.exec<{ v: string }>("SELECT v FROM meta WHERE k = ?", k)[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));
+ if (v === null) this.store.exec("DELETE FROM meta WHERE k = ?", k);
+ else this.store.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 {
@@ -167,6 +238,11 @@ export class WorkIndex {
return Number.isFinite(v) ? v : 0;
}
+ /** Marks the projection changed: the open list's ETag moves. Call inside the writing transaction. */
+ private bump(): void {
+ this.setMeta("version", this.metaNumber("version") + 1);
+ }
+
/** 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);
@@ -176,20 +252,28 @@ export class WorkIndex {
return this.metaJson<StoredRepo>("repo");
}
+ private newClient(repo: WorkRepo, accountId: string): WorkGitHub {
+ return new WorkGitHub({ repo, account: this.deps.account(accountId), clock: this.clock, fetch: this.deps.fetch });
+ }
+
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 } : {}) });
+ this.github = this.newClient(repo, accountId);
return this.github;
}
+ private problemNow(): { problem: RepositoryProblem | null; problemMessage: string | null } {
+ return { problem: (this.meta("problem") as RepositoryProblem | null) ?? null, problemMessage: this.meta("problem_message") };
+ }
+
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 };
+ return { installationId: repo.installationId, owner: repo.owner, name: repo.name, branch: repo.branch, ...this.problemNow() };
}
private readState(): ReadState {
@@ -199,10 +283,17 @@ export class WorkIndex {
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,
+ version: this.metaNumber("version"),
+ ...this.problemNow(),
};
}
+ /** Until when GitHub asked us to wait (core requests), from storage: it outlives the client. */
+ private pausedUntil(): number {
+ const until = this.metaNumber("pause_until");
+ return until > this.now() ? until : 0;
+ }
+
// ------------------------------------------------------------------ one at a time
private exclusive<T>(fn: () => Promise<T>): Promise<T> {
@@ -227,8 +318,8 @@ export class WorkIndex {
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.reparsing()) this.deps.waitUntil(this.kick());
- this.deps.waitUntil(this.deps.arm(now + ALARM_EVERY_MS));
+ if (now - seen > LOOK_AFTER_MS || this.reparsing()) this.deps.scheduler.waitUntil(this.kick());
+ this.deps.scheduler.waitUntil(this.deps.scheduler.arm(now + ALARM_EVERY_MS));
}
// ------------------------------------------------------------------ RPC
@@ -241,28 +332,38 @@ export class WorkIndex {
async poke(accountId: string): Promise<void> {
this.bind(accountId);
if (!this.repo()) return;
- this.deps.waitUntil(this.kick());
+ this.deps.scheduler.waitUntil(this.kick());
+ }
+
+ /** The open list's stamp, for its ETag: SQL only. A read like the others (it may look behind). */
+ async stamp(accountId: string): Promise<OpenStamp> {
+ this.bind(accountId);
+ this.noteRead();
+ const { head, asOf, version } = this.readState();
+ return { head, asOf, version };
}
+ /**
+ * Checks the choice against GitHub with a fresh client (a stored problem or pause plays no part),
+ * then stores it. The owner must be the installation's account.
+ */
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 } : {}),
- });
+ const trial = this.newClient({ installationId: choice.installationId, owner: choice.owner, name: choice.name, branch: choice.branch ?? "main" }, accountId);
let repo: StoredRepo;
try {
+ const login = await trial.accountLogin();
+ if (login.toLowerCase() !== choice.owner.toLowerCase()) {
+ return { ok: false, status: 400, code: "invalid_request", message: `The installation is on the GitHub account ${login}; owner must be ${login}.`, field: "owner", reason: "owner_mismatch" };
+ }
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();
+ repo = { installationId: choice.installationId, owner: found.owner, name: found.name, branch: choice.branch ?? found.defaultBranch, ...(found.id !== null ? { id: found.id } : {}) };
+ await this.newClient(repo, accountId).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 };
+ return { ok: false, status: 400, code: "invalid_request", message: error.message, 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 };
@@ -271,19 +372,21 @@ export class WorkIndex {
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(() => {
+ current.branch === repo.branch &&
+ (current.id !== undefined && repo.id !== undefined
+ ? current.id === repo.id
+ : current.owner.toLowerCase() === repo.owner.toLowerCase() && current.name.toLowerCase() === repo.name.toLowerCase());
+ this.store.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);
+ for (const table of TABLES) this.store.exec(`DELETE FROM ${table}`);
+ for (const k of ["cursor", "build", "walk", "dirs", "head_etag", "as_of", "tried_at", "pulls_at", "pause_until", "pulls_pause_until"]) this.setMeta(k, null);
}
this.setMeta("repo", JSON.stringify(repo));
- this.setMeta("problem", null);
+ this.clearProblem();
+ this.bump();
});
this.github = null;
- this.deps.waitUntil(this.kick());
+ this.deps.scheduler.waitUntil(this.kick());
return { ok: true, value: this.repository()! };
});
}
@@ -293,24 +396,22 @@ export class WorkIndex {
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();
+ const rows = this.store.exec<ItemRow & Row>(`SELECT ${ROW_COLUMNS} FROM items WHERE stage = 'open' ORDER BY number`);
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" };
+ const n = decodeCursor(query.cursor)?.n;
+ if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0) 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();
+ const select = () => this.store.exec<ItemRow & Row>(`SELECT ${ROW_COLUMNS} FROM items WHERE stage = 'closed' AND number < ? ORDER BY number DESC LIMIT ?`, before, limit + 1);
let rows = select();
const pending = rows.slice(0, limit).filter((r) => r.parser === 0);
- if (pending.length) {
- await this.fillLater(pending);
- rows = select();
- }
+ // Bodies not read yet are read now, for at most READ_WAIT_MS; the page then shows what it has.
+ if (pending.length && (await within(this.clock, READ_WAIT_MS, this.fillLater(pending).then(() => true), () => false))) rows = select();
+ else if (pending.length) 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 };
@@ -319,95 +420,173 @@ export class WorkIndex {
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];
+ const select = () => this.store.exec<ItemRow & { body: string } & Row>(`SELECT ${ROW_COLUMNS}, body FROM items WHERE number = ?`, number)[0];
let row = select();
if (row && row.parser === 0) {
- await this.fillLater([row]);
+ // Read now, within READ_WAIT_MS; else the caller is told to come back.
+ await within(this.clock, READ_WAIT_MS, this.fillLater([row]), () => undefined);
row = select();
+ if (row && row.parser === 0) return { ok: false, error: "unavailable", retryAfterMs: Math.max(1000, this.pausedUntil() - this.now(), 5_000) };
}
- return { ...this.readState(), repository: this.repository(), item: row ? this.indexed([row])[0]! : null, body: row && row.parser > 0 ? row.body : null };
+ return { ok: true, ...this.readState(), repository: this.repository(), item: row ? this.indexed([row])[0]! : null, body: row ? row.body : null };
}
+ /**
+ * An item's revisions, newest first, across every path it has had. From the walk's revisions
+ * when the walk is done; until then those and GitHub's commits of each path, within READ_WAIT_MS.
+ */
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];
+ const row = this.store.exec<{ path: string }>("SELECT path FROM items WHERE number = ?", number)[0];
if (!row) return { ok: false, error: "item_not_found" };
- let page = 1;
+ let after: { at: string; sha: string } | null = null;
if (cursor !== undefined) {
- const p = decodeCursor(cursor, "p");
- if (p === null || p < 1) return { ok: false, error: "invalid_cursor" };
- page = p;
+ const c = decodeCursor(cursor);
+ if (!c || typeof c.a !== "string" || typeof c.s !== "string" || !/^[0-9a-f]{40}$/.test(c.s)) return { ok: false, error: "invalid_cursor" };
+ after = { at: c.a, sha: c.s };
}
- 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 repo = this.repo()!;
+ const stored = this.store.exec<{ sha: string; at: string; author_name: string; summary: string; session_id: string | null } & Row>(
+ `SELECT sha, at, MIN(author_name) AS author_name, MIN(summary) AS summary, MIN(session_id) AS session_id FROM revisions
+ WHERE number = ? ${after ? "AND (at < ? OR (at = ? AND sha < ?))" : ""} GROUP BY sha, at ORDER BY at DESC, sha DESC LIMIT ?`,
+ number,
+ ...(after ? [after.at, after.at, after.sha] : []),
+ HISTORY_PAGE + 1,
+ );
+ const found = new Map<string, Revision>();
+ for (const r of stored) found.set(r.sha, { sha: r.sha, url: commitUrl(repo, r.sha), at: r.at, authorName: r.author_name, summary: r.summary, sessionId: r.session_id });
+ let more = stored.length > HISTORY_PAGE;
+
+ if (!this.walkDone()) {
+ const gh = this.client();
+ const head = this.readState().head;
+ if (!gh || !head || this.pausedUntil()) return { ok: false, error: "unavailable", retryAfterMs: Math.max(1000, this.pausedUntil() - this.now(), 5_000) };
+ const paths = this.pathsOf(number, row.path);
+ const fetched = within(
+ this.clock,
+ READ_WAIT_MS,
+ Promise.all(paths.map((path) => gh.commits({ sha: head, path, page: 1, perPage: HISTORY_PAGE + 1, ...(after ? { until: after.at } : {}) }))).then((lists) => lists as CommitInfo[][] | null),
+ () => null,
+ ).catch((error: unknown) => {
+ if (error instanceof GitHubGone || error instanceof GitHubPaused || error instanceof GitHubUnavailable) return null;
+ throw error;
+ });
+ const lists = await fetched;
+ if (!lists) return { ok: false, error: "unavailable", retryAfterMs: Math.max(1000, this.pausedUntil() - this.now(), 5_000) };
+ for (const list of lists) {
+ if (list.length > HISTORY_PAGE) more = true;
+ for (const c of list) {
+ const at = c.at ?? "";
+ if (after && !(at < after.at || (at === after.at && c.sha < after.sha))) continue;
+ if (found.has(c.sha)) continue;
+ const trailers = sessionTrailers(c.message);
+ found.set(c.sha, { sha: c.sha, url: commitUrl(repo, c.sha), at, authorName: c.authorName, summary: summaryOf(c.message), sessionId: trailers[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 };
}
+ const all = [...found.values()].sort((a, b) => (a.at !== b.at ? (a.at < b.at ? 1 : -1) : a.sha < b.sha ? 1 : -1));
+ const revisions = all.slice(0, HISTORY_PAGE);
+ if (all.length > HISTORY_PAGE) more = true;
+ const last = revisions[revisions.length - 1];
+ return { ok: true, ...this.readState(), revisions, nextCursor: more && last ? encodeCursor({ a: last.at, s: last.sha }) : null };
}
- /** The alarm: continue a build, look while there are readers, walk. Returns when to come back. */
+ /** Every path the item has had: its files now, the paths of its revisions, its name in both folders. */
+ private pathsOf(number: number, path: string): string[] {
+ const paths = new Set<string>();
+ for (const r of this.store.exec<{ path: string }>("SELECT path FROM files WHERE number = ? UNION SELECT path FROM revisions WHERE number = ?", number, number)) paths.add(r.path);
+ const file = path.slice(path.indexOf("/") + 1);
+ for (const dir of DIRS) paths.add(`${dir}/${file}`);
+ return [...paths].sort();
+ }
+
+ /** The alarm: continue a build, look while there are readers or a problem is due, walk. Returns when to come back. */
async alarm(): Promise<number | null> {
if (!this.repo()) return null;
await this.exclusive(async () => {
const now = this.now();
this.reparseBatch();
+ if (this.meta("problem") !== null) {
+ await this.look();
+ return;
+ }
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());
+ else await this.guard(() => this.walkStep(WALK_PAGES_PER_TICK, WALK_DETAILS_PER_TICK));
});
const now = this.now();
- const pausedUntil = this.metaNumber("pause_until");
let next: number | null = null;
- if (this.meta("build") !== null || this.reparsing()) 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;
+ if (this.meta("problem") !== null) next = Math.max(this.metaNumber("problem_retry_at"), now + BUILD_STEP_MS);
+ else if (this.meta("build") !== null || this.reparsing()) next = now + BUILD_STEP_MS;
+ else if (now - this.metaNumber("read_at") < READS_WINDOW_MS || !this.walkDone()) next = now + ALARM_EVERY_MS;
+ if (next !== null && this.pausedUntil() > next) next = this.pausedUntil();
return next;
}
// ------------------------------------------------------------------ looking
- /** Runs `fn` with GitHub failures recorded: a pause until it ends, a permanent failure as the problem. */
+ /**
+ * Runs `fn` with GitHub failures recorded: a pause until it ends (per resource), a permanent
+ * failure as the problem. A repository that is not found is looked for by its id first: renamed,
+ * it is followed and the next look carries on.
+ */
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;
+ if (error instanceof GitHubGone) {
+ if (error.problem === "repository_not_found" && (await this.relocate())) return;
+ this.setProblem(error.problem, error.message);
+ } else if (error instanceof GitHubPaused) {
+ this.setMeta(error.resource === "graphql" ? "pulls_pause_until" : "pause_until", error.until);
+ } else if (!(error instanceof GitHubUnavailable)) throw error;
+ }
+ }
+
+ private setProblem(problem: RepositoryProblem, message: string): void {
+ const tries = this.meta("problem") !== null ? this.metaNumber("problem_tries") + 1 : 0;
+ this.store.transaction(() => {
+ if (this.meta("problem") !== problem || this.meta("problem_message") !== message) this.bump();
+ this.setMeta("problem", problem);
+ this.setMeta("problem_message", message);
+ this.setMeta("problem_tries", tries);
+ this.setMeta("problem_retry_at", this.now() + Math.min(PROBLEM_RETRY_MS * 2 ** tries, PROBLEM_RETRY_MAX_MS));
+ });
+ }
+
+ private clearProblem(): void {
+ if (this.meta("problem") === null) return;
+ for (const k of ["problem", "problem_message", "problem_tries", "problem_retry_at"]) this.setMeta(k, null);
+ this.bump();
+ }
+
+ /** The stored repository not found by name: found by id under another name, it is stored and true. */
+ private async relocate(): Promise<boolean> {
+ const repo = this.repo();
+ const gh = this.client();
+ if (!repo?.id || !gh) return false;
+ try {
+ const found = await gh.locate(repo.id);
+ if (!found || (found.owner === repo.owner && found.name === repo.name)) return false;
+ this.follow(repo, found);
+ return true;
+ } catch {
+ return false;
}
}
- private problem(problem: RepositoryProblem): void {
- this.setMeta("problem", problem);
+ /** The repository is now called `found`: store it; the projection stays (it is the same repository). */
+ private follow(repo: StoredRepo, found: { owner: string; name: string }): void {
+ this.store.transaction(() => {
+ this.setMeta("repo", JSON.stringify({ ...repo, owner: found.owner, name: found.name }));
+ this.bump();
+ });
+ this.github = null;
}
/** Checks the head and moves the projection to it; then one step of background work. */
@@ -415,33 +594,46 @@ export class WorkIndex {
this.reparseBatch();
const gh = this.client();
if (!gh) return;
- if (this.metaNumber("pause_until") > this.now()) return;
+ if (this.pausedUntil()) return;
+ if (this.meta("problem") !== null && this.metaNumber("problem_retry_at") > 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);
+ this.store.transaction(() => this.clearProblem());
+ if (gh.moved) {
+ const found = await gh.repository();
+ if (found.owner !== gh.repo.owner || found.name !== gh.repo.name) this.follow(this.repo()!, found);
+ gh.moved = false;
+ }
+ // One piece of GitHub work per look: a build or an advance, else a batch of the build, else a step of the walk.
+ let moved = false;
if (head !== "unchanged") {
+ // Background work spends the organization's shared quota only when there is spare.
+ if (!gh.spare()) return;
const cursor = this.meta("cursor");
- const build = this.metaJson<{ head: string }>("build");
- if (build) {
+ if (this.meta("build") !== null) {
// A build in progress finishes at its head; the next look advances from there.
} else if (cursor === null) {
await this.build(gh, head.sha);
+ moved = true;
} else if (cursor !== head.sha) {
- const result = await this.advance(gh, cursor, head.sha);
- if (result === "rebuild") await this.build(gh, head.sha);
+ if ((await this.advance(gh, cursor, head.sha)) === "rebuild") await this.build(gh, head.sha);
+ moved = true;
}
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();
+ if (this.meta("build") !== null) this.deps.scheduler.waitUntil(this.deps.scheduler.arm(this.now() + BUILD_STEP_MS));
+ } else if (!moved && !this.walkDone()) {
+ await this.walkStep(1, WALK_DETAILS_PER_TICK);
}
- await this.refreshPulls(gh);
+ });
+ await this.guard(async () => {
+ const g = this.client();
+ if (g && this.meta("problem") === null) await this.refreshPulls(g);
});
}
@@ -452,192 +644,183 @@ export class WorkIndex {
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 dirs: DirShas = { work: null, done: null };
+ for (const dir of DIRS) {
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 });
- }
+ dirs[dir] = entry.sha;
+ for (const [path, f] of await this.listDir(gh, dir, entry.sha)) listing.set(path, f);
}
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]));
+ const store = this.store;
+ this.store.transaction(() => {
+ store.exec("DELETE FROM files");
+ for (const [path, f] of listing) store.exec("INSERT INTO files (path, number, blob) VALUES (?, ?, ?)", path, f.number, f.blob);
+ // The history may have been rewritten: what the walk learnt is learnt again from the new one.
+ // Links (the sessions that worked on an item) stay.
+ store.exec("DELETE FROM commits");
+ store.exec("DELETE FROM revisions");
+ const old = new Map(store.exec<{ number: number; path: string; blob: string; body: string; parser: number } & Row>("SELECT number, path, blob, body, parser FROM items").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);
+ store.exec("DELETE FROM items WHERE number = ?", number);
+ store.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(safeParse(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)));
- }
+ const keep = prev && prev.blob === w.blob && prev.parser > 0;
+ store.exec(
+ `INSERT INTO items (number, path, stage, blob, body, parsed, parser) VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (number) DO UPDATE SET path = excluded.path, stage = excluded.stage, blob = excluded.blob, body = excluded.body, parsed = excluded.parsed,
+ parser = excluded.parser, author_name = NULL, author_email = NULL, created_at = NULL, updated_at = NULL, closed_at = NULL, closed_by = NULL`,
+ number,
+ w.path,
+ ip.stage,
+ w.blob,
+ keep ? prev.body : "",
+ JSON.stringify(keep ? safeParse(ip, prev.body) : pendingParse(ip)),
+ keep ? PARSER_VERSION : 0,
+ );
}
- this.setMeta("cursor", null);
- this.setMeta("head_etag", null);
- this.setMeta("walk", null);
- this.setMeta("build", JSON.stringify({ head }));
+ for (const k of ["cursor", "head_etag", "walk", "dirs"]) this.setMeta(k, null);
+ this.setMeta("build", JSON.stringify({ head, dirs }));
+ this.bump();
});
}
- /** One batch of open items not read yet; the cursor is set when none is left. */
+ /** A folder's item files: path to number and blob. */
+ private async listDir(gh: WorkGitHub, dir: Dir, sha: string): Promise<Map<string, { number: number; blob: string }>> {
+ const out = new Map<string, { number: number; blob: string }>();
+ const tree = await gh.tree(sha);
+ if (!tree) throw new GitHubUnavailable(`GitHub has no tree ${sha}.`);
+ for (const e of tree.entries) {
+ const path = `${dir}/${e.name}`;
+ const ip = e.type === "blob" ? itemPath(path) : null;
+ if (ip) out.set(path, { number: ip.number, blob: e.sha });
+ }
+ return out;
+ }
+
+ /** One batch of open items not read yet; the cursor is set when none is left, and the walk starts. */
private async fillOpen(): Promise<void> {
- const build = this.metaJson<{ head: string }>("build");
+ const build = this.metaJson<{ head: string; dirs: DirShas }>("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 (!build || !gh || !gh.spare()) return;
+ const rows = this.store.exec<ItemRow & Row>(`SELECT ${ROW_COLUMNS} FROM items WHERE parser = 0 AND stage = 'open' ORDER BY number LIMIT ?`, FILL_BATCH);
+ await parallel(rows, (row) => this.fill(gh, row));
+ const left = this.store.exec<{ n: number }>("SELECT COUNT(*) AS n FROM items WHERE parser = 0 AND stage = 'open'")[0]!.n;
if (left > 0) return;
- this.deps.transaction(() => {
+ this.store.transaction(() => {
this.setMeta("cursor", build.head);
+ this.setMeta("dirs", JSON.stringify(build.dirs));
this.setMeta("build", null);
- this.setMeta("walk", JSON.stringify({ head: build.head, dir: "work", page: 1, index: 0 } satisfies WalkState));
+ this.setMeta("walk", JSON.stringify({ tasks: DIRS.map((dir) => ({ dir, head: build.head, page: 1 })) } satisfies WalkState));
+ this.bump();
});
}
/** 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> {
+ private async fill(gh: WorkGitHub, row: { number: number; path: string; blob: string }): 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(safeParse(ip, body)),
- PARSER_VERSION,
- updatedAt,
- row.number,
- row.blob,
- row.path,
- );
+ this.store.transaction(() => {
+ this.store.exec("UPDATE items SET body = ?, parsed = ?, parser = ? WHERE number = ? AND blob = ? AND path = ?", body, JSON.stringify(safeParse(ip, body)), PARSER_VERSION, row.number, row.blob, row.path);
+ this.bump();
+ });
}
- /** Closed items asked for before they were read: read them, waiting at most LAZY_WAIT_MS. */
- private async fillLater(rows: ItemRow[]): Promise<void> {
+ /** Bodies asked for before they were read: read them (joining a read already running), within the quota. */
+ private fillLater(rows: { number: number; path: string; blob: string }[]): 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);
+ if (!gh || this.pausedUntil() || !gh.spare()) return Promise.resolve();
+ const reads: Promise<void>[] = [];
+ const todo: typeof rows = [];
+ for (const r of rows) {
+ const running = this.filling.get(r.number);
+ if (running) reads.push(running);
+ else todo.push(r);
+ }
+ if (todo.length) {
+ const work = parallel(todo, (row) => this.guard(() => this.fill(gh, row)));
+ const done = work.finally(() => {
+ for (const r of todo) this.filling.delete(r.number);
+ });
+ for (const r of todo) this.filling.set(r.number, done);
+ this.deps.scheduler.waitUntil(done);
+ reads.push(done);
+ }
+ return Promise.all(reads).then(() => undefined);
}
// ------------------------------------------------------------------ advance
- /** `base...head` applied in one transaction; "rebuild" when the head is not ahead of the cursor. */
+ /**
+ * From the cursor `base` to `head`: compare for ancestry (and its files when complete), else the
+ * folder trees; the changed blobs; one transaction. "rebuild" only when the head is not ahead.
+ */
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);
+ if (!cmp || (cmp.status !== "ahead" && cmp.status !== "identical")) return "rebuild";
+
+ // The item files that changed: path to its blob at the head, or null when it is gone.
+ const changes = new Map<string, string | null>();
+ const touchedDirs = new Set<Dir>();
+ let dirsNow: DirShas | null = null;
+ if (cmp.files.length < COMPARE_FILES_MAX) {
+ for (const f of cmp.files) {
+ for (const p of [f.filename, f.previousFilename]) {
+ const dir = p ? dirOf(p) : null;
+ if (dir) touchedDirs.add(dir);
+ }
+ if (f.status === "renamed" && f.previousFilename && itemPath(f.previousFilename)) changes.set(f.previousFilename, null);
+ if (itemPath(f.filename)) changes.set(f.filename, f.status === "removed" ? null : f.sha);
}
- }
- 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);
+ } else {
+ // Compare's file list may be cut: the folders' trees, only those whose sha moved.
+ const root = await gh.tree(head);
+ if (!root) throw new GitHubUnavailable(`GitHub has no tree for ${head}.`);
+ const stored = this.metaJson<DirShas>("dirs");
+ dirsNow = { work: null, done: null };
+ for (const dir of DIRS) {
+ const entry = root.entries.find((e) => e.name === dir && e.type === "tree");
+ dirsNow[dir] = entry?.sha ?? null;
+ if (stored && stored[dir] === dirsNow[dir]) continue;
+ touchedDirs.add(dir);
+ const now = entry ? await this.listDir(gh, dir, entry.sha) : new Map<string, { number: number; blob: string }>();
+ const before = new Map(this.store.exec<{ path: string; blob: string } & Row>("SELECT path, blob FROM files WHERE path LIKE ?", `${dir}/%`).map((r) => [r.path, r.blob]));
+ for (const path of before.keys()) if (!now.has(path)) changes.set(path, null);
+ for (const [path, f] of now) if (before.get(path) !== f.blob) changes.set(path, f.blob);
}
}
// 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);
- }
- }
+ for (const path of changes.keys()) numbers.add(itemPath(path)!.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);
- }
+ for (const part of chunks([...numbers])) {
+ for (const r of this.store.exec<{ path: string; number: number; blob: string } & Row>(`SELECT path, number, blob FROM files WHERE number IN (${marks(part)})`, ...part)) {
+ files.set(r.path, { number: r.number, blob: r.blob });
}
}
+ for (const [path, blob] of changes) {
+ if (blob === null) files.delete(path);
+ else files.set(path, { number: itemPath(path)!.number, blob });
+ }
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);
+ const old = new Map<number, { number: number; path: string; stage: string; blob: string; body: string; parser: number } & Row>();
+ for (const part of chunks([...numbers])) {
+ for (const r of this.store.exec<{ number: number; path: string; stage: string; blob: string; body: string; parser: number } & Row>(
+ `SELECT number, path, stage, blob, body, parser FROM items WHERE number IN (${marks(part)})`,
+ ...part,
+ )) {
+ old.set(r.number, r);
+ }
}
- // Bodies to read, before the transaction.
+ // Bodies to read, before the transaction: open items now, closed ones only when few.
const needed = [...winners.values()].filter((w) => {
const prev = old.get(w.number);
return !prev || prev.blob !== w.blob || prev.parser === 0;
@@ -648,88 +831,68 @@ export class WorkIndex {
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 });
- }
- }
+ // A range of one commit with every file listed: its details are compare's.
+ const only = cmp.totalCommits === 1 && cmp.commits.length === 1 && cmp.files.length < COMPARE_FILES_MAX ? cmp.commits[0]! : null;
- 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);
+ const store = this.store;
+ this.store.transaction(() => {
+ for (const [path, blob] of changes) {
+ if (blob === null) store.exec("DELETE FROM files WHERE path = ?", path);
+ else store.exec("INSERT INTO files (path, number, blob) VALUES (?, ?, ?) ON CONFLICT (path) DO UPDATE SET number = excluded.number, blob = excluded.blob", path, itemPath(path)!.number, 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);
+ store.exec("DELETE FROM items WHERE number = ?", n);
+ store.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 ? safeParse(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`,
+ const changed = !prev || prev.blob !== w.blob || prev.path !== w.path;
+ const moved = !prev || prev.stage !== ip.stage;
+ // What changed is not dated yet; the walk dates it from the commit that did it.
+ store.exec(
+ `INSERT INTO items (number, path, stage, blob, body, parsed, parser) VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (number) DO UPDATE SET path = excluded.path, stage = excluded.stage, blob = excluded.blob, body = excluded.body,
+ parsed = excluded.parsed, parser = excluded.parser,
+ updated_at = CASE WHEN ? THEN NULL ELSE updated_at END,
+ closed_at = CASE WHEN ? THEN NULL ELSE closed_at END,
+ closed_by = CASE WHEN ? THEN NULL ELSE closed_by END`,
n,
w.path,
+ ip.stage,
w.blob,
body ?? "",
JSON.stringify(parsed),
body !== null ? PARSER_VERSION : 0,
- authorName,
- authorEmail,
- createdAt,
- updatedAt,
- closedAt,
- closedBy,
+ changed ? 1 : 0,
+ moved ? 1 : 0,
+ moved ? 1 : 0,
);
}
- for (const l of links) this.link(l.number, l.sessionId, l.at);
+ const walk = this.walkState();
+ if (only) {
+ this.apply(only, cmp.files);
+ this.store.exec("UPDATE commits SET listed = ? WHERE sha = ?", [...touchedDirs].map((d) => `,${d},`).join(""), only.sha);
+ } else {
+ for (const dir of touchedDirs) addTask(walk, dir, head);
+ }
+ this.setMeta("walk", JSON.stringify(walk));
+ this.setMeta("dirs", dirsNow ? JSON.stringify(dirsNow) : null);
this.setMeta("cursor", head);
this.setMeta("as_of", this.now());
+ this.bump();
});
+ // The range's commits: a page of each folder and a few details now, the rest from the alarm.
+ if (!only && touchedDirs.size) await this.walkStep(touchedDirs.size, ADVANCE_DETAILS);
return "done";
}
private link(number: number, sessionId: string, at: string): void {
- this.deps.sql.exec(
+ this.store.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,
@@ -739,82 +902,164 @@ export class WorkIndex {
// ------------------------------------------------------------------ walk
+ private walkState(): WalkState {
+ return this.metaJson<WalkState>("walk") ?? { tasks: [] };
+ }
+
+ /** Nothing left to list or detail: the revisions are the whole history. */
+ private walkDone(): boolean {
+ if (this.meta("cursor") === null) return false;
+ if (this.walkState().tasks.length) return false;
+ return this.store.exec<{ n: number }>("SELECT COUNT(*) AS n FROM commits WHERE detailed = 0")[0]!.n === 0;
+ }
+
/**
- * 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.
+ * Up to `pages` pages of folder commits, then up to `details` commits' files, newest first,
+ * while the quota is spare. Each commit's files are applied in one transaction.
*/
- private async walkTick(): Promise<void> {
- const walk = this.metaJson<WalkState>("walk");
+ private async walkStep(pages: number, details: number): Promise<void> {
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) return;
+ for (let i = 0; i < pages && gh.spare(); i++) {
+ const walk = this.walkState();
+ const task = walk.tasks[0];
+ if (!task) break;
+ const list = await gh.commits({ sha: task.head, path: task.dir, page: task.page, perPage: PER_PAGE_MAX });
+ this.store.transaction(() => {
+ const now = this.walkState();
+ const t = now.tasks.find((x) => x.dir === task.dir && x.head === task.head && x.page === task.page);
+ if (!t) return;
+ const mark = `,${t.dir},`;
+ let done = list.length < PER_PAGE_MAX;
+ for (const c of list) {
+ const known = this.store.exec<{ listed: string }>("SELECT listed FROM commits WHERE sha = ?", c.sha)[0];
+ if (known?.listed.includes(mark)) {
+ done = true;
+ break;
+ }
+ this.store.exec(
+ `INSERT INTO commits (sha, at, author_name, author_email, message, detailed, listed) VALUES (?, ?, ?, ?, ?, 0, ?)
+ ON CONFLICT (sha) DO UPDATE SET listed = listed || excluded.listed`,
+ c.sha,
+ c.at,
+ c.authorName.slice(0, 200),
+ c.authorEmail,
+ c.message.slice(0, 10_000),
+ mark,
+ );
+ }
+ if (done) now.tasks.splice(now.tasks.indexOf(t), 1);
+ else t.page += 1;
+ this.setMeta("walk", JSON.stringify(now));
+ });
+ }
+ const todo = this.store.exec<{ sha: string } & Row>("SELECT sha FROM commits WHERE detailed = 0 ORDER BY at DESC, sha DESC LIMIT ?", details);
+ for (const { sha } of todo) {
if (!gh.spare()) break;
- details.push({ commit: c, files: (await gh.commit(c.sha)).files });
+ const c = await gh.commit(sha);
+ this.store.transaction(() => {
+ this.apply(c, c.files);
+ this.bump();
+ });
}
- 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);
+ }
+
+ /**
+ * One commit's item files: a revision of each item, its links, and the dates and names the
+ * commit settles (the add, the move into done/, the latest change). Order-free: the walk may
+ * see commits in any order.
+ */
+ private apply(c: CommitInfo, files: FileChange[]): void {
+ const store = this.store;
+ const trailers = sessionTrailers(c.message);
+ const at = c.at ?? "";
+ for (const f of files) {
+ const ip = itemPath(f.filename);
+ const from = f.previousFilename ? itemPath(f.previousFilename) : null;
+ for (const number of new Set([ip?.number, from?.number].filter((n): n is number => n !== undefined))) {
+ store.exec(
+ "INSERT INTO revisions (number, sha, path, at, author_name, summary, session_id) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING",
+ number,
+ c.sha,
+ f.filename,
+ at,
+ c.authorName.slice(0, 200),
+ summaryOf(c.message),
+ trailers[0] ?? null,
+ );
+ const row = store.exec<{ path: string; stage: string; created_at: string | null; closed_at: string | null; updated_at: string | null } & Row>(
+ "SELECT path, stage, created_at, closed_at, updated_at FROM items WHERE number = ?",
+ number,
+ )[0];
+ if (!row) continue;
+ for (const sessionId of trailers) this.link(number, sessionId, at);
+ if (c.at === null) continue;
+ if (row.updated_at === null || c.at > row.updated_at) store.exec("UPDATE items SET updated_at = ? WHERE number = ?", c.at, number);
+ const mine = ip !== null && ip.number === number;
+ if (mine && (f.status === "added" || (f.status === "renamed" && !from)) && (row.created_at === null || c.at < row.created_at)) {
+ store.exec("UPDATE items SET created_at = ?, author_name = ?, author_email = ? WHERE number = ?", c.at, c.authorName.slice(0, 200), c.authorEmail, number);
+ }
+ const closes = mine && ip.stage === "closed" && (f.status === "added" || (f.status === "renamed" && from?.stage !== "closed"));
+ if (closes && row.stage === "closed" && (row.closed_at === null || c.at > row.closed_at)) {
+ store.exec("UPDATE items SET closed_at = ?, closed_by = ? WHERE number = ?", c.at, closerName(c), 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);
- });
+ }
+ store.exec(
+ `INSERT INTO commits (sha, at, author_name, author_email, message, detailed) VALUES (?, ?, ?, ?, ?, 1)
+ ON CONFLICT (sha) DO UPDATE SET detailed = 1`,
+ c.sha,
+ c.at,
+ c.authorName.slice(0, 200),
+ c.authorEmail,
+ c.message.slice(0, 10_000),
+ );
}
// ------------------------------------------------------------------ pull requests
- /** At most every 5 minutes while read: the state of open items' pull requests not final yet. */
+ /**
+ * At most every 5 minutes while read: one query for the open items' pull requests asked longest
+ * ago (never asked first). Merged and closed are final; unreadable is asked again after a day.
+ * GraphQL has its own pause.
+ */
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 (this.metaNumber("pulls_pause_until") > now || !gh.spare("graphql")) return;
+ const known = new Map(this.store.exec<{ url: string; state: string | null; checked_at: string } & Row>("SELECT url, state, checked_at FROM pulls").map((r) => [r.url, r]));
+ const recheck = new Date(now - UNREADABLE_RECHECK_MS).toISOString();
+ const due = new Map<string, string>();
+ for (const r of this.store.exec<{ parsed: string }>("SELECT parsed FROM items WHERE stage = 'open' AND parser > 0")) {
+ for (const url of (JSON.parse(r.parsed) as ParsedItem).pullRequests) {
+ if (!pullOf(url) || due.has(url)) continue;
+ const k = known.get(url);
+ if (k && (k.state === "merged" || k.state === "closed")) continue;
+ if (k && k.state === "unreadable" && k.checked_at > recheck) continue;
+ due.set(url, k?.checked_at ?? "");
+ }
}
- if (!urls.size) return;
+ if (!due.size) return;
+ const batch = [...due].sort((a, b) => (a[1] !== b[1] ? (a[1] < b[1] ? -1 : 1) : a[0] < b[0] ? -1 : 1)).slice(0, PULLS_PER_QUERY).map(([url]) => url);
this.setMeta("pulls_at", now);
let states: Awaited<ReturnType<WorkGitHub["pulls"]>>;
try {
- states = await gh.pulls([...urls].slice(0, PULLS_PER_QUERY));
+ states = await gh.pulls(batch);
} catch (error) {
- // No pull request permission is not a problem with the repository: the links stay plain.
+ // Pull request state is decoration: no failure of it is a problem with the repository.
if (error instanceof GitHubGone) return;
throw error;
}
const at = new Date(now).toISOString();
- this.deps.transaction(() => {
+ this.store.transaction(() => {
+ let changed = false;
for (const [url, s] of states) {
const state = s === "unreadable" ? "unreadable" : s.state;
const title = s === "unreadable" ? null : s.title;
- this.deps.sql.exec(
+ const k = known.get(url);
+ if (!k || k.state !== state || this.store.exec<{ title: string | null }>("SELECT title FROM pulls WHERE url = ?", url)[0]?.title !== title) changed = true;
+ this.store.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,
@@ -822,6 +1067,7 @@ export class WorkIndex {
at,
);
}
+ if (changed) this.bump();
});
}
@@ -838,15 +1084,18 @@ export class WorkIndex {
*/
private reparseBatch(): void {
if (!this.reparsing()) return;
- const rows = this.deps.sql
- .exec<{ number: number; path: string; body: string } & Row>("SELECT number, path, body FROM items WHERE parser > 0 AND parser <> ? LIMIT ?", PARSER_VERSION, REPARSE_BATCH)
- .toArray();
- this.deps.transaction(() => {
+ const rows = this.store.exec<{ number: number; path: string; body: string } & Row>(
+ "SELECT number, path, body FROM items WHERE parser > 0 AND parser <> ? LIMIT ?",
+ PARSER_VERSION,
+ REPARSE_BATCH,
+ );
+ this.store.transaction(() => {
for (const r of rows) {
const ip = itemPath(r.path);
- if (ip) this.deps.sql.exec("UPDATE items SET parsed = ?, parser = ? WHERE number = ?", JSON.stringify(safeParse(ip, r.body)), PARSER_VERSION, r.number);
+ if (ip) this.store.exec("UPDATE items SET parsed = ?, parser = ? WHERE number = ?", JSON.stringify(safeParse(ip, r.body)), PARSER_VERSION, r.number);
}
if (rows.length < REPARSE_BATCH) this.setMeta("parser_version", PARSER_VERSION);
+ this.bump();
});
}
@@ -855,28 +1104,37 @@ export class WorkIndex {
private indexed(rows: ItemRow[]): IndexedItem[] {
const repo = this.repo();
if (!rows.length || !repo) return [];
- const sql = this.deps.sql;
+ const store = this.store;
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]);
+ for (const part of chunks(numbers)) {
+ for (const f of store.exec<{ number: number; path: string } & Row>(`SELECT number, path FROM files WHERE number IN (${marks(part)}) ORDER BY path`, ...part)) {
+ others.set(f.number, [...(others.get(f.number) ?? []), f.path]);
+ }
+ for (const l of store.exec<{ number: number; session_id: string } & Row>(
+ `SELECT number, session_id FROM links WHERE number IN (${marks(part)}) ORDER BY last_at DESC, session_id`,
+ ...part,
+ )) {
+ links.set(l.number, [...(links.get(l.number) ?? []), l.session_id]);
+ }
}
+ const parsedRows = rows.map((r) => ({ r, parsed: JSON.parse(r.parsed) as ParsedItem }));
+ const urls = [...new Set(parsedRows.flatMap((p) => p.parsed.pullRequests))];
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;
+ for (const part of chunks(urls)) {
+ for (const p of store.exec<{ url: string; state: string | null; title: string | null } & Row>(`SELECT url, state, title FROM pulls WHERE url IN (${marks(part)})`, ...part)) pulls.set(p.url, p);
+ }
+ const blobBase = `https://github.com/${repo.owner}/${repo.name}/blob/${repo.branch.split("/").map(encodeURIComponent).join("/")}`;
+ return parsedRows.map(({ r, parsed }) => {
+ const stage = r.stage === "closed" ? "closed" : "open";
+ // S8: the hidden files are named, so a person can find and renumber them.
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("/")}`,
+ url: `${blobBase}/${r.path.split("/").map(encodeURIComponent).join("/")}`,
title: parsed.title,
stateLine: parsed.stateLine,
tags: parsed.tags,
@@ -907,6 +1165,17 @@ function stageOf(path: string): "open" | "closed" {
return path.startsWith("done/") ? "closed" : "open";
}
+function dirOf(path: string): Dir | null {
+ return path.startsWith("work/") ? "work" : path.startsWith("done/") ? "done" : null;
+}
+
+/** A folder's range to list: a task not started yet takes the newer head (it covers the older), else a new task first. */
+function addTask(walk: WalkState, dir: Dir, head: string): void {
+ const waiting = walk.tasks.find((t) => t.dir === dir && t.page === 1);
+ if (waiting) waiting.head = head;
+ else walk.tasks.unshift({ dir, head, page: 1 });
+}
+
/** 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 }>();
@@ -945,32 +1214,33 @@ function closerName(c: CommitInfo): string | null {
return (name.toLowerCase().endsWith(suffix) ? name.slice(0, -suffix.length) : name).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 summaryOf(message: string): string {
+ const end = message.indexOf("\n");
+ return (end === -1 ? message : message.slice(0, end)).replace(/\r$/, "").slice(0, 200);
+}
+
+function commitUrl(repo: WorkRepo, sha: string): string {
+ return `https://github.com/${repo.owner}/${repo.name}/commit/${sha}`;
+}
+
+function marks(values: unknown[]): string {
+ return values.map(() => "?").join(",");
+}
+
+function chunks<T>(values: T[]): T[][] {
+ const out: T[][] = [];
+ for (let i = 0; i < values.length; i += BIND_MAX) out.push(values.slice(i, i + BIND_MAX));
+ return out;
}
-function encodeCursor(value: Record<string, number>): string {
+function encodeCursor(value: Record<string, number | string>): string {
return btoa(JSON.stringify(value)).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
}
-function decodeCursor(cursor: string, key: string): number | null {
+function decodeCursor(cursor: string): Record<string, unknown> | 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;
+ const value = JSON.parse(atob(cursor.replace(/-/g, "+").replace(/_/g, "/"))) as unknown;
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
} catch {
return null;
}
diff --git a/services/managed-agents/src/computer/work/platform.ts b/services/managed-agents/src/computer/work/platform.ts
new file mode 100644
index 00000000..50a89bd8
--- /dev/null
+++ b/services/managed-agents/src/computer/work/platform.ts
@@ -0,0 +1,46 @@
+// What the Work index needs of the platform it runs on. index.ts, item.ts and github.ts use only
+// these, so they hold no platform; index-do.ts adapts a Durable Object to them, and the tests a
+// node:sqlite database and a hand-moved clock (test/work-index.test.ts).
+
+export type StoreValue = string | number | null;
+
+/** SQLite: statements and one synchronous transaction at a time. */
+export interface IndexStore {
+ /** Runs `sql` (several statements when there are no parameters); a SELECT's rows, else []. */
+ exec<T extends Record<string, StoreValue> = Record<string, StoreValue>>(sql: string, ...params: StoreValue[]): T[];
+ /** Runs `fn` as one transaction: all of its writes or none. */
+ transaction<T>(fn: () => T): T;
+}
+
+export interface Clock {
+ /** ms epoch. */
+ now(): number;
+ /** Calls `fn` once after `ms`; the returned function cancels it. */
+ timeout(ms: number, fn: () => void): () => void;
+}
+
+export interface Scheduler {
+ /** Makes sure the alarm fires at `at` or sooner. */
+ arm(at: number): Promise<void>;
+ /** Keeps the host alive until `promise` settles. */
+ waitUntil(promise: Promise<unknown>): void;
+}
+
+export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
+
+/** `promise`, or `onTimeout()` when it has not settled after `ms`. */
+export function within<T>(clock: Clock, ms: number, promise: Promise<T>, onTimeout: () => T): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const cancel = clock.timeout(ms, () => resolve(onTimeout()));
+ promise.then(
+ (value) => {
+ cancel();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cancel();
+ reject(error);
+ },
+ );
+ });
+}
diff --git a/services/managed-agents/test/fixtures/computer-sql.ts b/services/managed-agents/test/fixtures/computer-sql.ts
index c80f294a..50fa7b55 100644
--- a/services/managed-agents/test/fixtures/computer-sql.ts
+++ b/services/managed-agents/test/fixtures/computer-sql.ts
@@ -12,7 +12,7 @@ export function sqlStorage(): SqlStorage {
return cursor([], 0);
}
const statement = db.prepare(query);
- if (/^\s*(SELECT|PRAGMA)/i.test(query)) return cursor(statement.all(...(binds as never[])) as unknown[], 0);
+ if (/^\s*(SELECT|PRAGMA|EXPLAIN)/i.test(query)) return cursor(statement.all(...(binds as never[])) as unknown[], 0);
const result = statement.run(...(binds as never[]));
return cursor([], Number(result.changes));
},
diff --git a/services/managed-agents/test/fixtures/fake-github-repo.ts b/services/managed-agents/test/fixtures/fake-github-repo.ts
index b56470d7..66b728d1 100644
--- a/services/managed-agents/test/fixtures/fake-github-repo.ts
+++ b/services/managed-agents/test/fixtures/fake-github-repo.ts
@@ -3,8 +3,13 @@ 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.
+ * trees (a commit's root, then one directory), blobs, the repository (by name and by id), and the
+ * pull request GraphQL query. History is a list of commits with whole-tree snapshots; `forcePush`
+ * rewrites it.
+ *
+ * GitHub's limits hold: compare lists at most 300 files and a page of commits; lists take
+ * `per_page` up to 100 (30 when absent) and `page`; commits take `until`. Tree shas are content
+ * addressed, so an unchanged folder keeps its sha across commits.
*/
export interface FakeCommit {
@@ -32,8 +37,19 @@ export class FakeRepo {
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> }[] = [];
+ /** The next requests (of those `match` fits, when set) answer this; then normal service resumes. */
+ failNext: { status: number; headers?: Record<string, string>; message?: string; match?: RegExp }[] = [];
+ /** The GraphQL queries asked. */
+ queries: string[] = [];
+ /** The next this many requests never answer (until the client aborts them). */
+ hangNext = 0;
+ /** GitHub's id for the repository, which survives a rename. */
+ id = 4242;
+ /** Names the repository had: requests to them are redirected when `redirects`, else 404. */
+ formerNames: string[] = [];
+ redirects = true;
+ private readonly blobStore = new Map<string, string>();
+ private readonly trees = new Map<string, { path: string; type: string; sha: string }[]>();
remaining = 5000;
limit = 5000;
deleted = false;
@@ -56,6 +72,7 @@ export class FakeRepo {
else files.set(path, text);
}
this.clock += 60_000;
+ for (const text of files.values()) this.blobStore.set(this.blobSha(text), text);
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;
@@ -105,10 +122,28 @@ export class FakeRepo {
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;
+ /** Renames the repository; the old name redirects (or 404s when `redirects` is false). */
+ rename(name: string): void {
+ this.formerNames.push(this.name);
+ this.name = name;
+ }
+
+ /** The tree of `prefix` in `files` (content addressed), registered by its sha. */
+ private treeOf(files: Map<string, string>, prefix: string): string {
+ const entries = new Map<string, { path: string; type: string; sha: string }>();
+ const dirs = new Set<string>();
+ for (const [path, text] of 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 dirs.add(name.slice(0, slash));
+ }
+ for (const dir of dirs) entries.set(dir, { path: dir, type: "tree", sha: this.treeOf(files, `${prefix}${dir}/`) });
+ const list = [...entries.values()].sort((a, b) => (a.path < b.path ? -1 : 1));
+ const sha = sha1(`tree\n${JSON.stringify(list)}`);
+ this.trees.set(sha, list);
+ return sha;
}
/** The `fetch` the client is given. */
@@ -123,14 +158,24 @@ export class FakeRepo {
"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);
+ let redirected = false;
+ const json = (status: number, body: unknown, extra: Record<string, string> = {}) => {
+ const response = new Response(status === 304 ? null : JSON.stringify(body), { status, headers: { "content-type": "application/json", ...quota(), ...extra } });
+ if (redirected) Object.defineProperty(response, "redirected", { value: true });
+ return response;
+ };
+ if (this.hangNext > 0) {
+ this.hangNext -= 1;
+ return new Promise<Response>((_, reject) => init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true }));
+ }
+ const at = this.failNext.findIndex((f) => !f.match || f.match.test(url.pathname));
+ const fail = at === -1 ? undefined : this.failNext.splice(at, 1)[0];
+ if (fail) return json(fail.status, { message: fail.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;
+ this.queries.push(query);
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]}`);
@@ -138,17 +183,29 @@ export class FakeRepo {
}
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 about = () => ({ id: this.id, name: this.name, owner: { login: this.owner }, default_branch: this.defaultBranch });
+ if (url.pathname === `/repositories/${this.id}`) return this.deleted ? json(404, { message: "Not Found" }) : json(200, about());
+ // GitHub's owner and repository names are case-insensitive; a former name redirects.
+ const lower = url.pathname.toLowerCase();
+ const under = (b: string) => lower === b.toLowerCase() || lower.startsWith(`${b.toLowerCase()}/`);
+ const current = `/repos/${this.owner}/${this.name}`;
+ const former = this.formerNames.map((n) => `/repos/${this.owner}/${n}`).find(under);
+ let base: string;
+ if (this.deleted) return json(404, { message: "Not Found" });
+ if (under(current)) base = current;
+ else if (former && this.redirects) {
+ redirected = true;
+ base = former;
+ } else 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 === "") return json(200, about());
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" });
+ const perPage = () => Math.min(Number(url.searchParams.get("per_page") ?? "30"), 100);
let m = /^\/compare\/([0-9a-f]+)\.\.\.([0-9a-f]+)$/.exec(rest);
if (m) {
const [baseSha, headSha] = [m[1]!, m[2]!];
@@ -161,45 +218,44 @@ export class FakeRepo {
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),
+ commits: range.slice(0, perPage()).map((c) => this.commitJson(c)),
+ // GitHub lists at most 300 files.
+ files: this.diff(this.commits.get(baseSha)!.files, this.commits.get(headSha)!.files).slice(0, 300),
});
}
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" });
+ // 300 files a page.
+ const page = Number(url.searchParams.get("page") ?? "1");
+ return c ? json(200, { ...this.commitJson(c), files: this.changed(c).slice((page - 1) * 300, page * 300) }) : 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 until = url.searchParams.get("until");
+ const size = perPage();
+ if (!this.commits.has(from)) return json(404, { message: "Not Found" });
const touching = this.ancestors(from)
.map((s) => this.commits.get(s)!)
+ .filter((c) => !until || c.at <= until)
.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)));
+ return json(200, touching.slice((page - 1) * size, page * size).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 });
+ // A commit's sha names its root tree.
+ const commit = this.commits.get(id);
+ const sha = commit ? this.treeOf(commit.files, "") : id;
+ const tree = this.trees.get(sha);
+ if (!tree) return json(404, { message: "Not Found" });
+ return json(200, { sha, tree, truncated: false });
}
m = /^\/git\/blobs\/([0-9a-f]+)$/.exec(rest);
if (m) {
- const text = this.blobs().get(m[1]!);
+ const text = this.blobStore.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" });
diff --git a/services/managed-agents/test/fixtures/work-platform.ts b/services/managed-agents/test/fixtures/work-platform.ts
new file mode 100644
index 00000000..dc73a81e
--- /dev/null
+++ b/services/managed-agents/test/fixtures/work-platform.ts
@@ -0,0 +1,64 @@
+import type { Clock, IndexStore, StoreValue } from "../../src/computer/work/platform.js";
+import { sqlStorage } from "./computer-sql.js";
+
+/** Durable Object SQL binds at most 100 parameters per statement; the fake refuses more, as it does. */
+const BIND_LIMIT = 100;
+
+/** The Work index's store on node:sqlite (the computer modules' fake), with real transactions. */
+export function indexStore(sql: SqlStorage = sqlStorage()): IndexStore & { sql: SqlStorage } {
+ let depth = 0;
+ return {
+ sql,
+ exec<T extends Record<string, StoreValue>>(query: string, ...params: StoreValue[]): T[] {
+ if (params.length > BIND_LIMIT) throw new Error(`too many SQL variables: ${params.length}`);
+ return sql.exec(query, ...params).toArray() as T[];
+ },
+ transaction<T>(fn: () => T): T {
+ const name = `t${depth++}`;
+ sql.exec(`SAVEPOINT ${name}`);
+ try {
+ const out = fn();
+ sql.exec(`RELEASE ${name}`);
+ return out;
+ } catch (error) {
+ sql.exec(`ROLLBACK TO ${name}`);
+ sql.exec(`RELEASE ${name}`);
+ throw error;
+ } finally {
+ depth--;
+ }
+ },
+ };
+}
+
+/** A clock moved by hand: `tick` advances it and runs the timers that come due. */
+export class FakeClock implements Clock {
+ private timers: { at: number; fn: () => void }[] = [];
+
+ constructor(public t = Date.parse("2026-11-19T10:00:00Z")) {}
+
+ now(): number {
+ return this.t;
+ }
+
+ timeout(ms: number, fn: () => void): () => void {
+ const timer = { at: this.t + ms, fn };
+ this.timers.push(timer);
+ return () => {
+ this.timers = this.timers.filter((x) => x !== timer);
+ };
+ }
+
+ tick(ms: number): number {
+ this.t += ms;
+ const due = this.timers.filter((x) => x.at <= this.t);
+ this.timers = this.timers.filter((x) => x.at > this.t);
+ for (const timer of due) timer.fn();
+ return this.t;
+ }
+
+ /** Timers waiting. */
+ get waiting(): number {
+ return this.timers.length;
+ }
+}
diff --git a/services/managed-agents/test/work-api.test.ts b/services/managed-agents/test/work-api.test.ts
index 6bb2a2fe..2c47be6a 100644
--- a/services/managed-agents/test/work-api.test.ts
+++ b/services/managed-agents/test/work-api.test.ts
@@ -3,15 +3,17 @@ import { describe, expect, it, vi } from "vitest";
import { routeComputerApi, type ComputerApiStub } from "../src/computer/api-http.js";
import type { Session } from "../src/computer/api-types.js";
import type { ApiCaller, ApiRow } from "../src/computer/sessions-api.js";
-import { itemAttention } from "../src/computer/work/api.js";
-import { type SessionBrief, type WorkContextOp, workContext } from "../src/computer/work/briefs.js";
+import { branchName, itemAttention } from "../src/computer/work/api.js";
+import { type SessionBrief, type WorkContextOp, workContext, workStamp, workStampSetup } from "../src/computer/work/briefs.js";
import type { TokenMinter } from "../src/computer/work/github.js";
-import { WorkIndex } from "../src/computer/work/index.js";
+import { REQUEST_TIMEOUT_MS } from "../src/computer/work/github.js";
+import { READ_WAIT_MS, WorkIndex } from "../src/computer/work/index.js";
import type { WorkIndexRpc } from "../src/computer/work/index-contract.js";
import { memberId } from "../src/computer/session-ids.js";
import type { RequestIdentity } from "../src/edge/auth.js";
import { sqlStorage } from "./fixtures/computer-sql.js";
import { FakeRepo } from "./fixtures/fake-github-repo.js";
+import { FakeClock, indexStore } from "./fixtures/work-platform.js";
/** Work tracking 3.10: the Work API's routes, scopes and composition in the Worker. */
@@ -36,6 +38,7 @@ function computer(sessions: FakeSession[]) {
const sql = sqlStorage();
sql.exec(`CREATE TABLE sessions (runner_key TEXT, session_id TEXT, owner_id TEXT, owner_user_id TEXT, owner_name TEXT, owner_email TEXT, updated_at INTEGER);
CREATE TABLE people (slack_user_id TEXT PRIMARY KEY, dir TEXT, git_name TEXT, git_email TEXT, updated_at INTEGER);`);
+ workStampSetup(sql);
for (const s of sessions) {
sql.exec("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, 1)", s.row.key, s.row.sessionId, s.row.ownerId ?? null, s.row.ownerUserId, s.row.ownerName, s.row.ownerEmail ?? null);
}
@@ -57,6 +60,7 @@ function computer(sessions: FakeSession[]) {
const ops: WorkContextOp[] = [];
const stub: ComputerApiStub = {
computerApi: vi.fn(async (_account, caller, op) => {
+ if (op.op === "work.stamp") return workStamp(sql);
if (op.op !== "work.context") throw new Error(`unexpected ${op.op}`);
ops.push(op as WorkContextOp);
return workContext({ sql, api }, caller, op as WorkContextOp);
@@ -68,8 +72,12 @@ function computer(sessions: FakeSession[]) {
/** A Work index over a fake GitHub, as the binding answers it. */
async function workIndex(repo: FakeRepo) {
const pending: Promise<unknown>[] = [];
- const account: TokenMinter = { mintGitHubInstallationToken: async () => ({ outcome: "minted", token: "ghs_test", expiresAt: "2099-01-01T00:00:00Z" }) };
- const index = new WorkIndex({ sql: sqlStorage(), transaction: (fn) => fn(), account: () => account, arm: async () => {}, waitUntil: (p) => void pending.push(p), fetch: repo.fetch });
+ const account: TokenMinter = {
+ mintGitHubInstallationToken: async () => ({ outcome: "minted", token: "ghs_test", expiresAt: "2099-01-01T00:00:00Z" }),
+ getGitHubInstallation: () => ({ accountLogin: "acme" }),
+ };
+ const clock = new FakeClock();
+ const index = new WorkIndex({ store: indexStore(), clock, scheduler: { arm: async () => {}, waitUntil: (p) => void pending.push(p) }, account: () => account, fetch: repo.fetch });
const rpc: WorkIndexRpc = {
repository: (a) => index.getRepository(a),
setRepository: (a, c, by) => index.setRepository(a, c, by),
@@ -77,11 +85,12 @@ async function workIndex(repo: FakeRepo) {
item: (a, n) => index.item(a, n),
history: (a, n, c) => index.history(a, n, c),
poke: (a) => index.poke(a),
+ stamp: (a) => index.stamp(a),
};
const settle = async () => {
while (pending.length) await Promise.allSettled(pending.splice(0));
};
- return { rpc, settle, env: { WORK_INDEX: { getByName: () => rpc } } };
+ return { rpc, settle, clock, index, env: { WORK_INDEX: { getByName: () => rpc } } };
}
function call(env: unknown, stub: ComputerApiStub, identity: RequestIdentity, method: string, path: string, init: { body?: string; headers?: Record<string, string> } = {}) {
@@ -167,7 +176,7 @@ describe("Work API scopes", () => {
});
describe("Work API requests", () => {
- const env = { WORK_INDEX: { getByName: () => ({ repository: async () => null, setRepository: vi.fn(async (_a: string, c: unknown) => ({ ok: true, value: c })), items: async () => ({ ok: false, error: "invalid_cursor" }), item: async () => ({ item: null, body: null }) }) } };
+ const env = { WORK_INDEX: { getByName: () => ({ repository: async () => null, setRepository: vi.fn(async (_a: string, c: unknown) => ({ ok: true, value: c })), items: async () => ({ ok: false, error: "invalid_cursor" }), item: async () => ({ ok: true, item: null, body: null, asOf: null }) }) } };
const stub: ComputerApiStub = { computerApi: vi.fn() };
const err = async (res: Response) => ({ status: res.status, ...(await json(res)).error });
@@ -204,7 +213,7 @@ describe("Work API composition", () => {
expect(res.status).toBe(200);
const page = await json(res);
expect(Object.keys(page)).toEqual(["repository", "head", "asOf", "building", "items"]);
- expect(page.repository).toEqual({ installationId: "12", owner: "acme", name: "knowledge", branch: "main", problem: null });
+ expect(page.repository).toEqual({ installationId: "12", owner: "acme", name: "knowledge", branch: "main", problem: null, problemMessage: null });
expect(page.building).toBe(false);
const [one, two, four] = page.items;
@@ -250,6 +259,77 @@ describe("Work API composition", () => {
expect(moved.status).toBe(200);
});
+ it("answers an unchanged poll from the stamps alone: no list read, no composition; Work-As-Of on 200 and 304", async () => {
+ const { w, c } = await board();
+ const first = await call(w.env, c.stub, person, "GET", "/work/items?stage=open");
+ const asOf = first.headers.get("work-as-of");
+ expect(asOf).toMatch(/^\d{4}-\d\d-\d\dT/);
+ expect(asOf).toBe((await json(first)).asOf);
+ const items = vi.spyOn(w.index, "items");
+ const ops = c.ops.length;
+ const again = await call(w.env, c.stub, person, "GET", "/work/items?stage=open", { headers: { "if-none-match": first.headers.get("etag")! } });
+ expect(again.status).toBe(304);
+ expect(again.headers.get("work-as-of")).toBe(asOf);
+ expect(items).not.toHaveBeenCalled();
+ expect(c.ops.length).toBe(ops);
+ // One item and its history carry it too.
+ expect((await call(w.env, c.stub, person, "GET", "/work/items/1")).headers.get("work-as-of")).toBe(asOf);
+ });
+
+ it("moves the ETag on any write to sessions or people, also one that leaves updated_at alone", async () => {
+ const { w, c } = await board();
+ const etag = (await call(w.env, c.stub, person, "GET", "/work/items?stage=open")).headers.get("etag")!;
+ c.sql.exec("UPDATE sessions SET owner_name = 'Mia' WHERE session_id = ?", SID.mine);
+ const renamed = await call(w.env, c.stub, person, "GET", "/work/items?stage=open", { headers: { "if-none-match": etag } });
+ expect(renamed.status).toBe(200);
+ const next = renamed.headers.get("etag")!;
+ expect(next).not.toBe(etag);
+ c.sql.exec("UPDATE people SET git_name = 'Cy Two' WHERE slack_user_id = 'U_CY'");
+ expect((await call(w.env, c.stub, person, "GET", "/work/items?stage=open", { headers: { "if-none-match": next } })).status).toBe(200);
+ });
+
+ it("finds a person by email through an index, not a scan", () => {
+ const { sql } = computer([]);
+ const plan = (q: string) => (sql.exec(`EXPLAIN QUERY PLAN ${q}`, "[email protected]").toArray() as { detail: string }[]).map((r) => r.detail).join("; ");
+ expect(plan("SELECT owner_user_id FROM sessions WHERE lower(owner_email) = ? AND owner_user_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1")).toMatch(/USING INDEX sessions_owner_email_lower/);
+ expect(plan("SELECT slack_user_id FROM people p WHERE lower(p.git_email) = ? LIMIT 1")).toMatch(/USING INDEX people_git_email_lower/);
+ expect(plan("SELECT owner_email FROM sessions WHERE owner_user_id = ?")).toMatch(/USING INDEX sessions_owner_user/);
+ });
+
+ it("gives a null updatedAt until the commit is known, never 1970", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": doc(1, "A") });
+ const w = await workIndex(repo);
+ const c = computer([]);
+ expect((await call(w.env, c.stub, person, "PUT", "/work/repository", { body: JSON.stringify({ installationId: 12, owner: "acme", name: "knowledge" }) })).status).toBe(200);
+ await w.settle();
+ const page = await json(await call(w.env, c.stub, person, "GET", "/work/items?stage=open"));
+ expect(page.items[0].updatedAt).toBeNull();
+ expect(page.items[0].createdAt).toBeNull();
+ });
+
+ it("answers 503 with a retry hint when a closed item's body does not come from GitHub in time", async () => {
+ const { repo, w, c } = await board();
+ repo.hangNext = 1;
+ const pending = call(w.env, c.stub, person, "GET", "/work/items/3");
+ await new Promise((resolve) => setImmediate(resolve));
+ w.clock.tick(READ_WAIT_MS);
+ const res = await pending;
+ expect(res.status).toBe(503);
+ expect(res.headers.get("retry-after")).toMatch(/^\d+$/);
+ expect((await json(res)).error).toMatchObject({ code: "unavailable", retryAfterMs: expect.any(Number) });
+ w.clock.tick(REQUEST_TIMEOUT_MS);
+ await w.settle();
+ expect((await call(w.env, c.stub, person, "GET", "/work/items/3")).status).toBe(200);
+ });
+
+ it("refuses a repository outside the installation's account", async () => {
+ const w = await workIndex(new FakeRepo({}));
+ const c = computer([]);
+ const res = await call(w.env, c.stub, person, "PUT", "/work/repository", { body: JSON.stringify({ installationId: 12, owner: "elsewhere", name: "knowledge" }) });
+ expect(res.status).toBe(400);
+ expect((await json(res)).error).toMatchObject({ code: "invalid_request", field: "owner", reason: "owner_mismatch" });
+ });
+
it("pages closed items and answers one item with its body", async () => {
const { w, c } = await board();
const closed = await json(await call(w.env, c.stub, person, "GET", "/work/items?stage=closed&limit=10"));
@@ -274,6 +354,15 @@ describe("Work API composition", () => {
});
});
+describe("branchName", () => {
+ it("follows git check-ref-format for a branch", () => {
+ for (const ok of ["main", "trunk", "feat/work-index", "release-1.2", "a_b", "x@y", "ü"]) expect(branchName(ok), ok).toBe(true);
+ for (const bad of ["", "-x", "a..b", "a/", "/a", "a//b", "a.lock", "a/b.lock", ".a", "a/.b", "a.", "a b", "a~b", "a^b", "a:b", "a?b", "a*b", "a[b", "a\\b", "@", "a@{b", "a\u0001b", "a\u007fb", "x".repeat(256)]) {
+ expect(branchName(bad), JSON.stringify(bad)).toBe(false);
+ }
+ });
+});
+
describe("itemAttention", () => {
const brief = (over: Partial<SessionBrief>): SessionBrief => ({ id: "cs_x", title: null, ownerId: BO, ownerName: "Bo", status: "idle", openAskAt: null, lastActiveAt: "2026-11-19T00:00:00Z", ...over });
diff --git a/services/managed-agents/test/work-index.test.ts b/services/managed-agents/test/work-index.test.ts
index 89a7cfcf..c74b792a 100644
--- a/services/managed-agents/test/work-index.test.ts
+++ b/services/managed-agents/test/work-index.test.ts
@@ -1,39 +1,61 @@
+import { readFileSync } from "node:fs";
+
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, REPARSE_BATCH, WorkIndex } from "../src/computer/work/index.js";
+import { DEFAULT_PAUSE_MS, REQUEST_TIMEOUT_MS, type TokenMinter } from "../src/computer/work/github.js";
+import {
+ ADVANCE_DETAILS,
+ ALARM_EVERY_MS,
+ FILL_BATCH,
+ LOOK_AFTER_MS,
+ PROBLEM_RETRY_MS,
+ PULLS_EVERY_MS,
+ PULLS_PER_QUERY,
+ READ_WAIT_MS,
+ UNREADABLE_RECHECK_MS,
+ REPARSE_BATCH,
+ WorkIndex,
+} from "../src/computer/work/index.js";
import type { IndexedItem, ItemsResult } from "../src/computer/work/index-contract.js";
import { PARSER_VERSION } from "../src/computer/work/item.js";
import { sqlStorage } from "./fixtures/computer-sql.js";
import { FakeRepo } from "./fixtures/fake-github-repo.js";
+import { FakeClock, indexStore } from "./fixtures/work-platform.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");
+function setup(repo: FakeRepo, options: { sql?: SqlStorage; mint?: Partial<TokenMinter>; clock?: FakeClock } = {}) {
+ const clock = options.clock ?? new FakeClock();
const pending: Promise<unknown>[] = [];
const mints: unknown[] = [];
let alarmAt: number | null = null;
const sql = options.sql ?? sqlStorage();
- const account: TokenMinter = options.mint ?? {
+ const account: TokenMinter = {
async mintGitHubInstallationToken(input) {
mints.push(input);
- return { outcome: "minted", token: "ghs_test", expiresAt: new Date(t + 3_600_000).toISOString() };
+ return { outcome: "minted", token: "ghs_test", expiresAt: new Date(clock.now() + 3_600_000).toISOString() };
},
+ getGitHubInstallation: () => ({ accountLogin: "acme" }),
+ ...options.mint,
};
+ const fetches: string[] = [];
const index = new WorkIndex({
- sql,
- transaction: (fn) => fn(),
+ store: indexStore(sql),
+ clock,
+ scheduler: {
+ arm: async (at) => {
+ if (alarmAt === null || at < alarmAt) alarmAt = at;
+ },
+ waitUntil: (p) => void pending.push(p),
+ },
account: () => account,
- arm: async (at) => {
- if (alarmAt === null || at < alarmAt) alarmAt = at;
+ fetch: (url, init) => {
+ fetches.push(url);
+ return repo.fetch(url, init);
},
- waitUntil: (p) => void pending.push(p),
- fetch: repo.fetch,
- now: () => t,
});
const settle = async () => {
while (pending.length) await Promise.allSettled(pending.splice(0));
@@ -42,18 +64,20 @@ function setup(repo: FakeRepo, options: { sql?: SqlStorage; mint?: TokenMinter }
index,
sql,
mints,
+ clock,
settle,
- tick: (ms: number) => (t += ms),
- now: () => t,
+ tick: (ms: number) => clock.tick(ms),
+ now: () => clock.now(),
alarmAt: () => alarmAt,
+ walkDone: () => index["walkDone"]() as boolean,
/** Runs alarms until there is nothing more to do (or `max` runs). */
- async drain(max = 50) {
+ async drain(max = 200) {
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;
+ if (next > clock.now()) clock.tick(next - clock.now());
+ if (index["meta"]("build") === null && index["walkDone"]() && clock.now() - Number(index["meta"]("read_at")) > 10 * 60_000) return;
}
},
};
@@ -75,6 +99,11 @@ const open = async (s: ReturnType<typeof setup>) => {
if (!r.ok) throw new Error("not ok");
return r;
};
+const itemOf = async (s: ReturnType<typeof setup>, n: number) => {
+ const r = await s.index.item(ORG, n);
+ if (!r.ok) throw new Error("unavailable");
+ return r.item;
+};
const byNumber = (r: ItemsResult & { ok: true }) => new Map<number, IndexedItem>(r.items.map((i) => [i.number, i]));
describe("build", () => {
@@ -97,7 +126,8 @@ describe("build", () => {
[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);
+ // Not dated until the walk reads the commits: null, never a guess.
+ expect(r.items[0]!.updatedAt).toBeNull();
// The token is narrowed to the repository, contents read.
expect(s.mints[0]).toEqual({ installationId: "inst_1", permissions: { contents: "read" }, repositories: ["knowledge"] });
@@ -135,15 +165,15 @@ describe("build", () => {
const s = await connect(repo);
s.tick(11 * 60_000);
await s.drain();
- const one = (await s.index.item(ORG, 1)).item!;
+ const one = (await itemOf(s, 1))!;
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!;
+ const two = (await itemOf(s, 2))!;
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();
+ expect(s.walkDone()).toBe(true);
});
});
@@ -191,7 +221,7 @@ describe("advance", () => {
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!;
+ let one = (await itemOf(s, 1))!;
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.
@@ -199,14 +229,14 @@ describe("advance", () => {
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!;
+ one = (await itemOf(s, 1))!;
expect(one).toMatchObject({ stage: "open", closedAt: null, closedBy: null });
- const two = (await s.index.item(ORG, 2)).item!;
+ const two = (await itemOf(s, 2))!;
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 () => {
+ it("Session: trailers link: one commit uses the range's files, more ask each commit of the range once", 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();
@@ -214,16 +244,16 @@ describe("advance", () => {
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"]);
+ expect((await itemOf(s, 1))!.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"]);
+ expect(repo.take().filter((l) => /\/commits\/[0-9a-f]{40}$/.test(l))).toHaveLength(2);
+ expect((await itemOf(s, 2))!.sessionIds).toEqual(["cs_2"]);
+ expect((await itemOf(s, 1))!.sessionIds).toEqual(["cs_1"]);
});
it("an added item takes its author from the commit; a removed one loses its row and links", async () => {
@@ -232,11 +262,11 @@ describe("advance", () => {
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"] });
+ expect((await itemOf(s, 2))).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((await itemOf(s, 2))).toBeNull();
expect(s.sql.exec("SELECT * FROM links WHERE number = 2").toArray()).toEqual([]);
});
@@ -258,18 +288,18 @@ describe("advance", () => {
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!;
+ let five = (await itemOf(s, 5))!;
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!;
+ five = (await itemOf(s, 5))!;
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!;
+ five = (await itemOf(s, 5))!;
expect(five).toMatchObject({ path: "done/5-old.md", stage: "closed", title: "Old", warnings: [] });
});
});
@@ -316,10 +346,10 @@ describe("GitHub trouble", () => {
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();
+ expect(s.walkDone()).toBe(false);
});
- it("a deleted repository sets problem; it clears when the repository is back", async () => {
+ it("a deleted repository sets problem; the alarm retries it slowly and clears it 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;
@@ -328,13 +358,25 @@ describe("GitHub trouble", () => {
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.problemMessage).toMatch(/does not exist/);
+ expect(r.repository).toMatchObject({ problem: "repository_not_found", problemMessage: r.problemMessage });
expect(r.items).toHaveLength(1);
- repo.deleted = false;
+ // Retried after a minute, then two, ...: a read in between asks nothing.
+ repo.take();
s.tick(LOOK_AFTER_MS + 1);
await open(s);
await s.settle();
- expect((await open(s)).problem).toBeNull();
+ expect(repo.take()).toEqual([]);
+ s.tick(PROBLEM_RETRY_MS);
+ expect(await s.index.alarm()).toBe(s.now() + 2 * PROBLEM_RETRY_MS);
+ expect(repo.take().length).toBeGreaterThan(0);
+ // Back: the next retry heals it, with no reader and no change to the setting.
+ repo.deleted = false;
+ s.tick(11 * 60_000);
+ await s.index.alarm();
+ const healed = await open(s);
+ expect(healed.problem).toBeNull();
+ expect(healed.problemMessage).toBeNull();
});
it("a removed installation is installation_removed", async () => {
@@ -343,7 +385,7 @@ describe("GitHub trouble", () => {
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" };
+ return connected ? { outcome: "minted", token: "t", expiresAt: new Date(Date.parse("2026-11-20T00:00:00Z")).toISOString() } : { outcome: "not_connected" };
},
},
});
@@ -375,7 +417,8 @@ describe("pull requests", () => {
{ 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" } });
+ // Narrowed to the repositories of the links.
+ expect(s.mints).toContainEqual({ installationId: "inst_1", permissions: { pull_requests: "read" }, repositories: ["app"] });
repo.take();
s.tick(LOOK_AFTER_MS + 1);
await open(s);
@@ -488,3 +531,351 @@ describe("the alarm", () => {
expect(await s.index.alarm()).toBeNull();
});
});
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+const shape = (lines: string[]) => lines.map((l) => l.split("?")[0]!.replace(/[0-9a-f]{40}/g, "SHA"));
+const count = (lines: string[], re: RegExp) => lines.filter((l) => re.test(l)).length;
+
+describe("portability", () => {
+ it("index.ts, item.ts, github.ts and platform.ts name no platform; index-do.ts is the adapter", () => {
+ const read = (f: string) => readFileSync(decodeURIComponent(new URL(`../src/computer/work/${f}`, import.meta.url).pathname), "utf8");
+ for (const f of ["index.ts", "item.ts", "github.ts", "platform.ts"]) {
+ const text = read(f);
+ expect(text, f).not.toMatch(/cloudflare:/);
+ expect(text, f).not.toMatch(/\bSqlStorage\b|\bDurableObject|\bctx\.storage\b|\bDate\.now\(|\bsetTimeout\(|(^|[^.\w])fetch\(/m);
+ }
+ expect(read("index-do.ts")).toMatch(/from "cloudflare:workers"/);
+ });
+});
+
+describe("GitHub trouble, 403s and timeouts", () => {
+ it("a 403 naming a secondary limit pauses a minute at least; another 403 is temporary; only 'not accessible by integration' is a problem", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.failNext.push({ status: 403, message: "You have exceeded a secondary rate limit. Please wait a few minutes." });
+ 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"))).toBeGreaterThanOrEqual(s.now() + DEFAULT_PAUSE_MS);
+
+ s.tick(DEFAULT_PAUSE_MS + 1);
+ repo.failNext.push({ status: 403, message: "Forbidden" });
+ await open(s);
+ await s.settle();
+ expect((await open(s)).problem).toBeNull();
+ expect(Number(s.index["meta"]("pause_until"))).toBeLessThan(s.now());
+
+ s.tick(LOOK_AFTER_MS + 1);
+ repo.failNext.push({ status: 403, message: "Resource not accessible by integration" });
+ await open(s);
+ await s.settle();
+ expect((await open(s)).problem).toBe("access_denied");
+ });
+
+ it("a GraphQL rate limit pauses pull request state only; the head still advances", async () => {
+ const pr = "https://github.com/acme/app/pull/1";
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A", `PR: ${pr}\n`) });
+ repo.pulls.set(pr, { state: "OPEN", title: "One" });
+ const s = await connect(repo);
+ repo.failNext.push({ status: 403, match: /graphql/, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(s.now() / 1000) + 3600) } });
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect(Number(s.index["meta"]("pulls_pause_until"))).toBeGreaterThan(s.now() + 30 * 60_000);
+ expect(s.index["meta"]("pause_until")).toBeNull();
+ repo.commit({ "work/1-a.md": item(1, "A2", `PR: ${pr}\n`) });
+ s.tick(PULLS_EVERY_MS);
+ repo.take();
+ await open(s);
+ await s.settle();
+ expect((await open(s)).items[0]!.title).toBe("A2");
+ expect(count(repo.take(), /graphql/)).toBe(0);
+ });
+
+ it("a request GitHub never answers is aborted after 10 s; reads answer meanwhile and the chain is free after", 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.hangNext = 1;
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await flush();
+ // The look hangs on the head; reads do not wait for it.
+ expect((await open(s)).items[0]!.title).toBe("A");
+ expect((await s.index.item(ORG, 1)).ok).toBe(true);
+ s.tick(REQUEST_TIMEOUT_MS);
+ await s.settle();
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect((await open(s)).items[0]!.title).toBe("A2");
+ });
+
+ it("a closed item not read yet answers unavailable within 5 s when GitHub hangs, and reads on the next try", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "done/3-old.md": item(3, "Old") });
+ const s = await connect(repo);
+ repo.hangNext = 1;
+ const answer = s.index.item(ORG, 3);
+ await flush();
+ s.tick(READ_WAIT_MS);
+ expect(await answer).toMatchObject({ ok: false, error: "unavailable" });
+ s.tick(REQUEST_TIMEOUT_MS);
+ await s.settle();
+ expect(await s.index.item(ORG, 3)).toMatchObject({ ok: true, item: { parsed: true, title: "Old" } });
+ });
+
+ it("history while the walk is not done answers unavailable within 5 s when GitHub hangs", 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();
+ expect(s.walkDone()).toBe(false);
+ repo.hangNext = 5;
+ const answer = s.index.history(ORG, 1);
+ await flush();
+ s.tick(READ_WAIT_MS);
+ expect(await answer).toMatchObject({ ok: false, error: "unavailable", retryAfterMs: expect.any(Number) });
+ s.tick(REQUEST_TIMEOUT_MS);
+ await s.settle();
+ });
+});
+
+describe("the setting", () => {
+ it("a stale problem never refuses setRepository; the setting clears it", 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();
+ expect((await open(s)).problem).toBe("repository_not_found");
+ repo.deleted = false;
+ const r = await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ expect(r).toMatchObject({ ok: true, value: { problem: null, problemMessage: null } });
+ // The same repository: the projection stays.
+ expect(s.sql.exec("SELECT number FROM items").toArray()).toHaveLength(1);
+ });
+
+ it("the owner must be the installation's account", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = setup(repo);
+ expect(await s.index.setRepository(ORG, { installationId: "inst_1", owner: "someone-else", name: "knowledge" }, by)).toMatchObject({
+ ok: false,
+ status: 400,
+ field: "owner",
+ reason: "owner_mismatch",
+ });
+ expect(repo.take()).toEqual([]);
+ });
+
+ it("follows a renamed repository: through GitHub's redirect, or by its id when the old name is gone", async () => {
+ for (const redirects of [true, false]) {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ const s = await connect(repo);
+ repo.redirects = redirects;
+ repo.rename("kb");
+ repo.commit({ "work/1-a.md": item(1, "A2") });
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ const r = await open(s);
+ expect(r.repository, `redirects ${redirects}`).toMatchObject({ owner: "acme", name: "kb", problem: null });
+ expect(r.items[0]).toMatchObject({ title: "A2", url: "https://github.com/acme/kb/blob/main/work/1-a.md" });
+ }
+ });
+});
+
+describe("dates and closers", () => {
+ it("a close the advance did not detail has no closedAt or closedBy until the walk reaches it (never the newest commit, never 1970)", async () => {
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B") });
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ const close = repo.commit({}, "Close 1", { name: "Bob", email: "[email protected]" }, { "work/1-a.md": "done/1-a.md" });
+ for (let i = 0; i < ADVANCE_DETAILS + 2; i++) repo.commit({ "work/2-b.md": item(2, "B", `v${i}`) }, `Edit ${i}`, { name: "Cy", email: "[email protected]" });
+ await s.index.poke(ORG);
+ await s.settle();
+ expect(await itemOf(s, 1)).toMatchObject({ stage: "closed", closedAt: null, closedBy: null, updatedAt: null });
+ expect((await itemOf(s, 2))!.updatedAt).toBe(repo.commits.get(repo.head!)!.at);
+ s.tick(11 * 60_000);
+ await s.drain();
+ expect(await itemOf(s, 1)).toMatchObject({ closedAt: repo.commits.get(close)!.at, closedBy: "Bob", updatedAt: repo.commits.get(close)!.at });
+ });
+});
+
+describe("history from the walk", () => {
+ it("is served from stored revisions across renames and the move to done/, paged by a keyset cursor, with no GitHub call", async () => {
+ const repo = new FakeRepo({});
+ repo.commit({ "work/1-a.md": item(1, "A") }, "Add 1");
+ for (let i = 0; i < 35; i++) repo.commit({ "work/1-a.md": item(1, "A", `v${i}`) }, `Edit ${i}${i === 3 ? "\n\nSession: cs_3" : ""}`);
+ repo.commit({}, "Rename 1", { name: "Ana", email: "[email protected]" }, { "work/1-a.md": "work/1-better.md" });
+ repo.commit({}, "Close 1", { name: "Ana", email: "[email protected]" }, { "work/1-better.md": "done/1-better.md" });
+ repo.commit({ "work/2-x.md": item(2, "X") }, "Add 2");
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ expect(s.walkDone()).toBe(true);
+ repo.take();
+ const first = await s.index.history(ORG, 1);
+ if (!first.ok) throw new Error("not ok");
+ expect(first.revisions).toHaveLength(30);
+ expect(first.revisions.slice(0, 3).map((r) => r.summary)).toEqual(["Close 1", "Rename 1", "Edit 34"]);
+ const second = await s.index.history(ORG, 1, first.nextCursor!);
+ if (!second.ok) throw new Error("not ok");
+ expect(second.revisions.map((r) => r.summary).slice(-2)).toEqual(["Edit 0", "Add 1"]);
+ expect(second.revisions).toHaveLength(38 - 30);
+ expect(second.nextCursor).toBeNull();
+ expect(second.revisions.find((r) => r.summary === "Edit 3")!.sessionId).toBe("cs_3");
+ await s.settle();
+ // A read may look at the head (once a 10 s window); history itself asks GitHub nothing.
+ expect(repo.take().filter((l) => !l.includes("/git/ref/"))).toEqual([]);
+ });
+});
+describe("call budgets", () => {
+ it("the first build of 150 open and 500 closed items: a ref, three trees and the 150 open blobs; then the walk", async () => {
+ const files: Record<string, string> = {};
+ for (let n = 1; n <= 150; n++) files[`work/${n}-open.md`] = item(n, `Open ${n}`);
+ for (let n = 151; n <= 650; n++) files[`done/${n}-closed.md`] = item(n, `Closed ${n}`);
+ const repo = new FakeRepo(files);
+ const s = setup(repo);
+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);
+ // The setting's check: the repository and the branch.
+ expect(shape(repo.take())).toEqual(["GET /repos/acme/knowledge", "GET /repos/acme/knowledge/git/ref/heads/main"]);
+ await s.settle();
+ for (let i = 0; i < 10 && s.index["meta"]("build") !== null; i++) {
+ s.tick(1000);
+ await s.index.alarm();
+ }
+ expect(s.index["meta"]("build")).toBeNull();
+ const build = repo.take();
+ expect(count(build, /\/git\/ref\//)).toBe(1);
+ expect(count(build, /\/git\/trees\//)).toBe(3);
+ expect(count(build, /\/git\/blobs\//)).toBe(150);
+ expect(build).toHaveLength(154);
+ expect((await open(s)).items).toHaveLength(150);
+ // The walk: a page of each folder's commits, and the import commit's 650 files in 3 pages.
+ s.tick(11 * 60_000);
+ await s.drain();
+ const walk = repo.take();
+ expect(count(walk, /\/commits\?/)).toBe(2);
+ expect(count(walk, /\/commits\/[0-9a-f]{40}/)).toBe(3);
+ const rows = s.sql.exec("SELECT COUNT(*) AS n FROM items WHERE created_at IS NULL").toArray()[0] as { n: number };
+ expect(rows.n).toBe(0);
+ });
+
+ it("an advance over 500 commits touching 400 other files stays an advance, within its budget; the walk finishes the dates", async () => {
+ const files: Record<string, string> = {};
+ for (let n = 1; n <= 150; n++) files[`work/${n}-item.md`] = item(n, `Item ${n}`);
+ const repo = new FakeRepo(files);
+ const s = await connect(repo);
+ s.tick(11 * 60_000);
+ await s.drain();
+ expect(s.walkDone()).toBe(true);
+ for (let k = 0; k < 400; k++) repo.commit({ [`notes/${k}.md`]: `note ${k}` }, `Note ${k}`);
+ for (let n = 1; n <= 100; n++) repo.commit({ [`work/${n}-item.md`]: item(n, `Item ${n}`, "edited") }, `Edit ${n}\n\nSession: cs_${n}`);
+ repo.take();
+ await s.index.poke(ORG);
+ await s.settle();
+ const calls = repo.take();
+ // ref + compare + root and work/ trees + 100 changed blobs + a page of work/ commits + 10 details.
+ const budget = 1 + 1 + 2 + 100 + 1 + ADVANCE_DETAILS;
+ expect(calls.length).toBeLessThanOrEqual(budget);
+ expect(count(calls, /\/compare\//)).toBe(1);
+ expect(count(calls, /\/git\/trees\//)).toBe(2);
+ expect(count(calls, /\/git\/blobs\//)).toBe(100);
+ expect(count(calls, /\/commits\/[0-9a-f]{40}/)).toBeLessThanOrEqual(ADVANCE_DETAILS);
+ expect(count(calls, /per_page=1(&|$)/)).toBe(0);
+ const r = await open(s);
+ expect(r.head).toBe(repo.head);
+ expect(r.building).toBe(false);
+ expect(byNumber(r).get(100)!.stateLine).toContain("edited");
+ s.tick(11 * 60_000);
+ await s.drain();
+ const after = byNumber(await open(s));
+ expect(after.get(1)!.sessionIds).toEqual(["cs_1"]);
+ expect(after.get(1)!.updatedAt).not.toBeNull();
+ expect(after.get(150)!.sessionIds).toEqual([]);
+ expect(s.walkDone()).toBe(true);
+ });
+
+ it("a board poll on an unchanged head is one ref request a 10 s window, a 304; an item page is no call", 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();
+ repo.take();
+ for (let i = 0; i < 5; i++) {
+ s.tick(2_000);
+ await open(s);
+ await s.settle();
+ }
+ expect(shape(repo.take())).toEqual(["GET /repos/acme/knowledge/git/ref/heads/main"]);
+ await s.index.item(ORG, 1);
+ await s.index.history(ORG, 1);
+ await s.settle();
+ expect(repo.take()).toEqual([]);
+ });
+});
+
+describe("pull request polling", () => {
+ it("asks the never-asked first then the longest ago, never a merged or closed one again, unreadable after a day, narrowed to the account's repositories", async () => {
+ const urls: string[] = [];
+ for (let n = 1; n <= 55; n++) urls.push(`https://github.com/acme/app/pull/${n}`);
+ urls.push("https://github.com/acme/Site/pull/1", "https://github.com/other/x/pull/1");
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A", `PR: ${urls.join(" ")}\n`) });
+ for (const url of urls.slice(0, 56)) repo.pulls.set(url, { state: "OPEN", title: url });
+ repo.pulls.set(urls[0]!, { state: "MERGED", title: "merged" });
+ const s = await connect(repo);
+ const asked = () => repo.queries.splice(0).flatMap((q) => [...q.matchAll(/owner: "([^"]+)", name: "([^"]+)"\) \{ pullRequest\(number: (\d+)\)/g)].map((m) => `https://github.com/${m[1]}/${m[2]}/pull/${m[3]}`));
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ const first = asked();
+ expect(first).toHaveLength(PULLS_PER_QUERY);
+ // The other account's link is never asked, and is unreadable.
+ expect(first).not.toContain("https://github.com/other/x/pull/1");
+ const pullMints = s.mints.filter((m) => (m as { permissions: object }).permissions.hasOwnProperty("pull_requests")) as { repositories: string[] }[];
+ for (const m of pullMints) for (const name of m.repositories) expect(["app", "site"]).toContain(name);
+
+ s.tick(PULLS_EVERY_MS);
+ await open(s);
+ await s.settle();
+ const second = asked();
+ // Every link never asked comes first; the merged one is not asked again.
+ const never = urls.slice(0, 56).filter((u) => !first.includes(u));
+ for (const u of never) expect(second).toContain(u);
+ expect(second).not.toContain(urls[0]);
+ expect(second).not.toContain("https://github.com/other/x/pull/1");
+ const prs = (await open(s)).items[0]!.pullRequests;
+ expect(prs.find((p) => p.url === urls[0])!.state).toBe("merged");
+ expect(prs.find((p) => p.url.includes("other/x"))!.state).toBeNull();
+ const unreadable = s.sql.exec("SELECT state FROM pulls WHERE url = ?", "https://github.com/other/x/pull/1").toArray()[0] as { state: string };
+ expect(unreadable.state).toBe("unreadable");
+ });
+
+ it("asks an unreadable link again only after a day", async () => {
+ const gone = "https://github.com/acme/app/pull/9";
+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A", `PR: ${gone}\n`) });
+ const s = await connect(repo);
+ const asks = () => repo.take().filter((l) => l.includes("graphql")).length;
+ s.tick(LOOK_AFTER_MS + 1);
+ await open(s);
+ await s.settle();
+ expect(asks()).toBe(1);
+ expect(s.sql.exec("SELECT state FROM pulls").toArray()).toEqual([{ state: "unreadable" }]);
+ s.tick(PULLS_EVERY_MS + 1);
+ await open(s);
+ await s.settle();
+ expect(asks()).toBe(0);
+ repo.pulls.set(gone, { state: "OPEN", title: "Back" });
+ s.tick(UNREADABLE_RECHECK_MS);
+ await open(s);
+ await s.settle();
+ expect(asks()).toBe(1);
+ expect((await open(s)).items[0]!.pullRequests).toEqual([{ url: gone, state: "open", title: "Back" }]);
+ });
+});