Files
streamline/scripts/backfill_meego_closed_review.ts
2026-11-16 17:26:44 -08:00

162 lines
6.2 KiB
TypeScript

#!/usr/bin/env bun
/**
* Backfill: `manual_review` bugs whose Meego ticket is already Close / Done.
*
* Marks them `fix_succeeded` (看板「修复成功 / Fixed」), writes the live Meego
* state, and scans the bound Bits MR the same way mr_sync does. No Lark card,
* no Meego comment, no Meego transition — the ticket is already closed.
*
* bun scripts/backfill_meego_closed_review.ts # dry-run
* bun scripts/backfill_meego_closed_review.ts --commit # write
*
* Routing after the write (comboTaskStateOf):
* Meego resolved/open → awaiting_qa
* Meego close/done + MR closed → merged (DONE)
* Meego close/done (else) → awaiting_merge
* Bits merged → merged (DONE)
* Merged MRs stamp `mrMergedAt` from Bits merged_time, then create_time —
* never Date.now(), so the dashboard doesn't pile every merge on today.
*
* Pass `--resolved` to also accept Meego RESOLVED (→ 待 QA), not just close/done.
*/
import { readFileSync } from "node:fs";
import { getTask, updateTask, listTasks } from "../control-server/src/db";
import { BITS_FIXED_OPERATOR, getMrInfo, extractMrIdFromUrl, mrStatePatchFromInfo } from "../control-server/src/bits";
import { broadcast } from "../control-server/src/bus";
import { enrichTask } from "../control-server/src/enrich";
import { comboTaskStateOf, meegoIsClosed } from "../control-server/src/types";
import type { Task } from "../control-server/src/types";
/**
* meegoId → live Meego state_key. Default file is written by the investigation
* (CLOSE/DONE only). Plugin OpenAPI from a laptop often can't mint a token
* against meego.larkoffice.com, so we don't re-fetch here — the file is the
* live snapshot. Override with --states PATH (JSON object).
*/
function loadStates(): Map<string, string> {
const idx = process.argv.indexOf("--states");
const path = idx >= 0 ? process.argv[idx + 1] : "/tmp/sl-meego-closed-states.json";
const allowResolved = process.argv.includes("--resolved");
const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, string>;
const m = new Map<string, string>();
for (const [id, state] of Object.entries(raw)) {
const s = String(state).toLowerCase();
if (meegoIsClosed(state) || (allowResolved && s === "resolved")) m.set(String(id), state);
}
return m;
}
const COMMIT = process.argv.includes("--commit");
interface Plan {
id: string;
title: string;
meegoId: string;
meegoLive: string;
mrUrl: string | null;
patch: Partial<Task>;
combo: ReturnType<typeof comboTaskStateOf>;
bitsError?: string;
}
function comboOf(t: Task, patch: Partial<Task>) {
return comboTaskStateOf({
mrState: patch.mrState !== undefined ? (patch.mrState as string | null) : t.mrState,
meegoState: patch.meegoState !== undefined ? (patch.meegoState as string | null) : t.meegoState,
});
}
async function planOne(t: Task, meegoLive: string): Promise<Plan> {
const patch: Partial<Task> = {
status: "fix_succeeded",
meegoState: meegoLive,
mrSyncedAt: Date.now(),
failureReason: null,
};
let bitsError: string | undefined;
const mrId = t.mrUrl ? extractMrIdFromUrl(t.mrUrl) : null;
if (mrId) {
const info = await getMrInfo(mrId, null, BITS_FIXED_OPERATOR);
if (!info.ok) bitsError = info.error || "getMrInfo failed";
else Object.assign(patch, mrStatePatchFromInfo(t, info));
}
return {
id: t.id,
title: t.title,
meegoId: t.meegoId!,
meegoLive,
mrUrl: t.mrUrl,
patch,
combo: comboOf(t, patch),
bitsError,
};
}
const states = loadStates();
console.log(`[backfill] loaded ${states.size} close/done Meego id(s) from snapshot`);
const all = await listTasks();
const review = all.filter((t) => t.status === "manual_review" && t.meegoId);
console.log(`[backfill] ${review.length} manual_review bug(s) with a Meego id (commit=${COMMIT})`);
const plans: Plan[] = [];
let notInSnapshot = 0;
for (const t of review) {
const live = states.get(String(t.meegoId));
if (!live) { notInSnapshot++; continue; }
plans.push(await planOne(t, live));
}
const byCombo: Record<string, number> = {};
for (const p of plans) byCombo[p.combo ?? "null"] = (byCombo[p.combo ?? "null"] ?? 0) + 1;
const withMr = plans.filter((p) => p.mrUrl).length;
const mergedAtSet = plans.filter((p) => p.patch.mrMergedAt != null).length;
const bitsFail = plans.filter((p) => p.bitsError).length;
console.log(`[backfill] eligible close/done: ${plans.length} not in snapshot: ${notInSnapshot}`);
console.log(`[backfill] with MR: ${withMr} no MR: ${plans.length - withMr} mrMergedAt stamped: ${mergedAtSet} bits errors: ${bitsFail}`);
console.log(`[backfill] combo after write:`, byCombo);
const sample = (rows: Plan[], n = 8) => {
for (const p of rows.slice(0, n)) {
const mr = p.patch.mrState ?? "(none)";
const at = p.patch.mrMergedAt ? new Date(p.patch.mrMergedAt as number).toISOString() : "-";
console.log(` ${p.combo ?? "?"} meego=${p.meegoLive} mr=${mr} mergedAt=${at} ${p.meegoId} ${p.id.slice(0, 8)} ${p.title.slice(0, 60)}`);
if (p.bitsError) console.log(` bits: ${p.bitsError}`);
}
if (rows.length > n) console.log(` … +${rows.length - n} more`);
};
console.log("\n— awaiting_merge (MR still open) —");
sample(plans.filter((p) => p.combo === "awaiting_merge"));
console.log("\n— awaiting_qa (Meego resolved / open) —");
sample(plans.filter((p) => p.combo === "awaiting_qa"), 12);
console.log("\n— merged / DONE (no open MR) —");
sample(plans.filter((p) => p.combo === "merged"), 12);
if (!COMMIT) {
console.log("\n[backfill] dry-run. pass --commit to write.");
process.exit(0);
}
let ok = 0;
let fail = 0;
for (const p of plans) {
try {
const fresh = await getTask(p.id);
if (!fresh || fresh.status !== "manual_review") {
console.warn(`[backfill] skip ${p.id}: status is now ${fresh?.status ?? "gone"}`);
continue;
}
await updateTask(p.id, p.patch);
const next = await getTask(p.id);
if (next) broadcast({ type: "task:updated", payload: await enrichTask(next) });
ok++;
} catch (err) {
fail++;
console.warn(`[backfill] ${p.id}: ${(err as Error).message}`);
}
}
console.log(`[backfill] wrote ${ok}, failed ${fail}`);
process.exit(fail ? 1 : 0);