From 34cd4d6c163c36baab1623c3c0fc2d2e623b27a5 Mon Sep 17 00:00:00 2001 From: Tom Kaczocha Date: Fri, 16 Oct 2026 07:26:07 +1000 Subject: [PATCH 1/5] test(factory): port softfac's approval, text check and blocker tests Issue: #13 Red: domain/approval.ts and the new github.ts exports do not exist yet. --- .../src/factory/domain/approval.test.ts | 75 + .../server/src/factory/tracker/github.test.ts | 1581 +++++++++++++++++ 2 files changed, 1656 insertions(+) create mode 100644 apps/server/src/factory/domain/approval.test.ts diff --git a/apps/server/src/factory/domain/approval.test.ts b/apps/server/src/factory/domain/approval.test.ts new file mode 100644 index 0000000000000..e0f94d69144bc --- /dev/null +++ b/apps/server/src/factory/domain/approval.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { refusalReason, unapprovedComment, type Refusal } from "./approval.ts"; + +const AT = "2026-10-04T10:00:00Z"; + +const NOT_BY_INSTRUCTOR = "factory:ready was not applied by an instructor"; +const EDITED_AFTER = + "the issue text was edited after factory:ready was applied by someone who is not an instructor"; +const CANNOT_READ_LABEL = "the factory could not read who applied factory:ready"; +const CANNOT_READ_HISTORY = "the factory could not read the full edit history of the issue text"; + +const OPENING = + "The factory did not start on this issue and has moved it back to `factory:proposed`."; +const REVIEW_AND_RELABEL = + "Review the issue text, then apply `factory:ready` again. An instructor must apply the label, and the text must not be edited afterwards by anyone who is not an instructor."; +const FILE_A_NEW_ISSUE = + "The issue's edit history is too long for the factory to check. File a new issue with the final text and apply `factory:ready` to it."; + +const cases: ReadonlyArray = [ + [{ kind: "label-not-found" }, CANNOT_READ_LABEL, REVIEW_AND_RELABEL], + [{ kind: "label-history-incomplete" }, CANNOT_READ_LABEL, REVIEW_AND_RELABEL], + [ + { kind: "labeled-by-non-instructor", by: "mallory", labeledAt: AT }, + NOT_BY_INSTRUCTOR, + REVIEW_AND_RELABEL, + ], + [ + { kind: "labeled-by-non-instructor", by: null, labeledAt: AT }, + NOT_BY_INSTRUCTOR, + REVIEW_AND_RELABEL, + ], + [{ kind: "edited-after-label", labeledAt: AT }, EDITED_AFTER, REVIEW_AND_RELABEL], + [{ kind: "edit-history-incomplete", labeledAt: AT }, CANNOT_READ_HISTORY, FILE_A_NEW_ISSUE], +]; + +describe("refusalReason", () => { + it.each(cases)("%j has softfac's fixed reason", (refusal, reason) => { + expect(refusalReason(refusal)).toBe(reason); + }); + + it("gives the unreadable label history and the missing label one reason", () => { + expect(refusalReason({ kind: "label-not-found" })).toBe( + refusalReason({ kind: "label-history-incomplete" }), + ); + }); +}); + +describe("unapprovedComment", () => { + it.each(cases)("%j is the factory's fixed text", (refusal, reason, whatToDo) => { + expect(unapprovedComment(refusal)).toBe(`${OPENING}\n\nReason: ${reason}\n\n${whatToDo}`); + }); + + it("is softfac's literal comment for an edit after the label", () => { + expect(unapprovedComment({ kind: "edited-after-label", labeledAt: AT })).toBe( + "The factory did not start on this issue and has moved it back to `factory:proposed`.\n\nReason: the issue text was edited after factory:ready was applied by someone who is not an instructor\n\nReview the issue text, then apply `factory:ready` again. An instructor must apply the label, and the text must not be edited afterwards by anyone who is not an instructor.", + ); + }); + + it("is softfac's literal comment for a history that is too long", () => { + expect(unapprovedComment({ kind: "edit-history-incomplete", labeledAt: AT })).toBe( + "The factory did not start on this issue and has moved it back to `factory:proposed`.\n\nReason: the factory could not read the full edit history of the issue text\n\nThe issue's edit history is too long for the factory to check. File a new issue with the final text and apply `factory:ready` to it.", + ); + }); + + it("quotes nothing from the issue or the login", () => { + const text = unapprovedComment({ + kind: "labeled-by-non-instructor", + by: "mallory", + labeledAt: AT, + }); + expect(text).not.toContain("mallory"); + expect(text).not.toContain(AT); + }); +}); diff --git a/apps/server/src/factory/tracker/github.test.ts b/apps/server/src/factory/tracker/github.test.ts index cfc845dcf6c5e..d543b6f975c55 100644 --- a/apps/server/src/factory/tracker/github.test.ts +++ b/apps/server/src/factory/tracker/github.test.ts @@ -3,8 +3,10 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { PROJECT_CONFIG_PATH } from "../config.ts"; +import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; import { FactoryProcess, type RunInput, type RunResult, RunSpawnError } from "../process.ts"; import { + APPROVAL_QUERY, GitHubFailed, GitHubInvalidArgument, GitHubOutputTooLarge, @@ -16,8 +18,12 @@ import { MARKER, MAX_FILE_BYTES, STATUS_MARKER, + type Blocker, type GitHubError, + type IssueRef, + dependsOn, isNotFound, + isUtcSecond, makeGitHub, } from "./github.ts"; @@ -2004,3 +2010,1578 @@ it.effect("checks that gh cannot read is the gh failure", () => assert.strictEqual(error._tag, "GitHubFailed"); }), ); + +// ---- blockers: ported from softfac's github.rs ---- + +const blockedByCall = (issue: string) => [ + "api", + `repos/rawphp/softfac/issues/${issue}/dependencies/blocked_by`, + "--paginate", +]; +const blockerRow = (number: number, state: string, repo: string) => + `{"id":${number},"number":${number},"state":"${state}","title":"t","repository_url":"https://api.github.com/repos/${repo}","labels":[]}`; +const openBlocker = (number: number, repo: string): Blocker => ({ repo, number }); + +it.effect("an issue with no blockers has no open blockers", () => + Effect.gen(function* () { + const t = setup(reply("[]")); + assert.deepStrictEqual(yield* t.ok(t.github.openBlockers(14)), []); + assert.deepStrictEqual(t.calls(), [blockedByCall("14")]); + }), +); + +it.effect("a closed blocker is resolved whatever closed it", () => + Effect.gen(function* () { + const t = setup( + reply( + `[${blockerRow(13, "closed", "rawphp/softfac")},${blockerRow(12, "closed", "rawphp/other")}]`, + ), + ); + assert.deepStrictEqual(yield* t.ok(t.github.openBlockers(14)), []); + }), +); + +it.effect("open blockers keep the repo they are in", () => + Effect.gen(function* () { + const t = setup( + reply( + `[${blockerRow(13, "open", "rawphp/softfac")},${blockerRow(12, "closed", "rawphp/softfac")},${blockerRow(7, "open", "acme/widgets")}]`, + ), + ); + assert.deepStrictEqual(yield* t.ok(t.github.openBlockers(14)), [ + openBlocker(13, "rawphp/softfac"), + openBlocker(7, "acme/widgets"), + ]); + }), +); + +it.effect("blockers on every page are read", () => + Effect.gen(function* () { + // `gh api --paginate` may print each page as its own array. + const t = setup( + reply( + `[${blockerRow(1, "closed", "rawphp/softfac")}][${blockerRow(2, "open", "rawphp/softfac")}]`, + ), + ); + assert.deepStrictEqual(yield* t.ok(t.github.openBlockers(14)), [ + openBlocker(2, "rawphp/softfac"), + ]); + }), +); + +it.effect("blockers that cannot be read are an error", () => + Effect.gen(function* () { + const spawn = setup(spawnError()); + assert.strictEqual((yield* spawn.err(spawn.github.openBlockers(14)))._tag, "GitHubSpawnError"); + + const failed = setup(fail(1, "Not Found")); + assert.strictEqual((yield* failed.err(failed.github.openBlockers(14)))._tag, "GitHubFailed"); + + for (const stdout of ["oops", "", '{"message":"x"}']) { + const t = setup(reply(stdout)); + const error = yield* t.err(t.github.openBlockers(14)); + assert.strictEqual(error._tag, "GitHubParse", stdout); + } + }), +); + +it.effect("an open blocker whose repo is unknown is an error, not a guess", () => + Effect.gen(function* () { + for (const row of [ + '{"number":3,"state":"open"}', + '{"number":3,"state":"open","repository_url":"x"}', + ]) { + const t = setup(reply(`[${row}]`)); + const error = yield* t.err(t.github.openBlockers(14)); + assert.strictEqual(error._tag, "GitHubParse", row); + } + }), +); + +// ---- the Depends on section ---- + +const same = (number: number): IssueRef => ({ repo: null, number }); +const cross = (repo: string, number: number): IssueRef => ({ repo, number }); + +it("depends on reads same repo references", () => { + const body = "Intro\n\n## Depends on\n\n- #13\n- #15 until it lands\n"; + assert.deepStrictEqual(dependsOn(body), [same(13), same(15)]); +}); + +it("depends on reads cross repo references", () => { + const body = "## Depends on\nacme/widgets#7, my-org/some.repo_x#42\n"; + assert.deepStrictEqual(dependsOn(body), [ + cross("acme/widgets", 7), + cross("my-org/some.repo_x", 42), + ]); +}); + +it("depends on reads both kinds in order and once", () => { + const body = "## Depends on\n#3 and acme/widgets#7 and #3 again, #9\n"; + assert.deepStrictEqual(dependsOn(body), [same(3), cross("acme/widgets", 7), same(9)]); +}); + +it("depends on does not count the number of a cross repo reference twice", () => { + assert.deepStrictEqual(dependsOn("## Depends on\nacme/widgets#7\n"), [cross("acme/widgets", 7)]); +}); + +it("depends on none or empty or missing names nothing", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n\nNone\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\nnone.\n## Next\n#4\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\n\n## Fix\n#4\n"), []); + assert.deepStrictEqual(dependsOn("## Cause\nSee #4\n"), []); + assert.deepStrictEqual(dependsOn(""), []); +}); + +it("depends on ignores text after the next heading", () => { + const body = "## Depends on\n#13\n### Notes\n#99\n## Fix\nacme/widgets#98\n"; + assert.deepStrictEqual(dependsOn(body), [same(13)]); +}); + +it("depends on ignores references before the section", () => { + assert.deepStrictEqual(dependsOn("## Cause\nSee #5\n\n## Depends on\n#13\n"), [same(13)]); +}); + +it("depends on heading is case insensitive and allows trailing spaces", () => { + assert.deepStrictEqual(dependsOn("## depends ON \r\n#13\r\n"), [same(13)]); +}); + +it("depends on needs digits after the hash", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n#abc # 4 #\n"), []); +}); + +it("depends on skips a hash that word characters run into", () => { + assert.deepStrictEqual(dependsOn("## Depends on\nsee page#12 and /widgets#7, then #3\n"), [ + same(3), + ]); +}); + +it("depends on ends at a heading line with nothing after the hashes", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n#3\n##\n#4\n"), [same(3)]); +}); + +it("depends on heading needs two hashes and a space", () => { + assert.deepStrictEqual(dependsOn("##Depends on\n#3\n"), []); + assert.deepStrictEqual(dependsOn("### Depends on\n#3\n"), []); + assert.deepStrictEqual(dependsOn("# Depends on\n#3\n"), []); +}); + +// ---- text blockers ---- + +const bodyCall = (issue: string) => ["issue", "view", issue, "--repo", REPO, "--json", "body"]; +const restCall = (repo: string, issue: string) => ["api", `repos/${repo}/issues/${issue}`]; +const bodyReply = (body: string) => JSON.stringify({ body }); + +it.effect("text blockers of a body without the section read nothing more", () => + Effect.gen(function* () { + const t = setup(reply(bodyReply("## Cause\nSee #5\n"))); + assert.deepStrictEqual(yield* t.ok(t.github.textBlockers(14)), []); + assert.deepStrictEqual(t.calls(), [bodyCall("14")]); + + const empty = setup(reply('{"body":null}')); + assert.deepStrictEqual(yield* empty.ok(empty.github.textBlockers(14)), []); + }), +); + +it.effect("text blockers are the named issues that are not closed", () => + Effect.gen(function* () { + const t = setup( + reply(bodyReply("## Depends on\n#13, acme/widgets#7 and #5\n\n## Fix\n#99\n")), + reply('{"number":13,"state":"open","title":"t"}'), + reply('{"number":7,"state":"closed"}'), + reply('{"number":5,"state":"open"}'), + ); + assert.deepStrictEqual(yield* t.ok(t.github.textBlockers(14)), [ + openBlocker(13, REPO), + openBlocker(5, REPO), + ]); + assert.deepStrictEqual(t.calls(), [ + bodyCall("14"), + restCall(REPO, "13"), + restCall("acme/widgets", "7"), + restCall(REPO, "5"), + ]); + }), +); + +it.effect("text blockers resolved once every named issue is closed", () => + Effect.gen(function* () { + const t = setup(reply(bodyReply("## Depends on\n#13\n")), reply('{"state":"closed"}')); + assert.deepStrictEqual(yield* t.ok(t.github.textBlockers(14)), []); + }), +); + +it.effect("a named issue that cannot be read is an error, not a resolved blocker", () => + Effect.gen(function* () { + const body = bodyReply("## Depends on\n#13, #5\n"); + const missing = setup( + reply(body), + reply('{"state":"closed"}'), + fail(1, "gh: Not Found (HTTP 404)"), + ); + assert.strictEqual((yield* missing.err(missing.github.textBlockers(14)))._tag, "GitHubFailed"); + + const oops = setup(reply(body), reply("oops")); + assert.strictEqual((yield* oops.err(oops.github.textBlockers(14)))._tag, "GitHubParse"); + + const empty = setup(reply(body), reply("{}")); + assert.strictEqual((yield* empty.err(empty.github.textBlockers(14)))._tag, "GitHubParse"); + }), +); + +it.effect("a body that cannot be read is an error", () => + Effect.gen(function* () { + const failed = setup(fail(1, "boom")); + assert.strictEqual((yield* failed.err(failed.github.textBlockers(14)))._tag, "GitHubFailed"); + const oops = setup(reply("oops")); + assert.strictEqual((yield* oops.err(oops.github.textBlockers(14)))._tag, "GitHubParse"); + }), +); + +// ---- approval: ported from softfac's github.rs ---- + +/** When the instructor applied `factory:ready` in most of the approval tests. */ +const LABELED = "2026-10-04T10:00:00Z"; +/** After LABELED, and before LATER. */ +const AFTER = "2026-10-04T10:30:00Z"; +const LATER = "2026-10-04T11:00:00Z"; +/** When the issue was written: the oldest entry of the edit history, by its author. */ +const CREATED = "2026-10-04T08:00:00Z"; + +type Who = string | null; +type Edit = readonly [at: string, who: Who]; +type TimelineNode = Record; + +const pad = (n: number) => String(n).padStart(2, "0"); + +const approvalCall = () => [ + "api", + "graphql", + "-f", + `query=${APPROVAL_QUERY}`, + "-f", + "owner=rawphp", + "-f", + "name=softfac", + "-F", + "number=6", +]; + +const actorOf = (who: Who) => (who === null ? null : { __typename: "User", login: who }); + +const labelEvent = (kind: string, at: string, actor: Who, label: string): TimelineNode => ({ + __typename: kind, + createdAt: at, + actor: actorOf(actor), + label: { name: label }, +}); +/** A RenamedTitleEvent: only who and when are asked for, never the titles. */ +const renameEvent = (at: string, actor: Who): TimelineNode => ({ + __typename: "RenamedTitleEvent", + createdAt: at, + actor: actorOf(actor), +}); +const readyOn = (at: string, actor: Who) => labelEvent("LabeledEvent", at, actor, "factory:ready"); +const readyOff = (at: string, actor: Who) => + labelEvent("UnlabeledEvent", at, actor, "factory:ready"); + +/** `userContentEdits` as GitHub answers `first: 100`: newest first, with the real total. */ +const editsJson = (newestFirst: ReadonlyArray, total: number) => ({ + totalCount: total, + nodes: newestFirst.map(([editedAt, who]) => ({ editedAt, editor: actorOf(who) })), +}); + +/** A history written oldest first, as the tests think of it, in GitHub's order. */ +const newestFirst = (oldestFirst: ReadonlyArray): Array => [...oldestFirst].reverse(); + +/** The approval answer with exactly these history nodes (newest first) and this total. */ +const approvalReplyRaw = ( + events: ReadonlyArray, + totalEvents: number, + last: Edit | null, + editNodes: ReadonlyArray, + totalEdits: number, +) => + JSON.stringify({ + data: { + repository: { + issue: { + timelineItems: { totalCount: totalEvents, nodes: events }, + lastEditedAt: last === null ? null : last[0], + editor: last === null ? null : actorOf(last[1]), + userContentEdits: editsJson(editNodes, totalEdits), + }, + }, + }, + }); + +/** `events` are oldest first, as GitHub lists them. `edits` is the history oldest first. */ +const approvalReply = ( + events: ReadonlyArray, + totalEvents: number, + last: Edit | null, + edits: ReadonlyArray, +) => approvalReplyRaw(events, totalEvents, last, newestFirst(edits), edits.length); + +/** The events as the tests think of them, with the real total. */ +const eventsReply = ( + events: ReadonlyArray, + last: Edit | null, + edits: ReadonlyArray, +) => approvalReply(events, events.length, last, edits); + +const creationOnly = (author: string): Array => [[CREATED, author]]; + +const approvalOf = (answer: string, who: ReadonlyArray) => + Effect.gen(function* () { + const t = setup(reply(answer)); + const found = yield* t.ok(t.github.approval(6, who)); + assert.deepStrictEqual(t.calls(), [approvalCall()]); + return found; + }); + +const approved = (labeledAt: string, labeledBy: string): Approval => ({ + kind: "approved", + labeledAt, + labeledBy, +}); +const refused = (refusal: Refusal): Approval => ({ kind: "refused", refusal }); +const editedAfter = (labeledAt: string): Refusal => ({ kind: "edited-after-label", labeledAt }); +const historyCut = (labeledAt: string): Refusal => ({ + kind: "edit-history-incomplete", + labeledAt, +}); +const byNonInstructor = (by: Who, labeledAt: string): Refusal => ({ + kind: "labeled-by-non-instructor", + by, + labeledAt, +}); +const NOT_FOUND: Refusal = { kind: "label-not-found" }; +const LABEL_CUT: Refusal = { kind: "label-history-incomplete" }; + +it.effect("approval reads the real shapes and sends one call", () => + Effect.gen(function* () { + const real = + '{"data":{"repository":{"issue":{"timelineItems":{"totalCount":3,"nodes":[{"__typename":"UnlabeledEvent","createdAt":"2026-10-04T11:36:21Z","actor":{"__typename":"User","login":"rawphp"},"label":{"name":"factory:building"}},{"__typename":"LabeledEvent","createdAt":"2026-10-04T11:36:21Z","actor":{"__typename":"User","login":"rawphp"},"label":{"name":"factory:ready"}},{"__typename":"RenamedTitleEvent","createdAt":"2026-10-04T11:48:55Z","actor":{"__typename":"User","login":"rawphp"}}]},"lastEditedAt":null,"editor":null,"userContentEdits":{"totalCount":1,"nodes":[{"editedAt":"2026-10-04T09:50:06Z","editor":{"__typename":"User","login":"outside-user"}}]}}}}}'; + assert.deepStrictEqual( + yield* approvalOf(real, ["rawphp"]), + approved("2026-10-04T11:36:21Z", "rawphp"), + ); + }), +); + +it("the approval query asks for label events and the edit history", () => { + for (const part of [ + "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100)", + "totalCount", + "... on LabeledEvent { createdAt actor { __typename login } label { name } }", + "... on UnlabeledEvent { createdAt actor { __typename login } label { name } }", + "... on RenamedTitleEvent { createdAt actor { __typename login } }", + "lastEditedAt", + "editor { __typename login }", + "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } }", + "$owner", + "$name", + "$number", + ]) { + assert.include(APPROVAL_QUERY, part); + } + assert.notInclude(APPROVAL_QUERY, "comments"); + // Titles are attacker-influenced text and are never asked for. + assert.notInclude(APPROVAL_QUERY, "Title {"); + assert.notInclude(APPROVAL_QUERY, "currentTitle"); + assert.notInclude(APPROVAL_QUERY, "previousTitle"); +}); + +it("the approval query is softfac's, byte for byte", () => { + assert.strictEqual( + APPROVAL_QUERY, + "query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { totalCount nodes { __typename ... on LabeledEvent { createdAt actor { __typename login } label { name } } ... on UnlabeledEvent { createdAt actor { __typename login } label { name } } ... on RenamedTitleEvent { createdAt actor { __typename login } } } } lastEditedAt editor { __typename login } userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }", + ); +}); + +it.effect("an outside author's unedited report labelled by an instructor is approved", () => + Effect.gen(function* () { + // The creation entry is by the author, before the label, and is ignored. + const answer = eventsReply([readyOn(LABELED, "tom")], null, creationOnly("outsider")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("an issue with no history at all is approved when an instructor labelled it", () => + Effect.gen(function* () { + const answer = eventsReply([readyOn(LABELED, "tom")], null, []); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("the instructor comparison ignores case", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "TomK")], + [AFTER, "TOMK"], + [ + [CREATED, "outsider"], + [AFTER, "TOMK"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tomk"]), approved(LABELED, "TomK")); + }), +); + +it.effect("other labels in the events are ignored", () => + Effect.gen(function* () { + const answer = eventsReply( + [ + labelEvent("LabeledEvent", "2026-10-04T09:00:00Z", "eve", "bug"), + readyOn(LABELED, "tom"), + labelEvent("UnlabeledEvent", AFTER, "eve", "bug"), + labelEvent("LabeledEvent", AFTER, "eve", "factory:readyish"), + ], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect( + "a label applied, removed and applied again by an instructor counts the later event", + () => + Effect.gen(function* () { + // A non-instructor applied it first and an instructor reviewed and re-applied it. + const answer = eventsReply( + [ + readyOn("2026-10-04T09:00:00Z", "eve"), + readyOff("2026-10-04T09:30:00Z", "tom"), + readyOn(LABELED, "tom"), + ], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("a label applied by an instructor then reapplied by a non-instructor is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [ + readyOn("2026-10-04T09:00:00Z", "tom"), + readyOff("2026-10-04T09:30:00Z", "tom"), + readyOn(LABELED, "eve"), + ], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor("eve", LABELED)), + ); + }), +); + +it.effect("a label applied by a non-instructor is refused", () => + Effect.gen(function* () { + const answer = eventsReply([readyOn(LABELED, "eve")], null, creationOnly("eve")); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor("eve", LABELED)), + ); + }), +); + +it.effect("a label applied by a deleted account is refused", () => + Effect.gen(function* () { + const answer = eventsReply([readyOn(LABELED, null)], null, creationOnly("tom")); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor(null, LABELED)), + ); + }), +); + +it.effect("a label that was removed and not applied again is not found", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn("2026-10-04T09:00:00Z", "tom"), readyOff(LABELED, "tom")], + null, + creationOnly("tom"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(NOT_FOUND)); + }), +); + +it.effect("no label events at all is not found", () => + Effect.gen(function* () { + const answer = eventsReply([], null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(NOT_FOUND)); + }), +); + +/** `n` events about another label, oldest first. */ +const noise = (n: number): Array => + Array.from({ length: n }, (_, i) => + labelEvent( + i % 2 === 0 ? "LabeledEvent" : "UnlabeledEvent", + "2026-10-04T09:00:00Z", + "tom", + "bug", + ), + ); + +it.effect("a hundred events of a longer history without the label is incomplete", () => + Effect.gen(function* () { + const answer = approvalReply(noise(100), 150, null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(LABEL_CUT)); + }), +); + +it.effect("a label found among the newest hundred is enough whatever the total", () => + Effect.gen(function* () { + const events = [...noise(99), readyOn(LABELED, "tom")]; + const answer = approvalReply(events, 400, null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("a removal among the newest hundred is not a missing history", () => + Effect.gen(function* () { + // The label was taken off in view: the history is not why it is missing. + const events = [readyOn("2026-10-04T08:30:00Z", "tom"), ...noise(98), readyOff(LABELED, "tom")]; + const answer = approvalReply(events, 100, null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(NOT_FOUND)); + }), +); + +it.effect("a complete hundred or a short page without the label is only not found", () => + Effect.gen(function* () { + // Exactly 100 in all: nothing is hidden. + const whole = approvalReply(noise(100), 100, null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(whole, ["tom"]), refused(NOT_FOUND)); + // A page short of 100 is not the cut-off that rule is about. + const short = approvalReply(noise(99), 120, null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(short, ["tom"]), refused(NOT_FOUND)); + }), +); + +it.effect("an instructor edit after the label is approved", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, "amy"], + [ + [CREATED, "eve"], + [AFTER, "amy"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom", "amy"]), approved(LABELED, "tom")); + }), +); + +it.effect("a non-instructor edit after the label is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, "eve"], + [ + [CREATED, "eve"], + [AFTER, "eve"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("a non-instructor edit followed by an instructor edit is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom")], + [LATER, "tom"], + [ + [CREATED, "eve"], + [AFTER, "eve"], + [LATER, "tom"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("an edit by a deleted account after the label is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, null], + [ + [CREATED, "eve"], + [AFTER, null], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("edits before the label are ignored whoever made them", () => + Effect.gen(function* () { + // The instructor approved the text as it stood when they applied the label. + const answer = eventsReply( + [readyOn(LABELED, "tom")], + ["2026-10-04T09:30:00Z", "eve"], + [ + [CREATED, "eve"], + ["2026-10-04T09:00:00Z", null], + ["2026-10-04T09:30:00Z", "eve"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("an edit in the same second as the label counts as after it", () => + Effect.gen(function* () { + const stranger = eventsReply( + [readyOn(LABELED, "tom")], + [LABELED, "eve"], + [ + [CREATED, "eve"], + [LABELED, "eve"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(stranger, ["tom"]), refused(editedAfter(LABELED))); + // An instructor's edit in that second is fine, and one second earlier is before it. + const instructor = eventsReply( + [readyOn(LABELED, "tom")], + [LABELED, "tom"], + [ + [CREATED, "eve"], + [LABELED, "tom"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(instructor, ["tom"]), approved(LABELED, "tom")); + const before = eventsReply( + [readyOn(LABELED, "tom")], + ["2026-10-04T09:59:59Z", "eve"], + [ + [CREATED, "eve"], + ["2026-10-04T09:59:59Z", "eve"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(before, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("only the label that is in force sets the cut off for edits", () => + Effect.gen(function* () { + // An edit between an old, removed label and the label now in force is before it. + const answer = eventsReply( + [ + readyOn("2026-10-04T09:00:00Z", "tom"), + readyOff("2026-10-04T09:10:00Z", "tom"), + readyOn(LABELED, "tom"), + ], + ["2026-10-04T09:30:00Z", "eve"], + [ + [CREATED, "eve"], + ["2026-10-04T09:30:00Z", "eve"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +/** `n` seconds, one apart, from 10:01:00. */ +const secondsAfterLabel = (n: number): Array => + Array.from( + { length: n }, + (_, i) => `2026-10-04T10:${pad(1 + Math.floor(i / 60))}:${pad(i % 60)}Z`, + ); + +it.effect("a full page of edits is an incomplete history", () => + Effect.gen(function* () { + const times = secondsAfterLabel(100); + const history = (n: number): Array => times.slice(0, n).map((t) => [t, "tom"]); + const last = (n: number): Edit => [times[n - 1]!, "tom"]; + const events = () => [readyOn(LABELED, "tom")]; + assert.deepStrictEqual( + yield* approvalOf(eventsReply(events(), last(99), history(99)), ["tom"]), + approved(LABELED, "tom"), + ); + assert.deepStrictEqual( + yield* approvalOf(eventsReply(events(), last(100), history(100)), ["tom"]), + refused(historyCut(LABELED)), + ); + }), +); + +it.effect( + "an edit total above the page is an incomplete history when the label may be hidden", + () => + Effect.gen(function* () { + // Both shown entries are after the label, so older ones could be too. + const nodes: Array = [ + [LATER, "tom"], + [AFTER, "tom"], + ]; + const last: Edit = [LATER, "tom"]; + const run = (total: number) => + approvalOf(approvalReplyRaw([readyOn(LABELED, "tom")], 1, last, nodes, total), ["tom"]); + assert.deepStrictEqual(yield* run(2), approved(LABELED, "tom")); + assert.deepStrictEqual(yield* run(5), refused(historyCut(LABELED))); + }), +); + +it.effect("the newest edit entry must be the last edit", () => + Effect.gen(function* () { + const create: Edit = [CREATED, "tom"]; + const last: Edit = [AFTER, "tom"]; + const run = (nodes: ReadonlyArray) => + approvalOf(approvalReplyRaw([readyOn(LABELED, "tom")], 1, last, nodes, nodes.length), [ + "tom", + "amy", + ]); + assert.deepStrictEqual(yield* run([[AFTER, "tom"], create]), approved(LABELED, "tom")); + // Another time, another editor (both instructors), or no entry for it. + const wrong: ReadonlyArray> = [ + [["2026-10-04T10:20:00Z", "tom"], create], + [[AFTER, "amy"], create], + [create], + [], + ]; + for (const nodes of wrong) { + assert.deepStrictEqual(yield* run(nodes), refused(historyCut(LABELED))); + } + }), +); + +it.effect("a visible stranger edit is named even when the history is also cut off", () => + Effect.gen(function* () { + const nodes: Array = [ + [AFTER, "eve"], + [CREATED, "tom"], + ]; + const answer = approvalReplyRaw([readyOn(LABELED, "tom")], 1, [AFTER, "eve"], nodes, 9); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("the label is judged before the edits", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "eve")], + [AFTER, "eve"], + [ + [CREATED, "eve"], + [AFTER, "eve"], + ], + ); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor("eve", LABELED)), + ); + }), +); + +it.effect("approval with no instructors approves nothing", () => + Effect.gen(function* () { + const answer = eventsReply([readyOn(LABELED, "tom")], null, creationOnly("tom")); + assert.deepStrictEqual(yield* approvalOf(answer, []), refused(byNonInstructor("tom", LABELED))); + }), +); + +/** The error `approval` gives for this answer, or null when it reads it. */ +const approvalError = (answer: string) => + Effect.gen(function* () { + const t = setup(reply(answer)); + return yield* t.ok( + t.github + .approval(6, ["tom"]) + .pipe(Effect.match({ onFailure: (e) => e, onSuccess: () => null })), + ); + }); + +/** Whether `answer` is a parse error that names the approval call. */ +const isApprovalParseError = (answer: string) => + approvalError(answer).pipe( + Effect.map( + (error) => + error !== null && + error._tag === "GitHubParse" && + JSON.stringify(error.args) === JSON.stringify(approvalCall()), + ), + ); + +it.effect("approval answers that cannot be read are parse errors", () => + Effect.gen(function* () { + const good = (events: unknown, edits: unknown) => + JSON.stringify({ + data: { + repository: { + issue: { + timelineItems: { totalCount: 1, nodes: events }, + lastEditedAt: null, + editor: null, + userContentEdits: edits, + }, + }, + }, + }); + const edits = editsJson([[CREATED, "tom"]], 1); + // The control: this one is fine. + assert.isFalse(yield* isApprovalParseError(good([readyOn(LABELED, "tom")], edits))); + + for (const bad of [ + "not json", + "", + "{}", + '{"data":{"repository":null}}', + '{"errors":[{"message":"x"}]}', + // No label events, no edit history, no total counts. + '{"data":{"repository":{"issue":{"lastEditedAt":null,"editor":null,"userContentEdits":{"totalCount":0,"nodes":[]}}}}}', + '{"data":{"repository":{"issue":{"timelineItems":{"totalCount":0,"nodes":[]},"lastEditedAt":null,"editor":null}}}}', + '{"data":{"repository":{"issue":{"timelineItems":{"nodes":[]},"lastEditedAt":null,"editor":null,"userContentEdits":{"totalCount":0,"nodes":[]}}}}}', + ]) { + assert.isTrue(yield* isApprovalParseError(bad), bad); + } + // A node missing its time, its label, or its type, or of a type we did not ask for. + for (const broken of [ + { __typename: "LabeledEvent", actor: { login: "tom" }, label: { name: "factory:ready" } }, + { __typename: "LabeledEvent", createdAt: LABELED, actor: { login: "tom" } }, + { createdAt: LABELED, actor: { login: "tom" }, label: { name: "factory:ready" } }, + { __typename: "ClosedEvent", createdAt: LABELED }, + ]) { + assert.isTrue(yield* isApprovalParseError(good([broken], edits)), JSON.stringify(broken)); + } + }), +); + +it.effect("a malformed timestamp is a parse error", () => + Effect.gen(function* () { + for (const at of ["2026-10-04 10:00:00Z", "2026-10-04T10:00:00", "", "yesterday"]) { + // In the label event. + const inLabel = eventsReply([readyOn(at, "tom")], null, creationOnly("tom")); + assert.isTrue(yield* isApprovalParseError(inLabel), `label at ${at}`); + // In the edit history. + const inEdit = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, "tom"], + [ + [CREATED, "tom"], + [at, "tom"], + ], + ); + assert.isTrue(yield* isApprovalParseError(inEdit), `edit at ${at}`); + // In lastEditedAt. + const inLast = eventsReply( + [readyOn(LABELED, "tom")], + [at, "tom"], + [ + [CREATED, "tom"], + [at, "tom"], + ], + ); + assert.isTrue(yield* isApprovalParseError(inLast), `last edit at ${at}`); + // In a rename. + const inRename = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(at, "tom")], + null, + creationOnly("tom"), + ); + assert.isTrue(yield* isApprovalParseError(inRename), `rename at ${at}`); + } + }), +); + +it("a UTC second is exactly YYYY-MM-DDTHH:MM:SSZ", () => { + assert.isTrue(isUtcSecond("2026-10-04T10:00:00Z")); + for (const text of [ + "", + "2026-10-04 10:00:00Z", + "2026-10-04T10:00:00", + "2026-10-04T10:00:00.5Z", + "2026-10-04T10:00:00+10:00", + " 2026-10-04T10:00:00Z", + "2026-10-04T10:00:00Z\n", + "2026-1a-04T10:00:00Z", + ]) { + assert.isFalse(isUtcSecond(text), JSON.stringify(text)); + } +}); + +it.effect("approval failures from gh are errors with the call", () => + Effect.gen(function* () { + const failed = setup(fail(1, "HTTP 502")); + const error = yield* failed.err(failed.github.approval(6, ["tom"])); + assert.strictEqual(error._tag, "GitHubFailed"); + assert.deepStrictEqual(error._tag === "GitHubFailed" && error.args, approvalCall()); + assert.strictEqual(error._tag === "GitHubFailed" && error.status, 1); + + const spawn = setup(spawnError()); + assert.strictEqual( + (yield* spawn.err(spawn.github.approval(6, ["tom"])))._tag, + "GitHubSpawnError", + ); + }), +); + +// ---- approval: titles, same second, long histories, non-human actors ---- + +/** `n` instructor renames after the label, oldest first, one second apart. */ +const renamesAfterLabel = (n: number): Array => + secondsAfterLabel(n).map((at) => renameEvent(at, "tom")); + +it.effect("a title renamed by a non-instructor after the label is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, "eve")], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("a title renamed by an instructor after the label is approved", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, "AMY")], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom", "amy"]), approved(LABELED, "tom")); + }), +); + +it.effect("a rename by a deleted account after the label is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, null)], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("a stranger rename followed by an instructor rename is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, "eve"), renameEvent(LATER, "tom")], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("a stranger rename is refused even when every body edit is an instructor's", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(LATER, "eve")], + [AFTER, "tom"], + [ + [CREATED, "eve"], + [AFTER, "tom"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("renames before the label in force are ignored", () => + Effect.gen(function* () { + // Before the label, and between a removed label and the one in force. + const answer = eventsReply( + [ + renameEvent("2026-10-04T08:30:00Z", "eve"), + readyOn("2026-10-04T09:00:00Z", "tom"), + readyOff("2026-10-04T09:10:00Z", "tom"), + renameEvent("2026-10-04T09:30:00Z", null), + readyOn(LABELED, "tom"), + ], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("a rename in the same second as the label counts as after it", () => + Effect.gen(function* () { + const stranger = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(LABELED, "eve")], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(stranger, ["tom"]), refused(editedAfter(LABELED))); + const instructor = eventsReply( + [ + renameEvent("2026-10-04T09:59:59Z", "eve"), + readyOn(LABELED, "tom"), + renameEvent(LABELED, "tom"), + ], + null, + creationOnly("eve"), + ); + assert.deepStrictEqual(yield* approvalOf(instructor, ["tom"]), approved(LABELED, "tom")); + }), +); + +it.effect("labels and renames share the page and the label in force is enough", () => + Effect.gen(function* () { + // The label is the oldest event shown, so every later event, the renames included, is on + // the page: events come oldest first and the page is the newest 100. Nothing before the + // label matters, whatever the total. + const events = [readyOn(LABELED, "tom"), ...renamesAfterLabel(99)]; + const answer = approvalReply(events, 400, null, creationOnly("eve")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + + // A stranger's rename on that page is seen. + const withStranger = [...events]; + withStranger[50] = renameEvent("2026-10-04T10:20:00Z", "eve"); + const seen = approvalReply(withStranger, 400, null, creationOnly("eve")); + assert.deepStrictEqual(yield* approvalOf(seen, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect( + "a page of renames without the label is a missing label history, not a stranger edit", + () => + Effect.gen(function* () { + // The label is older than all 100 shown events. Nothing shown can be told to be after it. + const events = Array.from({ length: 100 }, () => renameEvent(AFTER, "eve")); + const answer = approvalReply(events, 150, null, creationOnly("eve")); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(LABEL_CUT)); + }), +); + +/** `n` seconds, one apart, from `hour`:00:00. */ +const editTimes = (hour: number, n: number): Array => + Array.from( + { length: n }, + (_, i) => `2026-10-04T${pad(hour)}:${pad(Math.floor(i / 60))}:${pad(i % 60)}Z`, + ); + +it.effect( + "a hundred edits with the oldest shown before the label are judged by the visible ones", + () => + Effect.gen(function* () { + // 99 entries before the label (09:xx) and the newest, an instructor's, after it. + const history: Array = [ + ...editTimes(9, 99).map((t): Edit => [t, "tom"]), + [AFTER, "tom"], + ]; + const events = () => [readyOn(LABELED, "tom")]; + const answer = eventsReply(events(), [AFTER, "tom"], history); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + + // The same page with the newest edit by a stranger. + const withStranger: Array = [...history.slice(0, -1), [AFTER, "eve"]]; + const refusedAnswer = eventsReply(events(), [AFTER, "eve"], withStranger); + assert.deepStrictEqual( + yield* approvalOf(refusedAnswer, ["tom"]), + refused(editedAfter(LABELED)), + ); + }), +); + +it.effect("a hundred edits all after the label cannot be judged", () => + Effect.gen(function* () { + const times = secondsAfterLabel(100); + const history = times.map((t): Edit => [t, "tom"]); + const answer = eventsReply([readyOn(LABELED, "tom")], [times[99]!, "tom"], history); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), refused(historyCut(LABELED))); + }), +); + +it.effect("a total above the page is judged when the oldest shown entry is before the label", () => + Effect.gen(function* () { + const last: Edit = [LATER, "tom"]; + const run = (nodes: ReadonlyArray) => + approvalOf(approvalReplyRaw([readyOn(LABELED, "tom")], 1, last, nodes, 150), ["tom"]); + assert.deepStrictEqual( + yield* run([ + [LATER, "tom"], + [AFTER, "tom"], + ["2026-10-04T09:30:00Z", "tom"], + ]), + approved(LABELED, "tom"), + ); + // The oldest shown entry must be strictly before the label. + assert.deepStrictEqual( + yield* run([ + [LATER, "tom"], + [LABELED, "tom"], + ]), + refused(historyCut(LABELED)), + ); + assert.deepStrictEqual( + yield* run([ + [LATER, "tom"], + [AFTER, "tom"], + ]), + refused(historyCut(LABELED)), + ); + }), +); + +it.effect("a cut page still needs its newest entry to be the last edit", () => + Effect.gen(function* () { + const nodes: Array = [ + [LATER, "tom"], + ...editTimes(9, 99) + .reverse() + .map((t): Edit => [t, "tom"]), + ]; + assert.strictEqual(nodes.length, 100); + const run = (last: Edit) => + approvalOf(approvalReplyRaw([readyOn(LABELED, "tom")], 1, last, nodes, 100), ["tom"]); + assert.deepStrictEqual(yield* run([LATER, "tom"]), approved(LABELED, "tom")); + // GitHub says the last edit was another one. + assert.deepStrictEqual(yield* run([AFTER, "tom"]), refused(historyCut(LABELED))); + assert.deepStrictEqual(yield* run([LATER, "amy"]), refused(historyCut(LABELED))); + }), +); + +it.effect("a label applied by an actor that is not a user is refused whatever its login", () => + Effect.gen(function* () { + for (const typename of ["Bot", "Organization", "Mannequin", "EnterpriseUserAccount", ""]) { + const event = { ...readyOn(LABELED, "tom"), actor: { __typename: typename, login: "tom" } }; + const answer = eventsReply([event], null, creationOnly("eve")); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor("tom", LABELED)), + typename, + ); + } + }), +); + +it.effect("an actor without a typename is not an instructor", () => + Effect.gen(function* () { + const event = { ...readyOn(LABELED, "tom"), actor: { login: "tom" } }; + const answer = eventsReply([event], null, creationOnly("eve")); + assert.deepStrictEqual( + yield* approvalOf(answer, ["tom"]), + refused(byNonInstructor("tom", LABELED)), + ); + }), +); + +/** `answer` with the type of the newest history entry's editor replaced. */ +const withEditorTypename = (answer: string, typename: string): string => { + const json = JSON.parse(answer) as { + data: { + repository: { + issue: { userContentEdits: { nodes: Array<{ editor: { __typename: string } }> } }; + }; + }; + }; + json.data.repository.issue.userContentEdits.nodes[0]!.editor.__typename = typename; + return JSON.stringify(json); +}; + +it.effect("a body edit or rename by something that is not a user after the label is refused", () => + Effect.gen(function* () { + const answer = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, "tom"], + [ + [CREATED, "eve"], + [AFTER, "tom"], + ], + ); + assert.deepStrictEqual(yield* approvalOf(answer, ["tom"]), approved(LABELED, "tom")); + for (const typename of ["Bot", "Mannequin", ""]) { + assert.deepStrictEqual( + yield* approvalOf(withEditorTypename(answer, typename), ["tom"]), + refused(editedAfter(LABELED)), + `edit by ${typename}`, + ); + } + + const rename = { ...renameEvent(AFTER, "tom"), actor: { __typename: "Bot", login: "tom" } }; + const renamed = eventsReply([readyOn(LABELED, "tom"), rename], null, creationOnly("eve")); + assert.deepStrictEqual(yield* approvalOf(renamed, ["tom"]), refused(editedAfter(LABELED))); + }), +); + +it.effect("a creation entry by something that is not a user before the label is ignored", () => + Effect.gen(function* () { + const answer = eventsReply([readyOn(LABELED, "tom")], null, creationOnly("dependabot")); + assert.deepStrictEqual( + yield* approvalOf(withEditorTypename(answer, "Bot"), ["tom"]), + approved(LABELED, "tom"), + ); + }), +); + +it.effect("approval for a repo that is not owner/name makes no call", () => + Effect.gen(function* () { + const t = setup(); + const error = yield* t.err( + makeGitHub({ repo: "softfac", ghConfigDir: GH_CONFIG_DIR }).approval(6, ["tom"]), + ); + assert.strictEqual(error._tag, "GitHubParse"); + assert.deepStrictEqual(t.calls(), []); + }), +); + +// ---- text check ---- + +const textCheckOf = (answer: string, since: string, who: ReadonlyArray) => + Effect.gen(function* () { + const t = setup(reply(answer)); + const found: TextCheck = yield* t.ok(t.github.textCheck(6, since, who)); + assert.deepStrictEqual(t.calls(), [approvalCall()]); + return found; + }); + +it.effect("text check tells unchanged from changed from unjudged", () => + Effect.gen(function* () { + // Unchanged: instructors only. + const instructors = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, "tom")], + [AFTER, "tom"], + [ + [CREATED, "eve"], + [AFTER, "tom"], + ], + ); + assert.strictEqual(yield* textCheckOf(instructors, LABELED, ["tom"]), "unchanged"); + // Changed: a stranger's rename, a deleted account's edit. + const renamed = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(AFTER, "eve")], + null, + creationOnly("eve"), + ); + assert.strictEqual(yield* textCheckOf(renamed, LABELED, ["tom"]), "changed"); + const edited = eventsReply( + [readyOn(LABELED, "tom")], + [AFTER, null], + [ + [CREATED, "eve"], + [AFTER, null], + ], + ); + assert.strictEqual(yield* textCheckOf(edited, LABELED, ["tom"]), "changed"); + }), +); + +it.effect("text check says unjudged when the histories cannot be read whole", () => + Effect.gen(function* () { + // A full page of body edits after the label, all by instructors, with more behind it. + const times = secondsAfterLabel(100); + const oldestFirst = times.map((t): Edit => [t, "tom"]); + const last: Edit = [times[99]!, "tom"]; + const full = eventsReply([readyOn(LABELED, "tom")], last, oldestFirst); + assert.strictEqual(yield* textCheckOf(full, LABELED, ["tom"]), "unjudged"); + // A stranger shown on that page is still a change: it wins. + const withStranger = [...oldestFirst]; + withStranger[50] = [times[50]!, "eve"]; + const stranger = eventsReply([readyOn(LABELED, "tom")], last, withStranger); + assert.strictEqual(yield* textCheckOf(stranger, LABELED, ["tom"]), "changed"); + }), +); + +it.effect("text check ignores who applied labels but not bots", () => + Effect.gen(function* () { + // Labels are not text: a stranger's label event is not a change. + const labelled = eventsReply( + [readyOn(LABELED, "tom"), labelEvent("LabeledEvent", AFTER, "eve", "bug")], + null, + creationOnly("eve"), + ); + assert.strictEqual(yield* textCheckOf(labelled, LABELED, ["tom"]), "unchanged"); + // A bot with an instructor's login is not an instructor. + const rename = { ...renameEvent(AFTER, "tom"), actor: { __typename: "Bot", login: "tom" } }; + const bot = eventsReply([readyOn(LABELED, "tom"), rename], null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(bot, LABELED, ["tom"]), "changed"); + }), +); + +it.effect("text check cannot judge histories that may hide something", () => + Effect.gen(function* () { + // A full page of body edits all at or after the moment. + const times = secondsAfterLabel(100); + const history = times.map((t): Edit => [t, "tom"]); + const edits = eventsReply([readyOn(LABELED, "tom")], [times[99]!, "tom"], history); + assert.strictEqual(yield* textCheckOf(edits, LABELED, ["tom"]), "unjudged"); + + // A full timeline page whose oldest event is at or after the moment may hide renames. + const events = Array.from({ length: 100 }, () => renameEvent(AFTER, "tom")); + const full = approvalReply(events, 150, null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(full, LABELED, ["tom"]), "unjudged"); + // The same page with its oldest event before the moment shows everything after it. + const reaching = [renameEvent("2026-10-04T09:00:00Z", "eve"), ...events.slice(1)]; + const reachingAnswer = approvalReply(reaching, 150, null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(reachingAnswer, LABELED, ["tom"]), "unchanged"); + + // The newest body entry must be the last edit. + const stale = approvalReplyRaw( + [readyOn(LABELED, "tom")], + 1, + [AFTER, "tom"], + [[CREATED, "eve"]], + 1, + ); + assert.strictEqual(yield* textCheckOf(stale, LABELED, ["tom"]), "unjudged"); + }), +); + +it.effect("a cut off timeline page whose oldest event is exactly at since cannot be judged", () => + Effect.gen(function* () { + // Events before `since` could still be hidden at the same second, so the page must reach + // strictly before it. + const page = (oldest: string) => + approvalReply( + [ + renameEvent(oldest, "tom"), + ...Array.from({ length: 99 }, () => renameEvent(AFTER, "tom")), + ], + 150, + null, + creationOnly("eve"), + ); + assert.strictEqual(yield* textCheckOf(page(LABELED), LABELED, ["tom"]), "unjudged"); + assert.strictEqual(yield* textCheckOf(page(AFTER), LABELED, ["tom"]), "unjudged"); + assert.strictEqual( + yield* textCheckOf(page("2026-10-04T09:59:59Z"), LABELED, ["tom"]), + "unchanged", + ); + }), +); + +it.effect("each half of the timeline cut off rule alone stops the judgement", () => + Effect.gen(function* () { + const renames = (n: number) => Array.from({ length: n }, () => renameEvent(AFTER, "tom")); + // A full page of 100 with nothing more: still a page that may have been cut. + const full = approvalReply(renames(100), 100, null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(full, LABELED, ["tom"]), "unjudged"); + // Fewer than 100 shown with a larger total: something is hidden. + const short = approvalReply(renames(99), 120, null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(short, LABELED, ["tom"]), "unjudged"); + // The control: 99 shown of a total of 99 is the whole timeline. + const whole = approvalReply(renames(99), 99, null, creationOnly("eve")); + assert.strictEqual(yield* textCheckOf(whole, LABELED, ["tom"]), "unchanged"); + }), +); + +it.effect("text check is changed for a stranger edit or rename at or after the moment", () => + Effect.gen(function* () { + const edited = (at: string, who: Who) => + eventsReply( + [readyOn(LABELED, "tom")], + [at, who], + [ + [CREATED, "eve"], + [at, who], + ], + ); + const renamed = (at: string, who: Who) => + eventsReply([readyOn(LABELED, "tom"), renameEvent(at, who)], null, creationOnly("eve")); + for (const at of [LABELED, AFTER]) { + for (const who of ["eve", null]) { + assert.strictEqual(yield* textCheckOf(edited(at, who), LABELED, ["tom"]), "changed"); + assert.strictEqual(yield* textCheckOf(renamed(at, who), LABELED, ["tom"]), "changed"); + } + } + // One second before the moment is before it. + assert.strictEqual( + yield* textCheckOf(edited("2026-10-04T09:59:59Z", "eve"), LABELED, ["tom"]), + "unchanged", + ); + assert.strictEqual( + yield* textCheckOf(renamed("2026-10-04T09:59:59Z", "eve"), LABELED, ["tom"]), + "unchanged", + ); + }), +); + +it.effect("text check with a timestamp that is not GitHub's form makes no call", () => + Effect.gen(function* () { + for (const since of ["", "2026-10-04 10:00:00Z", "2026-10-04T10:00:00", "now"]) { + const t = setup(); + const error = yield* t.err(t.github.textCheck(6, since, ["tom"])); + assert.strictEqual(error._tag, "GitHubParse", since); + assert.deepStrictEqual(error._tag === "GitHubParse" && error.args, ["api", "graphql"]); + assert.deepStrictEqual(t.calls(), [], since); + } + }), +); + +it.effect("text check errors are typed", () => + Effect.gen(function* () { + const bad = setup(reply("not json")); + const parse = yield* bad.err(bad.github.textCheck(6, LABELED, ["tom"])); + assert.strictEqual(parse._tag, "GitHubParse"); + assert.deepStrictEqual(parse._tag === "GitHubParse" && parse.args, approvalCall()); + + const failed = setup(fail(1, "HTTP 502")); + const error = yield* failed.err(failed.github.textCheck(6, LABELED, ["tom"])); + assert.strictEqual(error._tag, "GitHubFailed"); + assert.strictEqual(error._tag === "GitHubFailed" && error.status, 1); + + const answer = eventsReply([readyOn(LABELED, "tom")], ["later", "tom"], creationOnly("tom")); + const malformed = setup(reply(answer)); + assert.strictEqual( + (yield* malformed.err(malformed.github.textCheck(6, LABELED, ["tom"])))._tag, + "GitHubParse", + ); + }), +); + +// ---- text edited since ---- + +const editedSinceOf = (answer: string, since: string) => + Effect.gen(function* () { + const t = setup(reply(answer)); + const found = yield* t.ok(t.github.textEditedSince(6, since)); + assert.deepStrictEqual(t.calls(), [approvalCall()]); + return found; + }); + +it.effect("text edited since is false when nothing touched the text at or after the moment", () => + Effect.gen(function* () { + // An edit and a rename before the moment, by anyone, and a label event after it. + const answer = eventsReply( + [ + renameEvent("2026-10-04T09:00:00Z", "eve"), + readyOn(LABELED, "tom"), + labelEvent("LabeledEvent", AFTER, "eve", "bug"), + ], + ["2026-10-04T09:59:59Z", "tom"], + [ + [CREATED, "eve"], + ["2026-10-04T09:59:59Z", "tom"], + ], + ); + assert.isFalse(yield* editedSinceOf(answer, LABELED)); + }), +); + +it.effect( + "text edited since is true for any edit or rename at or after the moment, even an instructor's", + () => + Effect.gen(function* () { + for (const at of [LABELED, AFTER]) { + const edited = eventsReply( + [readyOn(LABELED, "tom")], + [at, "tom"], + [ + [CREATED, "eve"], + [at, "tom"], + ], + ); + assert.isTrue(yield* editedSinceOf(edited, LABELED), `edit at ${at}`); + const renamed = eventsReply( + [readyOn(LABELED, "tom"), renameEvent(at, "tom")], + null, + creationOnly("eve"), + ); + assert.isTrue(yield* editedSinceOf(renamed, LABELED), `rename at ${at}`); + } + }), +); + +it.effect("text edited since is true when the timeline may hide a rename", () => + Effect.gen(function* () { + // A full page of newer label events with more behind it: a rename at the moment could be + // among the hidden ones. + const events = Array.from({ length: 100 }, (_, i) => + labelEvent( + "LabeledEvent", + `2026-10-04T11:${pad(Math.floor(i / 60))}:${pad(i % 60)}Z`, + "eve", + "bug", + ), + ); + const answer = approvalReply(events, 150, null, creationOnly("eve")); + assert.isTrue(yield* editedSinceOf(answer, LABELED)); + }), +); + +it.effect("text edited since refuses a moment that is not a GitHub timestamp", () => + Effect.gen(function* () { + const t = setup(); + const error = yield* t.err(t.github.textEditedSince(6, "yesterday")); + assert.strictEqual(error._tag, "GitHubParse"); + assert.deepStrictEqual(t.calls(), []); + }), +); + +// ---- the GitHub tracker delegates (from softfac's runner tests) ---- + +it.effect( + "approval sends one graphql call for the issue and uses the instructors it is given", + () => + Effect.gen(function* () { + const answer = JSON.stringify({ + data: { + repository: { + issue: { + timelineItems: { + totalCount: 1, + nodes: [readyOn("2026-10-04T11:36:21Z", "rawphp")], + }, + lastEditedAt: null, + editor: null, + userContentEdits: editsJson([["2026-10-04T09:50:06Z", "outsider"]], 1), + }, + }, + }, + }); + const t = setup(reply(answer)); + const found = yield* t.ok(t.github.approval(10, ["rawphp"])); + assert.deepStrictEqual(found, approved("2026-10-04T11:36:21Z", "rawphp")); + const calls = t.calls(); + assert.strictEqual(calls.length, 1); + assert.deepStrictEqual(calls[0]!.slice(0, 2), ["api", "graphql"]); + assert.include(calls[0]!, "number=10"); + }), +); + +/** A recorded answer of the approval query: the label at 10:00 and an outsider's rename at 10:30. */ +const RENAMED_BY_OUTSIDER = + '{"data":{"repository":{"issue":{"timelineItems":{"totalCount":2,"nodes":[{"__typename":"LabeledEvent","createdAt":"2026-10-04T10:00:00Z","actor":{"__typename":"User","login":"rawphp"},"label":{"name":"factory:ready"}},{"__typename":"RenamedTitleEvent","createdAt":"2026-10-04T10:30:00Z","actor":{"__typename":"User","login":"outsider"}}]},"lastEditedAt":null,"editor":null,"userContentEdits":{"totalCount":1,"nodes":[{"editedAt":"2026-10-04T09:50:06Z","editor":{"__typename":"User","login":"outsider"}}]}}}}}'; + +it.effect("text check sends one graphql call per check and uses the instructors it is given", () => + Effect.gen(function* () { + const t = setup( + reply(RENAMED_BY_OUTSIDER), + reply(RENAMED_BY_OUTSIDER), + reply(RENAMED_BY_OUTSIDER), + ); + // The rename is at or after the first moment and before the second. + assert.strictEqual( + yield* t.ok(t.github.textCheck(10, "2026-10-04T10:00:00Z", ["rawphp"])), + "changed", + ); + assert.strictEqual( + yield* t.ok(t.github.textCheck(10, "2026-10-04T10:30:01Z", ["rawphp"])), + "unchanged", + ); + // The list passed is the one used: with the outsider as an instructor it is unchanged. + assert.strictEqual( + yield* t.ok(t.github.textCheck(10, "2026-10-04T10:00:00Z", ["outsider"])), + "unchanged", + ); + const calls = t.calls(); + assert.strictEqual(calls.length, 3); + for (const call of calls) { + assert.strictEqual(call.length, 10); + assert.deepStrictEqual(call.slice(0, 3), ["api", "graphql", "-f"]); + assert.isTrue(call[3]!.startsWith("query=query($owner: String!, $name: String!")); + assert.include(call[3]!, "RENAMED_TITLE_EVENT"); + assert.deepStrictEqual(call.slice(4), [ + "-f", + "owner=rawphp", + "-f", + "name=softfac", + "-F", + "number=10", + ]); + } + }), +); From f82bda835fbf018f5a009362517c46a05e16955b Mon Sep 17 00:00:00 2001 From: Tom Kaczocha Date: Fri, 16 Oct 2026 07:29:28 +1000 Subject: [PATCH 2/5] feat(factory): the approval rule, text checks and blockers over gh Issue: #13 --- apps/server/src/factory/domain/approval.ts | 67 +++ .../server/src/factory/tracker/github.test.ts | 4 +- apps/server/src/factory/tracker/github.ts | 454 ++++++++++++++++++ 3 files changed, 523 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/factory/domain/approval.ts diff --git a/apps/server/src/factory/domain/approval.ts b/apps/server/src/factory/domain/approval.ts new file mode 100644 index 0000000000000..96a229cd8fb3a --- /dev/null +++ b/apps/server/src/factory/domain/approval.ts @@ -0,0 +1,67 @@ +/** + * The approval rule's verdicts and the words the factory says when it refuses. The rule itself + * reads GitHub's history and lives with the tracker; this file holds what it concludes and + * what is then written on the issue. Pure: no I/O. + */ + +/** + * Why an issue is not approved. A fixed set, so nothing from the issue can reach a comment. + * Times are GitHub's `YYYY-MM-DDTHH:MM:SSZ`. + */ +export type Refusal = + /** No `factory:ready` event in force among the label events read. It has no label time. */ + | { readonly kind: "label-not-found" } + /** A full page of a longer label history without the event in force. It has no label time. */ + | { readonly kind: "label-history-incomplete" } + /** The label in force was applied by someone who is not an instructor (`by` null: a deleted account). */ + | { + readonly kind: "labeled-by-non-instructor"; + readonly by: string | null; + readonly labeledAt: string; + } + /** Someone who is not an instructor edited the body or renamed the title after the label. */ + | { readonly kind: "edited-after-label"; readonly labeledAt: string } + /** The body's edit history is cut off, so it cannot show every edit. */ + | { readonly kind: "edit-history-incomplete"; readonly labeledAt: string }; + +/** + * Whether the factory may build the issue: an instructor applied the label in force, and + * every edit and rename since was an instructor's. + */ +export type Approval = + | { readonly kind: "approved"; readonly labeledAt: string; readonly labeledBy: string } + | { readonly kind: "refused"; readonly refusal: Refusal }; + +/** + * Whether the issue text is as an instructor left it: `unchanged`, `changed` by someone who is + * not an instructor, or `unjudged` when the histories do not reach back far enough to tell. + */ +export type TextCheck = "unchanged" | "changed" | "unjudged"; + +/** The fixed reason for a refusal. Nothing from the issue, not even a login, is in it. */ +export const refusalReason = (refusal: Refusal): string => { + switch (refusal.kind) { + case "labeled-by-non-instructor": + return "factory:ready was not applied by an instructor"; + case "edited-after-label": + return "the issue text was edited after factory:ready was applied by someone who is not an instructor"; + case "label-not-found": + case "label-history-incomplete": + return "the factory could not read who applied factory:ready"; + case "edit-history-incomplete": + return "the factory could not read the full edit history of the issue text"; + } +}; + +/** + * The comment on an issue the factory refused to build: its own fixed text, quoting nothing + * from the issue. + */ +export const unapprovedComment = (refusal: Refusal): string => { + const whatToDo = + refusal.kind === "edit-history-incomplete" + ? // Applying the label again cannot help: the history only grows. + "The issue's edit history is too long for the factory to check. File a new issue with the final text and apply `factory:ready` to it." + : "Review the issue text, then apply `factory:ready` again. An instructor must apply the label, and the text must not be edited afterwards by anyone who is not an instructor."; + return `The factory did not start on this issue and has moved it back to \`factory:proposed\`.\n\nReason: ${refusalReason(refusal)}\n\n${whatToDo}`; +}; diff --git a/apps/server/src/factory/tracker/github.test.ts b/apps/server/src/factory/tracker/github.test.ts index d543b6f975c55..ac01995ed8243 100644 --- a/apps/server/src/factory/tracker/github.test.ts +++ b/apps/server/src/factory/tracker/github.test.ts @@ -2293,7 +2293,7 @@ const editsJson = (newestFirst: ReadonlyArray, total: number) => ({ }); /** A history written oldest first, as the tests think of it, in GitHub's order. */ -const newestFirst = (oldestFirst: ReadonlyArray): Array => [...oldestFirst].reverse(); +const newestFirst = (oldestFirst: ReadonlyArray): Array => oldestFirst.toReversed(); /** The approval answer with exactly these history nodes (newest first) and this total. */ const approvalReplyRaw = ( @@ -3131,7 +3131,7 @@ it.effect("a cut page still needs its newest entry to be the last edit", () => const nodes: Array = [ [LATER, "tom"], ...editTimes(9, 99) - .reverse() + .toReversed() .map((t): Edit => [t, "tom"]), ]; assert.strictEqual(nodes.length, 100); diff --git a/apps/server/src/factory/tracker/github.ts b/apps/server/src/factory/tracker/github.ts index 5d2371701f8a5..5c3e3c40ed642 100644 --- a/apps/server/src/factory/tracker/github.ts +++ b/apps/server/src/factory/tracker/github.ts @@ -2,6 +2,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { PROJECT_CONFIG_PATH } from "../config.ts"; +import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; import { STATES, stateColor, @@ -12,6 +13,8 @@ import { } from "../domain/lifecycle.ts"; import { FactoryProcess } from "../process.ts"; +export type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; + /** * GitHub issues, labels, comments and files through the `gh` CLI, ported from * softfac's github.rs. Every call runs `gh` through `FactoryProcess`, so a test @@ -185,6 +188,18 @@ const CommentRows = Schema.Array( }), ); +const BlockerRows = Schema.Array( + Schema.Struct({ + number: Schema.Number, + state: Schema.String, + repository_url: OptionalText, + }), +); + +const IssueBody = Schema.Struct({ body: OptionalText }); +/** The REST state is lowercase: `open` or `closed`. */ +const IssueRestState = Schema.Struct({ state: Schema.String }); + const RepoView = Schema.Struct({ default_branch: OptionalText }); const RefView = Schema.Struct({ @@ -425,6 +440,235 @@ const checkOutcome = (status: string, conclusion: string | null): readonly [Chec const withMarker = (body: string, marker: string): string => `${body}\n\n${marker}`; +// ---- the Depends on section ---- + +/** An issue named in the `## Depends on` section of an issue body. */ +export interface IssueRef { + /** `owner/name` when the text names a repo; null means the repo of the issue it was written in. */ + readonly repo: string | null; + readonly number: number; +} + +/** An open issue that blocks another one. */ +export interface Blocker { + /** `owner/name` of the repo the blocking issue is in. */ + readonly repo: string; + readonly number: number; +} + +const isRepoChar = (char: string): boolean => /^[A-Za-z0-9._-]$/.test(char); +const isDigit = (char: string): boolean => char >= "0" && char <= "9"; + +/** The lines of a text as Rust's `lines()` gives them: split on `\n`, one `\r` before it dropped. */ +const textLines = (text: string): Array => { + const lines = text.split("\n"); + if (lines[lines.length - 1] === "") lines.pop(); + return lines.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)); +}; + +/** A markdown heading: `#`s then a space, a tab or the end of the line. `#13` is a reference. */ +const isHeading = (line: string): boolean => { + const rest = line.replace(/^#+/, ""); + return rest.length < line.length && (rest === "" || rest[0] === " " || rest[0] === "\t"); +}; + +/** The lines of the `## Depends on` section: after its heading, up to the next heading line. */ +const dependsOnLines = (body: string): Array => { + const lines: Array = []; + let inSection = false; + for (const line of textLines(body)) { + if (inSection) { + if (isHeading(line)) break; + lines.push(line); + } else { + inSection = + line.startsWith("## ") || line.startsWith("##\t") + ? line.slice(3).trim().toLowerCase() === "depends on" + : false; + } + } + return lines; +}; + +/** + * The issues named in the `## Depends on` section of an issue body, in order of first + * appearance, each once. The section runs from its heading to the next heading line. It names + * `#` and `/#`; "None", an empty section and no section name nothing. + */ +export const dependsOn = (body: string): Array => { + const found: Array = []; + for (const line of dependsOnLines(body)) { + for (let at = 0; at < line.length; at++) { + if (line[at] !== "#") continue; + let end = at + 1; + while (end < line.length && isDigit(line[end]!)) end++; + const number = Number(line.slice(at + 1, end)); + if (end === at + 1 || !Number.isSafeInteger(number)) continue; + let repoStart = at; + while (repoStart > 0 && isRepoChar(line[repoStart - 1]!)) repoStart--; + let repo: string | null = null; + if (repoStart < at && repoStart > 0 && line[repoStart - 1] === "/") { + let ownerStart = repoStart - 1; + while (ownerStart > 0 && isRepoChar(line[ownerStart - 1]!)) ownerStart--; + if (ownerStart === repoStart - 1) continue; + repo = line.slice(ownerStart, at); + } else if (repoStart < at) { + // Word characters run straight into the `#`, as in `page#12`: not an issue. + continue; + } + if (!found.some((issue) => issue.repo === repo && issue.number === number)) { + found.push({ repo, number }); + } + } + } + return found; +}; + +// ---- the approval rule's reading of GitHub's history ---- + +/** How many label events and body edits the approval query asks for. A history this long may be cut off. */ +const HISTORY_PAGE = 100; + +/** GitHub's uniform UTC form, so ordering the text orders the times. */ +export const isUtcSecond = (text: string): boolean => + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(text); + +/** + * Who applied the issue's labels, who renamed it and who edited its body. `last: 100` of the + * timeline items is the newest 100 (GitHub lists them oldest first), and + * `userContentEdits(first: 100)` is the newest 100 edits (it lists newest first). Titles are + * not asked for. `__typename` on an actor tells a person from a GitHub App. + */ +export const APPROVAL_QUERY = + "query($owner: String!, $name: String!, $number: Int!) { " + + "repository(owner: $owner, name: $name) { issue(number: $number) { " + + "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { " + + "totalCount nodes { " + + "__typename " + + "... on LabeledEvent { createdAt actor { __typename login } label { name } } " + + "... on UnlabeledEvent { createdAt actor { __typename login } label { name } } " + + "... on RenamedTitleEvent { createdAt actor { __typename login } } } } " + + "lastEditedAt editor { __typename login } " + + "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }"; + +/** `typename` is only there when the query asked for it; a rule that wants a person needs a `User`. */ +const Actor = Schema.Struct({ + __typename: OptionalText, + login: Schema.String, +}); +type Actor = typeof Actor.Type; + +const LabelChange = Schema.Struct({ + createdAt: Schema.String, + actor: Schema.optional(Schema.NullOr(Actor)), + label: Schema.Struct({ name: Schema.String }), +}); + +/** One label event or title rename; a node of any other type is an answer this module cannot read. */ +const TimelineNode = Schema.Union([ + Schema.Struct({ __typename: Schema.Literal("LabeledEvent"), ...LabelChange.fields }), + Schema.Struct({ __typename: Schema.Literal("UnlabeledEvent"), ...LabelChange.fields }), + Schema.Struct({ + __typename: Schema.Literal("RenamedTitleEvent"), + createdAt: Schema.String, + actor: Schema.optional(Schema.NullOr(Actor)), + }), +]); +type TimelineNode = typeof TimelineNode.Type; + +const ApprovalAnswer = Schema.Struct({ + data: Schema.Struct({ + repository: Schema.Struct({ + issue: Schema.Struct({ + timelineItems: Schema.Struct({ + totalCount: Schema.Number, + nodes: Schema.Array(TimelineNode), + }), + lastEditedAt: OptionalText, + editor: Schema.optional(Schema.NullOr(Actor)), + userContentEdits: Schema.Struct({ + totalCount: Schema.Number, + nodes: Schema.Array( + Schema.Struct({ + editedAt: Schema.String, + editor: Schema.optional(Schema.NullOr(Actor)), + }), + ), + }), + }), + }), + }), +}); +type ApprovalIssue = (typeof ApprovalAnswer.Type)["data"]["repository"]["issue"]; + +const asciiLower = (text: string): string => text.replace(/[A-Z]/g, (char) => char.toLowerCase()); + +/** + * An instructor who is a person: GitHub says the actor is a `User`. A GitHub App's GraphQL login + * can lack the `[bot]` suffix, so a login that matches an instructor is not enough. + */ +const isHumanInstructor = ( + actor: Actor | null | undefined, + instructors: ReadonlyArray, +): boolean => + actor !== null && + actor !== undefined && + actor.__typename === "User" && + instructors.some((name) => asciiLower(name) === asciiLower(actor.login)); + +/** Whether the timeline page shows every event at or after `since`: not cut off, or its oldest is before `since`. */ +const timelineReaches = (issue: ApprovalIssue, since: string): boolean => { + const { totalCount, nodes } = issue.timelineItems; + const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; + return !cutOff || (nodes[0] !== undefined && nodes[0].createdAt < since); +}; + +/** Whether the newest history entry is the last edit, by the last editor. */ +const newestIsLastEdit = (issue: ApprovalIssue): boolean => { + if (issue.lastEditedAt === null || issue.lastEditedAt === undefined) return true; + const newest = issue.userContentEdits.nodes[0]; + return ( + newest !== undefined && + newest.editedAt === issue.lastEditedAt && + (newest.editor?.login ?? null) === (issue.editor?.login ?? null) + ); +}; + +/** + * Whether the body's edit history can be trusted for every edit at or after `since`: the entries + * come newest first, so when it is cut off the oldest one shown must be before `since`. + */ +const editsWholeSince = (issue: ApprovalIssue, since: string): boolean => { + const { totalCount, nodes } = issue.userContentEdits; + const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; + const reachesBack = !cutOff || (nodes.length > 0 && nodes[nodes.length - 1]!.editedAt < since); + return reachesBack && newestIsLastEdit(issue); +}; + +/** + * Judges every body edit and title rename with time at or after `since`. A moment in the same + * second counts as after, because timestamps have no finer order. `reaches` says the renames on + * the timeline page cover everything at or after `since`. + */ +const textChangesSince = ( + issue: ApprovalIssue, + since: string, + instructors: ReadonlyArray, + reaches: boolean, +): TextCheck => { + const editByStranger = issue.userContentEdits.nodes.some( + (edit) => edit.editedAt >= since && !isHumanInstructor(edit.editor, instructors), + ); + const renameByStranger = issue.timelineItems.nodes.some( + (event) => + event.__typename === "RenamedTitleEvent" && + event.createdAt >= since && + !isHumanInstructor(event.actor, instructors), + ); + if (editByStranger || renameByStranger) return "changed"; + return editsWholeSince(issue, since) && reaches ? "unchanged" : "unjudged"; +}; + // ---- the client ---- export interface GitHubOptions { @@ -899,6 +1143,211 @@ export const makeGitHub = (options: GitHubOptions) => { }); }); + // ---- blockers ---- + + /** + * The issues that GitHub marks as blocking `issue` (Relationships, "Mark as blocked by") and + * that are not closed, in the order GitHub lists them. An issue is resolved once it is closed, + * for any reason, in any repo. The `## Depends on` text is not read here; see `textBlockers`. + */ + const openBlockers = (issue: number): GitHubEffect> => + Effect.gen(function* () { + const args = ["api", `repos/${repo}/issues/${issue}/dependencies/blocked_by`, "--paginate"]; + const listed = yield* ghPages(args, BlockerRows, "JSON arrays of issues"); + const open: Array = []; + for (const raw of listed.filter((row) => row.state !== "closed")) { + // The blocker's repo is named in `repository_url`. Without it the caller would have to + // guess, so the answer is an error and the issue is not claimed. + const url = raw.repository_url ?? ""; + const cut = url.indexOf("/repos/"); + const named = cut < 0 ? "" : url.slice(cut + "/repos/".length); + const parts = named.split("/"); + if (parts.length !== 2 || parts[0] === "" || parts[1] === "") { + return yield* parseError( + args, + `issues that each name their repo in repository_url (#${raw.number} did not)`, + ); + } + open.push({ repo: named, number: raw.number }); + } + return open; + }); + + /** + * The issues named in the `## Depends on` section of `issue` that are not closed, in the order + * the text names them. A reference without a repo is in this repo. It costs one read of the + * body and one of each named issue, and is an error when any of them cannot be read: an issue + * that cannot be read is not taken as resolved. + */ + const textBlockers = (issue: number): GitHubEffect> => + Effect.gen(function* () { + const bodyArgs = [...repoArgs(["issue", "view", String(issue)]), "--json", "body"]; + const raw = yield* ghJson(bodyArgs, IssueBody, "an object with the issue's body"); + const open: Array = []; + for (const named of dependsOn(raw.body ?? "")) { + const namedRepo = named.repo ?? repo; + const args = ["api", `repos/${namedRepo}/issues/${named.number}`]; + const read = yield* ghJson(args, IssueRestState, "an object with the issue's state"); + if (read.state.toLowerCase() !== "closed") { + open.push({ repo: namedRepo, number: named.number }); + } + } + return open; + }); + + // ---- approval ---- + + /** `gh api graphql` arguments for a query over one issue; a repo that is not `owner/name` is refused before any call. */ + const issueQueryArgs = (query: string, issue: number): GitHubEffect> => + Effect.gen(function* () { + const slash = repo.indexOf("/"); + if (slash < 0) { + return yield* parseError( + ["api", "graphql"], + `a repo written as owner/name, got \`${repo}\``, + ); + } + return [ + "api", + "graphql", + "-f", + `query=${query}`, + "-f", + `owner=${repo.slice(0, slash)}`, + "-f", + `name=${repo.slice(slash + 1)}`, + "-F", + `number=${issue}`, + ]; + }); + + /** Runs the approval query for the issue and checks every timestamp in the answer. */ + const readHistory = (issue: number): GitHubEffect => + Effect.gen(function* () { + const args = yield* issueQueryArgs(APPROVAL_QUERY, issue); + const answer = yield* ghJson(args, ApprovalAnswer, "a GraphQL response with the issue"); + const found = answer.data.repository.issue; + const times = [ + ...found.timelineItems.nodes.map((event) => event.createdAt), + ...found.userContentEdits.nodes.map((edit) => edit.editedAt), + ...(found.lastEditedAt === null || found.lastEditedAt === undefined + ? [] + : [found.lastEditedAt]), + ]; + for (const at of times) { + if (!isUtcSecond(at)) { + return yield* parseError(args, `a timestamp as YYYY-MM-DDTHH:MM:SSZ, got ${quoted(at)}`); + } + } + return found; + }); + + /** `since` as the one call's argument check: only GitHub's `YYYY-MM-DDTHH:MM:SSZ`, before any call. */ + const requireUtcSecond = (since: string): GitHubEffect => + isUtcSecond(since) + ? Effect.void + : Effect.fail( + parseError(["api", "graphql"], `\`since\` as YYYY-MM-DDTHH:MM:SSZ, got ${quoted(since)}`), + ); + + /** + * Whether the factory may build the issue: an instructor applied the `factory:ready` label + * that is in force now, and every edit of the body and every rename of the title at or after + * that moment was an instructor's. One GraphQL call. + * + * The timeline events (label changes and renames, oldest first) are walked so that the walk + * keeps the last `factory:ready` event that no later removal cancelled. Label names are matched + * exactly. Only the newest 100 events are read; the one in force among them is enough, because + * every later event, a rename included, is on the page too. A full page of a longer history + * without it is `label-history-incomplete`. + * + * An edit or rename before the label's time is ignored: the instructor approved the text as it + * stood. One in the label's own second counts as after it. Timestamps are compared as strings. + * Only a `User` can be an instructor: a deleted account or a bot never is. + */ + const approval = (issue: number, instructors: ReadonlyArray): GitHubEffect => + Effect.gen(function* () { + const found = yield* readHistory(issue); + const ready = stateLabel("ready"); + + let inForce: Extract | null = null; + for (const event of found.timelineItems.nodes) { + if (event.__typename === "LabeledEvent" && event.label.name === ready) inForce = event; + else if (event.__typename === "UnlabeledEvent" && event.label.name === ready) { + inForce = null; + } + } + if (inForce === null) { + const { totalCount, nodes } = found.timelineItems; + const cutOff = nodes.length >= HISTORY_PAGE && totalCount > HISTORY_PAGE; + const refusal: Refusal = { kind: cutOff ? "label-history-incomplete" : "label-not-found" }; + return { kind: "refused", refusal } satisfies Approval; + } + const labeledAt = inForce.createdAt; + const actor = inForce.actor; + if (actor === null || actor === undefined || !isHumanInstructor(actor, instructors)) { + return { + kind: "refused", + refusal: { kind: "labeled-by-non-instructor", by: actor?.login ?? null, labeledAt }, + } satisfies Approval; + } + + // The label is on the page, so the renames at or after it are too. + switch (textChangesSince(found, labeledAt, instructors, true)) { + case "changed": + return { + kind: "refused", + refusal: { kind: "edited-after-label", labeledAt }, + } satisfies Approval; + case "unjudged": + return { + kind: "refused", + refusal: { kind: "edit-history-incomplete", labeledAt }, + } satisfies Approval; + case "unchanged": + return { kind: "approved", labeledAt, labeledBy: actor.login } satisfies Approval; + } + }); + + /** + * Whether the issue text is as an instructor left it: every body edit and every title rename + * at or after `since` (a moment in the same second counts) was made by an instructor who is a + * `User`, and the histories reach back far enough to tell. Keeps apart a text someone else + * changed from one whose histories cannot be judged: a stranger's change that can be read wins + * over a history that is also too long. One call, with the approval's own query and rules. + * Labels are not text and are not looked at. + */ + const textCheck = ( + issue: number, + since: string, + instructors: ReadonlyArray, + ): GitHubEffect => + Effect.gen(function* () { + yield* requireUtcSecond(since); + const found = yield* readHistory(issue); + return textChangesSince(found, since, instructors, timelineReaches(found, since)); + }); + + /** + * Whether anyone, an instructor included, edited the body or renamed the title at or after + * `since`. For the resume after a time limit: the next session continues the earlier one's + * work only on the text that work was approved on. A timeline page that may hide a rename at + * or after the moment counts as a change. One call, the approval's own query. + */ + const textEditedSince = (issue: number, since: string): GitHubEffect => + Effect.gen(function* () { + yield* requireUtcSecond(since); + const found = yield* readHistory(issue); + const edited = + found.lastEditedAt !== null && found.lastEditedAt !== undefined + ? found.lastEditedAt >= since + : false; + const renamed = found.timelineItems.nodes.some( + (event) => event.__typename === "RenamedTitleEvent" && event.createdAt >= since, + ); + return edited || renamed || !timelineReaches(found, since); + }); + return { listIssues, issue, @@ -920,5 +1369,10 @@ export const makeGitHub = (options: GitHubOptions) => { commentOnPr, compare, checks, + openBlockers, + textBlockers, + approval, + textCheck, + textEditedSince, }; }; From 072e64cb0733af2b959c91a3ba9a47fb7240f6c2 Mon Sep 17 00:00:00 2001 From: Tom Kaczocha Date: Fri, 16 Oct 2026 07:35:07 +1000 Subject: [PATCH 3/5] refactor(factory): split the pure approval judgement and Depends on parser out of github.ts Issue: #13 Addresses maintainability-1. --- .../src/factory/domain/dependsOn.test.ts | 70 ++++++ apps/server/src/factory/domain/dependsOn.ts | 76 ++++++ .../factory/tracker/approvalHistory.test.ts | 49 ++++ .../src/factory/tracker/approvalHistory.ts | 153 ++++++++++++ .../server/src/factory/tracker/github.test.ts | 120 +-------- apps/server/src/factory/tracker/github.ts | 232 +----------------- 6 files changed, 361 insertions(+), 339 deletions(-) create mode 100644 apps/server/src/factory/domain/dependsOn.test.ts create mode 100644 apps/server/src/factory/domain/dependsOn.ts create mode 100644 apps/server/src/factory/tracker/approvalHistory.test.ts create mode 100644 apps/server/src/factory/tracker/approvalHistory.ts diff --git a/apps/server/src/factory/domain/dependsOn.test.ts b/apps/server/src/factory/domain/dependsOn.test.ts new file mode 100644 index 0000000000000..8bd3395a2bd5c --- /dev/null +++ b/apps/server/src/factory/domain/dependsOn.test.ts @@ -0,0 +1,70 @@ +import { assert, it } from "@effect/vitest"; + +import { dependsOn, type IssueRef } from "./dependsOn.ts"; + +const same = (number: number): IssueRef => ({ repo: null, number }); +const cross = (repo: string, number: number): IssueRef => ({ repo, number }); + +it("depends on reads same repo references", () => { + const body = "Intro\n\n## Depends on\n\n- #13\n- #15 until it lands\n"; + assert.deepStrictEqual(dependsOn(body), [same(13), same(15)]); +}); + +it("depends on reads cross repo references", () => { + const body = "## Depends on\nacme/widgets#7, my-org/some.repo_x#42\n"; + assert.deepStrictEqual(dependsOn(body), [ + cross("acme/widgets", 7), + cross("my-org/some.repo_x", 42), + ]); +}); + +it("depends on reads both kinds in order and once", () => { + const body = "## Depends on\n#3 and acme/widgets#7 and #3 again, #9\n"; + assert.deepStrictEqual(dependsOn(body), [same(3), cross("acme/widgets", 7), same(9)]); +}); + +it("depends on does not count the number of a cross repo reference twice", () => { + assert.deepStrictEqual(dependsOn("## Depends on\nacme/widgets#7\n"), [cross("acme/widgets", 7)]); +}); + +it("depends on none or empty or missing names nothing", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n\nNone\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\nnone.\n## Next\n#4\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\n"), []); + assert.deepStrictEqual(dependsOn("## Depends on\n\n## Fix\n#4\n"), []); + assert.deepStrictEqual(dependsOn("## Cause\nSee #4\n"), []); + assert.deepStrictEqual(dependsOn(""), []); +}); + +it("depends on ignores text after the next heading", () => { + const body = "## Depends on\n#13\n### Notes\n#99\n## Fix\nacme/widgets#98\n"; + assert.deepStrictEqual(dependsOn(body), [same(13)]); +}); + +it("depends on ignores references before the section", () => { + assert.deepStrictEqual(dependsOn("## Cause\nSee #5\n\n## Depends on\n#13\n"), [same(13)]); +}); + +it("depends on heading is case insensitive and allows trailing spaces", () => { + assert.deepStrictEqual(dependsOn("## depends ON \r\n#13\r\n"), [same(13)]); +}); + +it("depends on needs digits after the hash", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n#abc # 4 #\n"), []); +}); + +it("depends on skips a hash that word characters run into", () => { + assert.deepStrictEqual(dependsOn("## Depends on\nsee page#12 and /widgets#7, then #3\n"), [ + same(3), + ]); +}); + +it("depends on ends at a heading line with nothing after the hashes", () => { + assert.deepStrictEqual(dependsOn("## Depends on\n#3\n##\n#4\n"), [same(3)]); +}); + +it("depends on heading needs two hashes and a space", () => { + assert.deepStrictEqual(dependsOn("##Depends on\n#3\n"), []); + assert.deepStrictEqual(dependsOn("### Depends on\n#3\n"), []); + assert.deepStrictEqual(dependsOn("# Depends on\n#3\n"), []); +}); diff --git a/apps/server/src/factory/domain/dependsOn.ts b/apps/server/src/factory/domain/dependsOn.ts new file mode 100644 index 0000000000000..def08dc340477 --- /dev/null +++ b/apps/server/src/factory/domain/dependsOn.ts @@ -0,0 +1,76 @@ +/** The `## Depends on` section of an issue body: pure text parsing, no `gh` call. */ + +/** An issue named in the `## Depends on` section of an issue body. */ +export interface IssueRef { + /** `owner/name` when the text names a repo; null means the repo of the issue it was written in. */ + readonly repo: string | null; + readonly number: number; +} + +const isRepoChar = (char: string): boolean => /^[A-Za-z0-9._-]$/.test(char); +const isDigit = (char: string): boolean => char >= "0" && char <= "9"; + +/** The lines of a text as Rust's `lines()` gives them: split on `\n`, one `\r` before it dropped. */ +const textLines = (text: string): Array => { + const lines = text.split("\n"); + if (lines[lines.length - 1] === "") lines.pop(); + return lines.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)); +}; + +/** A markdown heading: `#`s then a space, a tab or the end of the line. `#13` is a reference. */ +const isHeading = (line: string): boolean => { + const rest = line.replace(/^#+/, ""); + return rest.length < line.length && (rest === "" || rest[0] === " " || rest[0] === "\t"); +}; + +/** The lines of the `## Depends on` section: after its heading, up to the next heading line. */ +const dependsOnLines = (body: string): Array => { + const lines: Array = []; + let inSection = false; + for (const line of textLines(body)) { + if (inSection) { + if (isHeading(line)) break; + lines.push(line); + } else { + inSection = + line.startsWith("## ") || line.startsWith("##\t") + ? line.slice(3).trim().toLowerCase() === "depends on" + : false; + } + } + return lines; +}; + +/** + * The issues named in the `## Depends on` section of an issue body, in order of first + * appearance, each once. The section runs from its heading to the next heading line. It names + * `#` and `/#`; "None", an empty section and no section name nothing. + */ +export const dependsOn = (body: string): Array => { + const found: Array = []; + for (const line of dependsOnLines(body)) { + for (let at = 0; at < line.length; at++) { + if (line[at] !== "#") continue; + let end = at + 1; + while (end < line.length && isDigit(line[end]!)) end++; + const number = Number(line.slice(at + 1, end)); + if (end === at + 1 || !Number.isSafeInteger(number)) continue; + let repoStart = at; + while (repoStart > 0 && isRepoChar(line[repoStart - 1]!)) repoStart--; + let repo: string | null = null; + if (repoStart < at && repoStart > 0 && line[repoStart - 1] === "/") { + let ownerStart = repoStart - 1; + while (ownerStart > 0 && isRepoChar(line[ownerStart - 1]!)) ownerStart--; + if (ownerStart === repoStart - 1) continue; + repo = line.slice(ownerStart, at); + } else if (repoStart < at) { + // Word characters run straight into the `#`, as in `page#12`: not an issue. + continue; + } + if (!found.some((issue) => issue.repo === repo && issue.number === number)) { + found.push({ repo, number }); + } + } + } + return found; +}; diff --git a/apps/server/src/factory/tracker/approvalHistory.test.ts b/apps/server/src/factory/tracker/approvalHistory.test.ts new file mode 100644 index 0000000000000..145c7f8207f6f --- /dev/null +++ b/apps/server/src/factory/tracker/approvalHistory.test.ts @@ -0,0 +1,49 @@ +import { assert, it } from "@effect/vitest"; + +import { APPROVAL_QUERY, isUtcSecond } from "./approvalHistory.ts"; + +it("the approval query asks for label events and the edit history", () => { + for (const part of [ + "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100)", + "totalCount", + "... on LabeledEvent { createdAt actor { __typename login } label { name } }", + "... on UnlabeledEvent { createdAt actor { __typename login } label { name } }", + "... on RenamedTitleEvent { createdAt actor { __typename login } }", + "lastEditedAt", + "editor { __typename login }", + "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } }", + "$owner", + "$name", + "$number", + ]) { + assert.include(APPROVAL_QUERY, part); + } + assert.notInclude(APPROVAL_QUERY, "comments"); + // Titles are attacker-influenced text and are never asked for. + assert.notInclude(APPROVAL_QUERY, "Title {"); + assert.notInclude(APPROVAL_QUERY, "currentTitle"); + assert.notInclude(APPROVAL_QUERY, "previousTitle"); +}); + +it("the approval query is softfac's, byte for byte", () => { + assert.strictEqual( + APPROVAL_QUERY, + "query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { totalCount nodes { __typename ... on LabeledEvent { createdAt actor { __typename login } label { name } } ... on UnlabeledEvent { createdAt actor { __typename login } label { name } } ... on RenamedTitleEvent { createdAt actor { __typename login } } } } lastEditedAt editor { __typename login } userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }", + ); +}); + +it("a UTC second is exactly YYYY-MM-DDTHH:MM:SSZ", () => { + assert.isTrue(isUtcSecond("2026-10-04T10:00:00Z")); + for (const text of [ + "", + "2026-10-04 10:00:00Z", + "2026-10-04T10:00:00", + "2026-10-04T10:00:00.5Z", + "2026-10-04T10:00:00+10:00", + " 2026-10-04T10:00:00Z", + "2026-10-04T10:00:00Z\n", + "2026-1a-04T10:00:00Z", + ]) { + assert.isFalse(isUtcSecond(text), JSON.stringify(text)); + } +}); diff --git a/apps/server/src/factory/tracker/approvalHistory.ts b/apps/server/src/factory/tracker/approvalHistory.ts new file mode 100644 index 0000000000000..7c96cd76c63d0 --- /dev/null +++ b/apps/server/src/factory/tracker/approvalHistory.ts @@ -0,0 +1,153 @@ +import * as Schema from "effect/Schema"; + +import type { TextCheck } from "../domain/approval.ts"; + +/** + * The pure half of the approval rule: the shape of GitHub's answer about an issue's label + * events and edit history, and the judgement over it. It makes no `gh` call. + */ + +const OptionalText = Schema.optional(Schema.NullOr(Schema.String)); + +/** How many label events and body edits the approval query asks for. A history this long may be cut off. */ +export const HISTORY_PAGE = 100; + +/** GitHub's uniform UTC form, so ordering the text orders the times. */ +export const isUtcSecond = (text: string): boolean => + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(text); + +/** + * Who applied the issue's labels, who renamed it and who edited its body. `last: 100` of the + * timeline items is the newest 100 (GitHub lists them oldest first), and + * `userContentEdits(first: 100)` is the newest 100 edits (it lists newest first). Titles are + * not asked for. `__typename` on an actor tells a person from a GitHub App. + */ +export const APPROVAL_QUERY = + "query($owner: String!, $name: String!, $number: Int!) { " + + "repository(owner: $owner, name: $name) { issue(number: $number) { " + + "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { " + + "totalCount nodes { " + + "__typename " + + "... on LabeledEvent { createdAt actor { __typename login } label { name } } " + + "... on UnlabeledEvent { createdAt actor { __typename login } label { name } } " + + "... on RenamedTitleEvent { createdAt actor { __typename login } } } } " + + "lastEditedAt editor { __typename login } " + + "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }"; + +/** `typename` is only there when the query asked for it; a rule that wants a person needs a `User`. */ +export const Actor = Schema.Struct({ + __typename: OptionalText, + login: Schema.String, +}); +export type Actor = typeof Actor.Type; + +const LabelChange = Schema.Struct({ + createdAt: Schema.String, + actor: Schema.optional(Schema.NullOr(Actor)), + label: Schema.Struct({ name: Schema.String }), +}); + +/** One label event or title rename; a node of any other type is an answer this module cannot read. */ +export const TimelineNode = Schema.Union([ + Schema.Struct({ __typename: Schema.Literal("LabeledEvent"), ...LabelChange.fields }), + Schema.Struct({ __typename: Schema.Literal("UnlabeledEvent"), ...LabelChange.fields }), + Schema.Struct({ + __typename: Schema.Literal("RenamedTitleEvent"), + createdAt: Schema.String, + actor: Schema.optional(Schema.NullOr(Actor)), + }), +]); +export type TimelineNode = typeof TimelineNode.Type; + +export const ApprovalAnswer = Schema.Struct({ + data: Schema.Struct({ + repository: Schema.Struct({ + issue: Schema.Struct({ + timelineItems: Schema.Struct({ + totalCount: Schema.Number, + nodes: Schema.Array(TimelineNode), + }), + lastEditedAt: OptionalText, + editor: Schema.optional(Schema.NullOr(Actor)), + userContentEdits: Schema.Struct({ + totalCount: Schema.Number, + nodes: Schema.Array( + Schema.Struct({ + editedAt: Schema.String, + editor: Schema.optional(Schema.NullOr(Actor)), + }), + ), + }), + }), + }), + }), +}); +export type ApprovalIssue = (typeof ApprovalAnswer.Type)["data"]["repository"]["issue"]; + +const asciiLower = (text: string): string => text.replace(/[A-Z]/g, (char) => char.toLowerCase()); + +/** + * An instructor who is a person: GitHub says the actor is a `User`. A GitHub App's GraphQL login + * can lack the `[bot]` suffix, so a login that matches an instructor is not enough. + */ +export const isHumanInstructor = ( + actor: Actor | null | undefined, + instructors: ReadonlyArray, +): boolean => + actor !== null && + actor !== undefined && + actor.__typename === "User" && + instructors.some((name) => asciiLower(name) === asciiLower(actor.login)); + +/** Whether the timeline page shows every event at or after `since`: not cut off, or its oldest is before `since`. */ +export const timelineReaches = (issue: ApprovalIssue, since: string): boolean => { + const { totalCount, nodes } = issue.timelineItems; + const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; + return !cutOff || (nodes[0] !== undefined && nodes[0].createdAt < since); +}; + +/** Whether the newest history entry is the last edit, by the last editor. */ +const newestIsLastEdit = (issue: ApprovalIssue): boolean => { + if (issue.lastEditedAt === null || issue.lastEditedAt === undefined) return true; + const newest = issue.userContentEdits.nodes[0]; + return ( + newest !== undefined && + newest.editedAt === issue.lastEditedAt && + (newest.editor?.login ?? null) === (issue.editor?.login ?? null) + ); +}; + +/** + * Whether the body's edit history can be trusted for every edit at or after `since`: the entries + * come newest first, so when it is cut off the oldest one shown must be before `since`. + */ +const editsWholeSince = (issue: ApprovalIssue, since: string): boolean => { + const { totalCount, nodes } = issue.userContentEdits; + const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; + const reachesBack = !cutOff || (nodes.length > 0 && nodes[nodes.length - 1]!.editedAt < since); + return reachesBack && newestIsLastEdit(issue); +}; + +/** + * Judges every body edit and title rename with time at or after `since`. A moment in the same + * second counts as after, because timestamps have no finer order. `reaches` says the renames on + * the timeline page cover everything at or after `since`. + */ +export const textChangesSince = ( + issue: ApprovalIssue, + since: string, + instructors: ReadonlyArray, + reaches: boolean, +): TextCheck => { + const editByStranger = issue.userContentEdits.nodes.some( + (edit) => edit.editedAt >= since && !isHumanInstructor(edit.editor, instructors), + ); + const renameByStranger = issue.timelineItems.nodes.some( + (event) => + event.__typename === "RenamedTitleEvent" && + event.createdAt >= since && + !isHumanInstructor(event.actor, instructors), + ); + if (editByStranger || renameByStranger) return "changed"; + return editsWholeSince(issue, since) && reaches ? "unchanged" : "unjudged"; +}; diff --git a/apps/server/src/factory/tracker/github.test.ts b/apps/server/src/factory/tracker/github.test.ts index ac01995ed8243..dd3ae6031bbe4 100644 --- a/apps/server/src/factory/tracker/github.test.ts +++ b/apps/server/src/factory/tracker/github.test.ts @@ -5,8 +5,8 @@ import * as Layer from "effect/Layer"; import { PROJECT_CONFIG_PATH } from "../config.ts"; import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; import { FactoryProcess, type RunInput, type RunResult, RunSpawnError } from "../process.ts"; +import { APPROVAL_QUERY } from "./approvalHistory.ts"; import { - APPROVAL_QUERY, GitHubFailed, GitHubInvalidArgument, GitHubOutputTooLarge, @@ -20,10 +20,7 @@ import { STATUS_MARKER, type Blocker, type GitHubError, - type IssueRef, - dependsOn, isNotFound, - isUtcSecond, makeGitHub, } from "./github.ts"; @@ -2098,75 +2095,6 @@ it.effect("an open blocker whose repo is unknown is an error, not a guess", () = }), ); -// ---- the Depends on section ---- - -const same = (number: number): IssueRef => ({ repo: null, number }); -const cross = (repo: string, number: number): IssueRef => ({ repo, number }); - -it("depends on reads same repo references", () => { - const body = "Intro\n\n## Depends on\n\n- #13\n- #15 until it lands\n"; - assert.deepStrictEqual(dependsOn(body), [same(13), same(15)]); -}); - -it("depends on reads cross repo references", () => { - const body = "## Depends on\nacme/widgets#7, my-org/some.repo_x#42\n"; - assert.deepStrictEqual(dependsOn(body), [ - cross("acme/widgets", 7), - cross("my-org/some.repo_x", 42), - ]); -}); - -it("depends on reads both kinds in order and once", () => { - const body = "## Depends on\n#3 and acme/widgets#7 and #3 again, #9\n"; - assert.deepStrictEqual(dependsOn(body), [same(3), cross("acme/widgets", 7), same(9)]); -}); - -it("depends on does not count the number of a cross repo reference twice", () => { - assert.deepStrictEqual(dependsOn("## Depends on\nacme/widgets#7\n"), [cross("acme/widgets", 7)]); -}); - -it("depends on none or empty or missing names nothing", () => { - assert.deepStrictEqual(dependsOn("## Depends on\n\nNone\n"), []); - assert.deepStrictEqual(dependsOn("## Depends on\nnone.\n## Next\n#4\n"), []); - assert.deepStrictEqual(dependsOn("## Depends on\n"), []); - assert.deepStrictEqual(dependsOn("## Depends on\n\n## Fix\n#4\n"), []); - assert.deepStrictEqual(dependsOn("## Cause\nSee #4\n"), []); - assert.deepStrictEqual(dependsOn(""), []); -}); - -it("depends on ignores text after the next heading", () => { - const body = "## Depends on\n#13\n### Notes\n#99\n## Fix\nacme/widgets#98\n"; - assert.deepStrictEqual(dependsOn(body), [same(13)]); -}); - -it("depends on ignores references before the section", () => { - assert.deepStrictEqual(dependsOn("## Cause\nSee #5\n\n## Depends on\n#13\n"), [same(13)]); -}); - -it("depends on heading is case insensitive and allows trailing spaces", () => { - assert.deepStrictEqual(dependsOn("## depends ON \r\n#13\r\n"), [same(13)]); -}); - -it("depends on needs digits after the hash", () => { - assert.deepStrictEqual(dependsOn("## Depends on\n#abc # 4 #\n"), []); -}); - -it("depends on skips a hash that word characters run into", () => { - assert.deepStrictEqual(dependsOn("## Depends on\nsee page#12 and /widgets#7, then #3\n"), [ - same(3), - ]); -}); - -it("depends on ends at a heading line with nothing after the hashes", () => { - assert.deepStrictEqual(dependsOn("## Depends on\n#3\n##\n#4\n"), [same(3)]); -}); - -it("depends on heading needs two hashes and a space", () => { - assert.deepStrictEqual(dependsOn("##Depends on\n#3\n"), []); - assert.deepStrictEqual(dependsOn("### Depends on\n#3\n"), []); - assert.deepStrictEqual(dependsOn("# Depends on\n#3\n"), []); -}); - // ---- text blockers ---- const bodyCall = (issue: string) => ["issue", "view", issue, "--repo", REPO, "--json", "body"]; @@ -2371,36 +2299,6 @@ it.effect("approval reads the real shapes and sends one call", () => }), ); -it("the approval query asks for label events and the edit history", () => { - for (const part of [ - "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100)", - "totalCount", - "... on LabeledEvent { createdAt actor { __typename login } label { name } }", - "... on UnlabeledEvent { createdAt actor { __typename login } label { name } }", - "... on RenamedTitleEvent { createdAt actor { __typename login } }", - "lastEditedAt", - "editor { __typename login }", - "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } }", - "$owner", - "$name", - "$number", - ]) { - assert.include(APPROVAL_QUERY, part); - } - assert.notInclude(APPROVAL_QUERY, "comments"); - // Titles are attacker-influenced text and are never asked for. - assert.notInclude(APPROVAL_QUERY, "Title {"); - assert.notInclude(APPROVAL_QUERY, "currentTitle"); - assert.notInclude(APPROVAL_QUERY, "previousTitle"); -}); - -it("the approval query is softfac's, byte for byte", () => { - assert.strictEqual( - APPROVAL_QUERY, - "query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { totalCount nodes { __typename ... on LabeledEvent { createdAt actor { __typename login } label { name } } ... on UnlabeledEvent { createdAt actor { __typename login } label { name } } ... on RenamedTitleEvent { createdAt actor { __typename login } } } } lastEditedAt editor { __typename login } userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }", - ); -}); - it.effect("an outside author's unedited report labelled by an instructor is approved", () => Effect.gen(function* () { // The creation entry is by the author, before the label, and is ignored. @@ -2893,22 +2791,6 @@ it.effect("a malformed timestamp is a parse error", () => }), ); -it("a UTC second is exactly YYYY-MM-DDTHH:MM:SSZ", () => { - assert.isTrue(isUtcSecond("2026-10-04T10:00:00Z")); - for (const text of [ - "", - "2026-10-04 10:00:00Z", - "2026-10-04T10:00:00", - "2026-10-04T10:00:00.5Z", - "2026-10-04T10:00:00+10:00", - " 2026-10-04T10:00:00Z", - "2026-10-04T10:00:00Z\n", - "2026-1a-04T10:00:00Z", - ]) { - assert.isFalse(isUtcSecond(text), JSON.stringify(text)); - } -}); - it.effect("approval failures from gh are errors with the call", () => Effect.gen(function* () { const failed = setup(fail(1, "HTTP 502")); diff --git a/apps/server/src/factory/tracker/github.ts b/apps/server/src/factory/tracker/github.ts index 5c3e3c40ed642..472a487a016e8 100644 --- a/apps/server/src/factory/tracker/github.ts +++ b/apps/server/src/factory/tracker/github.ts @@ -3,6 +3,7 @@ import * as Schema from "effect/Schema"; import { PROJECT_CONFIG_PATH } from "../config.ts"; import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; +import { dependsOn } from "../domain/dependsOn.ts"; import { STATES, stateColor, @@ -12,6 +13,17 @@ import { type State, } from "../domain/lifecycle.ts"; import { FactoryProcess } from "../process.ts"; +import { + APPROVAL_QUERY, + ApprovalAnswer, + HISTORY_PAGE, + isHumanInstructor, + isUtcSecond, + textChangesSince, + timelineReaches, + type ApprovalIssue, + type TimelineNode, +} from "./approvalHistory.ts"; export type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; @@ -442,13 +454,6 @@ const withMarker = (body: string, marker: string): string => `${body}\n\n${marke // ---- the Depends on section ---- -/** An issue named in the `## Depends on` section of an issue body. */ -export interface IssueRef { - /** `owner/name` when the text names a repo; null means the repo of the issue it was written in. */ - readonly repo: string | null; - readonly number: number; -} - /** An open issue that blocks another one. */ export interface Blocker { /** `owner/name` of the repo the blocking issue is in. */ @@ -456,219 +461,6 @@ export interface Blocker { readonly number: number; } -const isRepoChar = (char: string): boolean => /^[A-Za-z0-9._-]$/.test(char); -const isDigit = (char: string): boolean => char >= "0" && char <= "9"; - -/** The lines of a text as Rust's `lines()` gives them: split on `\n`, one `\r` before it dropped. */ -const textLines = (text: string): Array => { - const lines = text.split("\n"); - if (lines[lines.length - 1] === "") lines.pop(); - return lines.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line)); -}; - -/** A markdown heading: `#`s then a space, a tab or the end of the line. `#13` is a reference. */ -const isHeading = (line: string): boolean => { - const rest = line.replace(/^#+/, ""); - return rest.length < line.length && (rest === "" || rest[0] === " " || rest[0] === "\t"); -}; - -/** The lines of the `## Depends on` section: after its heading, up to the next heading line. */ -const dependsOnLines = (body: string): Array => { - const lines: Array = []; - let inSection = false; - for (const line of textLines(body)) { - if (inSection) { - if (isHeading(line)) break; - lines.push(line); - } else { - inSection = - line.startsWith("## ") || line.startsWith("##\t") - ? line.slice(3).trim().toLowerCase() === "depends on" - : false; - } - } - return lines; -}; - -/** - * The issues named in the `## Depends on` section of an issue body, in order of first - * appearance, each once. The section runs from its heading to the next heading line. It names - * `#` and `/#`; "None", an empty section and no section name nothing. - */ -export const dependsOn = (body: string): Array => { - const found: Array = []; - for (const line of dependsOnLines(body)) { - for (let at = 0; at < line.length; at++) { - if (line[at] !== "#") continue; - let end = at + 1; - while (end < line.length && isDigit(line[end]!)) end++; - const number = Number(line.slice(at + 1, end)); - if (end === at + 1 || !Number.isSafeInteger(number)) continue; - let repoStart = at; - while (repoStart > 0 && isRepoChar(line[repoStart - 1]!)) repoStart--; - let repo: string | null = null; - if (repoStart < at && repoStart > 0 && line[repoStart - 1] === "/") { - let ownerStart = repoStart - 1; - while (ownerStart > 0 && isRepoChar(line[ownerStart - 1]!)) ownerStart--; - if (ownerStart === repoStart - 1) continue; - repo = line.slice(ownerStart, at); - } else if (repoStart < at) { - // Word characters run straight into the `#`, as in `page#12`: not an issue. - continue; - } - if (!found.some((issue) => issue.repo === repo && issue.number === number)) { - found.push({ repo, number }); - } - } - } - return found; -}; - -// ---- the approval rule's reading of GitHub's history ---- - -/** How many label events and body edits the approval query asks for. A history this long may be cut off. */ -const HISTORY_PAGE = 100; - -/** GitHub's uniform UTC form, so ordering the text orders the times. */ -export const isUtcSecond = (text: string): boolean => - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(text); - -/** - * Who applied the issue's labels, who renamed it and who edited its body. `last: 100` of the - * timeline items is the newest 100 (GitHub lists them oldest first), and - * `userContentEdits(first: 100)` is the newest 100 edits (it lists newest first). Titles are - * not asked for. `__typename` on an actor tells a person from a GitHub App. - */ -export const APPROVAL_QUERY = - "query($owner: String!, $name: String!, $number: Int!) { " + - "repository(owner: $owner, name: $name) { issue(number: $number) { " + - "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { " + - "totalCount nodes { " + - "__typename " + - "... on LabeledEvent { createdAt actor { __typename login } label { name } } " + - "... on UnlabeledEvent { createdAt actor { __typename login } label { name } } " + - "... on RenamedTitleEvent { createdAt actor { __typename login } } } } " + - "lastEditedAt editor { __typename login } " + - "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }"; - -/** `typename` is only there when the query asked for it; a rule that wants a person needs a `User`. */ -const Actor = Schema.Struct({ - __typename: OptionalText, - login: Schema.String, -}); -type Actor = typeof Actor.Type; - -const LabelChange = Schema.Struct({ - createdAt: Schema.String, - actor: Schema.optional(Schema.NullOr(Actor)), - label: Schema.Struct({ name: Schema.String }), -}); - -/** One label event or title rename; a node of any other type is an answer this module cannot read. */ -const TimelineNode = Schema.Union([ - Schema.Struct({ __typename: Schema.Literal("LabeledEvent"), ...LabelChange.fields }), - Schema.Struct({ __typename: Schema.Literal("UnlabeledEvent"), ...LabelChange.fields }), - Schema.Struct({ - __typename: Schema.Literal("RenamedTitleEvent"), - createdAt: Schema.String, - actor: Schema.optional(Schema.NullOr(Actor)), - }), -]); -type TimelineNode = typeof TimelineNode.Type; - -const ApprovalAnswer = Schema.Struct({ - data: Schema.Struct({ - repository: Schema.Struct({ - issue: Schema.Struct({ - timelineItems: Schema.Struct({ - totalCount: Schema.Number, - nodes: Schema.Array(TimelineNode), - }), - lastEditedAt: OptionalText, - editor: Schema.optional(Schema.NullOr(Actor)), - userContentEdits: Schema.Struct({ - totalCount: Schema.Number, - nodes: Schema.Array( - Schema.Struct({ - editedAt: Schema.String, - editor: Schema.optional(Schema.NullOr(Actor)), - }), - ), - }), - }), - }), - }), -}); -type ApprovalIssue = (typeof ApprovalAnswer.Type)["data"]["repository"]["issue"]; - -const asciiLower = (text: string): string => text.replace(/[A-Z]/g, (char) => char.toLowerCase()); - -/** - * An instructor who is a person: GitHub says the actor is a `User`. A GitHub App's GraphQL login - * can lack the `[bot]` suffix, so a login that matches an instructor is not enough. - */ -const isHumanInstructor = ( - actor: Actor | null | undefined, - instructors: ReadonlyArray, -): boolean => - actor !== null && - actor !== undefined && - actor.__typename === "User" && - instructors.some((name) => asciiLower(name) === asciiLower(actor.login)); - -/** Whether the timeline page shows every event at or after `since`: not cut off, or its oldest is before `since`. */ -const timelineReaches = (issue: ApprovalIssue, since: string): boolean => { - const { totalCount, nodes } = issue.timelineItems; - const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; - return !cutOff || (nodes[0] !== undefined && nodes[0].createdAt < since); -}; - -/** Whether the newest history entry is the last edit, by the last editor. */ -const newestIsLastEdit = (issue: ApprovalIssue): boolean => { - if (issue.lastEditedAt === null || issue.lastEditedAt === undefined) return true; - const newest = issue.userContentEdits.nodes[0]; - return ( - newest !== undefined && - newest.editedAt === issue.lastEditedAt && - (newest.editor?.login ?? null) === (issue.editor?.login ?? null) - ); -}; - -/** - * Whether the body's edit history can be trusted for every edit at or after `since`: the entries - * come newest first, so when it is cut off the oldest one shown must be before `since`. - */ -const editsWholeSince = (issue: ApprovalIssue, since: string): boolean => { - const { totalCount, nodes } = issue.userContentEdits; - const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; - const reachesBack = !cutOff || (nodes.length > 0 && nodes[nodes.length - 1]!.editedAt < since); - return reachesBack && newestIsLastEdit(issue); -}; - -/** - * Judges every body edit and title rename with time at or after `since`. A moment in the same - * second counts as after, because timestamps have no finer order. `reaches` says the renames on - * the timeline page cover everything at or after `since`. - */ -const textChangesSince = ( - issue: ApprovalIssue, - since: string, - instructors: ReadonlyArray, - reaches: boolean, -): TextCheck => { - const editByStranger = issue.userContentEdits.nodes.some( - (edit) => edit.editedAt >= since && !isHumanInstructor(edit.editor, instructors), - ); - const renameByStranger = issue.timelineItems.nodes.some( - (event) => - event.__typename === "RenamedTitleEvent" && - event.createdAt >= since && - !isHumanInstructor(event.actor, instructors), - ); - if (editByStranger || renameByStranger) return "changed"; - return editsWholeSince(issue, since) && reaches ? "unchanged" : "unjudged"; -}; - // ---- the client ---- export interface GitHubOptions { From f96097b2e0865aaa6c23cf5145b509060a8addf4 Mon Sep 17 00:00:00 2001 From: Tom Kaczocha Date: Fri, 16 Oct 2026 07:39:04 +1000 Subject: [PATCH 4/5] test(factory): a blocker in a state other than the exact `closed` still blocks Issue: #13 Pins the rule testing-1 found untested: openBlockers resolves a row only on REST's exact lowercase `closed`, as softfac does. Passes at this tip. --- .../server/src/factory/tracker/github.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/apps/server/src/factory/tracker/github.test.ts b/apps/server/src/factory/tracker/github.test.ts index dd3ae6031bbe4..2304b1834ea68 100644 --- a/apps/server/src/factory/tracker/github.test.ts +++ b/apps/server/src/factory/tracker/github.test.ts @@ -2038,6 +2038,25 @@ it.effect("a closed blocker is resolved whatever closed it", () => }), ); +it.effect( + "only the exact REST state `closed` resolves a blocker; any other state still blocks", + () => + Effect.gen(function* () { + // The dependency listing's state is REST's lowercase `open` or `closed`. A state the + // factory does not know, or one in another case, is not taken as resolved: the issue + // waits rather than starting on a guess. + const t = setup( + reply( + `[${blockerRow(13, "unknown", "rawphp/softfac")},${blockerRow(12, "CLOSED", "rawphp/softfac")},${blockerRow(11, "closed", "rawphp/softfac")}]`, + ), + ); + assert.deepStrictEqual(yield* t.ok(t.github.openBlockers(14)), [ + openBlocker(13, "rawphp/softfac"), + openBlocker(12, "rawphp/softfac"), + ]); + }), +); + it.effect("open blockers keep the repo they are in", () => Effect.gen(function* () { const t = setup( From fcd513ae8a72224a2b48a6839d5ee5bd352b23ab Mon Sep 17 00:00:00 2001 From: Tom Kaczocha Date: Fri, 16 Oct 2026 08:42:22 +1000 Subject: [PATCH 5/5] fix(factory): bound and tighten the Depends on reads, and judge approval in pure code - textBlockers resolves a named issue only on the exact REST state `closed`, as openBlockers does. - textBlockers refuses a Depends on section naming more than MAX_DEPENDS_ON (100) issues before reading any of them, so an issue body cannot fan out into thousands of gh calls. - dependsOn skips an owner or repo made only of dots, which would step out of the API path. - The approval judgement and textEditedSince's decision move into pure judgeApproval and editedSince in approvalHistory.ts, with unit tests; github.ts only reads the history. - The approval query's page sizes come from HISTORY_PAGE, and the two cut-off checks share isCutOff. --- .../src/factory/domain/dependsOn.test.ts | 11 ++ apps/server/src/factory/domain/dependsOn.ts | 7 +- .../factory/tracker/approvalHistory.test.ts | 139 +++++++++++++++++- .../src/factory/tracker/approvalHistory.ts | 87 +++++++++-- .../server/src/factory/tracker/github.test.ts | 35 +++++ apps/server/src/factory/tracker/github.ts | 106 ++++--------- 6 files changed, 299 insertions(+), 86 deletions(-) diff --git a/apps/server/src/factory/domain/dependsOn.test.ts b/apps/server/src/factory/domain/dependsOn.test.ts index 8bd3395a2bd5c..c8a6d31968897 100644 --- a/apps/server/src/factory/domain/dependsOn.test.ts +++ b/apps/server/src/factory/domain/dependsOn.test.ts @@ -68,3 +68,14 @@ it("depends on heading needs two hashes and a space", () => { assert.deepStrictEqual(dependsOn("### Depends on\n#3\n"), []); assert.deepStrictEqual(dependsOn("# Depends on\n#3\n"), []); }); + +it("depends on skips an owner or repo made only of dots, which would leave the API path", () => { + assert.deepStrictEqual( + dependsOn("## Depends on\n../..#3 ./widgets#4 acme/..#5 acme/.#6 ...//x#8\n"), + [], + ); + assert.deepStrictEqual(dependsOn("## Depends on\nacme/.github#7 a.b/c..d#9\n"), [ + cross("acme/.github", 7), + cross("a.b/c..d", 9), + ]); +}); diff --git a/apps/server/src/factory/domain/dependsOn.ts b/apps/server/src/factory/domain/dependsOn.ts index def08dc340477..8ce5c3b8eb9d6 100644 --- a/apps/server/src/factory/domain/dependsOn.ts +++ b/apps/server/src/factory/domain/dependsOn.ts @@ -9,6 +9,7 @@ export interface IssueRef { const isRepoChar = (char: string): boolean => /^[A-Za-z0-9._-]$/.test(char); const isDigit = (char: string): boolean => char >= "0" && char <= "9"; +const isDots = (segment: string): boolean => /^\.+$/.test(segment); /** The lines of a text as Rust's `lines()` gives them: split on `\n`, one `\r` before it dropped. */ const textLines = (text: string): Array => { @@ -62,7 +63,11 @@ export const dependsOn = (body: string): Array => { let ownerStart = repoStart - 1; while (ownerStart > 0 && isRepoChar(line[ownerStart - 1]!)) ownerStart--; if (ownerStart === repoStart - 1) continue; - repo = line.slice(ownerStart, at); + const owner = line.slice(ownerStart, repoStart - 1); + const name = line.slice(repoStart, at); + // `.` and `..` would step out of `repos//` in the API path: not a repo. + if (isDots(owner) || isDots(name)) continue; + repo = `${owner}/${name}`; } else if (repoStart < at) { // Word characters run straight into the `#`, as in `page#12`: not an issue. continue; diff --git a/apps/server/src/factory/tracker/approvalHistory.test.ts b/apps/server/src/factory/tracker/approvalHistory.test.ts index 145c7f8207f6f..2a340394ca7e2 100644 --- a/apps/server/src/factory/tracker/approvalHistory.test.ts +++ b/apps/server/src/factory/tracker/approvalHistory.test.ts @@ -1,6 +1,16 @@ import { assert, it } from "@effect/vitest"; -import { APPROVAL_QUERY, isUtcSecond } from "./approvalHistory.ts"; +import type { Approval } from "../domain/approval.ts"; + +import { + APPROVAL_QUERY, + type ApprovalIssue, + editedSince, + HISTORY_PAGE, + isUtcSecond, + judgeApproval, + type TimelineNode, +} from "./approvalHistory.ts"; it("the approval query asks for label events and the edit history", () => { for (const part of [ @@ -47,3 +57,130 @@ it("a UTC second is exactly YYYY-MM-DDTHH:MM:SSZ", () => { assert.isFalse(isUtcSecond(text), JSON.stringify(text)); } }); + +// ---- the judgement over an answer, with no gh call ---- + +const READY = "factory:ready"; +const BEFORE = "2026-10-04T09:00:00Z"; +const LABELED = "2026-10-04T10:00:00Z"; +const AFTER = "2026-10-04T10:30:00Z"; + +const user = (login: string) => ({ __typename: "User", login }); +const labeled = (at: string, login: string, name = READY): TimelineNode => ({ + __typename: "LabeledEvent", + createdAt: at, + actor: user(login), + label: { name }, +}); +const unlabeled = (at: string, login: string): TimelineNode => ({ + __typename: "UnlabeledEvent", + createdAt: at, + actor: user(login), + label: { name: READY }, +}); +const renamed = (at: string, login: string): TimelineNode => ({ + __typename: "RenamedTitleEvent", + createdAt: at, + actor: user(login), +}); + +/** An answer with these events (oldest first) and body edits (newest first), totals as given. */ +const issueOf = ( + events: ReadonlyArray, + edits: ReadonlyArray = [], + totals: { readonly events?: number; readonly edits?: number } = {}, +): ApprovalIssue => ({ + timelineItems: { totalCount: totals.events ?? events.length, nodes: events }, + lastEditedAt: edits[0]?.[0] ?? null, + editor: edits[0] === undefined ? null : user(edits[0][1]), + userContentEdits: { + totalCount: totals.edits ?? edits.length, + nodes: edits.map(([editedAt, login]) => ({ editedAt, editor: user(login) })), + }, +}); + +it("judgeApproval approves the label in force applied by an instructor", () => { + assert.deepStrictEqual(judgeApproval(issueOf([labeled(LABELED, "Tom")]), READY, ["tom"]), { + kind: "approved", + labeledAt: LABELED, + labeledBy: "Tom", + }); +}); + +it("judgeApproval finds no label when a later removal cancelled it or the name differs", () => { + const notFound: Approval = { kind: "refused", refusal: { kind: "label-not-found" } }; + const removed = issueOf([labeled(LABELED, "tom"), unlabeled(AFTER, "tom")]); + assert.deepStrictEqual(judgeApproval(removed, READY, ["tom"]), notFound); + const other = issueOf([labeled(LABELED, "tom", "Factory:Ready")]); + assert.deepStrictEqual(judgeApproval(other, READY, ["tom"]), notFound); +}); + +it("judgeApproval says a full page of a longer history without the label is incomplete", () => { + const page = Array.from({ length: HISTORY_PAGE }, () => renamed(BEFORE, "tom")); + assert.deepStrictEqual( + judgeApproval(issueOf(page, [], { events: HISTORY_PAGE + 1 }), READY, ["tom"]), + { kind: "refused", refusal: { kind: "label-history-incomplete" } }, + ); + assert.deepStrictEqual(judgeApproval(issueOf(page), READY, ["tom"]), { + kind: "refused", + refusal: { kind: "label-not-found" }, + }); +}); + +it("judgeApproval refuses a label applied by someone who is not an instructor", () => { + assert.deepStrictEqual(judgeApproval(issueOf([labeled(LABELED, "eve")]), READY, ["tom"]), { + kind: "refused", + refusal: { kind: "labeled-by-non-instructor", by: "eve", labeledAt: LABELED }, + }); + const bot: TimelineNode = { + __typename: "LabeledEvent", + createdAt: LABELED, + actor: { __typename: "Bot", login: "tom" }, + label: { name: READY }, + }; + assert.deepStrictEqual(judgeApproval(issueOf([bot]), READY, ["tom"]), { + kind: "refused", + refusal: { kind: "labeled-by-non-instructor", by: "tom", labeledAt: LABELED }, + }); + const deleted: TimelineNode = { ...bot, actor: null }; + assert.deepStrictEqual(judgeApproval(issueOf([deleted]), READY, ["tom"]), { + kind: "refused", + refusal: { kind: "labeled-by-non-instructor", by: null, labeledAt: LABELED }, + }); +}); + +it("judgeApproval refuses a stranger's edit or rename at or after the label, not before", () => { + const edited: Approval = { + kind: "refused", + refusal: { kind: "edited-after-label", labeledAt: LABELED }, + }; + const editAfter = issueOf([labeled(LABELED, "tom")], [[LABELED, "eve"]]); + assert.deepStrictEqual(judgeApproval(editAfter, READY, ["tom"]), edited); + const renameAfter = issueOf([labeled(LABELED, "tom"), renamed(AFTER, "eve")]); + assert.deepStrictEqual(judgeApproval(renameAfter, READY, ["tom"]), edited); + const before = issueOf([renamed(BEFORE, "eve"), labeled(LABELED, "tom")], [[BEFORE, "eve"]]); + assert.equal(judgeApproval(before, READY, ["tom"]).kind, "approved"); + const instructor = issueOf([labeled(LABELED, "tom"), renamed(AFTER, "tom")], [[AFTER, "tom"]]); + assert.equal(judgeApproval(instructor, READY, ["tom"]).kind, "approved"); +}); + +it("judgeApproval refuses an edit history cut off after the label", () => { + const edits = Array.from({ length: HISTORY_PAGE }, () => [AFTER, "tom"] as const); + assert.deepStrictEqual(judgeApproval(issueOf([labeled(LABELED, "tom")], edits), READY, ["tom"]), { + kind: "refused", + refusal: { kind: "edit-history-incomplete", labeledAt: LABELED }, + }); +}); + +it("editedSince counts anyone's edit or rename at or after the moment", () => { + assert.isFalse(editedSince(issueOf([renamed(BEFORE, "tom")], [[BEFORE, "tom"]]), LABELED)); + assert.isTrue(editedSince(issueOf([], [[LABELED, "tom"]]), LABELED)); + assert.isTrue(editedSince(issueOf([renamed(AFTER, "tom")]), LABELED)); +}); + +it("editedSince counts a timeline page that may hide a rename as a change", () => { + const page = Array.from({ length: HISTORY_PAGE }, () => labeled(AFTER, "tom", "other")); + assert.isTrue(editedSince(issueOf(page), LABELED)); + const reachesBack = [labeled(BEFORE, "tom", "other"), ...page.slice(1)]; + assert.isFalse(editedSince(issueOf(reachesBack), LABELED)); +}); diff --git a/apps/server/src/factory/tracker/approvalHistory.ts b/apps/server/src/factory/tracker/approvalHistory.ts index 7c96cd76c63d0..3c860e76bfafc 100644 --- a/apps/server/src/factory/tracker/approvalHistory.ts +++ b/apps/server/src/factory/tracker/approvalHistory.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -import type { TextCheck } from "../domain/approval.ts"; +import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; /** * The pure half of the approval rule: the shape of GitHub's answer about an issue's label @@ -25,14 +25,14 @@ export const isUtcSecond = (text: string): boolean => export const APPROVAL_QUERY = "query($owner: String!, $name: String!, $number: Int!) { " + "repository(owner: $owner, name: $name) { issue(number: $number) { " + - "timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: 100) { " + + `timelineItems(itemTypes: [LABELED_EVENT, UNLABELED_EVENT, RENAMED_TITLE_EVENT], last: ${HISTORY_PAGE}) { ` + "totalCount nodes { " + "__typename " + "... on LabeledEvent { createdAt actor { __typename login } label { name } } " + "... on UnlabeledEvent { createdAt actor { __typename login } label { name } } " + "... on RenamedTitleEvent { createdAt actor { __typename login } } } } " + "lastEditedAt editor { __typename login } " + - "userContentEdits(first: 100) { totalCount nodes { editedAt editor { __typename login } } } } } }"; + `userContentEdits(first: ${HISTORY_PAGE}) { totalCount nodes { editedAt editor { __typename login } } } } } }`; /** `typename` is only there when the query asked for it; a rule that wants a person needs a `User`. */ export const Actor = Schema.Struct({ @@ -99,11 +99,14 @@ export const isHumanInstructor = ( actor.__typename === "User" && instructors.some((name) => asciiLower(name) === asciiLower(actor.login)); +/** Whether a page may leave out older entries: it is full, or GitHub counts more than it holds. */ +const isCutOff = (page: { readonly totalCount: number; readonly nodes: ReadonlyArray }) => + page.nodes.length >= HISTORY_PAGE || page.totalCount > page.nodes.length; + /** Whether the timeline page shows every event at or after `since`: not cut off, or its oldest is before `since`. */ export const timelineReaches = (issue: ApprovalIssue, since: string): boolean => { - const { totalCount, nodes } = issue.timelineItems; - const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; - return !cutOff || (nodes[0] !== undefined && nodes[0].createdAt < since); + const { nodes } = issue.timelineItems; + return !isCutOff(issue.timelineItems) || (nodes[0] !== undefined && nodes[0].createdAt < since); }; /** Whether the newest history entry is the last edit, by the last editor. */ @@ -122,9 +125,10 @@ const newestIsLastEdit = (issue: ApprovalIssue): boolean => { * come newest first, so when it is cut off the oldest one shown must be before `since`. */ const editsWholeSince = (issue: ApprovalIssue, since: string): boolean => { - const { totalCount, nodes } = issue.userContentEdits; - const cutOff = nodes.length >= HISTORY_PAGE || totalCount > nodes.length; - const reachesBack = !cutOff || (nodes.length > 0 && nodes[nodes.length - 1]!.editedAt < since); + const { nodes } = issue.userContentEdits; + const reachesBack = + !isCutOff(issue.userContentEdits) || + (nodes.length > 0 && nodes[nodes.length - 1]!.editedAt < since); return reachesBack && newestIsLastEdit(issue); }; @@ -151,3 +155,68 @@ export const textChangesSince = ( if (editByStranger || renameByStranger) return "changed"; return editsWholeSince(issue, since) && reaches ? "unchanged" : "unjudged"; }; + +/** + * Whether the factory may build the issue: an instructor applied the `ready` label that is in + * force now, and every edit of the body and every rename of the title at or after that moment + * was an instructor's. + * + * The timeline events (label changes and renames, oldest first) are walked so that the walk + * keeps the last `ready` event that no later removal cancelled. Label names are matched + * exactly. Only the newest page of events is read; the one in force among them is enough, + * because every later event, a rename included, is on the page too. A full page of a longer + * history without it is `label-history-incomplete`. + * + * An edit or rename before the label's time is ignored: the instructor approved the text as it + * stood. One in the label's own second counts as after it. Timestamps are compared as strings. + * Only a `User` can be an instructor: a deleted account or a bot never is. + */ +export const judgeApproval = ( + issue: ApprovalIssue, + ready: string, + instructors: ReadonlyArray, +): Approval => { + let inForce: Extract | null = null; + for (const event of issue.timelineItems.nodes) { + if (event.__typename === "LabeledEvent" && event.label.name === ready) inForce = event; + else if (event.__typename === "UnlabeledEvent" && event.label.name === ready) inForce = null; + } + if (inForce === null) { + const { totalCount, nodes } = issue.timelineItems; + const cutOff = nodes.length >= HISTORY_PAGE && totalCount > HISTORY_PAGE; + const refusal: Refusal = { kind: cutOff ? "label-history-incomplete" : "label-not-found" }; + return { kind: "refused", refusal }; + } + const labeledAt = inForce.createdAt; + const actor = inForce.actor; + if (actor === null || actor === undefined || !isHumanInstructor(actor, instructors)) { + return { + kind: "refused", + refusal: { kind: "labeled-by-non-instructor", by: actor?.login ?? null, labeledAt }, + }; + } + // The label is on the page, so the renames at or after it are too. + switch (textChangesSince(issue, labeledAt, instructors, true)) { + case "changed": + return { kind: "refused", refusal: { kind: "edited-after-label", labeledAt } }; + case "unjudged": + return { kind: "refused", refusal: { kind: "edit-history-incomplete", labeledAt } }; + case "unchanged": + return { kind: "approved", labeledAt, labeledBy: actor.login }; + } +}; + +/** + * Whether anyone, an instructor included, edited the body or renamed the title at or after + * `since`. A timeline page that may hide a rename at or after the moment counts as a change. + */ +export const editedSince = (issue: ApprovalIssue, since: string): boolean => { + const edited = + issue.lastEditedAt !== null && issue.lastEditedAt !== undefined + ? issue.lastEditedAt >= since + : false; + const renamed = issue.timelineItems.nodes.some( + (event) => event.__typename === "RenamedTitleEvent" && event.createdAt >= since, + ); + return edited || renamed || !timelineReaches(issue, since); +}; diff --git a/apps/server/src/factory/tracker/github.test.ts b/apps/server/src/factory/tracker/github.test.ts index 2304b1834ea68..6d81c4406db9f 100644 --- a/apps/server/src/factory/tracker/github.test.ts +++ b/apps/server/src/factory/tracker/github.test.ts @@ -16,6 +16,7 @@ import { GitHubTimedOut, LIST_LIMIT, MARKER, + MAX_DEPENDS_ON, MAX_FILE_BYTES, STATUS_MARKER, type Blocker, @@ -2159,6 +2160,40 @@ it.effect("text blockers resolved once every named issue is closed", () => }), ); +it.effect("only the exact REST state `closed` resolves a named issue; any other still blocks", () => + Effect.gen(function* () { + // The same rule as the dependency listing: a state in another case is not taken as resolved. + const t = setup( + reply(bodyReply("## Depends on\n#13, #12, #11\n")), + reply('{"state":"CLOSED"}'), + reply('{"state":"unknown"}'), + reply('{"state":"closed"}'), + ); + assert.deepStrictEqual(yield* t.ok(t.github.textBlockers(14)), [ + openBlocker(13, REPO), + openBlocker(12, REPO), + ]); + }), +); + +it.effect("a Depends on section naming more than the cap is an error before any is read", () => + Effect.gen(function* () { + const refs = (count: number) => + Array.from({ length: count }, (_, at) => `#${at + 1}`).join(" "); + + const over = setup(reply(bodyReply(`## Depends on\n${refs(MAX_DEPENDS_ON + 1)}\n`))); + assert.strictEqual((yield* over.err(over.github.textBlockers(14)))._tag, "GitHubParse"); + assert.deepStrictEqual(over.calls(), [bodyCall("14")]); + + const atCap = setup( + reply(bodyReply(`## Depends on\n${refs(MAX_DEPENDS_ON)}\n`)), + ...Array.from({ length: MAX_DEPENDS_ON }, () => reply('{"state":"closed"}')), + ); + assert.deepStrictEqual(yield* atCap.ok(atCap.github.textBlockers(14)), []); + assert.strictEqual(atCap.calls().length, MAX_DEPENDS_ON + 1); + }), +); + it.effect("a named issue that cannot be read is an error, not a resolved blocker", () => Effect.gen(function* () { const body = bodyReply("## Depends on\n#13, #5\n"); diff --git a/apps/server/src/factory/tracker/github.ts b/apps/server/src/factory/tracker/github.ts index 472a487a016e8..e70d33fd04be3 100644 --- a/apps/server/src/factory/tracker/github.ts +++ b/apps/server/src/factory/tracker/github.ts @@ -2,7 +2,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { PROJECT_CONFIG_PATH } from "../config.ts"; -import type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; +import type { Approval, TextCheck } from "../domain/approval.ts"; import { dependsOn } from "../domain/dependsOn.ts"; import { STATES, @@ -16,13 +16,12 @@ import { FactoryProcess } from "../process.ts"; import { APPROVAL_QUERY, ApprovalAnswer, - HISTORY_PAGE, - isHumanInstructor, + editedSince, isUtcSecond, + judgeApproval, textChangesSince, timelineReaches, type ApprovalIssue, - type TimelineNode, } from "./approvalHistory.ts"; export type { Approval, Refusal, TextCheck } from "../domain/approval.ts"; @@ -209,7 +208,7 @@ const BlockerRows = Schema.Array( ); const IssueBody = Schema.Struct({ body: OptionalText }); -/** The REST state is lowercase: `open` or `closed`. */ +/** The REST state is lowercase: `open` or `closed`. Any other state, in any case, still blocks. */ const IssueRestState = Schema.Struct({ state: Schema.String }); const RepoView = Schema.Struct({ default_branch: OptionalText }); @@ -454,6 +453,12 @@ const withMarker = (body: string, marker: string): string => `${body}\n\n${marke // ---- the Depends on section ---- +/** + * The most issues a `## Depends on` section may name. Each costs a `gh` call on every check, so + * a longer list is refused rather than read: the issue author does not need approval to write it. + */ +export const MAX_DEPENDS_ON = 100; + /** An open issue that blocks another one. */ export interface Blocker { /** `owner/name` of the repo the blocking issue is in. */ @@ -969,19 +974,27 @@ export const makeGitHub = (options: GitHubOptions) => { * The issues named in the `## Depends on` section of `issue` that are not closed, in the order * the text names them. A reference without a repo is in this repo. It costs one read of the * body and one of each named issue, and is an error when any of them cannot be read: an issue - * that cannot be read is not taken as resolved. + * that cannot be read is not taken as resolved. A section naming more than `MAX_DEPENDS_ON` + * issues is an error before any of them is read. */ const textBlockers = (issue: number): GitHubEffect> => Effect.gen(function* () { const bodyArgs = [...repoArgs(["issue", "view", String(issue)]), "--json", "body"]; const raw = yield* ghJson(bodyArgs, IssueBody, "an object with the issue's body"); + const named = dependsOn(raw.body ?? ""); + if (named.length > MAX_DEPENDS_ON) { + return yield* parseError( + bodyArgs, + `a Depends on section naming at most ${MAX_DEPENDS_ON} issues, got ${named.length}`, + ); + } const open: Array = []; - for (const named of dependsOn(raw.body ?? "")) { - const namedRepo = named.repo ?? repo; - const args = ["api", `repos/${namedRepo}/issues/${named.number}`]; + for (const ref of named) { + const namedRepo = ref.repo ?? repo; + const args = ["api", `repos/${namedRepo}/issues/${ref.number}`]; const read = yield* ghJson(args, IssueRestState, "an object with the issue's state"); - if (read.state.toLowerCase() !== "closed") { - open.push({ repo: namedRepo, number: named.number }); + if (read.state !== "closed") { + open.push({ repo: namedRepo, number: ref.number }); } } return open; @@ -1043,63 +1056,14 @@ export const makeGitHub = (options: GitHubOptions) => { ); /** - * Whether the factory may build the issue: an instructor applied the `factory:ready` label - * that is in force now, and every edit of the body and every rename of the title at or after - * that moment was an instructor's. One GraphQL call. - * - * The timeline events (label changes and renames, oldest first) are walked so that the walk - * keeps the last `factory:ready` event that no later removal cancelled. Label names are matched - * exactly. Only the newest 100 events are read; the one in force among them is enough, because - * every later event, a rename included, is on the page too. A full page of a longer history - * without it is `label-history-incomplete`. - * - * An edit or rename before the label's time is ignored: the instructor approved the text as it - * stood. One in the label's own second counts as after it. Timestamps are compared as strings. - * Only a `User` can be an instructor: a deleted account or a bot never is. + * Whether the factory may build the issue, by `judgeApproval` over the issue's label events and + * edit history: an instructor applied the `factory:ready` label in force now, and every edit + * and rename since was an instructor's. One GraphQL call. */ const approval = (issue: number, instructors: ReadonlyArray): GitHubEffect => - Effect.gen(function* () { - const found = yield* readHistory(issue); - const ready = stateLabel("ready"); - - let inForce: Extract | null = null; - for (const event of found.timelineItems.nodes) { - if (event.__typename === "LabeledEvent" && event.label.name === ready) inForce = event; - else if (event.__typename === "UnlabeledEvent" && event.label.name === ready) { - inForce = null; - } - } - if (inForce === null) { - const { totalCount, nodes } = found.timelineItems; - const cutOff = nodes.length >= HISTORY_PAGE && totalCount > HISTORY_PAGE; - const refusal: Refusal = { kind: cutOff ? "label-history-incomplete" : "label-not-found" }; - return { kind: "refused", refusal } satisfies Approval; - } - const labeledAt = inForce.createdAt; - const actor = inForce.actor; - if (actor === null || actor === undefined || !isHumanInstructor(actor, instructors)) { - return { - kind: "refused", - refusal: { kind: "labeled-by-non-instructor", by: actor?.login ?? null, labeledAt }, - } satisfies Approval; - } - - // The label is on the page, so the renames at or after it are too. - switch (textChangesSince(found, labeledAt, instructors, true)) { - case "changed": - return { - kind: "refused", - refusal: { kind: "edited-after-label", labeledAt }, - } satisfies Approval; - case "unjudged": - return { - kind: "refused", - refusal: { kind: "edit-history-incomplete", labeledAt }, - } satisfies Approval; - case "unchanged": - return { kind: "approved", labeledAt, labeledBy: actor.login } satisfies Approval; - } - }); + Effect.map(readHistory(issue), (found) => + judgeApproval(found, stateLabel("ready"), instructors), + ); /** * Whether the issue text is as an instructor left it: every body edit and every title rename @@ -1129,15 +1093,7 @@ export const makeGitHub = (options: GitHubOptions) => { const textEditedSince = (issue: number, since: string): GitHubEffect => Effect.gen(function* () { yield* requireUtcSecond(since); - const found = yield* readHistory(issue); - const edited = - found.lastEditedAt !== null && found.lastEditedAt !== undefined - ? found.lastEditedAt >= since - : false; - const renamed = found.timelineItems.nodes.some( - (event) => event.__typename === "RenamedTitleEvent" && event.createdAt >= since, - ); - return edited || renamed || !timelineReaches(found, since); + return editedSince(yield* readHistory(issue), since); }); return {