Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 7743394860 fix(server): ignore publication timestamp changes in PR reviews
Use GitHub’s edit timestamp for submitted reviews and published inline comments. A timestamp change during publication must not wake the agent again.
2026-11-28 07:10:55 +00:00
paseo-bot[bot]andSirGiveALot 7500c920eb fix(server): keep edited PR comment polling bounded
Read comments in revision order so edits to older comments reach the watcher without paging through the entire thread on every poll.

Co-authored-by: SirGiveALot <easyname889@gmail.com>
2026-11-28 06:46:30 +00:00
SirGiveALot 3a6b68cce9 fix(server): wake change-request watchers for edited review activity
- Fetch GitHub activity revision metadata through older comment pages.
- Persist per-activity revisions and notify the existing owner once per edit, including after restart.
- Reconcile legacy ID-only baselines once without replaying all historical comments.
- Keep the existing poller, digest and message-delivery path; 18 focused tests passed.
2026-11-28 06:46:30 +00:00
6 changed files with 372 additions and 25 deletions
@@ -23,6 +23,7 @@ const persistedWatchGroupSchema = z.object({
url: z.url(),
snapshot: changeRequestStatusSchema,
seenActivity: z.array(z.string()),
activityUpdatedAt: z.record(z.string(), z.string()).optional(),
watchers: z.array(z.object({ agentId: z.string(), startedAt: z.string().optional() })),
});
type PersistedWatchGroup = z.infer<typeof persistedWatchGroupSchema>;
@@ -61,6 +62,8 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
previous.checks.filter((check) => check.state === "failed").map((check) => check.id),
);
const seen = new Set(group.seenActivity);
const activityUpdatedAt = { ...group.activityUpdatedAt };
let reconciledLegacyActivity = false;
const changes = next.checks
.filter(
(check) =>
@@ -77,12 +80,31 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
changes.push(`Checks passed on ${next.headSha}.`);
}
for (const activity of next.activity) {
if (seen.has(activity.id)) continue;
changes.push(activity.message ?? `New ${activity.kind}: ${activity.url}`);
const known = seen.has(activity.id);
const previousRevision = activityUpdatedAt[activity.id];
const revised =
activity.updatedAt !== undefined &&
(previousRevision === undefined || activity.updatedAt > previousRevision);
if (known && !revised) continue;
if (known && previousRevision === undefined) {
// An ID-only baseline cannot tell which edits happened before upgrade.
// Reconcile once per watch, rather than replaying every historical comment.
reconciledLegacyActivity = true;
} else {
changes.push(
activity.message ?? `${known ? "Updated" : "New"} ${activity.kind}: ${activity.url}`,
);
}
seen.add(activity.id);
if (activity.updatedAt !== undefined) activityUpdatedAt[activity.id] = activity.updatedAt;
}
if (reconciledLegacyActivity) {
changes.push(
`Existing review activity reconciled after watcher upgrade; recheck current status: ${group.url}`,
);
}
if (next.state !== "open") changes.push(`Change request ${next.state}.`);
return { changes, seenActivity: [...seen] };
return { changes, seenActivity: [...seen], activityUpdatedAt };
}
export type ChangeRequestWatches = ReturnType<typeof createChangeRequestWatches>;
@@ -270,6 +292,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
void ready.catch(() => undefined);
const release = source.observe(url, {
knownActivity: () => new Set(groups.get(url)?.seenActivity),
knownActivityRevisions: () => groups.get(url)?.activityUpdatedAt,
snapshot: (snapshot) =>
serialize(async () => {
if (closed || observations.get(url) !== observation) return;
@@ -279,7 +302,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
resolve(snapshot);
return;
}
const { changes, seenActivity } = describeUpdate(group, snapshot);
const { changes, seenActivity, activityUpdatedAt } = describeUpdate(group, snapshot);
const { activity: _activity, ...status } = snapshot;
if (!changes.length) {
if (JSON.stringify(status) !== JSON.stringify(group.snapshot)) {
@@ -294,6 +317,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
...group,
snapshot: status,
seenActivity,
activityUpdatedAt,
watchers: status.state === "open" ? group.watchers : [],
});
if (!closed) recordChanges(url, group.watchers, changes, observedAt);
@@ -395,6 +419,13 @@ export function createChangeRequestWatches(deps: Dependencies) {
url,
snapshot,
seenActivity: group?.seenActivity ?? activity.map(({ id }) => id),
activityUpdatedAt:
group?.activityUpdatedAt ??
Object.fromEntries(
activity
.filter((item) => item.updatedAt !== undefined)
.map((item) => [item.id, item.updatedAt!]),
),
watchers: [
...(group?.watchers ?? []),
{ agentId, startedAt: new Date().toISOString() },
@@ -396,6 +396,94 @@ test("keeps a durable baseline across restart and drops undelivered digests", as
}
});
test("wakes the owner once for an edited summary and preserves revisions across restart", async () => {
vi.useFakeTimers();
const home = await createTestHome();
let h = createHarness(home);
const comment = {
id: "summary",
kind: "comment" as const,
url: `${url}#issuecomment-1`,
updatedAt: "2026-11-27T10:00:00Z",
};
try {
await h.watches.start();
await h.watches.subscribe("owner", url);
await h.observations.get(url)!.snapshot({ ...initial, activity: [comment] });
await vi.advanceTimersByTimeAsync(32_000);
h.turns.length = 0;
h.busy.add("owner");
const edited = { ...comment, updatedAt: "2026-11-27T11:00:00Z" };
await h.observations.get(url)!.snapshot({ ...initial, activity: [edited] });
await h.observations.get(url)!.snapshot({ ...initial, activity: [edited] });
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toEqual([]);
h.idle("owner");
await vi.advanceTimersByTimeAsync(2_000);
expect(h.turns).toHaveLength(1);
expect(h.turns[0]).toMatchObject({ recipientId: "owner" });
expect(h.turns[0]!.prompt).toContain(`Updated comment: ${comment.url}`);
expect(h.turns[0]!.prompt.match(/Updated comment:/g)).toHaveLength(1);
await h.close();
h = createHarness(home);
await h.watches.start();
await h.observations.get(url)!.snapshot({ ...initial, activity: [edited] });
await h.observations.get(url)!.snapshot({ ...initial, activity: [comment] });
await h.observations.get(url)!.snapshot({ ...initial, activity: [edited] });
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toEqual([]);
await h.observations.get(url)!.snapshot({
...initial,
activity: [{ ...edited, updatedAt: "2026-11-27T12:00:00Z" }],
});
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toHaveLength(1);
expect(h.turns[0]!.prompt).toContain(`Updated comment: ${comment.url}`);
} finally {
await h.close();
await rm(home, { recursive: true, force: true });
}
});
test("reconciles legacy ID-only baselines once without replaying every old comment", async () => {
vi.useFakeTimers();
const home = await createTestHome();
const { activity: _activity, ...snapshot } = initial;
await writeFile(
join(home, "change-request-watches.json"),
JSON.stringify([
{
url,
snapshot,
seenActivity: ["first", "second"],
watchers: [{ agentId: "owner" }],
},
]),
);
const h = createHarness(home);
const activity = ["first", "second"].map((id) => ({
id,
kind: "comment" as const,
url: `${url}#issuecomment-${id}`,
updatedAt: "2026-11-27T10:00:00Z",
}));
try {
await h.watches.start();
await h.observations.get(url)!.snapshot({ ...initial, activity });
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toHaveLength(1);
expect(h.turns[0]!.prompt).toContain("recheck current status");
expect(h.turns[0]!.prompt).not.toContain("#issuecomment-");
await h.observations.get(url)!.snapshot({ ...initial, activity });
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toHaveLength(1);
} finally {
await h.close();
await rm(home, { recursive: true, force: true });
}
});
test("recovers active watches even when pruning archived watchers cannot be written", async () => {
const home = await createTestHome();
const file = join(home, "change-request-watches.json");
@@ -19,6 +19,7 @@ const changeRequestSnapshotSchema = changeRequestStatusSchema.extend({
id: z.string(),
kind: z.enum(["comment", "inline comment", "review", "approval"]),
url: z.string(),
updatedAt: z.string().optional(),
message: z.string().optional(),
}),
),
@@ -38,6 +39,7 @@ export interface ChangeRequestSource {
error(error: unknown): void;
/** Activity the daemon has committed to its baseline. */
knownActivity?(): ReadonlySet<string>;
knownActivityRevisions?(): Readonly<Record<string, string>> | undefined;
},
): () => void;
}
@@ -100,9 +100,16 @@ function checkState(status: string | null): ChangeRequestSnapshot["checksState"]
return "neutral";
}
const activitySchema = z.object({ id: z.string(), url: z.string().url() });
const reviewSchema = activitySchema.extend({ submittedAt: z.string().nullable() });
const inlineSchema = activitySchema.extend({ publishedAt: z.string().nullable() });
const activitySchema = z.object({
id: z.string(),
url: z.string().url(),
updatedAt: z.string().optional(),
});
const editableActivitySchema = activitySchema.omit({ updatedAt: true }).extend({
lastEditedAt: z.string().nullable(),
});
const reviewSchema = editableActivitySchema.extend({ submittedAt: z.string().nullable() });
const inlineSchema = editableActivitySchema.extend({ publishedAt: z.string().nullable() });
const prStates = { OPEN: "open", CLOSED: "closed", MERGED: "merged" } as const;
const prSchema = z.object({
state: z.enum(["OPEN", "CLOSED", "MERGED"]),
@@ -122,9 +129,9 @@ function connection(name: string, fields: string, cursor?: string, size = PAGE_S
}
function conversation(cursor?: string) {
return `comments(last: ${PAGE_SIZE}${cursor ? `, before: ${JSON.stringify(cursor)}` : ""}) {
return `comments(last: ${PAGE_SIZE}, orderBy: { field: UPDATED_AT, direction: ASC }${cursor ? `, before: ${JSON.stringify(cursor)}` : ""}) {
pageInfo { hasNextPage: hasPreviousPage endCursor: startCursor }
nodes { id url }
nodes { id url updatedAt }
}`;
}
@@ -155,21 +162,21 @@ interface ReadOptions {
batchSize: number;
firstBatchSize: number;
onChecks(url: string, headSha: string, contexts: unknown[]): void;
knownActivity(url: string): ReadonlySet<string> | undefined;
isObserved(url: string): boolean;
knownActivityRevisions(url: string): Readonly<Record<string, string>> | undefined;
}
const pullRequestResult = z
.object({ pullRequest: z.unknown() })
.transform((result) => result.pullRequest);
const threadResult = z.object({ comments: pageSchema });
const reviewFields = "id url submittedAt";
const inlineFields = "id url publishedAt";
const reviewFields = "id url submittedAt lastEditedAt";
const inlineFields = "id url publishedAt lastEditedAt";
const threadFields = `id ${connection("comments", inlineFields, undefined, 10)}`;
export async function readGitHubChangeRequests(
urls: string[],
{ read, batchSize, firstBatchSize, onChecks, knownActivity, isObserved }: ReadOptions,
{ read, batchSize, firstBatchSize, onChecks, isObserved, knownActivityRevisions }: ReadOptions,
): Promise<Map<string, ChangeRequestSnapshot | Error>> {
const snapshots = new Map<string, ChangeRequestSnapshot>();
const failed = new Map<string, Error>();
@@ -264,26 +271,38 @@ export async function readGitHubChangeRequests(
},
);
}
const seen = knownActivity(url);
const revisions = knownActivityRevisions(url);
let committedUpdate: string | undefined;
schedulePages(
url,
pr.comments,
(nodes) => {
const comments = z.array(activitySchema).parse(nodes);
for (const item of comments) {
if (!seen?.has(item.id)) snapshot.activity.push({ ...item, kind: "comment" });
snapshot.activity.push({ ...item, kind: "comment" });
}
// Walk from newest to oldest. Finish reading all comments that
// share the committed timestamp, even if they span pages.
for (const { id, updatedAt } of comments.toReversed()) {
if (updatedAt === undefined) continue;
if (committedUpdate === undefined && revisions?.[id] === updatedAt) {
committedUpdate = updatedAt;
}
if (committedUpdate !== undefined && updatedAt < committedUpdate) return false;
}
// Walk recent comments first and stop when reaching the committed baseline.
return !comments.some(({ id }) => seen?.has(id));
},
(cursor) => pullRequest(url, conversation(cursor)),
(value) =>
z.object({ comments: pageSchema }).parse(pullRequestResult.parse(value)).comments,
);
schedulePullRequestPages(url, "reviews", reviewFields, pr.reviews, (nodes) => {
for (const item of z.array(reviewSchema).parse(nodes)) {
if (item.submittedAt)
snapshot.activity.push({ id: item.id, url: item.url, kind: "review" });
for (const { submittedAt, lastEditedAt, ...item } of z.array(reviewSchema).parse(nodes)) {
if (submittedAt)
snapshot.activity.push({
...item,
updatedAt: lastEditedAt ?? submittedAt,
kind: "review",
});
}
});
schedulePullRequestPages(
@@ -302,11 +321,13 @@ export async function readGitHubChangeRequests(
url,
comments,
(inlineNodes) => {
for (const item of z.array(inlineSchema).parse(inlineNodes)) {
if (item.publishedAt)
for (const { publishedAt, lastEditedAt, ...item } of z
.array(inlineSchema)
.parse(inlineNodes)) {
if (publishedAt)
snapshot.activity.push({
id: item.id,
url: item.url,
...item,
updatedAt: lastEditedAt ?? publishedAt,
kind: "inline comment",
});
}
@@ -5190,6 +5190,211 @@ describe("exact GitHub pull request observations", () => {
vi.useRealTimers();
}
});
it("reads edits in update order and stops paging after the committed revision", async () => {
vi.useFakeTimers();
const empty = { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } };
const url = "https://github.com/owner/repo/pull/42";
const edited = { id: "edited", url, updatedAt: "2026-11-27T12:00:00Z" };
const known = { id: "known", url, updatedAt: "2026-11-27T11:00:00Z" };
const older = { id: "older", url, updatedAt: "2026-11-27T10:00:00Z" };
const rateLimit = {
limit: 5000,
remaining: 4900,
resetAt: new Date(Date.now() + 100_000).toISOString(),
};
const runner = createRunner([
JSON.stringify({
data: {
rateLimit,
request0: {
pullRequest: {
state: "OPEN",
headRefOid: "abc",
reviewDecision: null,
statusCheckRollup: null,
comments: {
nodes: [older, known, edited],
pageInfo: { hasNextPage: true, endCursor: "older-comments" },
},
reviews: empty,
reviewThreads: empty,
},
},
},
}),
]);
const service = createGitHubService({ runner: runner.runner, resolveGhPath: async () => "gh" });
const received: unknown[] = [];
const errors: unknown[] = [];
try {
service.changeRequests.observe(url, {
knownActivityRevisions: () => ({
edited: "2026-11-27T09:00:00Z",
known: known.updatedAt,
older: older.updatedAt,
}),
async snapshot(snapshot) {
received.push(snapshot);
},
error(error) {
errors.push(error);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(errors).toEqual([]);
expect(received[0]).toMatchObject({
activity: expect.arrayContaining([{ ...edited, kind: "comment" }]),
});
expect(runner.calls).toHaveLength(1);
expect(runner.calls[0]?.args.at(-1)).toContain(
"orderBy: { field: UPDATED_AT, direction: ASC }",
);
} finally {
service.dispose?.();
vi.useRealTimers();
}
});
it("observes revisions of known comments on older pages and edited review activity", async () => {
vi.useFakeTimers();
const empty = { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } };
const address = "https://github.com/owner/repo/pull/42";
const recent = {
id: "recent",
url: `${address}#issuecomment-2`,
updatedAt: "2026-11-27T10:00:00Z",
};
const old = { id: "old", url: `${address}#issuecomment-1` };
const rateLimit = {
limit: 5000,
remaining: 4900,
resetAt: new Date(Date.now() + 100_000).toISOString(),
};
const responses: string[] = [];
const submittedAt = "2026-11-27T09:00:00Z";
for (const [updatedAt, lastEditedAt] of [
[submittedAt, null],
["2026-11-27T09:00:01Z", null],
["2026-11-27T11:00:00Z", "2026-11-27T11:00:00Z"],
]) {
responses.push(
JSON.stringify({
data: {
rateLimit,
request0: {
pullRequest: {
state: "OPEN",
headRefOid: "abc",
reviewDecision: null,
statusCheckRollup: null,
comments: {
nodes: [recent],
pageInfo: { hasNextPage: true, endCursor: "older-comments" },
},
reviews: {
...empty,
nodes: [
{
id: "review",
url: `${address}#pullrequestreview-1`,
submittedAt,
updatedAt,
lastEditedAt,
},
],
},
reviewThreads: {
...empty,
nodes: [
{
id: "thread",
comments: {
...empty,
nodes: [
{
id: "inline",
url: `${address}#discussion_r1`,
publishedAt: submittedAt,
updatedAt,
lastEditedAt,
},
],
},
},
],
},
},
},
},
}),
JSON.stringify({
data: {
rateLimit,
request0: { pullRequest: { comments: { ...empty, nodes: [{ ...old, updatedAt }] } } },
},
}),
);
}
const runner = createRunner(responses);
const service = createGitHubService({ runner: runner.runner, resolveGhPath: async () => "gh" });
const received: Array<{ activity: Array<{ id: string; updatedAt?: string }> }> = [];
const errors: unknown[] = [];
try {
service.changeRequests.observe(address, {
knownActivity: () => new Set(["recent", "old", "review", "inline"]),
async snapshot(snapshot) {
received.push(snapshot);
},
error(error) {
errors.push(error);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(received[0]?.activity).toContainEqual({
...old,
updatedAt: "2026-11-27T09:00:00Z",
kind: "comment",
});
await vi.advanceTimersByTimeAsync(20_000);
expect(errors).toEqual([]);
expect(received[1]?.activity).toEqual(
expect.arrayContaining([
{
id: "review",
url: `${address}#pullrequestreview-1`,
updatedAt: submittedAt,
kind: "review",
},
{
id: "inline",
url: `${address}#discussion_r1`,
updatedAt: submittedAt,
kind: "inline comment",
},
]),
);
await vi.advanceTimersByTimeAsync(20_000);
expect(received[2]?.activity).toEqual(
expect.arrayContaining([
{ ...old, updatedAt: "2026-11-27T11:00:00Z", kind: "comment" },
{
id: "review",
url: `${address}#pullrequestreview-1`,
updatedAt: "2026-11-27T11:00:00Z",
kind: "review",
},
{
id: "inline",
url: `${address}#discussion_r1`,
updatedAt: "2026-11-27T11:00:00Z",
kind: "inline comment",
},
]),
);
} finally {
service.dispose?.();
vi.useRealTimers();
}
});
});
it("batches co-due workspace discovery and exact PR reads with one check rollup", async () => {
@@ -1739,8 +1739,8 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
return data;
},
batchSize: GITHUB_POLL_BATCH_MAX,
knownActivityRevisions: (url) => watching.get(url)?.callbacks.knownActivityRevisions?.(),
onChecks: (url, headSha, contexts) => checks.get(url)!({ headSha, contexts }),
knownActivity: (url) => watching.get(url)?.callbacks.knownActivity?.(),
firstBatchSize,
isObserved,
});