Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion pm-stack/projector/src/projector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,27 @@ function itemRef(repo: string, number: number): string {
return `${repo}#${number}`;
}

/** A list-page element is a plain object (not null, not an array). */
function isPlainObject(obj: unknown): obj is Record<string, any> {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
}

/** A list-page element is projectable as an issue/PR only when it is a
* plain object carrying a safe-integer `number` (#7009): anything else
* either crashed the projection with a raw TypeError (null, string,
* number elements) or upserted a phantom `repo#undefined` row (array,
* missing/non-integer number). */
function isProjectableItem(obj: unknown): obj is Record<string, any> {
return isPlainObject(obj) && Number.isSafeInteger((obj as Record<string, unknown>).number);
}

function fromIssueOrPr(repo: string, obj: Record<string, any>, kind: "issue" | "pr"): Omit<ItemRow, "fetched_at"> {
if (!isProjectableItem(obj)) {
// Named module-vocabulary refusal, never a raw TypeError and never
// a phantom row (#7009). Reconcile validates before calling and
// skips-with-count instead of reaching this.
throw new Error("projector: refusing to project an element without a safe-integer number");
}
const number = obj.number as number;
const createdAt = iso(obj.created_at) ?? iso(obj.updated_at) ?? new Date().toISOString();
const updatedAt = iso(obj.updated_at) ?? createdAt;
Expand Down Expand Up @@ -152,7 +172,7 @@ function issueIsPr(issue: Record<string, any>): boolean {
return Boolean(issue?.pull_request) || Boolean(issue?.html_url?.includes("/pull/"));
}

export { fromIssueOrPr, issueIsPr, itemRef };
export { fromIssueOrPr, isPlainObject, isProjectableItem, issueIsPr, itemRef };

/**
* Apply a single GitHub webhook event to the store. Returns the item refs
Expand Down
35 changes: 30 additions & 5 deletions pm-stack/projector/src/reconcile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// an upsert keyed by a repo-qualified ID, and a monotonic guard prevents stale
// overwrites. Cursors (repo, stream) make each poll incremental.
import type { Client } from "@libsql/client";
import { fromIssueOrPr } from "./projector";
import { fromIssueOrPr, isPlainObject, isProjectableItem } from "./projector";
import * as store from "./store";
import { apiTokenFor, listResource, type GitHubAuth } from "./github";

Expand All @@ -30,6 +30,7 @@ async function reconcileStream(
repo: string;
stream: Stream;
written: number;
skipped?: number;
cursor: string | null;
error?: string;
errors?: { pr: number; error: string }[];
Expand Down Expand Up @@ -61,29 +62,39 @@ async function reconcileStream(
fetchFn,
);
let cursor: string | null = null;
let skipped = 0;
for (const pr of pulls) {
if (!isProjectableItem(pr)) {
skipped++;
continue;
}
const row = fromIssueOrPr(repo, pr, "pr");
await store.upsertItem(db, row);
await mark(1);
const u = pr.updated_at ?? pr.created_at;
if (typeof u === "string" && (!cursor || u > cursor)) cursor = u;
}
return { repo, stream, written: written.n, cursor };
return { repo, stream, written: written.n, ...(skipped > 0 ? { skipped } : {}), cursor };
}

if (stream === "issues") {
const path = `repos/${repo}/issues?${q}&filter=all`;
const rows = await listResource<Record<string, any>>(auth, path, fetchFn);
let cursor: string | null = null;
let skipped = 0;
for (const obj of rows) {
if (!isProjectableItem(obj)) {
skipped++;
continue;
}
if (Boolean(obj.pull_request)) continue;
const row = fromIssueOrPr(repo, obj, "issue");
await store.upsertItem(db, row);
await mark(1);
const u = obj.updated_at ?? obj.created_at;
if (typeof u === "string" && (!cursor || u > cursor)) cursor = u;
}
return { repo, stream, written: written.n, cursor };
return { repo, stream, written: written.n, ...(skipped > 0 ? { skipped } : {}), cursor };
}

if (stream === "issue_comments" || stream === "review_comments") {
Expand All @@ -94,7 +105,12 @@ async function reconcileStream(
const collection = stream === "issue_comments" ? "issues/comments" : "pulls/comments";
const rows = await listResource<Record<string, any>>(auth, `repos/${repo}/${collection}?per_page=100`, fetchFn);
let cursor: string | null = null;
let skipped = 0;
for (const c of rows) {
if (!isPlainObject(c)) {
skipped++;
continue;
}
// The API comment objects carry the containing issue/PR only via URL;
// derive the repo-qualified ref from it.
const ref = commentRef(repo, c);
Expand Down Expand Up @@ -123,7 +139,7 @@ async function reconcileStream(
const u = c.updated_at ?? c.created_at;
if (typeof u === "string" && (!cursor || u > cursor)) cursor = u;
}
return { repo, stream, written: written.n, cursor };
return { repo, stream, written: written.n, ...(skipped > 0 ? { skipped } : {}), cursor };
}

if (stream === "reviews") {
Expand All @@ -136,15 +152,24 @@ async function reconcileStream(
// unfiltered each time, so no PR is skipped permanently.
const prs = await listResource<Record<string, any>>(auth, `repos/${repo}/pulls?per_page=100&state=all`, fetchFn);
let cursor: string | null = null;
let skipped = 0;
const errors: { pr: number; error: string }[] = [];
for (const pr of prs) {
if (!isProjectableItem(pr)) {
skipped++;
continue;
}
try {
const reviews = await listResource<Record<string, any>>(
auth,
`repos/${repo}/pulls/${pr.number}/reviews?per_page=100`,
fetchFn,
);
for (const r of reviews) {
if (!isPlainObject(r)) {
skipped++;
continue;
}
const ref = `${repo}#${pr.number}`;
const createdAt = r.submitted_at ?? r.created_at ?? null;
if (!createdAt) continue;
Expand Down Expand Up @@ -174,7 +199,7 @@ async function reconcileStream(
errors.push({ pr: pr.number, error: String((e as Error).message) });
}
}
return { repo, stream, written: written.n, cursor, ...(errors.length > 0 ? { errors } : {}) };
return { repo, stream, written: written.n, ...(skipped > 0 ? { skipped } : {}), cursor, ...(errors.length > 0 ? { errors } : {}) };
}

return { repo, stream, written: 0, cursor: null };
Expand Down
96 changes: 96 additions & 0 deletions pm-stack/projector/test/reconcile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,99 @@ describe("reconcileRepos reviews stream per-PR guard (#2745)", () => {
expect(await getSyncCursor(db, repo, "reviews")).toBe("2026-10-06T00:00:00Z");
});
});

describe("wrong-shape list elements (#7009)", () => {
test("fromIssueOrPr refuses non-object / bad-number elements with a named error, never a raw TypeError or phantom row", () => {
for (const bad of [null, "str", 42, [], {}, { number: 1.5 }, { number: "7" }, { number: undefined }]) {
let err: unknown = null;
try {
fromIssueOrPr("o/r", bad as never, "issue");
} catch (e) {
err = e;
}
expect(err).toBeInstanceOf(Error);
expect(err).not.toBeInstanceOf(TypeError);
expect((err as Error).message).toContain("refusing to project");
}
});

test("reconcile skips bad elements with a count, stores the good ones, and still advances cursors", async () => {
const repo = "developing-today/bad-elements";
const item = (n: number, at: string) => ({
number: n,
html_url: `https://github.com/${repo}/issues/${n}`,
url: `https://api.github.com/repos/${repo}/issues/${n}`,
title: `item ${n}`,
state: "open",
user: { login: "drew" },
labels: [],
assignees: [],
created_at: "2026-10-01T00:00:00Z",
updated_at: at,
});
const fetchFn = (async (url: string) => {
if (url.includes("/issues/comments")) {
return jsonRes([
null,
"junk",
{
id: 7001,
html_url: `https://github.com/${repo}/issues/1#issuecomment-7001`,
body: "good comment",
user: { login: "drew" },
created_at: "2026-10-03T00:00:00Z",
updated_at: "2026-10-04T00:00:00Z",
},
]);
}
if (url.includes("/pulls/comments")) return jsonRes([42]);
if (url.includes("/pulls/1/reviews")) {
return jsonRes([
null,
{ id: 701, body: "ok review", user: { login: "drew" }, state: "APPROVED", submitted_at: "2026-10-05T00:00:00Z" },
]);
}
if (url.includes("/pulls?")) {
return jsonRes([item(1, "2026-10-02T00:00:00Z"), null, { title: "no number" }, []]);
}
if (url.includes("/issues?")) {
return jsonRes([item(1, "2026-10-02T00:00:00Z"), "junk", item(2, "2026-10-06T00:00:00Z"), { number: 2.5 }]);
}
return jsonRes([]);
}) as unknown as typeof fetch;

const result = await reconcileRepos(db, { PM_REPOS: repo, GITHUB_TOKEN: "test-token" }, fetchFn);
expect(result.ok).toBe(true);
const streams = result.streams as Record<string, any>[];
const byStream = (name: string) => streams.find((s) => s.stream === name)!;

const issues = byStream("issues");
expect(issues.error).toBeUndefined();
expect(issues.written).toBe(2);
expect(issues.skipped).toBe(2);
expect(issues.cursor).toBe("2026-10-06T00:00:00Z");
expect((await getItems(db, [`${repo}#1`, `${repo}#2`])).length).toBe(2);
expect((await getItems(db, [`${repo}#undefined`])).length).toBe(0);

const prs = byStream("prs");
expect(prs.error).toBeUndefined();
expect(prs.written).toBe(1);
expect(prs.skipped).toBe(3);

const issueComments = byStream("issue_comments");
expect(issueComments.error).toBeUndefined();
expect(issueComments.written).toBe(1);
expect(issueComments.skipped).toBe(2);
expect((await getComments(db, [`${repo}#1`])).map((c) => c.id)).toContain("7001");

const reviewComments = byStream("review_comments");
expect(reviewComments.error).toBeUndefined();
expect(reviewComments.skipped).toBe(1);

const reviews = byStream("reviews");
expect(reviews.error).toBeUndefined();
expect(reviews.written).toBe(1);
expect(reviews.skipped).toBe(4);
expect((await getComments(db, [`${repo}#1`])).map((c) => c.id).sort()).toEqual(["7001", "701"]);
});
});
Loading