mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-29 09:33:55 +01:00
Recognise the GitHub App's bot as ours on repos that write as the app
This commit is contained in:
1 parent
d3b5771bb8
commit
62019e9b1a
8 files changed
+107
-39
No files matched your search
+18
-9
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { commentApprovalOf } from "../act/approval.ts";
|
||||
import { actionable } from "../decisions.ts";
|
||||
import { ownLogins } from "../github/identity.ts";
|
||||
import { notOwnIntegrationSql, groupHeldSql, backlogHeldSql } from "../dupes/held.ts";
|
||||
import { conflictBucket } from "../fixup/conflict-state.ts";
|
||||
import { pushApprovalOf } from "../fixup/approval.ts";
|
||||
@@ -53,6 +54,8 @@ export type LoadOptions = {
|
||||
refs?: Iterable<string>;
|
||||
/** Decision time in ms (default: the clock). */
|
||||
now?: number;
|
||||
/** The GitHub App's slug, when it is not to be read from the registered app (null: none). */
|
||||
appSlug?: string | null;
|
||||
/** The classification run for labels (default: latestRun). */
|
||||
run?: string | null;
|
||||
};
|
||||
@@ -131,7 +134,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
const gates = gatesOf(db, opts.repo);
|
||||
const holds = mergeHolds(db, opts.repo);
|
||||
const inBatch = batchStates(db, opts.repo);
|
||||
const own = ownFixPrs(db, opts.repo);
|
||||
const own = ownFixPrs(db, opts.repo, opts.appSlug);
|
||||
const assigned = assignmentsOf(db, opts.repo);
|
||||
const mainRed = redMainRepos(db);
|
||||
const tripped = activeTrips(db);
|
||||
@@ -141,7 +144,6 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
const pushedHere = db.prepare("SELECT 1 FROM push_outcomes WHERE repo = ? AND number = ? AND to_oid = ?");
|
||||
const answers = new Map(actionable(db).filter((a) => a.kind === "merge").map((a) => [a.id, a.answer]));
|
||||
const pipelineOn = pipelineWrites((db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_enabled'").get() as { value: string } | undefined)?.value);
|
||||
const pipelineLogin = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? null;
|
||||
const posts = new Map((db.prepare("SELECT repo, number, review_id, head_oid, posted_at, opus_at FROM review_posts").all() as { repo: string; number: number; review_id: string; head_oid: string | null; posted_at: string | null; opus_at: string | null }[])
|
||||
.map((p) => [`${p.repo}#${p.number}`, p]));
|
||||
const grouped = new Set((db.prepare(`SELECT gi.repo || '#' || gi.number AS ref FROM dupe_group_items gi JOIN decisions g ON g.id = gi.decision_id
|
||||
@@ -229,7 +231,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
const lines = (r.additions ?? 0) + (r.deletions ?? 0);
|
||||
const base: PrFacts = {
|
||||
repo: r.repo, number: r.number, assignment: assigned(ref, r.assignees), now, pipelineOn, tripped, ghState: r.state, head, draft: fresh ? r.c_state !== "OPEN" || !!r.c_draft : !!r.is_draft,
|
||||
author: r.author, authorIsPipeline: r.author !== null && r.author === pipelineLogin, tier: "not", lines, size: sizeOf(lines), label: null, needsDecisionFlag: false,
|
||||
author: r.author, authorIsPipeline: r.author !== null && own.isOwn(r.repo, r.author), tier: "not", lines, size: sizeOf(lines), label: null, needsDecisionFlag: false,
|
||||
scopeAnswer: scope.get(ref) ?? null,
|
||||
inScope, integration, batchPr: !!r.batch_pr, heldBacklog: !!r.held_backlog, heldDuplicate: !r.held_backlog && !!r.held_dup, mergeHeld: holds.has(ref),
|
||||
fast: (r.score ?? 0) >= FAST_FLOOR, score: r.score, repoFacts: rf.f,
|
||||
@@ -239,7 +241,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
decision: { asked: false, openQuestion: false, answer: null, mergeAnswerAfterReview: false, inOpenGroup: grouped.has(ref) },
|
||||
premerge: null, premergeFixUsed: false, sensitive: null, statementConflicts: [], pushable: false, pushChain: [], conflict: null, inActiveBatch: activeBatched.has(ref), fixup: null, carry: [], lint: [], cifix: null, postmerge: null, batch: null, mainFix: false, changesRequested: null, gateFailureNote: null,
|
||||
};
|
||||
base.inFlight = r.state === "OPEN" && !integration && !!r.author && r.author === own.login && own.prs.has(ref);
|
||||
base.inFlight = r.state === "OPEN" && !integration && !!r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref);
|
||||
if (integration) {
|
||||
base.runs = runsOf(batchTip.get(r.repo, r.number) as Wait | undefined, rf.f.ciApproved);
|
||||
out.push(base);
|
||||
@@ -317,7 +319,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
base.brokeByUs = brokeAt.get(ref) === head && r.c_head === head && effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks) === "failure";
|
||||
base.tier = (r.author ? tiers.get(r.author) : undefined) ?? "not";
|
||||
// The pipeline's own Fix PRs count as whitelisted; an operator's deny still wins.
|
||||
if (base.tier === "not" && r.author && r.author === own.login && own.prs.has(ref)) base.tier = "whitelisted";
|
||||
if (base.tier === "not" && r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref)) base.tier = "whitelisted";
|
||||
|
||||
const last = merges.get(r.repo, r.number, r.r_head) as { outcome: string; reason: string | null; ci: string | null; mergeable: string | null; at: string } | undefined;
|
||||
if (last) {
|
||||
@@ -374,7 +376,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
|
||||
};
|
||||
}
|
||||
base.batch = inBatch.get(`${ref}@${r.r_head}`) ?? null;
|
||||
base.mainFix = !!r.head_ref?.startsWith(MAIN_FIX_BRANCH_PREFIX) && !!r.author && r.author === own.login && own.prs.has(ref);
|
||||
base.mainFix = !!r.head_ref?.startsWith(MAIN_FIX_BRANCH_PREFIX) && !!r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref);
|
||||
const gate = gates.get(ref);
|
||||
const { why, live } = changesRequestedWhy(gate, r.updated_at, reviewRows.all(r.repo, r.number) as ReviewFact[], r.review_decision);
|
||||
if (gate && gate.failures >= GATE_FAILURES) base.gateFailureNote = failureNote(gate.failures);
|
||||
@@ -426,18 +428,25 @@ export function tiersOf(db: DatabaseSync, logins: string[]): Map<string, Tier> {
|
||||
}
|
||||
|
||||
/** PRs the pipeline opened itself from a Fix issues attempt or for a red default branch, as `repo#number`, when authored by its own account. */
|
||||
export function ownFixPrs(db: DatabaseSync, repo?: string): { login: string | null; prs: Set<string>; quiet: Set<string> } {
|
||||
export function ownFixPrs(db: DatabaseSync, repo?: string, slug?: string | null): { login: string | null; prs: Set<string>; quiet: Set<string>; isOwn: (repo: string, author: string | null) => boolean } {
|
||||
const logins = new Map<string, Set<string>>();
|
||||
const isOwn = (r: string, author: string | null): boolean => {
|
||||
if (!author) return false;
|
||||
let set = logins.get(r);
|
||||
if (!set) logins.set(r, (set = ownLogins(db, r, slug)));
|
||||
return set.has(author.toLowerCase());
|
||||
};
|
||||
const login = (db.prepare("SELECT value FROM main.settings WHERE key = ?").get(PIPELINE_LOGIN_KEY) as { value: string } | undefined)?.value ?? null;
|
||||
const prs = new Set<string>();
|
||||
const quiet = quietFixPrs(db, repo);
|
||||
if (!login) return { login, prs, quiet };
|
||||
if (!login) return { login, prs, quiet, isOwn };
|
||||
for (const ref of quiet) prs.add(ref);
|
||||
for (const r of db.prepare("SELECT repo, pr_url FROM main.fix_attempts WHERE pr_url IS NOT NULL" + (repo ? " AND repo = ?" : "")).all(...(repo ? [repo] : [])) as { repo: string; pr_url: string }[]) {
|
||||
const m = r.pr_url.match(/\/pull\/(\d+)$/);
|
||||
if (m) prs.add(`${r.repo}#${m[1]}`);
|
||||
}
|
||||
for (const r of db.prepare("SELECT repo, pr_number AS n FROM main.main_fixes WHERE pr_number IS NOT NULL" + (repo ? " AND repo = ?" : "")).all(...(repo ? [repo] : [])) as { repo: string; n: number }[]) prs.add(`${r.repo}#${r.n}`);
|
||||
return { login, prs, quiet };
|
||||
return { login, prs, quiet, isOwn };
|
||||
}
|
||||
|
||||
/** Reads the pipeline account and the last successful assign or unassign of every item from the audit once; the returned function gives an item's assignment facts from its mirrored `assignees` (JSON). */
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "./trace.ts";
|
||||
import { canSeeInternals } from "./staff.ts";
|
||||
import { hiddenRepos, needVisible, visibleRepos } from "./visible.ts";
|
||||
import { allOwnLogins } from "../../github/identity.ts";
|
||||
|
||||
export const ACTIVITY_PAGE_DEFAULT = 50, ACTIVITY_PAGE_MAX = 200;
|
||||
/** Plan changes and stages come from every planner pass of every item and would bury the rest, so they show only when asked for. */
|
||||
@@ -23,7 +24,7 @@ export const ACTIVITY_DEFAULT_KINDS: TraceKind[] = KINDS.filter((k) => k !== "pl
|
||||
/** Sorts after every event id of the same time. */
|
||||
const LAST = "~";
|
||||
|
||||
export type Ctx = { db: DatabaseSync; own: string; staff: boolean; operator: boolean; hidden: string[]; visible: string[]; only: boolean; repo: string | null; limit: number; before: { at: string; id: string } | null };
|
||||
export type Ctx = { db: DatabaseSync; own: Set<string>; staff: boolean; operator: boolean; hidden: string[]; visible: string[]; only: boolean; repo: string | null; limit: number; before: { at: string; id: string } | null };
|
||||
type At = { repo: string; number: number };
|
||||
type Pulled = { events: (Ev & At)[]; /** Oldest time read when the source had more rows than it returned; null when it returned everything. */ floor: string | null };
|
||||
export type Source = { kinds: TraceKind[]; table: string; time: string; pull: (c: Ctx) => Pulled };
|
||||
@@ -74,8 +75,8 @@ export const SOURCES: Source[] = [
|
||||
item("created_at", "kind IS NOT NULL", openedEvent),
|
||||
item("merged_at", "merged_at IS NOT NULL", mergedEvent),
|
||||
item("closed_at", "closed_at IS NOT NULL AND merged_at IS NULL", closedEvent),
|
||||
plain<Parameters<typeof commentEvent>[0] & At>("github", "comments", "created_at", "repo, number, id, kind, author, created_at, review_state, commit_oid, LENGTH(COALESCE(body, '')) AS len", (r, c) => commentEvent(r, c.own), { only: (c) => (c.own ? { where: "author = ?", args: [c.own] } : null) }),
|
||||
plain<Parameters<typeof activityEvent>[0] & At>("github", "item_activity", "at", "repo, number, id, kind, at, actor, label, after_oid, before_oid", (r, c) => activityEvent(r, c.own), { only: (c) => (c.own ? { where: "actor = ?", args: [c.own] } : null) }),
|
||||
plain<Parameters<typeof commentEvent>[0] & At>("github", "comments", "created_at", "repo, number, id, kind, author, created_at, review_state, commit_oid, LENGTH(COALESCE(body, '')) AS len", (r, c) => commentEvent(r, c.own), { only: (c) => (c.own.size ? { where: `lower(author) IN (${[...c.own].map(() => "?").join(",")})`, args: [...c.own] } : null) }),
|
||||
plain<Parameters<typeof activityEvent>[0] & At>("github", "item_activity", "at", "repo, number, id, kind, at, actor, label, after_oid, before_oid", (r, c) => activityEvent(r, c.own), { only: (c) => (c.own.size ? { where: `lower(actor) IN (${[...c.own].map(() => "?").join(",")})`, args: [...c.own] } : null) }),
|
||||
plain<Parameters<typeof stageEvent>[0] & At>("plan", "stages", "at", "repo, number, rowid, stage, at, actor, note", stageEvent),
|
||||
plain<Parameters<typeof planEvent>[0] & At>("plan", "plan_history", "at", "repo, number, id, head, old_state, new_state, wait, reasons, at", planEvent),
|
||||
// A job over many items is one row of the stream, at its newest item.
|
||||
@@ -232,7 +233,7 @@ export async function activity(db: DatabaseSync, req: Req): Promise<ActivityPage
|
||||
}
|
||||
const base = {
|
||||
db, staff: canSeeInternals(req), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req), visible: await visibleRepos(db, req), repo,
|
||||
own: (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? "",
|
||||
own: allOwnLogins(db),
|
||||
};
|
||||
const sources = SOURCES.filter((s) => s.kinds.some((k) => kinds.has(k)));
|
||||
const stamp = stampOf(db, sources, [[...kinds].sort(), only, repo, limit, base.staff, base.operator, base.visible]);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { HttpError } from "../server/util.ts";
|
||||
import type { Req } from "../types.ts";
|
||||
import { itemState } from "./shown.ts";
|
||||
import { blankIfHidden, hiddenRepos } from "./visible.ts";
|
||||
import { allOwnLogins } from "../../github/identity.ts";
|
||||
|
||||
export const NEEDS_PAGE = 30;
|
||||
/** Older feedback is not asked for any more; the window also bounds the scans. */
|
||||
@@ -18,7 +19,7 @@ const WINDOW_MS = 60 * 86_400_000;
|
||||
|
||||
type Raw = { id: string; source: NeedsFeedbackRow["source"]; author: string; at: string; text: string; repo: string | null; number: number | null; decision: string | null; turn: number | null; comment: string | null; handled: number };
|
||||
|
||||
// One SELECT per source, each with a `handled` flag. They share the parameters :since, :cur (newest time wanted), :own and :bots.
|
||||
// One SELECT per source, each with a `handled` flag. They share the parameters :since, :cur (newest time wanted), :own (the box account), :owns (JSON list of every login that is ours) and :bots.
|
||||
const SOURCES: string[] = [
|
||||
// Feedback on a decision from anyone but an operator; handled once the decision was answered afterwards.
|
||||
`SELECT 'decision-comment:' || c.id AS id, 'decision' AS source, c.login AS author, c.at, c.body AS text, d.repo, d.number, d.id AS decision, NULL AS turn, c.id AS comment,
|
||||
@@ -36,16 +37,16 @@ const SOURCES: string[] = [
|
||||
// A GitHub comment or review that names the pipeline login (flagged when written, so an index finds them); handled once the
|
||||
// pipeline login posted on the item afterwards. Nothing without a pipeline login.
|
||||
`SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, NULL, c.id,
|
||||
EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND a.author = :own AND a.created_at > c.created_at)
|
||||
EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND lower(a.author) IN (SELECT value FROM json_each(:owns)) AND a.created_at > c.created_at)
|
||||
FROM comments c
|
||||
WHERE :own <> '' AND c.mentions_pipeline = 1 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND c.author <> :own`,
|
||||
WHERE :own <> '' AND c.mentions_pipeline = 1 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND lower(c.author) NOT IN (SELECT value FROM json_each(:owns))`,
|
||||
// The comment right after one of AutoCraft's own (a comment the audit log recorded with its URL and text, or the review we posted (audit `review-post`); the account's older manual comments do not count), on an item it commented on; bots do not count as replies.
|
||||
`SELECT 'comment:' || c.id, 'github', c.author, c.created_at, c.body, c.repo, c.number, NULL, NULL, c.id,
|
||||
EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND a.author = :own AND a.created_at > c.created_at)
|
||||
FROM (SELECT DISTINCT repo, number FROM comments WHERE author = :own) o JOIN comments c ON c.repo = o.repo AND c.number = o.number
|
||||
WHERE :own <> '' AND c.mentions_pipeline = 0 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND c.author <> :own AND c.author NOT LIKE '%[bot]' AND lower(c.author) NOT IN (SELECT value FROM json_each(:bots)) AND TRIM(COALESCE(c.body, '')) <> ''
|
||||
EXISTS (SELECT 1 FROM comments a WHERE a.repo = c.repo AND a.number = c.number AND lower(a.author) IN (SELECT value FROM json_each(:owns)) AND a.created_at > c.created_at)
|
||||
FROM (SELECT DISTINCT repo, number FROM comments WHERE lower(author) IN (SELECT value FROM json_each(:owns))) o JOIN comments c ON c.repo = o.repo AND c.number = o.number
|
||||
WHERE :own <> '' AND c.mentions_pipeline = 0 AND c.created_at >= :since AND c.created_at <= :cur AND c.author IS NOT NULL AND lower(c.author) NOT IN (SELECT value FROM json_each(:owns)) AND c.author NOT LIKE '%[bot]' AND lower(c.author) NOT IN (SELECT value FROM json_each(:bots)) AND TRIM(COALESCE(c.body, '')) <> ''
|
||||
AND EXISTS (SELECT 1 FROM (SELECT p.id, p.author, p.body FROM comments p WHERE p.repo = c.repo AND p.number = c.number AND p.created_at < c.created_at ORDER BY p.created_at DESC LIMIT 1) q
|
||||
WHERE q.author = :own AND EXISTS (SELECT 1 FROM audit a WHERE a.target = c.repo || '#' || c.number
|
||||
WHERE lower(q.author) IN (SELECT value FROM json_each(:owns)) AND EXISTS (SELECT 1 FROM audit a WHERE a.target = c.repo || '#' || c.number
|
||||
AND ((json_extract(a.details, '$.url') IS NOT NULL AND TRIM(REPLACE(json_extract(a.details, '$.text'), char(13), ''), ' ' || char(10) || char(9)) = TRIM(REPLACE(q.body, char(13), ''), ' ' || char(10) || char(9)))
|
||||
OR (a.action = 'review-post' AND json_extract(a.details, '$.review') = q.id))))`,
|
||||
];
|
||||
@@ -58,7 +59,7 @@ function hiddenSql(hidden: string[], params: Record<string, SQLInputValue>): str
|
||||
}
|
||||
|
||||
function feedback(db: DatabaseSync, hidden: string[], cursor: { at: string; id: string } | null, limit: number): { rows: Raw[]; more: boolean; unhandled: number } {
|
||||
const params: Record<string, SQLInputValue> = { since: new Date(Date.now() - WINDOW_MS).toISOString(), own: ownLogin(db), bots: JSON.stringify(reviewBots()) };
|
||||
const params: Record<string, SQLInputValue> = { since: new Date(Date.now() - WINDOW_MS).toISOString(), own: ownLogin(db), owns: JSON.stringify([...allOwnLogins(db)]), bots: JSON.stringify(reviewBots()) };
|
||||
const union = SOURCES.map((s) => `SELECT * FROM (${s})`).join(" UNION ALL ");
|
||||
const where = hiddenSql(hidden, params);
|
||||
const size = limit * 3 + 1;
|
||||
|
||||
+11
-10
@@ -14,10 +14,11 @@ import { AUDIT_ACTIONS, operatorOnly } from "./admin.ts";
|
||||
import { detailOf } from "./github-detail.ts";
|
||||
import { canSeeInternals } from "./staff.ts";
|
||||
import { hiddenRepos, needVisible } from "./visible.ts";
|
||||
import { ownLogins } from "../../github/identity.ts";
|
||||
|
||||
export type Ev = TraceEvent & { detail?: Record<string, unknown> };
|
||||
/** `staff`: operators and maintainers; `hidden`: repos the viewer may not see, whose runs are left out like getRun does. */
|
||||
type Ctx = { db: DatabaseSync; repo: string; n: number; ref: string; own: string; staff: boolean; /** A quiet pull request seen by a viewer: model output stays out of the trace. */ veiled: boolean; operator: boolean; hidden: string[] };
|
||||
type Ctx = { db: DatabaseSync; repo: string; n: number; ref: string; own: Set<string>; box: string; staff: boolean; /** A quiet pull request seen by a viewer: model output stays out of the trace. */ veiled: boolean; operator: boolean; hidden: string[] };
|
||||
type Source = { kinds: TraceKind[]; run: (c: Ctx) => Ev[] };
|
||||
|
||||
export const TRACE_PAGE_DEFAULT = 100, TRACE_PAGE_MAX = 500;
|
||||
@@ -49,8 +50,8 @@ export const closedEvent = (it: ItemRow): Ev => ({ id: "gh:closed", kind: "githu
|
||||
/** Longest comment text a trace event carries. */
|
||||
export const TRACE_BODY_MAX = 20_000;
|
||||
/** `body`, when given, is the stored text (the item trace selects it; the activity feed does not, to keep its pages light). */
|
||||
export const commentEvent = (c: { id: string; kind: string | null; author: string | null; created_at: string; review_state: string | null; commit_oid: string | null; len: number; body?: string | null; cut?: number }, own: string): Ev => {
|
||||
const ours = own !== "" && c.author === own;
|
||||
export const commentEvent = (c: { id: string; kind: string | null; author: string | null; created_at: string; review_state: string | null; commit_oid: string | null; len: number; body?: string | null; cut?: number }, own: Set<string>): Ev => {
|
||||
const ours = !!c.author && own.has(c.author.toLowerCase());
|
||||
const what = c.kind === "review" ? `review (${(c.review_state ?? "commented").toLowerCase().replace("_", " ")})` : "comment";
|
||||
return {
|
||||
id: `comment:${c.id}`, kind: "github", at: c.created_at, head: c.commit_oid, actor: ours ? step("AutoCraft") : person(c.author),
|
||||
@@ -58,8 +59,8 @@ export const commentEvent = (c: { id: string; kind: string | null; author: strin
|
||||
...(c.body && { body: c.body, ...(c.cut && { bodyCut: true }) }),
|
||||
};
|
||||
};
|
||||
export const activityEvent = (a: { id: string; kind: string; at: string; actor: string | null; label: string | null; after_oid: string | null; before_oid: string | null }, own: string): Ev => {
|
||||
const ours = own !== "" && a.actor === own;
|
||||
export const activityEvent = (a: { id: string; kind: string; at: string; actor: string | null; label: string | null; after_oid: string | null; before_oid: string | null }, own: Set<string>): Ev => {
|
||||
const ours = !!a.actor && own.has(a.actor.toLowerCase());
|
||||
const summary = a.kind === "force-push" ? `Force-pushed ${(a.before_oid ?? "").slice(0, 7)} → ${(a.after_oid ?? "").slice(0, 7)}` : `${a.kind === "labeled" ? "Added" : "Removed"} label ${a.label ?? ""}`;
|
||||
return { id: `activity:${a.id}`, kind: "github", at: a.at, head: a.kind === "force-push" ? a.after_oid : null, actor: ours ? step("AutoCraft") : person(a.actor), summary, ref: a.after_oid ? { head: a.after_oid } : {} };
|
||||
};
|
||||
@@ -80,7 +81,7 @@ const github: Source = {
|
||||
}
|
||||
for (const c of rows<{ oid: string; committed_at: string; author: string | null }>(db, "SELECT oid, MIN(committed_at, COALESCE(first_seen_at, committed_at)) AS committed_at, author FROM pr_commits WHERE repo = ? AND number = ?", repo, n)) {
|
||||
// Our own commits are shown by their audit rows.
|
||||
if (own !== "" && c.author === own) continue;
|
||||
if (c.author && own.has(c.author.toLowerCase())) continue;
|
||||
out.push({ id: `commit:${c.oid}`, kind: "github", at: c.committed_at, head: c.oid, actor: person(c.author), summary: `Pushed commit ${c.oid.slice(0, 7)}`, ref: { head: c.oid } });
|
||||
}
|
||||
for (const a of rows<{ id: string; kind: string; at: string; actor: string | null; label: string | null; after_oid: string | null; before_oid: string | null }>(db,
|
||||
@@ -407,7 +408,7 @@ function veilHeader(h: ItemTraceHeader): ItemTraceHeader {
|
||||
};
|
||||
}
|
||||
|
||||
function headerOf({ db, repo, n, own, hidden }: Ctx): ItemTraceHeader {
|
||||
function headerOf({ db, repo, n, box, hidden }: Ctx): ItemTraceHeader {
|
||||
const plan = db.prepare("SELECT head, state, actions, wait, reasons, note, view, planned_at FROM item_plans WHERE repo = ? AND number = ?").get(repo, n) as
|
||||
{ head: string | null; state: string; actions: string; wait: string | null; reasons: string; note: string | null; view: string; planned_at: string } | undefined;
|
||||
const view = obj(plan?.view);
|
||||
@@ -422,7 +423,7 @@ function headerOf({ db, repo, n, own, hidden }: Ctx): ItemTraceHeader {
|
||||
},
|
||||
next: acts.map((a) => ({ kind: a.kind as string, head: typeof a.head === "string" ? a.head : null })),
|
||||
who: {
|
||||
assignees, autocraftAssigned: own !== "" && assignees.includes(own),
|
||||
assignees, autocraftAssigned: box !== "" && assignees.includes(box),
|
||||
openDecisions: decisionIds({ db, repo, n, hidden } as Ctx).flatMap((id) => {
|
||||
const d = db.prepare("SELECT id, kind, question FROM decisions WHERE id = ? AND answer IS NULL").get(id) as { id: string; kind: string; question: string } | undefined;
|
||||
return d ? [{ id: d.id, kind: d.kind, question: clip(d.question, 140) }] : [];
|
||||
@@ -479,8 +480,8 @@ async function context(db: DatabaseSync, req: Req): Promise<Ctx> {
|
||||
if (!Number.isInteger(n)) throw new HttpError(400, "not an item number");
|
||||
await needVisible(db, req, repo);
|
||||
if (!db.prepare("SELECT 1 FROM items WHERE repo = ? AND number = ?").get(repo, n)) throw new HttpError(404, `no item ${repo}#${n} in the mirror`);
|
||||
const own = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? "";
|
||||
return { db, repo, n, ref: `${repo}#${n}`, own, staff: canSeeInternals(req), veiled: !canSeeInternals(req) && isQuiet(db, repo, n), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req) };
|
||||
const box = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value ?? "";
|
||||
return { db, repo, n, ref: `${repo}#${n}`, own: ownLogins(db, repo), box, staff: canSeeInternals(req), veiled: !canSeeInternals(req) && isQuiet(db, repo, n), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req) };
|
||||
}
|
||||
|
||||
/** Job errors and patch-check reasons carry log and patch text: viewers get the other fields. */
|
||||
|
||||
+6
-2
@@ -1,9 +1,10 @@
|
||||
// Items held back from the later stages while a duplicate decision about them
|
||||
// is open or was answered "close as duplicate", or any decision about them was
|
||||
// answered Backlog. An answer of "not a duplicate"
|
||||
// or "keep both" releases them. No Node imports besides the type.
|
||||
// or "keep both" releases them. No Node imports besides the type and the app-slug lookup.
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { pilotSql } from "../pilot.ts";
|
||||
import { appSlug } from "../github/identity.ts";
|
||||
|
||||
/** The fact line that names the original; the act step reads it. */
|
||||
export const DUP_FACT = "duplicate of ";
|
||||
@@ -35,10 +36,13 @@ export const backlogHeldSql = (alias: string): string =>
|
||||
WHERE json_extract(bj.value, '$.repo') = ${alias}.repo AND json_extract(bj.value, '$.number') = ${alias}.number)
|
||||
OR EXISTS (SELECT 1 FROM dupe_group_items bg WHERE bg.decision_id = db.id AND bg.repo = ${alias}.repo AND bg.number = ${alias}.number)))`;
|
||||
|
||||
const botLogins = (): string[] => { const s = appSlug()?.toLowerCase(); return s ? [s, `${s}[bot]`] : []; };
|
||||
|
||||
/** SQL condition, true when the item `alias` (a row of items) is not an integration batch PR the pipeline opened itself (see src/merge/batch.ts). Such PRs only carry reviewed PRs and never enter the pipeline as contributor PRs. */
|
||||
export const notOwnIntegrationSql = (alias: string): string =>
|
||||
`NOT EXISTS (SELECT 1 FROM main.merge_batches mb WHERE mb.repo = ${alias}.repo AND mb.pr_number = ${alias}.number
|
||||
AND ${alias}.author = (SELECT value FROM main.settings WHERE key = 'pipeline_login'))`;
|
||||
AND (${alias}.author = (SELECT value FROM main.settings WHERE key = 'pipeline_login')
|
||||
OR lower(${alias}.author) IN (SELECT value FROM json_each('${JSON.stringify(botLogins()).replaceAll("'", "''")}'))))`;
|
||||
|
||||
/** SQL condition, true when the item `alias` (a row of items) is not held by a duplicate decision, is not one of our integration PRs and is in the pilot (when one is set). For WHERE clauses of candidate queries. */
|
||||
export const notHeldSql = (alias: string): string =>
|
||||
|
||||
@@ -112,3 +112,33 @@ export async function commitIdentity(
|
||||
const w = await box();
|
||||
return { name: w.login, login: w.login, email: w.email };
|
||||
}
|
||||
|
||||
/** Slug of the registered GitHub App, read from the secrets file at most once a minute; null when none is registered or the file is unreadable. */
|
||||
let slugMemo: { at: number; slug: string | null } | null = null;
|
||||
export function appSlug(): string | null {
|
||||
if (slugMemo && Date.now() - slugMemo.at < 60_000) return slugMemo.slug;
|
||||
let slug: string | null = null;
|
||||
try { slug = readAppSecrets()?.slug ?? null; } catch { slug = null; }
|
||||
slugMemo = { at: Date.now(), slug };
|
||||
return slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logins whose items and comments are ours on `repo`: the box account (when recorded) and, on a repo that writes as the app, the app's bot
|
||||
* (a bare slug in the mirror, `<slug>[bot]` in REST). The box account stays in the set so items from before a switch remain ours.
|
||||
* Lower-cased. `slug` is injectable for tests; by default the registered app's.
|
||||
*/
|
||||
export function ownLogins(db: DatabaseSync, repo: string, slug: string | null = appSlug()): Set<string> {
|
||||
const out = new Set<string>();
|
||||
const box = (db.prepare("SELECT value FROM main.settings WHERE key = 'pipeline_login'").get() as { value: string } | undefined)?.value;
|
||||
if (box) out.add(box.toLowerCase());
|
||||
if (slug && repoIdentity(db, repo) === "app") { out.add(slug.toLowerCase()); out.add(`${slug.toLowerCase()}[bot]`); }
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every login that is ours on any repo (for views that span repos). */
|
||||
export function allOwnLogins(db: DatabaseSync, slug: string | null = appSlug()): Set<string> {
|
||||
const out = ownLogins(db, "", null);
|
||||
if (slug) { out.add(slug.toLowerCase()); out.add(`${slug.toLowerCase()}[bot]`); }
|
||||
return out;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type { Querier } from "../mirror.ts";
|
||||
import { FORMAL_REVIEWS, recordGate, recordGateFailure, type ReviewFact } from "../merge/changes-requested.ts";
|
||||
import { ENTRY_LIMIT, TOTAL_LIMIT, type DiscussionEntry } from "./parse.ts";
|
||||
import { ownerOf } from "../owners.ts";
|
||||
import { allOwnLogins, ownLogins } from "../github/identity.ts";
|
||||
|
||||
/** Setting that holds the pipeline account's login (also read by src/merge/queue.ts). */
|
||||
const LOGIN_KEY = "pipeline_login";
|
||||
@@ -89,14 +90,17 @@ export function discussionHash(xs: { id: string; body: string | null }[]): strin
|
||||
/** What a review read: when, and a hash of the counted entries. */
|
||||
export type Snapshot = { seen: string; hash: string | null };
|
||||
|
||||
/** The `:own` parameter of NOT_OURS. With no login known, '' stands in, so authorless rows stay out as before. */
|
||||
const ownJson = (own: Set<string>): string => JSON.stringify(own.size ? [...own] : [""]);
|
||||
|
||||
/** SQL for "written by someone other than us" (`c` is the comments table alias). */
|
||||
const NOT_OURS = `COALESCE(c.author, '') <> :own
|
||||
const NOT_OURS = `lower(COALESCE(c.author, '')) NOT IN (SELECT value FROM json_each(:own))
|
||||
AND c.id NOT IN (SELECT review_id FROM review_posts WHERE repo = c.repo AND number = c.number)`;
|
||||
|
||||
type MirrorRow = { id: string; kind: string; author: string | null; created_at: string | null; body: string | null; review_state: string | null; counted: number | null };
|
||||
const mirrorRows = (db: DatabaseSync, repo: string, number: number): MirrorRow[] =>
|
||||
db.prepare(`SELECT c.id, c.kind, c.author, c.created_at, c.body, c.review_state, c.counted FROM comments c
|
||||
WHERE c.repo = :repo AND c.number = :number AND ${NOT_OURS} ORDER BY c.created_at`).all({ repo, number, own: pipelineLogin(db) }) as MirrorRow[];
|
||||
WHERE c.repo = :repo AND c.number = :number AND ${NOT_OURS} ORDER BY c.created_at`).all({ repo, number, own: ownJson(ownLogins(db, repo)) }) as MirrorRow[];
|
||||
|
||||
/** Comments and review bodies from the mirror: the fallback for a call that has no GitHub connection. */
|
||||
function mirrorDiscussion(db: DatabaseSync, repo: string, number: number): { entries: DiscussionEntry[]; hash: string } {
|
||||
@@ -142,9 +146,9 @@ export async function liveDiscussion(q: Querier, db: DatabaseSync, repo: string,
|
||||
const res = await q.query(DISCUSSION_QUERY, { owner: ownerOf(repo), name: repo, number });
|
||||
const pr = res?.repository?.pullRequest;
|
||||
if (!pr) throw new Error(`${repo}#${number} not found on GitHub`);
|
||||
const own = pipelineLogin(db);
|
||||
const own = ownLogins(db, repo);
|
||||
const posted = new Set((db.prepare("SELECT review_id FROM review_posts WHERE repo = ? AND number = ?").all(repo, number) as { review_id: string }[]).map((r) => r.review_id));
|
||||
const mine = (a: Author | undefined, id?: string) => (!!own && a?.login === own) || (!!id && posted.has(id));
|
||||
const mine = (a: Author | undefined, id?: string) => (!!a?.login && own.has(a.login.toLowerCase())) || (!!id && posted.has(id));
|
||||
const prAuthor: string | null = pr.author?.login ?? null;
|
||||
const entries: DiscussionEntry[] = [];
|
||||
const counted: { id: string; body: string | null }[] = [];
|
||||
@@ -225,7 +229,7 @@ const stateMemo = new WeakMap<DatabaseSync, Map<string, { sig: string; state: Di
|
||||
/** Newest counted comment or review by someone else, and the hash of those, per "repo#n" from the mirror. Callers must not modify the result. */
|
||||
export function discussionState(db: DatabaseSync, repo?: string): DiscussionState {
|
||||
const seqs = db.prepare("SELECT topic, seq FROM change_seq WHERE topic IN ('items', 'reviews') ORDER BY topic").all() as { topic: string; seq: number }[];
|
||||
const sig = JSON.stringify([seqs, pipelineLogin(db)]);
|
||||
const sig = JSON.stringify([seqs, [...allOwnLogins(db)]]);
|
||||
const memo = stateMemo.get(db) ?? new Map<string, { sig: string; state: DiscussionState }>();
|
||||
stateMemo.set(db, memo);
|
||||
const key = repo ?? "";
|
||||
@@ -238,7 +242,7 @@ export function discussionState(db: DatabaseSync, repo?: string): DiscussionStat
|
||||
|
||||
function computeDiscussionState(db: DatabaseSync, repo?: string): DiscussionState {
|
||||
const rows = db.prepare(`SELECT c.repo, c.number, c.id, c.body, c.created_at FROM comments c
|
||||
WHERE (:repo IS NULL OR c.repo = :repo) AND c.counted = 1 AND ${NOT_OURS}`).all({ repo: repo ?? null, own: pipelineLogin(db) }) as { repo: string; number: number; id: string; body: string | null; created_at: string }[];
|
||||
WHERE (:repo IS NULL OR c.repo = :repo) AND c.counted = 1 AND ${NOT_OURS}`).all({ repo: repo ?? null, own: ownJson(repo ? ownLogins(db, repo) : allOwnLogins(db)) }) as { repo: string; number: number; id: string; body: string | null; created_at: string }[];
|
||||
const by = new Map<string, typeof rows>();
|
||||
for (const r of rows) {
|
||||
const k = `${r.repo}#${r.number}`;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// A PR the GitHub App's bot opened counts as ours on a repo that writes as the app, and not on a legacy repo.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { loadPrFacts } from "../src/core/facts.ts";
|
||||
import { ownLogins } from "../src/github/identity.ts";
|
||||
import { world } from "./world-db.ts";
|
||||
|
||||
test("the app's bot is ours on app repos only; the box account stays ours on both", () => {
|
||||
const w = world().repo().pr(1, { author: "my-app" }).pr(2, { author: "box" }).pr(3, { author: "stranger" });
|
||||
w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('pipeline_login', 'box')").run();
|
||||
const mine = () => Object.fromEntries(loadPrFacts(w.db, { appSlug: "my-app" }).map((f) => [f.number, f.authorIsPipeline]));
|
||||
assert.deepEqual(mine(), { 1: false, 2: true, 3: false });
|
||||
|
||||
w.db.prepare("INSERT INTO main.settings (key, value) VALUES ('repo_identity:app', 'app')").run();
|
||||
assert.deepEqual(mine(), { 1: true, 2: true, 3: false });
|
||||
assert.deepEqual([...ownLogins(w.db, "app", "My-App")].sort(), ["box", "my-app", "my-app[bot]"]);
|
||||
assert.deepEqual([...ownLogins(w.db, "app", null)], ["box"]);
|
||||
});
|
||||
Reference in new issue
Block a user