An open-source, faster Devin alternative
TypeScript
Work index: activity and derived owners from non-bulk commits
Igor Zalutski via Computer36475c438bda
diff --git a/services/managed-agents/src/computer/api-http.ts b/services/managed-agents/src/computer/api-http.tsindex 643f1857..e111d50c 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, WorkStampOp } from "./work/briefs.js";+import type { WorkContextOp, WorkRefsOp, 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 | WorkStampOp): Promise<ApiReply>;+ computerApi(accountId: string, caller: ApiCaller, op: ApiOp | SecretsApiOp | WorkContextOp | WorkStampOp | WorkRefsOp): Promise<ApiReply>;}const BODY_MAX_BYTES = 512 * 1024;@@ -69,6 +69,8 @@ export function matchApiRoute(method: string, suffix: string): Route | null {if (p[0] === "work") {if (p[1] === "repository" && p.length === 2) return method === "GET" ? { op: "work.repository.get" } : method === "PUT" ? { op: "work.repository.put" } : null;if (p[1] === "repositories") return is("GET", 2) ? { op: "work.repositories" } : null;+ // The items a session worked on, for the session's screen.+ if (p[1] === "sessions") return is("GET", 4) && p[3] === "items" ? { op: "work.session.items", sub: p[2] } : null;if (p[1] !== "items") return null;if (is("GET", 2)) return { op: "work.items" };if (is("GET", 3)) return { op: "work.item", sub: p[2] };@@ -272,7 +274,7 @@ const OPS = new Set(["sessions.interrupt", "sessions.compact", "sessions.suspend", "sessions.resume","turns.send", "turns.list", "turns.get", "turns.cancel", "events.list","asks.list", "asks.get", "asks.answer", "asks.dismiss", "subagents.list", "subagents.get", "subagents.stop",- "work.repository.get", "work.repository.put", "work.repositories", "work.items", "work.item", "work.history",+ "work.repository.get", "work.repository.put", "work.repositories", "work.items", "work.item", "work.history", "work.session.items",]);/** The request's one `httpapi.request`; never throws, never awaited. */diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 2e5d486e..96b0b43a 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -146,7 +146,7 @@ import {import { type SubmittedView, parseSecretCommand } from "./secrets.js";import { parseVariableCommand } from "./variables.js";import { type SecretsApiOp, SecretsStore } from "./secrets-store.js";-import { type WorkContextOp, type WorkStampOp, workContext, workStamp, workStampSetup } from "./work/briefs.js";+import { type WorkContextOp, type WorkRefsOp, type WorkStampOp, workContext, workRefs, workStamp, workStampSetup } from "./work/briefs.js";import { knowledgeRepository } from "./work/index-do.js";import { AccessStore } from "./access-store.js";import { AccessFlow } from "./access-flow.js";@@ -1631,13 +1631,14 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {// ------------------------------------------------------------------ session API (work 084)/** One session API operation (api-http.ts resolved the caller); never throws for a refusal. */- async computerApi(accountId: string, caller: ApiCaller, op: ApiOp | SecretsApiOp | WorkContextOp | WorkStampOp): Promise<ApiReply> {+ async computerApi(accountId: string, caller: ApiCaller, op: ApiOp | SecretsApiOp | WorkContextOp | WorkStampOp | WorkRefsOp): Promise<ApiReply> {this.bind(accountId);// Organization secrets (work 095) answer whether or not the sessions API is enabled for the organization.if (op.op.startsWith("secrets.")) return this.secrets.api(caller, op as SecretsApiOp);// The Work API's sessions and people (work tracking 3.10), likewise.if (op.op === "work.context") return workContext({ sql: this.ctx.storage.sql, api: this.api }, caller, op as WorkContextOp);if (op.op === "work.stamp") return workStamp(this.ctx.storage.sql);+ if (op.op === "work.refs") return workRefs({ api: this.api }, caller, op as WorkRefsOp);return this.api.handle(caller, op as ApiOp);}diff --git a/services/managed-agents/src/computer/work/api.ts b/services/managed-agents/src/computer/work/api.tsindex f9201d1c..a5285aec 100644--- a/services/managed-agents/src/computer/work/api.ts+++ b/services/managed-agents/src/computer/work/api.ts@@ -11,7 +11,7 @@// 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, WorkStampOp } from "./briefs.js";+import type { SessionBrief, WorkContext, WorkContextOp, WorkRefsOp, WorkStampOp } from "./briefs.js";import type { IndexedItem, ItemsResult, Revision, WorkIndexRpc } from "./index-contract.js";export interface Person {@@ -20,6 +20,11 @@ export interface Person {id: string | null;}+/** The owner: a person, and whether the doc names them (`declared`) or the commits do (`derived`). */+export interface Owner extends Person {+ source: "declared" | "derived";+}+export interface ItemAttention {state: "needs_you" | "waiting_on" | "working";name: string | null;@@ -35,8 +40,9 @@ export interface Item {title: string;stateLine: string | null;tags: string[];- owner: Person | null;+ owner: Owner | null;author: Person | null;+ /** The caller owns it, declared or derived. */mine: boolean;left: number | null;readyToClose: boolean;@@ -48,16 +54,20 @@ export interface Item {unpublished: boolean;/** The last commit that changed the file; null until the index has dated it. */updatedAt: string | null;+ /** The last commit that changed the file and was not a bulk edit; null when none is known. */+ lastActivityAt: string | null;+ /** `lastActivityAt` within the last 14 days, or a linked session is working or waiting (`attention`). */+ active: boolean;createdAt: string | null;closedAt: string | null;closedBy: string | null;}-export type WorkRouteOp = "work.repository.get" | "work.repository.put" | "work.repositories" | "work.items" | "work.item" | "work.history";+export type WorkRouteOp = "work.repository.get" | "work.repository.put" | "work.repositories" | "work.items" | "work.item" | "work.history" | "work.session.items";export interface WorkRoute {op: WorkRouteOp;- /** The item number's path segment, unvalidated. */+ /** The item number's (or, for `work.session.items`, the session id's) path segment, unvalidated. */sub?: string;}@@ -69,8 +79,8 @@ export interface WorkDeps {caller: ApiCaller;/** The Work index, or null when the binding is missing. */index: WorkIndexRpc | null;- /** The Computer object's `work.context` and `work.stamp`. */- context(op: WorkContextOp | WorkStampOp): Promise<ApiReply>;+ /** The Computer object's `work.context`, `work.stamp` and `work.refs`. */+ context(op: WorkContextOp | WorkStampOp | WorkRefsOp): Promise<ApiReply>;}/** The query parameters each route takes; any other is refused. */@@ -81,10 +91,12 @@ const PARAMS: Record<WorkRouteOp, readonly string[]> = {"work.items": ["stage", "cursor", "limit"],"work.item": [],"work.history": ["cursor"],+ "work.session.items": [],};const CLOSED_LIMIT_MAX = 100;const NUMBER = /^[1-9]\d{0,8}$/;+const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/;const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;const REPO_NAME = /^[A-Za-z0-9._-]{1,100}$/;const UNAVAILABLE: WorkReply = { status: 503, error: { code: "unavailable", message: "Work is unavailable. Try again shortly.", retryAfterMs: 5_000 } };@@ -139,7 +151,7 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearchconst [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);+ const etag = await etagOf(open.head, open.version, open.recent, stamp, deps.caller);if (ifNoneMatch !== null && matches(ifNoneMatch, etag)) return { status: 304, etag, asOf: open.asOf };}const cursor = query.get("cursor");@@ -154,7 +166,8 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearchif (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 };// 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 };+ const recent = result.items.filter((i) => i.stage === "open" && i.recent).length;+ return { status: 200, body: page, etag: await etagOf(result.head, result.version, recent, stamp!, deps.caller), asOf: result.asOf };}case "work.item": {@@ -168,6 +181,18 @@ export async function workApi(deps: WorkDeps, route: WorkRoute, query: URLSearchreturn { status: 200, body: { item: composed.items[0]!, body: result.body }, asOf: result.asOf };}+ case "work.session.items": {+ // The session must be one the caller may see; its id and key are what trailers name.+ const sessionId = route.sub ?? "";+ if (!SESSION_ID.test(sessionId)) return { status: 404, error: { code: "session_not_found", message: "No such session." } };+ const refs = await deps.context({ op: "work.refs", sessionId });+ if (refs.error) return refs;+ const result = await index.linked(deps.accountId, (refs.body as { refs: string[] }).refs);+ const composed = await compose(deps, result.items);+ if ("status" in composed) return composed;+ return { status: 200, body: { items: composed.items }, asOf: result.asOf };+ }+case "work.history": {if (!NUMBER.test(route.sub ?? "")) return notFound();const cursor = query.get("cursor");@@ -233,7 +258,7 @@ export function branchName(name: string): boolean {/** The index's items joined with the caller's sessions and the members behind emails. */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 emails = [...new Set(items.flatMap((i) => [i.owner?.email ?? null, 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: [] };if ("status" in context) return context;const mine = new Set(context.callerEmails.map((e) => e.toLowerCase()));@@ -244,6 +269,7 @@ async function compose(deps: WorkDeps, items: IndexedItem[]): Promise<{ items: Ireturn {items: items.map((i): Item => {const briefs = linkedBriefs(i.sessionIds, context.sessions);+ const attention = itemAttention(briefs, deps.caller.member);return {number: i.number,stage: i.stage,@@ -252,17 +278,19 @@ async function compose(deps: WorkDeps, items: IndexedItem[]): Promise<{ items: Ititle: i.title,stateLine: i.stateLine,tags: i.tags,- owner: i.owner ? person(i.owner) : null,+ owner: i.owner ? { ...person(i.owner.email, i.owner.name), source: i.owner.source } : null,author: i.author?.email ? person(i.author.email, i.author.name) : null,- mine: i.owner !== null && mine.has(i.owner.toLowerCase()),+ mine: i.owner !== null && mine.has(i.owner.email.toLowerCase()),left: i.left,readyToClose: i.readyToClose,warnings: i.warnings,pullRequests: i.pullRequests,- attention: itemAttention(briefs, deps.caller.member),+ attention,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,+ lastActivityAt: i.lastActivityAt,+ active: i.recent || attention !== null,createdAt: i.createdAt,closedAt: i.closedAt,closedBy: i.closedBy,@@ -308,12 +336,13 @@ export function itemAttention(briefs: SessionBrief[], member: string): ItemAtten}/**- * 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).+ * The open list's ETag: the head, then a digest of the index's version, how many open items are+ * recent (one ages out of `active` with no commit), 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(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])));+export async function etagOf(head: string | null, version: number, recent: number, sessions: string, caller: Pick<ApiCaller, "member" | "email">): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([version, recent, sessions, caller.member, caller.email])));const stamp = [...new Uint8Array(digest).slice(0, 8)].map((b) => b.toString(16).padStart(2, "0")).join("");return `"${head ?? "none"}-${stamp}"`;}diff --git a/services/managed-agents/src/computer/work/briefs.ts b/services/managed-agents/src/computer/work/briefs.tsindex d2901018..584e781f 100644--- a/services/managed-agents/src/computer/work/briefs.ts+++ b/services/managed-agents/src/computer/work/briefs.ts@@ -29,6 +29,12 @@ export interface WorkStampOp {op: "work.stamp";}+/** A session's references, as a `Session:` trailer may name it: its public id and its key. */+export interface WorkRefsOp {+ op: "work.refs";+ sessionId: string;+}+/*** The stamp's counter and triggers, and the indexes the context's email lookups use. Run once the* `sessions` table has its API columns and `people` exists.@@ -90,6 +96,17 @@ export interface WorkContextDeps {const NO_REPLY = /noreply/i;+/**+ * What a commit's `Session:` trailer may name for the session: its public id, and the key a host+ * before the public ids wrote (the hook writes `SP_SESSION_ID`, which is either). 404 for a session+ * the caller may not see, as the sessions routes answer.+ */+export function workRefs(deps: Pick<WorkContextDeps, "api">, caller: ApiCaller, op: WorkRefsOp): ApiReply {+ const row = typeof op.sessionId === "string" ? deps.api.visible(caller, op.sessionId) : undefined;+ if (!row?.sessionId) return { status: 404, error: { code: "session_not_found", message: "No such session." } };+ return { status: 200, body: { refs: [...new Set([row.sessionId, row.key].filter((r) => !!r))] } };+}+export function workContext(deps: WorkContextDeps, caller: ApiCaller, op: WorkContextOp): ApiReply {const sessions: Record<string, SessionBrief> = {};for (const ref of op.sessionIds.slice(0, CONTEXT_MAX)) {diff --git a/services/managed-agents/src/computer/work/index-contract.ts b/services/managed-agents/src/computer/work/index-contract.tsindex 9e66ae49..39bf4462 100644--- a/services/managed-agents/src/computer/work/index-contract.ts+++ b/services/managed-agents/src/computer/work/index-contract.ts@@ -78,6 +78,20 @@ export interface OpenStamp {head: string | null;asOf: string | null;version: number;+ /** How many open items changed within RECENT_DAYS: moves when one ages out, with no commit. */+ recent: number;+}++/**+ * Who owns an item. `declared`: the frontmatter `owner:`. `derived`: the author of the latest commit+ * that touched the file and was not a bulk edit, else of its latest commit of any kind.+ */+export interface IndexedOwner {+ /** Lowercased. */+ email: string;+ /** The commit author's name without " via Computer"; null for a declared owner. */+ name: string | null;+ source: "declared" | "derived";}/** An item as the index holds it, before the Worker joins sessions and people. */@@ -90,8 +104,8 @@ export interface IndexedItem {title: string;stateLine: string | null;tags: string[];- /** The frontmatter owner email, lowercased. */- owner: string | null;+ /** Declared, else derived from the commits; null when neither is known. */+ owner: IndexedOwner | null;/** The author of the commit that added the file; null until the index has seen that commit. */author: { name: string; email: string | null } | null;left: number | null;@@ -101,6 +115,10 @@ export interface IndexedItem {/** Sessions with a commit that touched the file, most recent first. */sessionIds: string[];updatedAt: string | null;+ /** The latest commit that touched the file and was not a bulk edit (BULK_ITEMS); null when none is read. */+ lastActivityAt: string | null;+ /** `lastActivityAt` is within RECENT_DAYS of now. */+ recent: boolean;createdAt: string | null;closedAt: string | null;/** The name of the person who closed it; null when unknown or closed in a session. */@@ -124,6 +142,9 @@ export type ItemResult =/** The body is not read yet and GitHub did not give it within the read's wait. */| { ok: false; error: "unavailable"; retryAfterMs: number };+/** The items whose commits name one of a session's references in a `Session:` trailer. */+export type LinkedResult = ReadState & { ok: true; repository: Repository | null; items: IndexedItem[] };+export interface Revision {sha: string;url: string;@@ -147,6 +168,8 @@ export interface WorkIndexRpc {items(accountId: string, query: ItemsQuery): Promise<ItemsResult>;item(accountId: string, number: number): Promise<ItemResult>;history(accountId: string, number: number, cursor?: string): Promise<HistoryResult>;+ /** Open and closed items linked to any of `refs` (a session's public id and its runner key), by number. */+ linked(accountId: string, refs: string[]): Promise<LinkedResult>;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.tsindex 6ba8ff7f..e09cd260 100644--- a/services/managed-agents/src/computer/work/index-do.ts+++ b/services/managed-agents/src/computer/work/index-do.ts@@ -70,6 +70,10 @@ export class WorkIndexDurableObject extends DurableObject<WorkIndexEnv> implemenreturn this.index.history(accountId, number, cursor);}+ linked(accountId: string, refs: string[]) {+ return this.index.linked(accountId, refs);+ }+poke(accountId: string) {return this.index.poke(accountId);}diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.tsindex e66c13fc..018c8de4 100644--- a/services/managed-agents/src/computer/work/index.ts+++ b/services/managed-agents/src/computer/work/index.ts@@ -52,9 +52,11 @@ import {import type {HistoryResult,IndexedItem,+ IndexedOwner,ItemResult,ItemsQuery,ItemsResult,+ LinkedResult,OpenStamp,GrantingInstallation,ReadState,@@ -94,6 +96,8 @@ export const READ_WAIT_MS = 5_000;export const PROBLEM_RETRY_MS = 60_000;export const PROBLEM_RETRY_MAX_MS = 60 * 60_000;const HISTORY_PAGE = 30;+/** A session's linked items answered at most. */+const LINKED_MAX = 50;const CLOSED_LIMIT_DEFAULT = 50;const CLOSED_LIMIT_MAX = 100;const FETCH_PARALLEL = 6;@@ -104,7 +108,12 @@ 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_VERSION = 3;+/** A commit touching more item files than this is a bulk edit: no item's own activity, no owner. */+export const BULK_ITEMS = 5;+/** An item whose own last change is this recent is active (with a session at work, in the Worker). */+export const RECENT_DAYS = 14;+const DAY_MS = 86_400_000;const SCHEMA = `CREATE TABLE IF NOT EXISTS items (@@ -116,7 +125,9 @@ CREATE TABLE IF NOT EXISTS items (parsed TEXT NOT NULL,parser INTEGER NOT NULL,author_name TEXT, author_email TEXT, created_at TEXT,- updated_at TEXT, closed_at TEXT, closed_by TEXT+ updated_at TEXT, closed_at TEXT, closed_by TEXT,+ updated_name TEXT, updated_email TEXT,+ activity_at TEXT, activity_name TEXT, activity_email 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);@@ -148,7 +159,8 @@ export interface WorkIndexDeps {}/** 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";+const ROW_COLUMNS =+ "number, path, stage, blob, parsed, parser, author_name, author_email, created_at, updated_at, closed_at, closed_by, updated_name, updated_email, activity_at, activity_name, activity_email";interface ItemRow {number: number;@@ -163,6 +175,13 @@ interface ItemRow {updated_at: string | null;closed_at: string | null;closed_by: string | null;+ /** The author of the latest commit that touched the file. */+ updated_name: string | null;+ updated_email: string | null;+ /** The latest commit that touched the file and was not a bulk edit, and its author. */+ activity_at: string | null;+ activity_name: string | null;+ activity_email: string | null;}type Row = Record<string, StoreValue>;@@ -348,7 +367,13 @@ export class WorkIndex {this.bind(accountId);this.noteRead();const { head, asOf, version } = this.readState();- return { head, asOf, version };+ const recent = this.store.exec<{ n: number }>("SELECT COUNT(*) AS n FROM items WHERE stage = 'open' AND activity_at >= ?", this.recentSince())[0]!.n;+ return { head, asOf, version, recent };+ }++ /** The commits' time format (no milliseconds) RECENT_DAYS ago: a change at or after it is recent. */+ private recentSince(): string {+ return new Date(this.now() - RECENT_DAYS * DAY_MS).toISOString().replace(/\.\d{3}Z$/, "Z");}/**@@ -482,6 +507,21 @@ export class WorkIndex {return { ok: true, ...this.readState(), repository: this.repository(), item: row ? this.indexed([row])[0]! : null, body: row ? row.body : null };}+ /**+ * The items linked to a session: their commits carry one of `refs` in a `Session:` trailer. Open+ * and closed, by number; at most LINKED_MAX. Bodies not read yet show their slug.+ */+ async linked(accountId: string, refs: string[]): Promise<LinkedResult> {+ this.bind(accountId);+ this.noteRead();+ const wanted = [...new Set(refs.filter((r) => typeof r === "string" && r.length > 0 && r.length <= 128))].slice(0, BIND_MAX);+ const numbers = wanted.length+ ? this.store.exec<{ number: number } & Row>(`SELECT DISTINCT number FROM links WHERE session_id IN (${marks(wanted)}) ORDER BY number LIMIT ?`, ...wanted, LINKED_MAX).map((r) => r.number)+ : [];+ const rows = numbers.length ? this.store.exec<ItemRow & Row>(`SELECT ${ROW_COLUMNS} FROM items WHERE number IN (${marks(numbers)}) ORDER BY number`, ...numbers) : [];+ return { ok: true, ...this.readState(), repository: this.repository(), items: this.indexed(rows) };+ }+/*** 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.@@ -725,7 +765,8 @@ export class WorkIndex {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`,+ parser = excluded.parser, author_name = NULL, author_email = NULL, created_at = NULL, updated_at = NULL, closed_at = NULL, closed_by = NULL,+ updated_name = NULL, updated_email = NULL, activity_at = NULL, activity_name = NULL, activity_email = NULL`,number,w.path,ip.stage,@@ -1024,6 +1065,10 @@ export class WorkIndex {const store = this.store;const trailers = sessionTrailers(c.message);const at = c.at ?? "";+ const author = authorName(c);+ const email = c.authorEmail?.trim().toLowerCase() || null;+ // A commit across many items (a rename, a sweep) is nobody's work on any one of them.+ const bulk = itemNumbers(files).size > BULK_ITEMS;for (const f of files) {const ip = itemPath(f.filename);const from = f.previousFilename ? itemPath(f.previousFilename) : null;@@ -1038,14 +1083,19 @@ export class WorkIndex {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 = ?",+ const row = store.exec<{ path: string; stage: string; created_at: string | null; closed_at: string | null; updated_at: string | null; activity_at: string | null } & Row>(+ "SELECT path, stage, created_at, closed_at, updated_at, activity_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);+ if (row.updated_at === null || c.at > row.updated_at) {+ store.exec("UPDATE items SET updated_at = ?, updated_name = ?, updated_email = ? WHERE number = ?", c.at, author, email, number);+ }+ if (!bulk && (row.activity_at === null || c.at > row.activity_at)) {+ store.exec("UPDATE items SET activity_at = ?, activity_name = ?, activity_email = ? WHERE number = ?", c.at, author, email, 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);@@ -1176,6 +1226,7 @@ export class WorkIndex {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 recentSince = this.recentSince();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";@@ -1189,7 +1240,7 @@ export class WorkIndex {title: parsed.title,stateLine: parsed.stateLine,tags: parsed.tags,- owner: parsed.owner,+ owner: ownerOf(parsed.owner, r),author: r.author_name !== null ? { name: r.author_name, email: r.author_email } : null,left: parsed.left,readyToClose: readyToClose(stage, parsed),@@ -1201,6 +1252,8 @@ export class WorkIndex {}),sessionIds: links.get(r.number) ?? [],updatedAt: r.updated_at,+ lastActivityAt: r.activity_at,+ recent: r.activity_at !== null && r.activity_at >= recentSince,createdAt: r.created_at,closedAt: stage === "closed" ? r.closed_at : null,closedBy: stage === "closed" ? r.closed_by : null,@@ -1259,12 +1312,40 @@ function safeParse(ip: ItemPath, body: string): ParsedItem {/** Who closed: the commit's author, or null when a session made the commit (it says "closed in a session"). */function closerName(c: CommitInfo): string | null {if (sessionTrailers(c.message).length) return null;+ return authorName(c);+}++/** The commit author's name without the " via Computer" a session's commit carries; null when empty. */+function authorName(c: CommitInfo): string | null {// By hand, not `/\s+via Computer$/`: an unanchored `\s+` backtracks on a run of spaces.const name = c.authorName.slice(0, 200).trim();const suffix = " via computer";return (name.toLowerCase().endsWith(suffix) ? name.slice(0, -suffix.length) : name).trim() || null;}+/** The items a commit's files touch, by number (a rename counts both ends). */+function itemNumbers(files: FileChange[]): Set<number> {+ const out = new Set<number>();+ for (const f of files) {+ const ip = itemPath(f.filename);+ if (ip) out.add(ip.number);+ const from = f.previousFilename ? itemPath(f.previousFilename) : null;+ if (from) out.add(from.number);+ }+ return out;+}++/**+ * The frontmatter owner; else the author of the latest change that was not a bulk edit; else of+ * the latest change of any kind. A commit with no email names no owner.+ */+function ownerOf(declared: string | null, r: ItemRow): IndexedOwner | null {+ if (declared) return { email: declared, name: null, source: "declared" };+ if (r.activity_email) return { email: r.activity_email, name: r.activity_name, source: "derived" };+ if (r.updated_email) return { email: r.updated_email, name: r.updated_name, source: "derived" };+ return null;+}+function summaryOf(message: string): string {const end = message.indexOf("\n");return (end === -1 ? message : message.slice(0, end)).replace(/\r$/, "").slice(0, 200);diff --git a/services/managed-agents/test/work-index.test.ts b/services/managed-agents/test/work-index.test.tsindex d480ec59..4bccba06 100644--- a/services/managed-agents/test/work-index.test.ts+++ b/services/managed-agents/test/work-index.test.ts@@ -12,8 +12,10 @@ import {PULLS_EVERY_MS,PULLS_PER_QUERY,READ_WAIT_MS,+ RECENT_DAYS,UNREADABLE_RECHECK_MS,REPARSE_BATCH,+ BULK_ITEMS,WorkIndex,} from "../src/computer/work/index.js";import type { IndexedItem, ItemsResult } from "../src/computer/work/index-contract.js";@@ -178,6 +180,82 @@ describe("build", () => {});});+describe("activity and owners", () => {+ // The fake repository's commits start on 2026-11-01; the index's clock is set a day later.+ const early = () => new FakeClock(Date.parse("2026-11-02T00:00:00Z"));+ const bulk = (tag: string) => Object.fromEntries(Array.from({ length: BULK_ITEMS + 1 }, (_, i) => [`work/${i + 1}-x.md`, item(i + 1, `X ${i + 1}`, tag)]));++ it("an item's activity and derived owner are its latest commit touching at most five items; a bulk edit only moves updatedAt", async () => {+ const repo = new FakeRepo({});+ repo.commit(bulk("one"), "Import", { name: "Ana", email: "[email protected]" });+ repo.commit({ "work/1-x.md": item(1, "X 1", "two") }, "Edit 1", { name: "Bob via Computer", email: "[email protected]" });+ const own = repo.commits.get(repo.head!)!.at;+ repo.commit(bulk("three"), "Retag everything", { name: "Cy via Computer", email: "[email protected]" });+ const s = setup(repo, { clock: early() });+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);+ await s.settle();+ await s.drain();+ s.tick(11 * 60_000);+ await s.drain();+ expect(s.walkDone()).toBe(true);+ const one = (await itemOf(s, 1))!;+ expect(one.updatedAt).toBe(repo.commits.get(repo.head!)!.at);+ expect(one.lastActivityAt).toBe(own);+ expect(one.owner).toEqual({ email: "[email protected]", name: "Bob", source: "derived" });+ expect(one.recent).toBe(true);+ // Touched only by bulk edits: no activity, and the latest commit's author as the owner.+ const two = (await itemOf(s, 2))!;+ expect(two.lastActivityAt).toBeNull();+ expect(two.recent).toBe(false);+ expect(two.owner).toEqual({ email: "[email protected]", name: "Cy", source: "derived" });+ });++ it("the frontmatter owner is declared and wins over commits", async () => {+ const repo = new FakeRepo({});+ repo.commit({ "work/1-a.md": `---\nowner: [email protected]\n---\n${item(1, "A")}` }, "Add 1", { name: "Bob", email: "[email protected]" });+ const s = setup(repo, { clock: early() });+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);+ await s.settle();+ await s.drain();+ expect((await itemOf(s, 1))!.owner).toEqual({ email: "[email protected]", name: null, source: "declared" });+ });++ it("an advance sets activity from the compare's files; recent ages out after 14 days and the stamp counts it", async () => {+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B") });+ const s = setup(repo, { clock: early() });+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);+ await s.settle();+ await s.drain();+ repo.commit({ "work/1-a.md": item(1, "A", "more") }, "Edit 1", { name: "Bob via Computer", email: "[email protected]" });+ await s.index.poke(ORG);+ await s.settle();+ const one = (await itemOf(s, 1))!;+ expect(one).toMatchObject({ lastActivityAt: repo.commits.get(repo.head!)!.at, recent: true, owner: { name: "Bob", source: "derived" } });+ const before = await s.index.stamp(ORG);+ expect(before.recent).toBeGreaterThanOrEqual(1);+ s.tick(RECENT_DAYS * 86_400_000);+ expect((await itemOf(s, 1))!.recent).toBe(false);+ const after = await s.index.stamp(ORG);+ expect(after.recent).toBe(0);+ });++ it("linked answers the items a session's id or key names, once each", async () => {+ const repo = new FakeRepo({ "work/1-a.md": item(1, "A"), "work/2-b.md": item(2, "B"), "work/3-c.md": item(3, "C") });+ const s = await connect(repo);+ repo.commit({ "work/1-a.md": item(1, "A", "x") }, "Edit 1\n\nSession: cs_1");+ repo.commit({ "work/2-b.md": item(2, "B", "x") }, "Edit 2\n\nSession: T1:C1:111");+ repo.commit({ "work/1-a.md": item(1, "A", "y") }, "Edit 1 again\n\nSession: T1:C1:111");+ await s.index.poke(ORG);+ await s.settle();+ s.tick(11 * 60_000);+ await s.drain();+ const r = await s.index.linked(ORG, ["cs_1", "T1:C1:111"]);+ expect(r.ok && r.items.map((i) => i.number)).toEqual([1, 2]);+ const none = await s.index.linked(ORG, ["cs_none"]);+ expect(none.ok && none.items).toEqual([]);+ });+});+describe("advance", () => {it("a push costs a head check, one compare and one blob", async () => {const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });@@ -803,6 +881,37 @@ describe("call budgets", () => {expect(s.walkDone()).toBe(true);});+ it("150 items and 300 commits: the build as before, then a walk of a commit listing page per 100 and a detail per commit; activity and owners cost no more", 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);+ for (let k = 0; k < 300; k++) {+ const n = (k % 150) + 1;+ repo.commit({ [`work/${n}-item.md`]: item(n, `Item ${n}`, `edit ${k}`) }, `Edit ${n}`, { name: `P${k % 7} via Computer`, email: `p${k % 7}@acme.test` });+ }+ const s = setup(repo, { clock: new FakeClock(Date.parse("2026-11-02T00:00:00Z")) });+ await s.index.setRepository(ORG, { installationId: "inst_1", owner: "acme", name: "knowledge" }, by);+ repo.take();+ await s.settle();+ for (let i = 0; i < 10 && s.index["meta"]("build") !== null; i++) {+ s.tick(1000);+ await s.index.alarm();+ }+ expect(repo.take()).toHaveLength(1 + 2 + 150);+ s.tick(11 * 60_000);+ await s.drain();+ expect(s.walkDone()).toBe(true);+ const walk = repo.take();+ // 301 commits touch work/ (the import and 300 edits): 4 pages of 100, and done/'s one page.+ expect(count(walk, /\/commits\?/)).toBe(5);+ expect(count(walk, /\/commits\/[0-9a-f]{40}/)).toBe(301);+ expect(walk).toHaveLength(5 + 301);+ const r = byNumber(await open(s));+ // Item 1 was last edited by the 151st edit, k = 150.+ expect(r.get(1)!.owner).toMatchObject({ source: "derived", name: "P3", email: "[email protected]" });+ expect(r.get(1)!.lastActivityAt).not.toBeNull();+ });+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);