diff --git a/.github/workflows/integrity-sweep.yml b/.github/workflows/integrity-sweep.yml new file mode 100644 index 0000000..af369eb --- /dev/null +++ b/.github/workflows/integrity-sweep.yml @@ -0,0 +1,72 @@ +# Weekly Atlas data-integrity sweep. +# +# Calls the token-gated GET /api/ops/integrity (deterministic, certain-only rules in +# atlas/lib/integrity.ts) and reconciles the findings into the per-cause +# `data-integrity` issues (#338-#348, plus one catch-all issue the script creates +# once): new findings are appended as unticked lines, lines the sweep wrote whose +# finding is gone are ticked. Nothing is deleted and human-edited lines are never +# touched. See scripts/integrity-sweep/sweep.mjs. +# +# The DB reads happen on the Worker; this job never holds DB credentials. +# +# SECURITY: no `github.event.*` data is referenced. Secrets and the one typed boolean +# input reach the script via `env:` only, never inlined into a `run:` script. +# +# Required repository secrets: +# INTEGRITY_URL NEW - e.g. https://atlas.buspark.io/api/ops/integrity +# (the route must be deployed to that Worker first; deploys are manual) +# DIGEST_TOKEN already exists for the weekly digest; must match the Worker's +# DIGEST_TOKEN +# GITHUB_TOKEN is the built-in token, scoped below to issues: write. +name: Integrity sweep + +on: + schedule: + # 14:00 UTC Monday, an hour after the weekly digest. + - cron: "0 14 * * 1" + workflow_dispatch: + inputs: + dry_run: + description: "Read and print what would change, write nothing" + type: boolean + default: false + +# Least privilege: it edits issue bodies (and may create one issue), nothing else. +permissions: + contents: read + issues: write + +concurrency: + # Two overlapping runs would both append the same new lines. + group: integrity-sweep + cancel-in-progress: false + +jobs: + sweep: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - uses: actions/setup-node@v4 + with: + node-version: "20" + + # No secrets: if the reconciliation logic is broken, fail before touching issues. + - name: Verify the reconcile logic + run: node scripts/integrity-sweep/sweep.mjs --self-check + + - name: Sweep and reconcile issues + env: + INTEGRITY_URL: ${{ secrets.INTEGRITY_URL }} + DIGEST_TOKEN: ${{ secrets.DIGEST_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DRY_RUN: ${{ inputs.dry_run && '1' || '0' }} + run: | + if [ "$DRY_RUN" = "1" ]; then + node scripts/integrity-sweep/sweep.mjs --dry-run + else + node scripts/integrity-sweep/sweep.mjs + fi diff --git a/atlas/app/api/ops/integrity/route.ts b/atlas/app/api/ops/integrity/route.ts new file mode 100644 index 0000000..03ef69e --- /dev/null +++ b/atlas/app/api/ops/integrity/route.ts @@ -0,0 +1,32 @@ +// Certain-only data-integrity findings for the weekly sweep +// (scripts/integrity-sweep/sweep.mjs, run by .github/workflows/integrity-sweep.yml). +// +// GitHub Actions has no DB credentials on purpose, so the sweep reads Atlas through +// this route. Read-only, all orgs. The payload is project ids, field names and +// fixed problem sentences (lib/integrity.ts) — never a stored value — but it is +// still bearer-gated and fails closed, like /api/digest/weekly. +import { timingSafeEqual } from "node:crypto"; +import { getAllProjectsAdmin } from "@/lib/db"; +import { integrityFindings } from "@/lib/integrity"; + +function bearerMatches(header: string | null, token: string): boolean { + const a = Buffer.from(header || ""); + const b = Buffer.from(`Bearer ${token}`); + return a.length === b.length && timingSafeEqual(a, b); +} + +export async function GET(req: Request) { + const token = process.env.DIGEST_TOKEN; + const noStore = { "Cache-Control": "no-store" }; + if (!token) return Response.json({ error: "Integrity sweep is not configured (DIGEST_TOKEN unset)." }, { status: 503, headers: noStore }); + if (!bearerMatches(req.headers.get("authorization"), token)) { + return Response.json({ error: "Unauthorized" }, { status: 401, headers: noStore }); + } + const projects = await getAllProjectsAdmin(); + // projectCount lets the sweep refuse an empty read: zero findings from zero + // projects would otherwise tick every open line as "fixed". + return Response.json( + { projectCount: projects.length, findings: integrityFindings(projects), generatedAt: new Date().toISOString() }, + { headers: noStore } + ); +} diff --git a/atlas/lib/integrity.test.ts b/atlas/lib/integrity.test.ts new file mode 100644 index 0000000..4a576f8 --- /dev/null +++ b/atlas/lib/integrity.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect } from "vitest"; +import { personValueProblems, repoUrlProblems, projectIntegrity } from "./integrity"; +import type { Project, Run } from "./types"; + +// Fictional data only. +const run = (o: Partial = {}): Run => ({ term: "Fall 2025", course: "DS519", discipline: "SWE", students: [], ...o }); +const project = (o: Partial = {}): Project => + ({ id: "demo-proj", title: "Demo", blurb: "A tool that maps bus stops for a city agency.", partner: "Example Org", + clientType: "Nonprofit", tech: ["Python"], runs: [run()], ...o }) as Project; +const causes = (p: Project) => projectIntegrity(p).map((f) => `${f.cause}:${f.field}`); + +describe("personValueProblems", () => { + it("accepts ordinary names, including a preferred-name parenthetical", () => { + for (const v of ["Alex Rivera", "Wei (Amy) Zhang", "Jean-Luc Picard", "", " "]) { + expect(personValueProblems(v), v).toEqual([]); + } + }); + it("flags placeholders", () => { + for (const v of ["N/A", "TBD", "no EIR", "None yet", "Teammate 2", "Mentor Mentor"]) { + expect(personValueProblems(v), v).toEqual(["holds a placeholder, not a person"]); + } + }); + it("flags role labels glued to a name", () => { + expect(personValueProblems("Class Instructor Alex Rivera")).toContain("has a role label glued to the name"); + expect(personValueProblems("Client Sam Lee")).toContain("has a role label glued to the name"); + }); + it("flags two people in one field", () => { + expect(personValueProblems("Alex Rivera and Sam Lee")).toContain("holds more than one person"); + expect(personValueProblems("Alex Rivera // Sam Lee")).toContain("holds more than one person"); + }); + it("flags GitHub handles", () => { + expect(personValueProblems("Alex Rivera (arivera42)")).toContain("has a GitHub handle glued to the name"); + expect(personValueProblems("Alex Rivera (@arivera)")).toContain("has a GitHub handle glued to the name"); + expect(personValueProblems("Alex Rivera (GitHub: AR)")).toContain("has a GitHub handle glued to the name"); + }); + it("flags emails", () => { + expect(personValueProblems("alex@example.com")).toEqual(["holds an email address, not a name"]); + }); +}); + +describe("repoUrlProblems", () => { + it("accepts a repo root and non-GitHub hosts", () => { + expect(repoUrlProblems("https://github.com/example/demo")).toEqual([]); + expect(repoUrlProblems("https://github.com/example")).toEqual([]); + expect(repoUrlProblems("https://gitlab.com/a/b/-/tree/x")).toEqual([]); + }); + it("flags branch, issue, .git and non-URLs", () => { + expect(repoUrlProblems("https://github.com/example/demo/tree/dev")[0]).toMatch(/branch/); + expect(repoUrlProblems("https://github.com/example/demo/issues/3")[0]).toMatch(/issue/); + expect(repoUrlProblems("https://github.com/example/demo.git")).toEqual(['ends in ".git"']); + expect(repoUrlProblems("separate org")).toEqual(["is not a valid web address"]); + }); +}); + +describe("projectIntegrity", () => { + it("a clean project has no findings", () => { + expect(projectIntegrity(project({ repoUrl: "https://github.com/example/demo" }))).toEqual([]); + }); + + it("role findings name the run and field, never the value", () => { + const f = projectIntegrity(project({ runs: [run({ pm: "Alex Rivera and Sam Lee", classInstructors: ["TBD"] })] })); + expect(f.map((x) => x.field)).toEqual(["runs[Fall 2025].pm", "runs[Fall 2025].classInstructors[0]"]); + expect(f.every((x) => x.cause === "roles")).toBe(true); + expect(JSON.stringify(f)).not.toMatch(/Alex|Sam|TBD/); + }); + + it("blurb and tech-note text rules reuse the PD sync holds", () => { + const p = project({ + blurb: "We map bus stops. Contact alex@example.com for access.", + techNote: "List of tools/ tech stack preferred by client e.g. Tableau, PowerBI\nPython", + clientDesc: "db at postgres://admin:hunter2x@db.example.com/prod", + }); + const c = causes(p); + expect(c).toContain("contact_in_text:blurb"); + expect(c).toContain("tech_note:tech_note"); + expect(c).toContain("credentials:client_desc"); + expect(JSON.stringify(projectIntegrity(p))).not.toMatch(/alex@|hunter2/); + }); + + it("tech list rules", () => { + const c = projectIntegrity(project({ tech: ["Power BI", "PowerBI", "Tableau", "TBD"], techNote: "e.g. Tableau, PowerBI" })) + .map((f) => f.problem); + expect(c.some((x) => /more than once/.test(x))).toBe(true); + expect(c.some((x) => /placeholder/.test(x))).toBe(true); + expect(c.some((x) => /example line/.test(x))).toBe(true); + }); + + it("url rules: Drive folder as PD, non-Drive drive link, repo branch", () => { + const folder = "https://drive.google.com/drive/folders/abc"; + const c = causes(project({ pdUrl: folder, runs: [run({ pdUrl: folder })], driveUrl: "https://example.com/x", + repoUrl: "https://github.com/example/demo/tree/main" })); + expect(c).toEqual(["urls:repo_url", "urls:runs[Fall 2025].pd_url", "urls:drive_url"]); + }); + + it("run rules: malformed term, unknown course, discipline mismatch, duplicate run", () => { + const c = projectIntegrity(project({ runs: [ + run({ term: "" }), + run({ course: "Basket Weaving" }), + run({ term: "Spring 2025", discipline: "ML" }), + run({ term: "Spring 2025", discipline: "ML" }), + run({ term: "Summer 2025", course: "Spark! Summer Internship", discipline: "" }), + ] })).filter((f) => f.cause === "runs").map((f) => f.problem); + expect(c.some((x) => /no term/.test(x))).toBe(true); + expect(c.some((x) => /not one Atlas recognises/.test(x))).toBe(true); + expect(c.some((x) => /contradicts/.test(x))).toBe(true); + expect(c.some((x) => /share the same term/.test(x))).toBe(true); + expect(c.some((x) => /Summer 2025/.test(x))).toBe(false); // internships are fine + }); +}); diff --git a/atlas/lib/integrity.ts b/atlas/lib/integrity.ts new file mode 100644 index 0000000..39a9790 --- /dev/null +++ b/atlas/lib/integrity.ts @@ -0,0 +1,244 @@ +// Deterministic data-integrity rules for the weekly sweep +// (app/api/ops/integrity → scripts/integrity-sweep/sweep.mjs → GitHub issues). +// +// PURE, like lib/checks.ts and lib/pd-check.ts. Only rules that are CERTAINLY wrong +// live here: a finding becomes a checkbox in a public issue, so a heuristic that is +// sometimes fine would just train people to ignore the list. +// +// PRIVACY: the repo and its issues are public. `problem` is always a fixed sentence +// built from field labels and terms; it never interpolates a stored value, so no +// name, email or handle can leak into it. +// +// `cause` must match the issue marker (``) of the +// issue that collects it; the mapping lives in scripts/integrity-sweep/sweep.mjs. +import { cleanPersonName } from "./gdocs"; +import { cleanTechNote } from "./tech"; +import { judgePdFields, parsePd, EMAIL_RE, HOLD_BLURB, HOLD_TECH } from "./pd-check"; +import { checkDisciplines } from "./checks"; +import { disciplineFromCourse } from "./data"; +import { canonicalTerm } from "./semester"; +import type { Project, Run } from "./types"; + +export interface IntegrityFinding { + cause: string; + projectId: string; + field: string; + problem: string; +} + +// ---------------------------------------------------------------- roles ---- + +const ROLE_FIELDS: [keyof Run, string][] = [ + ["sparkProgramLead", "program lead"], + ["pm", "PM"], + ["tpm", "TPM"], + ["eir", "EIR"], + ["seniorAdvisor", "senior advisor"], + ["techAdvisor", "tech advisor"], +]; + +// cleanPersonName already rejects TBD/N/A and bare role labels; these are the +// placeholder sentences it does not know ("no EIR", "TBD - ask client"). +const PLACEHOLDER_START = /^(?:no|none|tbd|tba|n\/a)\b/i; +// A role label in front of a name: "Class Instructor X", "Client X", "Teammate". +const LABEL_GLUED = /^(?:class\s+instructor|instructor|client|teammate|mentor|eir|t?pm)\b|\bteammate\b|\bmentor\s+mentor\b/i; +const TWO_PEOPLE = /\s(?:and|&)\s|\/|;|\n/i; +// A handle in parentheses: "(@x)", "(x123)", "(github: x)" or an all-lowercase +// token. A capitalised parenthetical is a preferred name ("Wei (Amy)") and is fine. +const HANDLE_PAREN = /\((?:@[\w-]+|[^)\s]*\d[^)\s]*|[a-z][a-z0-9_-]*)\)|\([^)]*github[^)]*\)|(?:^|\s)@[\w-]+/; +const HANDLE_GITHUB = /\([^)]*github[^)]*\)/i; + +/** Why a single-person role value is not one person's name ([] = fine). */ +export function personValueProblems(value: string): string[] { + const v = (value || "").trim(); + if (!v) return []; + if (EMAIL_RE.test(v)) return ["holds an email address, not a name"]; + if (!cleanPersonName(v) || PLACEHOLDER_START.test(v)) return ["holds a placeholder, not a person"]; + const out: string[] = []; + if (LABEL_GLUED.test(v)) out.push("has a role label glued to the name"); + if (TWO_PEOPLE.test(v)) out.push("holds more than one person"); + if (HANDLE_PAREN.test(v) || HANDLE_GITHUB.test(v)) out.push("has a GitHub handle glued to the name"); + return out; +} + +const runLabel = (r: Run) => (canonicalTerm(r.term) ? `The ${canonicalTerm(r.term)} run` : "A run with no term"); +const runKey = (r: Run, i: number) => `runs[${canonicalTerm(r.term) || `#${i + 1}`}]`; + +function roleFindings(p: Project): IntegrityFinding[] { + const out: IntegrityFinding[] = []; + p.runs.forEach((r, i) => { + const values: [string, string, string][] = ROLE_FIELDS.map(([k, label]) => [String(k), label, String(r[k] ?? "")]); + (r.classInstructors ?? []).forEach((v, j) => values.push([`classInstructors[${j}]`, "class instructor", v])); + for (const [key, label, v] of values) { + for (const problem of personValueProblems(v)) { + out.push({ cause: "roles", projectId: p.id, field: `${runKey(r, i)}.${key}`, + problem: `${runLabel(r)}'s ${label} field ${problem}.` }); + } + } + }); + return out; +} + +// ----------------------------------------------------------------- text ---- + +// Connection strings with an inline password, provider key prefixes, private keys, +// and "password: ". A bare "password" mention is a +// logistics note (blurb_text), not a leaked secret. +const CREDENTIAL_RE = + /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s/:@]+:[^\s/@]+@|\bAKIA[0-9A-Z]{16}\b|\bgh[pousr]_[A-Za-z0-9]{30,}|\bsk-[A-Za-z0-9_-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:password|passwd|pwd|api[_ -]?key|secret)\s*[:=]\s*(?=\S*[\d!#$%^&*])\S{6,}/i; + +const EMPTY_PD = parsePd(""); + +const BLURB_PROBLEMS: Record = { + "blurb.email": ["contact_in_text", "The public blurb contains an email address."], + "blurb.logistics": ["blurb_text", "The public blurb contains internal logistics (meeting times, logins, pay or to-dos)."], + "blurb.template": ["blurb_text", "The public blurb contains leftover template instructions."], + "blurb.duplicated": ["blurb_text", "The public blurb contains the same text twice."], +}; + +function textFindings(p: Project): IntegrityFinding[] { + const out: IntegrityFinding[] = []; + const add = (cause: string, field: string, problem: string) => out.push({ cause, projectId: p.id, field, problem }); + const blurb = p.blurb || ""; + const techNote = p.techNote || ""; + + // Same rules, same codes, as the PD import's sync holds (lib/pd-check.ts). + for (const f of judgePdFields({ ...EMPTY_PD, blurb, techNote }, { term: "" })) { + if (blurb && HOLD_BLURB.has(f.code) && BLURB_PROBLEMS[f.code]) { + const [cause, problem] = BLURB_PROBLEMS[f.code]; + add(cause, "blurb", problem); + } + if (techNote && HOLD_TECH.has(f.code)) add("contact_in_text", "tech_note", "The tech note contains contact details (names or emails)."); + } + if (p.clientDesc && EMAIL_RE.test(p.clientDesc)) { + add("contact_in_text", "client_desc", "The public client description contains an email address."); + } + + // Anything the PD tech-note cleaner would strip is, by definition, not tech: + // template prompts, "/ Design System", TBD lines, comment anchors, meeting notes. + const lines = (s: string) => s.split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim()).join("\n").trim(); + if (techNote && lines(cleanTechNote(techNote)) !== lines(techNote)) { + add("tech_note", "tech_note", "The tech note contains PD template text, placeholders or pasted notes that are not tech."); + } + + for (const [field, text] of [["blurb", blurb], ["tech_note", techNote], ["client_desc", p.clientDesc || ""]]) { + if (CREDENTIAL_RE.test(text)) add("credentials", field, `The ${field.replace("_", " ")} contains what looks like a password, key or connection string.`); + } + return out; +} + +// ----------------------------------------------------------------- tech ---- + +const TAG_PLACEHOLDER = /^(?:e\.g\.?\b.*|tbd|tba|n\/?a|none|list of tools.*|tech stack.*)$/i; +const techKey = (t: string) => t.toLowerCase().replace(/[\s._-]+/g, ""); + +function techFindings(p: Project): IntegrityFinding[] { + const out: IntegrityFinding[] = []; + const add = (problem: string) => out.push({ cause: "tech", projectId: p.id, field: "tech", problem }); + const tech = (p.tech ?? []).map((t) => (t || "").trim()).filter(Boolean); + const keys = tech.map(techKey); + if (new Set(keys).size !== keys.length) add("The tech list has the same tool more than once (possibly under two spellings)."); + if (tech.some((t) => TAG_PLACEHOLDER.test(t))) add("The tech list contains a placeholder or template prompt, not a tool."); + // The PD template's example line is "e.g. Tableau, PowerBI"; both tags plus that + // prompt still in the note means the tags came from the example. + if (keys.includes("tableau") && keys.includes("powerbi") && /e\.g\.?,?\s*tableau/i.test(p.techNote || "")) { + add("Tableau and Power BI were parsed from the PD template's example line, not the project's tools."); + } + return out; +} + +// ----------------------------------------------------------------- urls ---- + +function parseUrl(s: string): URL | null { + try { + const u = new URL(s); + return u.protocol === "http:" || u.protocol === "https:" ? u : null; + } catch { + return null; + } +} + +const DRIVE_FOLDER = /^\/drive\/(?:u\/\d+\/)?folders\//; +const isDriveHost = (u: URL) => /^(?:drive|docs)\.google\.com$/i.test(u.hostname); + +/** Why a repo URL is malformed ([] = fine). Only GitHub's shape is judged. */ +export function repoUrlProblems(raw: string): string[] { + const s = (raw || "").trim(); + if (!s) return []; + const u = parseUrl(s); + if (!u) return ["is not a valid web address"]; + if (!/^(?:www\.)?github\.com$/i.test(u.hostname)) return []; + const segs = u.pathname.split("/").filter(Boolean); + const out: string[] = []; + if (segs.length >= 3) { + const kind = segs[2].toLowerCase(); + if (["issues", "pull", "pulls"].includes(kind)) out.push("points at an issue or pull request, not the repository"); + else if (["tree", "blob", "commit", "commits", "branches"].includes(kind)) out.push("points at a branch, commit or file, not the repository root"); + else out.push("points inside the repository, not its root"); + } + if (segs.length >= 2 && /\.git$/i.test(segs[1])) out.push('ends in ".git"'); + return out; +} + +function urlFindings(p: Project): IntegrityFinding[] { + const out: IntegrityFinding[] = []; + const add = (field: string, problem: string) => out.push({ cause: "urls", projectId: p.id, field, problem }); + for (const why of repoUrlProblems(p.repoUrl || "")) add("repo_url", `repo_url ${why}.`); + + const pd = (field: string, label: string, raw: string | null | undefined) => { + const s = (raw || "").trim(); + if (!s) return; + const u = parseUrl(s); + if (!u) add(field, `${label} is not a valid web address.`); + else if (isDriveHost(u) && DRIVE_FOLDER.test(u.pathname)) add(field, `${label} is a Drive folder, not the project-description document.`); + }; + // The top-level pd_url is derived from the latest run, so only report it when + // no run already carries the same value (otherwise every line doubles). + if (!p.runs.some((r) => (r.pdUrl || "").trim() === (p.pdUrl || "").trim())) pd("pd_url", "pd_url", p.pdUrl); + p.runs.forEach((r, i) => pd(`${runKey(r, i)}.pd_url`, `${runLabel(r)}'s pd_url`, r.pdUrl)); + + const drive = (p.driveUrl || "").trim(); + if (drive) { + const u = parseUrl(drive); + if (!u || !isDriveHost(u)) add("drive_url", "drive_url is not a Google Drive link."); + } + return out; +} + +// ----------------------------------------------------------------- runs ---- + +function runFindings(p: Project): IntegrityFinding[] { + const out: IntegrityFinding[] = []; + const seen = new Set(); + p.runs.forEach((r, i) => { + const add = (problem: string) => out.push({ cause: "runs", projectId: p.id, field: runKey(r, i), problem }); + const course = (r.course || "").trim(); + if (!canonicalTerm(r.term)) add("A run has no term or a malformed one (expected \"Fall YYYY\", \"Spring YYYY\" or \"Summer YYYY\")."); + if (course && !disciplineFromCourse(course) && !/internship/i.test(course)) { + add(`${runLabel(r)}'s course is not one Atlas recognises.`); + } + if (checkDisciplines([r]).some((f) => f.code === "discipline.mismatch")) { + add(`${runLabel(r)}'s discipline contradicts the discipline its course implies.`); + } + const k = `${canonicalTerm(r.term)}|${course.toLowerCase()}`; + if (canonicalTerm(r.term) && seen.has(k)) add(`Two runs share the same term and course (${canonicalTerm(r.term)}).`); + seen.add(k); + }); + return out; +} + +// ------------------------------------------------------------------ all ---- + +/** Every certain-only finding for one project, deduped, in a stable order. */ +export function projectIntegrity(p: Project): IntegrityFinding[] { + const all = [...roleFindings(p), ...textFindings(p), ...techFindings(p), ...urlFindings(p), ...runFindings(p)]; + const seen = new Set(); + return all.filter((f) => { + const k = `${f.cause}|${f.field}|${f.problem}`; + return seen.has(k) ? false : (seen.add(k), true); + }); +} + +export function integrityFindings(projects: Project[]): IntegrityFinding[] { + return projects.flatMap(projectIntegrity); +} diff --git a/atlas/lib/pd-check.ts b/atlas/lib/pd-check.ts index 4fc5687..da10c8e 100644 --- a/atlas/lib/pd-check.ts +++ b/atlas/lib/pd-check.ts @@ -312,7 +312,7 @@ const LOGISTICS: RegExp[] = [ /\bto be provided by\b/i, ]; const BLURB_TEMPLATE = /\b(?:insert|briefly describe|describe the project|provide a (?:brief )?(?:summary|description))\b|lorem ipsum/i; -const EMAIL_RE = /[\w.+-]+@[\w-]+\.[\w.]+/; +export const EMAIL_RE = /[\w.+-]+@[\w-]+\.[\w.]+/; const PM_ROLE = /^(?:pm|project manager)$/i; const TPM_ROLE = /^(?:tpm|technical project manager)$/i; @@ -667,8 +667,8 @@ export function checkPd( // Findings that mean a value must not be written by the automatic sync: each is // wrong on any page, not a style note. "Talks to students" is left out on purpose — // on current PDs it fires on fine third-person text ("Students will build…"). -const HOLD_BLURB = new Set(["blurb.email", "blurb.logistics", "blurb.template", "blurb.duplicated"]); -const HOLD_TECH = new Set(["tech.contacts_bleed"]); +export const HOLD_BLURB = new Set(["blurb.email", "blurb.logistics", "blurb.template", "blurb.duplicated"]); +export const HOLD_TECH = new Set(["tech.contacts_bleed"]); /** * Why the sync should NOT write this description / tech note, as messages diff --git a/scripts/integrity-sweep/sweep.mjs b/scripts/integrity-sweep/sweep.mjs new file mode 100644 index 0000000..f767978 --- /dev/null +++ b/scripts/integrity-sweep/sweep.mjs @@ -0,0 +1,271 @@ +#!/usr/bin/env node +// Weekly Atlas data-integrity sweep: reconcile GET /api/ops/integrity into the +// per-cause `data-integrity` GitHub issues (#338–#348). +// +// The issue body IS the state. For each issue: +// • a finding not yet listed → append "- [ ] `id` (field): problem " +// • a line the sweep wrote whose finding is gone → "- [ ]" becomes "- [x]" +// • nothing is ever deleted, and a line is only touched if it is an UNEDITED sweep +// line (KEY is a hash of its own text, so any human edit makes it foreign). +// • a ticked line whose finding came back gets a fresh unticked line; the ticked +// one is left alone (it may have been ticked by a person). +// Running twice changes nothing. +// +// Lines from the manual sweep are never ticked: their wording differs from the +// rules', so "not found by a rule" does not mean "fixed". To avoid listing the same +// row twice, a finding is not appended while an open human line names that project. +// ponytail: suppression is per project id per issue, not per problem; a second +// problem on the same project surfaces once the human line is ticked. +// +// node scripts/integrity-sweep/sweep.mjs --self-check # logic only, no network +// node scripts/integrity-sweep/sweep.mjs --dry-run # read everything, print, write nothing +// node scripts/integrity-sweep/sweep.mjs # CI: write issues +// +// Env: INTEGRITY_URL, DIGEST_TOKEN, GITHUB_TOKEN, GITHUB_REPOSITORY (set by Actions). +import { createHash } from "node:crypto"; + +const DRY = process.argv.includes("--dry-run"); +const SELF_CHECK = process.argv.includes("--self-check"); +const REPO = process.env.GITHUB_REPOSITORY || "BU-Spark/spark-portfolio"; +const LABEL = "data-integrity"; + +// cause (from lib/integrity.ts and the `` marker +// in each issue) → issue number. Anything not listed goes to the catch-all issue. +const CAUSE_ISSUES = { + blurb_overwritten: 338, + contact_in_text: 339, + tech_note: 340, + partner: 341, + roles: 342, + blurb_text: 343, + runs: 344, + urls: 345, + dupes: 346, + tech: 347, + people: 348, +}; +const CATCH_ALL_MARKER = ""; +const MAX_BODY = 65536; // GitHub's issue body limit + +// ── Pure reconciliation ────────────────────────────────────────────────── + +// Server text is ours, but it lands in markdown: keep each finding on one line and +// unable to forge a marker or break out of the code span. +const clean = (s) => String(s ?? "").replace(/[\r\n]+/g, " ").replace(/|`/g, "").trim(); +const keyOf = (id, field, problem) => createHash("sha256").update(`${id}|${field}|${problem}`).digest("hex").slice(0, 12); +const render = (f, done = false) => + `- [${done ? "x" : " "}] \`${f.projectId}\` (${f.field}): ${f.problem} `; + +const SWEEP_LINE = /^- \[([ xX])\] `([^`]+)` \(([^)]*)\): (.*) $/; +const ANY_BOX = /^- \[([ xX])\] `([^`]+)`/; + +export function normalizeFindings(findings) { + return findings + .map((f) => ({ cause: clean(f.cause), projectId: clean(f.projectId), field: clean(f.field).replace(/[()]/g, ""), problem: clean(f.problem) })) + .filter((f) => f.cause && f.projectId && f.field && f.problem); +} + +/** New body for one issue given the findings routed to it. Pure. */ +export function reconcile(body, findings) { + const lines = (body || "").replace(/\r\n/g, "\n").split("\n"); + const current = new Map(findings.map((f) => [keyOf(f.projectId, f.field, f.problem), f])); + const openKeys = new Set(); + const humanOpenIds = new Set(); + let lastBox = -1; + let ticked = 0; + + lines.forEach((line, i) => { + const box = line.match(ANY_BOX); + if (!box) return; + lastBox = i; + const m = line.match(SWEEP_LINE); + const ours = m && keyOf(m[2], m[3], m[4]) === m[5]; + if (!ours) { + if (box[1] === " ") humanOpenIds.add(box[2]); + return; + } + if (m[1] !== " ") return; // ticked: never touched + if (current.has(m[5])) openKeys.add(m[5]); + else { + lines[i] = line.replace("- [ ]", "- [x]"); + ticked++; + } + }); + + const added = []; + for (const [k, f] of current) { + if (openKeys.has(k) || humanOpenIds.has(f.projectId)) continue; + added.push(render(f)); + } + if (added.length) { + if (lastBox >= 0) lines.splice(lastBox + 1, 0, ...added); + else lines.push("", "### Found by the weekly sweep", ...added); + } + return { body: lines.join("\n"), ticked, added: added.length }; +} + +/** issue number (or "other") → findings. */ +export function route(findings) { + const out = new Map(); + for (const f of findings) { + const n = CAUSE_ISSUES[f.cause] ?? "other"; + if (!out.has(n)) out.set(n, []); + out.get(n).push(f); + } + return out; +} + +// ── Network ────────────────────────────────────────────────────────────── + +async function fetchWithTimeout(url, opts = {}, ms = 60000) { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), ms); + try { + return await fetch(url, { ...opts, signal: ctrl.signal }); + } finally { + clearTimeout(t); + } +} + +async function gh(path, opts = {}) { + const token = process.env.GITHUB_TOKEN; + const res = await fetchWithTimeout(`https://api.github.com${path}`, { + ...opts, + headers: { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...(opts.body ? { "Content-Type": "application/json" } : {}), + }, + }); + if (!res.ok) throw new Error(`GitHub ${opts.method || "GET"} ${path} → ${res.status}: ${(await res.text()).slice(0, 300)}`); + return res.json(); +} + +async function fetchFindings() { + const url = process.env.INTEGRITY_URL; + const token = process.env.DIGEST_TOKEN; + if (!url || !token) throw new Error("INTEGRITY_URL and DIGEST_TOKEN must be set."); + const res = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${token}` } }, 120000); + if (res.status !== 200) throw new Error(`Integrity endpoint returned HTTP ${res.status}`); + const data = await res.json(); + // Fail closed: an empty or malformed read must never tick every line as fixed. + if (!Array.isArray(data.findings)) throw new Error("Integrity response has no findings array."); + if (!(data.projectCount > 0)) throw new Error("Integrity endpoint read zero projects; refusing to reconcile."); + return { projectCount: data.projectCount, findings: normalizeFindings(data.findings) }; +} + +async function findCatchAll() { + for (let page = 1; page <= 10; page++) { + const list = await gh(`/repos/${REPO}/issues?labels=${LABEL}&state=all&per_page=100&page=${page}`); + const hit = list.find((i) => !i.pull_request && (i.body || "").includes(CATCH_ALL_MARKER)); + if (hit) return hit; + if (list.length < 100) return null; + } + return null; +} + +async function main() { + const { projectCount, findings } = await fetchFindings(); + console.log(`${findings.length} finding(s) across ${projectCount} project(s).`); + const routed = route(findings); + + // Every mapped issue is reconciled even with zero findings, so fixed lines tick. + const targets = Object.values(CAUSE_ISSUES).map((n) => ({ n, findings: routed.get(n) ?? [] })); + const other = routed.get("other") ?? []; + let catchAll = await findCatchAll(); + if (!catchAll && other.length) { + const causes = [...new Set(other.map((f) => f.cause))].join(", "); + if (DRY) console.log(`[dry-run] would create the catch-all issue for: ${causes}`); + else { + catchAll = await gh(`/repos/${REPO}/issues`, { + method: "POST", + body: JSON.stringify({ + title: "[Atlas integrity] Other findings from the weekly sweep", + labels: [LABEL], + body: `${CATCH_ALL_MARKER}\n**What:** Findings from the weekly integrity sweep whose cause has no dedicated issue (for example credentials or secrets pasted into a free-text field). Rows are referenced by project id and field only, because this repository is public.\n\n**How to resolve:** Fix the record in Atlas; the sweep ticks the line on its next run.\n\n### Affected`, + }), + }); + console.log(`Created catch-all issue #${catchAll.number}.`); + } + } + if (catchAll) targets.push({ n: catchAll.number, findings: other }); + + let failed = 0; + for (const { n, findings: fs } of targets) { + try { + const issue = await gh(`/repos/${REPO}/issues/${n}`); + const { body, ticked, added } = reconcile(issue.body || "", fs); + if (body === (issue.body || "").replace(/\r\n/g, "\n")) { + console.log(`#${n}: no change`); + continue; + } + if (body.length > MAX_BODY) throw new Error(`body would be ${body.length} chars (limit ${MAX_BODY})`); + const reopen = added > 0 && issue.state === "closed"; + console.log(`#${n}: tick ${ticked}, add ${added}${reopen ? ", reopen" : ""}`); + if (DRY) continue; + // ponytail: read-modify-write without a lock; a human edit in the second + // between GET and PATCH is lost. Fine for a weekly job. + await gh(`/repos/${REPO}/issues/${n}`, { + method: "PATCH", + body: JSON.stringify({ body, ...(reopen ? { state: "open" } : {}) }), + }); + } catch (e) { + failed++; + console.error(`#${n}: ${e.message}`); + } + } + if (failed) throw new Error(`${failed} issue(s) failed to reconcile.`); +} + +// ── Self-check ─────────────────────────────────────────────────────────── + +function selfCheck() { + const assert = (c, msg) => { + if (!c) throw new Error(`self-check failed: ${msg}`); + }; + const f1 = { cause: "roles", projectId: "demo-a", field: "runs[Fall 2025].pm", problem: "The Fall 2025 run's PM field holds more than one person." }; + const f2 = { cause: "roles", projectId: "demo-b", field: "runs[Fall 2025].eir", problem: "The Fall 2025 run's EIR field holds a placeholder, not a person." }; + const base = "\n**What:** x\n\n### Affected (1)\n- [ ] `demo-c`: human line.\n\nfooter"; + + // Append after the last checkbox, not after the footer. + const r1 = reconcile(base, [f1, f2]); + assert(r1.added === 2 && r1.ticked === 0, "two new findings appended"); + assert(r1.body.split("\n").at(-1) === "footer", "appended inside the list"); + // Idempotent. + const r2 = reconcile(r1.body, [f1, f2]); + assert(r2.body === r1.body && r2.added === 0 && r2.ticked === 0, "second run changes nothing"); + // Gone finding ticks; human line untouched. + const r3 = reconcile(r2.body, [f2]); + assert(r3.ticked === 1 && r3.body.includes(render(f1, true)) && r3.body.includes("- [ ] `demo-c`: human line."), "gone → ticked"); + assert(reconcile(r3.body, [f2]).body === r3.body, "ticked stays ticked"); + // Never edits a line a human changed. + const edited = r1.body.replace("holds more than one person.", "holds two people (checked with staff)."); + const r4 = reconcile(edited, []); + assert(r4.body.includes("- [ ] `demo-a` (runs[Fall 2025].pm): The Fall 2025 run's PM field holds two people"), "edited line untouched"); + assert(r4.ticked === 1, "only the unedited line ticks"); + // Regression after a tick: a fresh line, the ticked one kept; then stable. + const r5 = reconcile(r3.body, [f1, f2]); + assert(r5.added === 1 && r5.body.includes(render(f1, true)) && r5.body.includes(render(f1)), "regression re-listed"); + assert(reconcile(r5.body, [f1, f2]).body === r5.body, "regression stable"); + // An open human line for the same project suppresses a duplicate. + assert(reconcile(base, [{ ...f1, projectId: "demo-c" }]).added === 0, "human line suppresses"); + // Never deletes a line. + assert(r3.body.split("\n").length === r2.body.split("\n").length, "line count preserved"); + // No list yet → a heading is added. + assert(reconcile("intro", [f1]).body.includes("### Found by the weekly sweep"), "heading for empty body"); + // Routing. + const routed = route([f1, { ...f1, cause: "credentials" }]); + assert(routed.get(342).length === 1 && routed.get("other").length === 1, "routing"); + // Sanitising: no forged markers or broken spans. + const [n] = normalizeFindings([{ ...f1, problem: "a\n `x`" }]); + assert(!n.problem.includes("\n") && !n.problem.includes("