From 64662747ab95239cd8a40d8a72186525084a4c2f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:17:57 +0000 Subject: [PATCH 1/7] feat(pm): landing-k reads PRBASE, K and the two any-K legs before a landing Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- .../pm-dispatch/references/coordinator.md | 2 +- .../references/landing-operations.md | 8 +- scripts/pm/landing-k.mjs | 705 ++++++++++++++++++ 3 files changed, 710 insertions(+), 5 deletions(-) create mode 100644 scripts/pm/landing-k.mjs diff --git a/.claude/skills/pm-dispatch/references/coordinator.md b/.claude/skills/pm-dispatch/references/coordinator.md index f877c50d162..887ad8738e7 100644 --- a/.claude/skills/pm-dispatch/references/coordinator.md +++ b/.claude/skills/pm-dispatch/references/coordinator.md @@ -47,5 +47,5 @@ ## 七、语言与汇报(coordinator 与席位线程皆读) - 项目内对维护者用维护者的语言;GitHub 内容英文,照 SKILL.md 全体座位不变量。 -- 向维护者报任一 PR 状态前同轮重读:merged、draft、auto_merge、在队、reviews、`mergeable_state`。 +- 向维护者报 PR 状态前同轮读 `pr-state.mjs`:merged/draft/auto_merge/在队/reviews/`mergeable_state`。 - 无 APPROVED 也可能已被 ready 入队 ⇒ ⛔ 单读 reviews;已办即删;`dirty` ⇒ 退回线程先合 main。 diff --git a/.claude/skills/pm-dispatch/references/landing-operations.md b/.claude/skills/pm-dispatch/references/landing-operations.md index 2bb7525d9b7..010c7603ad7 100644 --- a/.claude/skills/pm-dispatch/references/landing-operations.md +++ b/.claude/skills/pm-dispatch/references/landing-operations.md @@ -38,10 +38,10 @@ - 该 op 实测离队见 `readings-queue.md`;在队受管面 PR 亦由落地席发(Prime Directive #14)。 - 谁入队谁看护:冲突或自因被踢 ⇒ 一轮巡查内出队修复再入队;他人 flake 照四分支重投。 - PR 侧红(非队列)同在本窗口处置:义务与三步只住 `readings-ci.md`「红检查先读日志」。 -- 挂 auto-merge/入队前读 K = `git rev-list --count --first-parent PRBASE..origin/main`。 +- 挂 auto-merge/入队前读 K = PRBASE 至 origin/main 的首父提交数,现读 `landing-k.mjs --pr N`。 - PRBASE = 末次绿 PR 跑 Test Core 所印 `Affected-set diff base`,⛔ 不取该跑起始时刻。 - K ≥ 15 ⇒ 先 merge main 等重跑绿,`behind` 例外;任何 K 同:标签 PR 的 PRBASE 后 main 落新语种包; -- 或共享预算 PR 遇 `git diff --name-only PRBASE..origin/main` 碰同本输入或账本;封闭两本,输入:账本: +- 或共享预算 PR 遇 PRBASE 后 main 碰同本输入或账本;封闭两本,输入:账本: - `skills/**`:`scripts/check-skills-token-ratchet.mjs`;`ui/**/locales/en.ts`:`ui/scripts/check-eager-closure-budget.mjs` - 标签即 `check-generated-translation-bundles`、`check-no-new-untranslated-declared-labels` 所计显示标签。 @@ -74,11 +74,11 @@ - 一态 = `pm:queue`+其车道 `domain:*`(归他车道即改域)/`pm:blocked`+`Blocked-by:`/hold+`Restart-when:`。 - 同笔评论写清交付了什么、剩下归谁;摘态不补态由写门拒收(`state-machine.md` 跨状态通则)。 - 每次合并后重拉一次车道盘点与预期状态对账,⛔ 不留给下轮巡检。 -- 取 open 卡清单对照预期 diff:预期之外从 open 消失的,就是被闭合关键词静默误关的卡。 +- 预期外从 open 消失的即被闭合关键词静默误关的卡;每次合并读 `sweep-closed-cards.mjs --pr N`。 - 落地后再核一次落地判据本身:队列的合并同样走 os-regen,A 的静默吞并一样能发生。 - 验收要 staging 读数:合并后经中继派 cloud `deploy-staging.yml` 一次,同合并仅一次,卡记运行号。 - MERGED 不是终点:发版后义务见 `release-aftercare.md`。 -- PR 开出至 MERGED,每看一眼(唤醒/巡检/报告前)同读检查与 `mergeable_state`;`unknown` 即重读。 +- PR 至 MERGED 每看一眼(唤醒/巡检/报告前)读检查与 `mergeable_state`,`unknown` 重读:`pr-state.mjs`。 - `dirty` ⇒ 当即合 `origin/main` 推新提交,⛔ 不等冲突通知;未见非 `dirty` ⛔ 不报无需你做。 这一移 head 的撤挂与重挂照 `contract-review.md` head 后移例外条。 - MERGED 或关闭即退订,同刻把 `mode:cloud` 派的会话 `archive_session`。 diff --git a/scripts/pm/landing-k.mjs b/scripts/pm/landing-k.mjs new file mode 100644 index 00000000000..657c869ed9b --- /dev/null +++ b/scripts/pm/landing-k.mjs @@ -0,0 +1,705 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * landing-k — the merge-lag reading a landing seat takes before it arms auto-merge or enqueues a PR. + * + * node scripts/pm/landing-k.mjs --pr 35482 + * node scripts/pm/landing-k.mjs --pr 35482 --json + * node scripts/pm/landing-k.mjs --pr 35482 --fixture k.json # offline: the fixture answers every read + * node scripts/pm/landing-k.mjs --self-test # offline, no network at all + * + * ## Why this file exists + * + * `references/landing-operations.md` (入队与落地, the K block) asks every landing seat, per PR, before arming or + * enqueueing, for one number and two legs. The reading was five hand steps: find the last green PR run, find its Test + * Core job, read the job log, copy the diff base, then `git rev-list` and two `git diff --name-only` checks. The rule + * names its own wrong turn (⛔ not the run's start time), the sign of a reading that has been typed wrong before. This + * file is the reading. ⛔ It writes nothing; the seat still owns the landing. + * + * ## The rule it encodes — rule text on `main`, pinned by the self-test (`RULE_PHRASES`) + * + * 1. K = `git rev-list --count --first-parent PRBASE..origin/main`. + * 2. PRBASE = the `Affected-set diff base` that the LAST GREEN PR run's Test Core printed + * (`scripts/ci/select-shard-packages.sh` spells the line; every `Test Core (k/N)` shard and the planner print it), + * ⛔ never that run's start time. "Green" = the run's `Test Core` aggregate job concluded `success`; "PR run" = a + * `pull_request` run of `ci.yml` whose head is one of this PR's commits (a branch name is reused across PRs, so + * the branch alone never decides). + * 3. K ≥ 15 ⇒ merge main first and wait for a green re-run. `behind` alone is not a reason (the K decides). + * 4. At any K, the locale leg: a label PR, when a new locale pack landed on main after PRBASE. A new locale pack is a + * file ADDED under a `translations/` directory in `PRBASE..main` whose locale (the file name up to its first dot) + * had no file in that directory at PRBASE. A label PR is read off the PR's file list against the surface the two + * translation gates count (`LABEL_SURFACE`) — a hit reads as a label PR, so the leg errs toward merging first. + * 5. At any K, the shared-budget leg: a PR that touches a closed book's input or ledger, when main's + * `git diff --name-only PRBASE..origin/main` touches the same book (`BUDGET_BOOKS`, the two the rule names). + * + * ## Fail closed — exit 3 is never read as 0 + * + * A log that cannot be read (expired, 404, refused), a run list with no green Test Core within the bound, a green run + * whose Test Core printed no diff base (its shards were skipped), a PRBASE the local clone does not hold as an ancestor + * of main, a local `origin/main` that is not GitHub's `main`, or a PR file list shorter than the PR's own count: each is + * exit 3 with the gap named. ⛔ The clean verdict is printed only when every leg answered. A leg that already says + * "merge main first" decides exit 1 even when another leg is unread; the unread leg is still named. + * + * ## What it does NOT read — named in the footer of every run + * + * `UNREAD_LEGS`: whether the PR's diff really changes a display label (the surface proxy above stands in for running + * the two gates), a new locale pack in a `ui/**\/locales/` tree (the rule's label gates read `translations/` bundles), + * section A's generated-artifact re-measure before arming, and the green re-run after a merge (`pr-state.mjs` reads + * checks). A seat reads those itself; the output says so every time. + * + * ## Exit codes — capture them BEFORE any pipe + * + * 0 every leg answered and none says merge: arm or enqueue as the rest of the bar allows + * 1 merge main first (K ≥ 15, the locale leg or the shared-budget leg) — each reason named; also `--self-test` failed + * 2 usage + * 3 CAN'T ANSWER — a read did not answer (named); ⛔ never read as 0 + * + * ## Self-test + * + * `--self-test` drives the reads, the legs and the CLI against fixtures, with the floor and the handshake AGENTS.md § + * "Writing a `--self-test`" requires (copied, never imported), and pins the rule text it replaces. + */ + +import { existsSync, readFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { isEntrypoint } from '../invoked-as.mjs'; +import { findExtractConfigs, isMetadataFormModulePath } from '../i18n-bundle-surface.mjs'; +import { DEFAULT_SWEEP_REPO } from './check-half-states.mjs'; +import { ghApi } from './gh-pages.mjs'; + +const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)); + +export const EXIT_OK = 0; +export const EXIT_MERGE_MAIN_FIRST = 1; +export const EXIT_SELF_TEST_FAILED = 1; +export const EXIT_USAGE = 2; +export const EXIT_CANT_ANSWER = 3; + +/** The K hold the rule names. */ +export const K_HOLD = 15; +export const CI_WORKFLOW = 'ci.yml'; +export const TEST_CORE_GATE = 'Test Core'; +export const TEST_CORE_SHARD = /^Test Core \(\d+\/\d+\)$/; +export const TEST_CORE_PLAN = 'Plan Test Core shards'; +/** `select-shard-packages.sh` spells it `Affected-set diff base: ()`; the log prefixes a timestamp. */ +export const DIFF_BASE_LINE = /Affected-set diff base: ([0-9a-f]{40})\s+\(([^)\n]*)\)/; +export const DIFF_BASE_SOURCE = 'scripts/ci/select-shard-packages.sh'; +/** How many run-list pages and runs one reading walks before it says it found no green run. */ +export const MAX_RUN_PAGES = 5; +export const MAX_RUNS_INSPECTED = 30; + +/** The two closed books the rule names: input → ledger. */ +export const BUDGET_BOOKS = Object.freeze([ + Object.freeze({ name: 'skills token ratchet', input: 'skills/**', ledger: 'scripts/check-skills-token-ratchet.mjs', inInput: (p) => p.startsWith('skills/') }), + Object.freeze({ name: 'ui eager-closure budget', input: 'ui/**/locales/en.ts', ledger: 'ui/scripts/check-eager-closure-budget.mjs', inInput: (p) => /^ui\/(?:.+\/)?locales\/en\.ts$/.test(p) }), +]); + +/** A file under a `translations/` directory, its locale being the name up to the first dot. */ +export const LOCALE_FILE = /^(.*\/)?translations\/([a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*)\.[^/]+$/; + +/** Where the rule lives, and the phrases this file is built from — the self-test pins each one present. */ +export const LANDING_PATH = '.claude/skills/pm-dispatch/references/landing-operations.md'; +export const RULE_PHRASES = Object.freeze([ + 'PRBASE = 末次绿 PR 跑 Test Core 所印 `Affected-set diff base`,⛔ 不取该跑起始时刻。', + 'K ≥ 15 ⇒ 先 merge main 等重跑绿,`behind` 例外;任何 K 同:标签 PR 的 PRBASE 后 main 落新语种包;', + '`skills/**`:`scripts/check-skills-token-ratchet.mjs`;`ui/**/locales/en.ts`:`ui/scripts/check-eager-closure-budget.mjs`', + '标签即 `check-generated-translation-bundles`、`check-no-new-untranslated-declared-labels` 所计显示标签。', + '`landing-k.mjs --pr N`', +]); + +/** The legs this file cannot read, printed under every run. */ +export const UNREAD_LEGS = Object.freeze([ + "whether this PR's diff really changes a display label — the PR file list is read against the translation gates' surface instead, and a hit counts as a label PR", + 'a new locale pack in a `ui/**/locales/` tree — the locale leg reads `translations/` bundles, the ones the two label gates count', + "section A's generated-artifact re-measure before arming — `os-regen-merge.sh` owns it", + 'the green re-run after a merge — read the checks with `pr-state.mjs --pr N`', +]); + +// --------------------------------------------------------------------------- +// The pure core +// --------------------------------------------------------------------------- + +/** The diff base a Test Core log printed, or null. */ +export function parseDiffBase(logText) { + const m = DIFF_BASE_LINE.exec(String(logText ?? '')); + return m ? { sha: m[1], why: m[2].trim(), line: m[0] } : null; +} + +/** The surface the two translation gates count, as a predicate over one repo path. */ +export function labelSurfaceReader(extractRoots) { + return (p) => { + if (p.includes('/translations/') || p.startsWith('translations/')) return 'a translation bundle'; + if (isMetadataFormModulePath(p)) return 'a metadata form module (the metadataForms half)'; + if (p.startsWith('packages/spec/src/')) return 'spec-declared labels'; + if (p.startsWith('examples/')) return 'an example config (check:i18n-coverage)'; + const root = extractRoots.find((r) => p.startsWith(r)); + return root ? `a package that owns an i18n extract config (${root.slice(0, -1)})` : null; + }; +} + +/** The package roots that own an `i18n-extract.config.ts`, walked from this checkout (the gate's own walk). */ +export function extractConfigRoots(root = REPO_ROOT) { + const dir = join(root, 'packages'); + if (!existsSync(dir)) return []; + return findExtractConfigs(dir, 'packages').map((c) => `${c.rel.split('/scripts/')[0]}/`); +} + +/** New locale packs among `added` paths: a (dir, locale) pair with no file at PRBASE. `filesAt(dir)` → names | null. */ +export function newLocalePacks(added, filesAt) { + const packs = new Map(); + const unread = []; + for (const p of added) { + const m = LOCALE_FILE.exec(p); + if (!m) continue; + const dir = `${m[1] ?? ''}translations`; + const key = `${dir}#${m[2]}`; + if (packs.has(key)) { + packs.get(key).files.push(p); + continue; + } + const before = filesAt(dir); + if (before === null) { + unread.push(dir); + continue; + } + if (!before.some((name) => name.startsWith(`${m[2]}.`))) packs.set(key, { dir, locale: m[2], files: [p] }); + } + return { packs: [...packs.values()], unread: [...new Set(unread)] }; +} + +/** The books a path list touches (input or ledger). */ +export function booksTouched(paths) { + return BUDGET_BOOKS.filter((b) => paths.some((p) => p === b.ledger || b.inInput(p))); +} + +// --------------------------------------------------------------------------- +// Reads — `get` answers JSON (`ghApi`), `getText` answers a log, `git` answers the local clone +// --------------------------------------------------------------------------- + +/** One `gh api ` read returned as text — a job log is not JSON. */ +export function ghText(path) { + const r = spawnSync('gh', ['api', path], { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 }); + if (r.status !== 0) return { ok: false, error: (r.stderr || r.error?.message || `gh exited ${r.status}`).trim().split('\n')[0] }; + return { ok: true, value: r.stdout }; +} + +/** The local clone, through `git -C `. Every answer is null when git did not answer. */ +export function localGit(root = REPO_ROOT) { + const run = (args) => spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }); + return { + resolve(ref) { + const r = run(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]); + return r.status === 0 ? r.stdout.trim() : null; + }, + hasCommit(sha) { + return run(['cat-file', '-e', `${sha}^{commit}`]).status === 0; + }, + /** true / false / null — exit 0 self-proves; exit 1 is "not an ancestor"; anything else did not answer. */ + isAncestor(a, b) { + const r = run(['merge-base', '--is-ancestor', a, b]); + return r.status === 0 ? true : r.status === 1 ? false : null; + }, + countFirstParent(a, b) { + const r = run(['rev-list', '--count', '--first-parent', `${a}..${b}`]); + return r.status === 0 ? Number(r.stdout.trim()) : null; + }, + diffNames(a, b, filter = null) { + const r = run(['diff', '--name-only', ...(filter ? [`--diff-filter=${filter}`] : []), a, b]); + return r.status === 0 ? r.stdout.split('\n').filter(Boolean) : null; + }, + filesAt(rev, dir) { + const r = run(['ls-tree', '--name-only', `${rev}:${dir}`]); + if (r.status === 0) return r.stdout.split('\n').filter(Boolean); + // A directory the tree did not hold at that revision is an empty answer, not an unread one. + return run(['cat-file', '-e', `${rev}^{commit}`]).status === 0 ? [] : null; + }, + }; +} + +/** Every row of an object-wrapped list (`{ total_count, : [] }`), paged, with the platform's count checked. */ +export function readWrapped(get, path, key, maxPages = MAX_RUN_PAGES) { + const rows = []; + let total = null; + for (let page = 1; page <= maxPages; page++) { + const sep = path.includes('?') ? '&' : '?'; + const r = get(`${path}${sep}per_page=100&page=${page}`); + if (!r.ok) return { ok: false, error: r.error }; + const list = r.value?.[key]; + if (!Array.isArray(list)) return { ok: false, error: `GET ${path} answered no \`${key}\` list` }; + total = r.value.total_count ?? total; + rows.push(...list); + if (list.length < 100) return { ok: true, value: rows, total, truncated: false }; + } + return { ok: true, value: rows, total, truncated: true }; +} + +/** Every row of a plain list endpoint, paged; a page that is not a list is an error. */ +function readList(get, path, maxPages = 30) { + const rows = []; + for (let page = 1; page <= maxPages; page++) { + const sep = path.includes('?') ? '&' : '?'; + const r = get(`${path}${sep}per_page=100&page=${page}`); + if (!r.ok) return r; + if (!Array.isArray(r.value)) return { ok: false, error: `GET ${path} answered no list` }; + rows.push(...r.value); + if (r.value.length < 100) return { ok: true, value: rows }; + } + return { ok: false, error: `GET ${path} still returned full pages after ${maxPages}` }; +} + +/** + * The last green PR run's diff base. Returns `{ ok, run, job, base }` or `{ ok: false, gap }`. + * Runs are walked newest first; a run counts only when its head is one of the PR's commits. + */ +export function readPrBase({ repo, pr, commits, get, getText }) { + const shas = new Set(commits); + const runs = readWrapped(get, `/repos/${repo}/actions/workflows/${CI_WORKFLOW}/runs?event=pull_request&branch=${encodeURIComponent(pr.head.ref)}`, 'workflow_runs'); + if (!runs.ok) return { ok: false, gap: `the ${CI_WORKFLOW} run list could not be read (${runs.error})` }; + const mine = runs.value.filter((r) => shas.has(r.head_sha)).sort((a, b) => String(b.created_at).localeCompare(String(a.created_at))); + let inspected = 0; + for (const run of mine) { + if (inspected >= MAX_RUNS_INSPECTED) break; + if (run.status !== 'completed') continue; + inspected++; + const jobs = readWrapped(get, `/repos/${repo}/actions/runs/${run.id}/jobs`, 'jobs'); + if (!jobs.ok) return { ok: false, gap: `run ${run.id}'s jobs could not be read (${jobs.error})` }; + const gate = jobs.value.find((j) => j.name === TEST_CORE_GATE); + if (!gate || gate.status !== 'completed' || gate.conclusion !== 'success') continue; + const sources = [...jobs.value.filter((j) => TEST_CORE_SHARD.test(j.name) && j.conclusion === 'success'), ...jobs.value.filter((j) => j.name === TEST_CORE_PLAN && j.conclusion === 'success')]; + if (sources.length === 0) return { ok: false, gap: `run ${run.id} (head ${run.head_sha.slice(0, 10)}) is the last green Test Core, but no Test Core shard or planner ran in it, so no \`Affected-set diff base\` was printed` }; + const job = sources[0]; + const log = getText(`/repos/${repo}/actions/jobs/${job.id}/logs`); + if (!log.ok) return { ok: false, gap: `the log of \`${job.name}\` (job ${job.id}, run ${run.id}) could not be read — expired or refused (${log.error})` }; + const base = parseDiffBase(log.value); + if (!base) return { ok: false, gap: `the log of \`${job.name}\` (job ${job.id}, run ${run.id}) carries no \`Affected-set diff base\` line` }; + return { ok: true, run, job, base }; + } + const why = runs.truncated ? ` (the run list was cut at ${MAX_RUN_PAGES} pages)` : ''; + return { ok: false, gap: `no completed pull_request ${CI_WORKFLOW} run on this PR's commits has a green \`${TEST_CORE_GATE}\` (${mine.length} run(s) on its commits, ${inspected} inspected)${why}` }; +} + +/** + * The whole reading. Pure over `get` / `getText` / `git` / `extractRoots`. + * Returns `{ pr, legs, merge: [reasons], gaps: [gaps], exit }`. + */ +export function landingK({ repo, number, mainRef = 'origin/main', get = ghApi, getText = ghText, git = localGit(), extractRoots = null }) { + const out = { repo, number, mainRef, pr: null, prbase: null, k: null, mainSha: null, locale: null, budget: null, merge: [], gaps: [], prerequisite: null }; + const prRow = get(`/repos/${repo}/pulls/${number}`); + if (!prRow.ok) { + out.prerequisite = `PR #${number} could not be read (${prRow.error})`; + return finish(out); + } + const pr = prRow.value; + out.pr = { number, state: pr.state, merged_at: pr.merged_at ?? null, draft: Boolean(pr.draft), head: pr.head?.sha ?? null, ref: pr.head?.ref ?? null, base: pr.base?.ref ?? null, changed_files: pr.changed_files ?? null }; + const commits = readList(get, `/repos/${repo}/pulls/${number}/commits`, 3); + if (!commits.ok) out.gaps.push(`the PR's commit list could not be read (${commits.error})`); + + // Main: the local ref the count runs against must be GitHub's main, or the count understates K. + const localMain = git.resolve(mainRef); + const remote = get(`/repos/${repo}/branches/${encodeURIComponent(pr.base?.ref ?? 'main')}`); + if (!localMain) out.gaps.push(`\`${mainRef}\` does not resolve in this clone`); + else if (!remote.ok) out.gaps.push(`GitHub's \`${pr.base?.ref ?? 'main'}\` could not be read to check \`${mainRef}\` is current (${remote.error})`); + else if (remote.value?.commit?.sha !== localMain) out.gaps.push(`\`${mainRef}\` is ${localMain.slice(0, 10)} here but GitHub's \`${pr.base?.ref}\` is ${String(remote.value?.commit?.sha).slice(0, 10)} — \`git fetch origin ${pr.base?.ref}\` and re-run`); + else out.mainSha = localMain; + + if (commits.ok) { + const base = readPrBase({ repo, pr, commits: commits.value.map((c) => c.sha), get, getText }); + if (!base.ok) out.gaps.push(base.gap); + else out.prbase = { sha: base.base.sha, why: base.base.why, run: base.run.id, run_head: base.run.head_sha, at_head: base.run.head_sha === pr.head?.sha, job: base.job.name, job_id: base.job.id }; + } + + const files = readList(get, `/repos/${repo}/pulls/${number}/files`, 30); + let prFiles = null; + if (!files.ok) out.gaps.push(`the PR's file list could not be read (${files.error})`); + else if (pr.changed_files != null && files.value.length < pr.changed_files) out.gaps.push(`the PR's file list returned ${files.value.length} file(s) and the PR counts ${pr.changed_files}`); + else prFiles = files.value.flatMap((f) => [f.filename, f.previous_filename].filter(Boolean)); + + if (out.prbase && out.mainSha) { + const b = out.prbase.sha; + if (!git.hasCommit(b)) out.gaps.push(`PRBASE ${b.slice(0, 10)} is not in this clone — \`git fetch origin ${pr.base?.ref}\` (deepen a shallow clone) and re-run`); + else { + const anc = git.isAncestor(b, out.mainSha); + if (anc !== true) out.gaps.push(`PRBASE ${b.slice(0, 10)} ${anc === false ? 'is not an ancestor of' : 'could not be checked against'} ${mainRef} in this clone — a shallow or stale clone cannot count K`); + else { + out.k = git.countFirstParent(b, out.mainSha); + if (out.k === null) out.gaps.push('`git rev-list --count --first-parent` did not answer'); + else if (out.k >= K_HOLD) out.merge.push(`K = ${out.k} ≥ ${K_HOLD}`); + const added = git.diffNames(b, out.mainSha, 'A'); + const names = git.diffNames(b, out.mainSha); + if (added === null || names === null) out.gaps.push('`git diff --name-only PRBASE..main` did not answer'); + else { + const roots = extractRoots ?? extractConfigRoots(); + const locale = newLocalePacks(added, (dir) => git.filesAt(b, dir)); + const isLabel = labelSurfaceReader(roots); + const labelHits = prFiles ? prFiles.map((p) => ({ p, why: isLabel(p) })).filter((h) => h.why) : null; + out.locale = { packs: locale.packs, label_hits: labelHits }; + if (locale.unread.length) out.gaps.push(`the tree at PRBASE could not be listed for ${locale.unread.join(', ')}`); + if (locale.packs.length && labelHits === null) out.gaps.push('a new locale pack landed after PRBASE and the PR file list is unread, so the label leg is unjudged'); + else if (locale.packs.length && labelHits.length) out.merge.push(`a new locale pack landed after PRBASE (${locale.packs.map((x) => `${x.locale} in ${x.dir}`).join(', ')}) under a label PR (${labelHits[0].p}: ${labelHits[0].why}${labelHits.length > 1 ? `, +${labelHits.length - 1} more` : ''})`); + const mainBooks = booksTouched(names); + const prBooks = prFiles ? booksTouched(prFiles) : null; + out.budget = { main: mainBooks.map((x) => x.name), pr: prBooks ? prBooks.map((x) => x.name) : null }; + if (prBooks === null && mainBooks.length) out.gaps.push('main moved a shared-budget book after PRBASE and the PR file list is unread, so the budget leg is unjudged'); + else if (prBooks) for (const book of prBooks.filter((x) => mainBooks.includes(x))) out.merge.push(`shared budget: this PR and main after PRBASE both touch the ${book.name} (${book.input} : ${book.ledger})`); + } + } + } + } + return finish(out); +} + +function finish(out) { + out.exit = out.prerequisite ? EXIT_CANT_ANSWER : out.merge.length ? EXIT_MERGE_MAIN_FIRST : out.gaps.length ? EXIT_CANT_ANSWER : EXIT_OK; + return out; +} + +export function verdictLine(r) { + if (r.prerequisite) return `landing-k CAN'T ANSWER — ${r.prerequisite}. ⛔ Not a 0: nothing was read.`; + if (r.merge.length) return `landing-k MERGE MAIN FIRST — ${r.merge.join('; ')}.${r.gaps.length ? ` (Also unread: ${r.gaps.join('; ')}.)` : ''}`; + if (r.gaps.length) return `landing-k CAN'T ANSWER — ${r.gaps.join('; ')}. ⛔ Not a 0: re-run when the reads answer.`; + return `landing-k OK — K = ${r.k} < ${K_HOLD}, no new locale pack under a label PR, no shared book moved under this PR's.`; +} + +export function renderText(r) { + const L = [`landing-k — ${r.repo} #${r.number}${r.pr ? ` · ${r.pr.merged_at ? `merged ${r.pr.merged_at}` : r.pr.state} · head ${String(r.pr.head).slice(0, 10)} · ${r.pr.ref}` : ''}`]; + if (r.prbase) L.push(`PRBASE ${r.prbase.sha.slice(0, 10)} (${r.prbase.why}) — from \`${r.prbase.job}\` of run ${r.prbase.run}, the last green ${TEST_CORE_GATE} (run head ${r.prbase.run_head.slice(0, 10)}${r.prbase.at_head ? ', the PR head' : ', NOT the PR head'})`); + else L.push('PRBASE — not read'); + L.push(r.k === null ? 'K — not read' : `K = ${r.k} first-parent commit(s) on ${r.mainRef} (${r.mainSha.slice(0, 10)}) since PRBASE · hold at ${K_HOLD} → ${r.k >= K_HOLD ? 'merge main first' : 'ok'} · \`behind\` alone is no reason`); + if (r.locale) { + const packs = r.locale.packs.length ? r.locale.packs.map((x) => `${x.locale} in ${x.dir}`).join(', ') : 'none'; + const label = r.locale.label_hits === null ? 'unread' : r.locale.label_hits.length ? `yes (${r.locale.label_hits.length} file(s) on the label surface, first ${r.locale.label_hits[0].p})` : 'no file on the label surface'; + L.push(`locale leg — new locale pack(s) after PRBASE: ${packs} · label PR: ${label}`); + } else L.push('locale leg — not read'); + if (r.budget) L.push(`shared-budget leg — main after PRBASE touches: ${r.budget.main.join(', ') || 'no book'} · this PR touches: ${r.budget.pr === null ? 'unread' : r.budget.pr.join(', ') || 'no book'}`); + else L.push('shared-budget leg — not read'); + L.push('Not read by this reader — the seat reads these itself:'); + for (const leg of UNREAD_LEGS) L.push(` · ${leg}`); + L.push(verdictLine(r)); + return L.join('\n'); +} + +export function renderJson(r) { + return { repo: r.repo, pr: r.pr, prbase: r.prbase, k: r.k, k_hold: K_HOLD, main_ref: r.mainRef, main_sha: r.mainSha, locale: r.locale, budget: r.budget, merge_reasons: r.merge, unread: r.prerequisite ? [r.prerequisite] : r.gaps, unread_legs: UNREAD_LEGS, exit: r.exit, verdict: verdictLine(r) }; +} + +// --------------------------------------------------------------------------- +// Fixture — an offline PR the same reads answer +// --------------------------------------------------------------------------- + +/** + * `{ pr, commits, files, runs, jobs: {runId: []}, logs: {jobId: text|null}, branch_sha, git: { refs: {ref: sha}, + * commits: [sha], ancestors: ["a..b"], counts: {"a..b": n}, added: {"a..b": []}, names: {"a..b": []}, + * trees: {"rev:dir": []} }, extract_roots }`. A path the fixture does not hold answers 404; a `null` log answers 410. + */ +export function fixtureReaders(fx, repo) { + const page = (rows, path) => { + const q = new URLSearchParams(path.split('?')[1] ?? ''); + const p = Number(q.get('page') ?? 1); + return rows.slice((p - 1) * 100, p * 100); + }; + const get = (path) => { + const bare = path.split('?')[0]; + if (bare === `/repos/${repo}/pulls/${fx.pr?.number}`) return fx.pr ? { ok: true, value: fx.pr } : { ok: false, error: 'HTTP 404' }; + if (bare === `/repos/${repo}/pulls/${fx.pr?.number}/commits`) return fx.commits === null ? { ok: false, error: 'HTTP 502' } : { ok: true, value: page((fx.commits ?? []).map((sha) => ({ sha })), path) }; + if (bare === `/repos/${repo}/pulls/${fx.pr?.number}/files`) return fx.files === null ? { ok: false, error: 'HTTP 502' } : { ok: true, value: page((fx.files ?? []).map((filename) => ({ filename })), path) }; + if (bare.startsWith(`/repos/${repo}/branches/`)) return fx.branch_sha ? { ok: true, value: { commit: { sha: fx.branch_sha } } } : { ok: false, error: 'HTTP 502' }; + if (bare === `/repos/${repo}/actions/workflows/${CI_WORKFLOW}/runs`) return fx.runs === null ? { ok: false, error: 'HTTP 502' } : { ok: true, value: { total_count: (fx.runs ?? []).length, workflow_runs: page(fx.runs ?? [], path) } }; + const m = /^\/repos\/[^/]+\/[^/]+\/actions\/runs\/(\d+)\/jobs$/.exec(bare); + if (m) return fx.jobs?.[m[1]] ? { ok: true, value: { total_count: fx.jobs[m[1]].length, jobs: page(fx.jobs[m[1]], path) } } : { ok: false, error: 'HTTP 404' }; + return { ok: false, error: `HTTP 404 (${bare})` }; + }; + const getText = (path) => { + const m = /\/actions\/jobs\/(\d+)\/logs$/.exec(path); + if (!m || !(m[1] in (fx.logs ?? {}))) return { ok: false, error: 'HTTP 404' }; + return fx.logs[m[1]] === null ? { ok: false, error: 'HTTP 410 Gone' } : { ok: true, value: fx.logs[m[1]] }; + }; + const g = fx.git ?? {}; + const git = { + resolve: (ref) => g.refs?.[ref] ?? null, + hasCommit: (sha) => (g.commits ?? []).includes(sha), + isAncestor: (a, b) => ((g.ancestors ?? []).includes(`${a}..${b}`) ? true : g.unanswered ? null : false), + countFirstParent: (a, b) => g.counts?.[`${a}..${b}`] ?? null, + diffNames: (a, b, filter) => (filter === 'A' ? g.added : g.names)?.[`${a}..${b}`] ?? null, + filesAt: (rev, dir) => (g.trees && `${rev}:${dir}` in g.trees ? g.trees[`${rev}:${dir}`] : g.trees_unread ? null : []), + }; + return { get, getText, git, extractRoots: fx.extract_roots ?? [] }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +const USAGE = [ + 'landing-k — the merge-lag reading before arming or enqueueing a PR (read-only).', + '', + ' node scripts/pm/landing-k.mjs --pr N [--repo OWNER/NAME] [--main-ref REF] [--json] [--fixture FILE]', + ' node scripts/pm/landing-k.mjs --self-test', + '', + ' Exits: 0 ok · 1 merge main first (each reason named) · 2 usage · 3 CAN\'T ANSWER (a read did not answer; never a 0).', +].join('\n'); + +export function parseArgs(argv) { + const opts = { repo: DEFAULT_SWEEP_REPO, pr: null, mainRef: 'origin/main', json: false, fixture: null, help: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const eq = /^(--[a-z-]+)=(.*)$/.exec(a); + const flag = eq ? eq[1] : a; + const take = () => (eq ? eq[2] : argv[++i]); + if (flag === '--json' && !eq) opts.json = true; + else if ((flag === '--help' || flag === '-h') && !eq) opts.help = true; + else if (flag === '--pr') { + const v = String(take() ?? '').replace(/^#/, ''); + if (!/^[1-9][0-9]*$/.test(v)) return { error: `--pr must be a PR number, got \`${v}\`` }; + opts.pr = Number(v); + } else if (flag === '--repo') { + opts.repo = String(take() ?? ''); + if (!/^[\w.-]+\/[\w.-]+$/.test(opts.repo)) return { error: `--repo must be OWNER/NAME, got \`${opts.repo}\`` }; + } else if (flag === '--main-ref') { + opts.mainRef = String(take() ?? ''); + if (!opts.mainRef) return { error: '--main-ref needs a ref' }; + } else if (flag === '--fixture') { + opts.fixture = take(); + if (!opts.fixture) return { error: '--fixture needs a file' }; + } else return { error: `\`${a}\` is not an argument this tool takes` }; + } + if (!opts.help && opts.pr === null) return { error: '--pr N is required' }; + return { opts }; +} + +export function main(argv, deps = {}) { + const parsed = parseArgs(argv); + if (parsed.error) { + console.error(`landing-k: ${parsed.error}`); + console.error(USAGE); + return EXIT_USAGE; + } + const o = parsed.opts; + if (o.help) { + console.log(USAGE); + return EXIT_OK; + } + let readers = deps.readers ?? null; + if (o.fixture) { + let fx; + try { + fx = JSON.parse(readFileSync(o.fixture, 'utf8')); + } catch (e) { + console.error(`landing-k: --fixture \`${o.fixture}\` could not be read as JSON (${e.message})`); + return EXIT_USAGE; + } + readers = fixtureReaders(fx, o.repo); + } + const r = landingK({ repo: o.repo, number: o.pr, mainRef: o.mainRef, ...(readers ?? {}) }); + console.log(o.json ? JSON.stringify(renderJson(r), null, 2) : renderText(r)); + return r.exit; +} + +// --------------------------------------------------------------------------- +// Self-test — floor (battery names pinned) + handshake, copied from the landed shape +// --------------------------------------------------------------------------- + +const SELF_TEST_BATTERIES = Object.freeze({ + 'the rule text: every phrase this file is built from is in the file that writes it': 4, + 'PRBASE: the last green Test Core run on this PR, its log line, never a branch alone': 7, + 'K: the count, the hold at 15, and a clone that cannot count': 6, + 'the locale leg: a new pack after PRBASE under a label PR, at any K': 6, + 'the shared-budget leg: the same book on both sides, at any K': 5, + 'fail closed: every unread leg is exit 3, never 0': 7, + 'the CLI: usage, exits and the footer': 7, +}); +const SELF_TEST_BATTERY_FLOOR = 7; +const UNATTRIBUTED_BATTERY = '(unattributed)'; +const batteryCases = new Map(); +let openBattery = null; +const battery = (name) => { + openBattery = name; +}; +let selfTestReachedVerdict = false; + +const quiet = (fn) => (...args) => { + const log = console.log; + const err = console.error; + const out = []; + console.log = (...a) => out.push(a.join(' ')); + console.error = (...a) => out.push(a.join(' ')); + try { + return { code: fn(...args), out: out.join('\n') }; + } finally { + console.log = log; + console.error = err; + } +}; + +export function selfTest() { + const cases = []; + const t = (name, actual, expected = true) => { + const key = openBattery ?? UNATTRIBUTED_BATTERY; + batteryCases.set(key, (batteryCases.get(key) ?? 0) + 1); + const ok = JSON.stringify(actual) === JSON.stringify(expected); + cases.push({ name, ok, detail: ok ? '' : `got ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}` }); + }; + const REPO = 'objectstack-ai/objectstack'; + const sha = (c) => c.repeat(40); + const BASE = sha('b'); + const MAIN = sha('a'); + const HEAD = sha('c'); + const OLD = sha('d'); + const log = (s = BASE) => `2026-11-19T13:07:09.7414776Z Affected-set diff base: ${s} (merge-base of origin/main and HEAD)\n`; + const job = (id, name, conclusion = 'success') => ({ id, name, status: 'completed', conclusion }); + const greenJobs = [job(11, 'Plan Test Core shards'), job(12, 'Test Core (1/10)'), job(13, TEST_CORE_GATE)]; + const fixture = (over = {}) => { + const fx = { + pr: { number: 7, state: 'open', draft: false, head: { sha: HEAD, ref: 'claude/x' }, base: { ref: 'main' }, changed_files: 1 }, + commits: [OLD, HEAD], + files: ['scripts/pm/x.mjs'], + branch_sha: MAIN, + runs: [{ id: 2, head_sha: HEAD, status: 'completed', created_at: '2026-11-19T13:00:00Z' }], + jobs: { 2: greenJobs }, + logs: { 12: log() }, + git: { refs: { 'origin/main': MAIN }, commits: [BASE], ancestors: [`${BASE}..${MAIN}`], counts: { [`${BASE}..${MAIN}`]: 3 }, added: { [`${BASE}..${MAIN}`]: [] }, names: { [`${BASE}..${MAIN}`]: [] } }, + extract_roots: ['packages/platform-objects/'], + ...over, + }; + if (over.git) fx.git = { ...fixture().git, ...over.git }; + return fx; + }; + const read = (fx) => landingK({ repo: REPO, number: 7, ...fixtureReaders(fx, REPO) }); + + battery('the rule text: every phrase this file is built from is in the file that writes it'); + { + const text = (p) => readFileSync(join(REPO_ROOT, p), 'utf8'); + t('⭐ landing-operations.md still says what this file encodes (a reworded K block reds here)', RULE_PHRASES.filter((p) => !text(LANDING_PATH).includes(p)), []); + t('⭐ the shard selector still prints the line PRBASE is read from', parseDiffBase(text(DIFF_BASE_SOURCE).split('\n').find((l) => l.includes('echo "Affected-set diff base:')).replace('$SCM_BASE', BASE).replace(/^\s*echo "/, '')) !== null, true); + t('both closed books still exist where the rule names their ledgers', BUDGET_BOOKS.filter((b) => !existsSync(join(REPO_ROOT, b.ledger))).map((b) => b.ledger), []); + t('ci.yml still names the aggregate, the shard and the planner jobs this file reads', [TEST_CORE_GATE, 'Test Core (${{ matrix.shard }}/10)', TEST_CORE_PLAN].filter((n) => !text(`.github/workflows/${CI_WORKFLOW}`).includes(`name: ${n}`)), []); + } + + battery('PRBASE: the last green Test Core run on this PR, its log line, never a branch alone'); + { + const ok = read(fixture()); + t('⭐ PRBASE is the diff base the shard log printed, with its reason', [ok.prbase?.sha, ok.prbase?.why, ok.prbase?.job], [BASE, 'merge-base of origin/main and HEAD', 'Test Core (1/10)']); + t('a log line with a timestamp prefix parses; a line without a sha does not', [parseDiffBase(log()).sha, parseDiffBase('Affected-set diff base: (none)')], [BASE, null]); + const reused = read(fixture({ runs: [{ id: 9, head_sha: sha('e'), status: 'completed', created_at: '2026-11-19T14:00:00Z' }, { id: 2, head_sha: HEAD, status: 'completed', created_at: '2026-11-19T13:00:00Z' }], jobs: { 9: greenJobs.map((j) => ({ ...j, id: j.id + 80 })), 2: greenJobs }, logs: { 92: log(sha('f')), 12: log() } })); + t("⭐ a newer green run on the same branch name but another PR's commit is never read", [reused.prbase?.run, reused.prbase?.sha], [2, BASE]); + const redThenGreen = read(fixture({ runs: [{ id: 3, head_sha: HEAD, status: 'completed', created_at: '2026-11-19T15:00:00Z' }, { id: 2, head_sha: OLD, status: 'completed', created_at: '2026-11-19T13:00:00Z' }], jobs: { 3: greenJobs.map((j) => (j.name === TEST_CORE_GATE ? { ...j, conclusion: 'failure' } : j)), 2: greenJobs } })); + t('⭐ a red Test Core is skipped: the last GREEN run decides, and the row says it is not at the PR head', [redThenGreen.prbase?.run, redThenGreen.prbase?.at_head], [2, false]); + const planOnly = read(fixture({ jobs: { 2: [job(11, 'Plan Test Core shards'), job(13, TEST_CORE_GATE)] }, logs: { 11: log() } })); + t('with no shard log, the planner of the same run is read (it prints the same line)', planOnly.prbase?.job, TEST_CORE_PLAN); + const running = read(fixture({ runs: [{ id: 4, head_sha: HEAD, status: 'in_progress', created_at: '2026-11-19T16:00:00Z' }, ...fixture().runs] })); + t('a run still in progress is not the last green run', running.prbase?.run, 2); + t('the text names the run, the job and the reason', renderText(ok).includes(`PRBASE ${BASE.slice(0, 10)} (merge-base of origin/main and HEAD) — from \`Test Core (1/10)\` of run 2`), true); + } + + battery('K: the count, the hold at 15, and a clone that cannot count'); + { + t('⭐ K below the hold with clean legs is OK, exit 0', [read(fixture()).k, read(fixture()).exit], [3, EXIT_OK]); + const k15 = read(fixture({ git: { counts: { [`${BASE}..${MAIN}`]: 15 } } })); + t('⭐ K = 15 is merge main first, exit 1, the reason named', [k15.exit, k15.merge[0]], [EXIT_MERGE_MAIN_FIRST, 'K = 15 ≥ 15']); + t('K = 14 is still ok', read(fixture({ git: { counts: { [`${BASE}..${MAIN}`]: 14 } } })).exit, EXIT_OK); + const stale = read(fixture({ branch_sha: sha('9') })); + t('⭐ a local origin/main that is not GitHub\'s main cannot count K: exit 3, the fetch named', [stale.exit, stale.gaps[0].includes('git fetch origin main')], [EXIT_CANT_ANSWER, true]); + const shallow = read(fixture({ git: { ancestors: [] } })); + t('⭐ a PRBASE that is not an ancestor of main in this clone is exit 3, never a count', [shallow.exit, shallow.k, shallow.gaps[0].includes('is not an ancestor of')], [EXIT_CANT_ANSWER, null, true]); + const absent = read(fixture({ git: { commits: [] } })); + t('a PRBASE missing from the clone is exit 3, the fetch named', [absent.exit, absent.gaps[0].includes('is not in this clone')], [EXIT_CANT_ANSWER, true]); + } + + battery('the locale leg: a new pack after PRBASE under a label PR, at any K'); + { + const dir = 'packages/platform-objects/src/apps/translations'; + const added = { [`${BASE}..${MAIN}`]: [`${dir}/pt-BR.ts`, `${dir}/pt-BR.objects.generated.ts`] }; + const trees = { [`${BASE}:${dir}`]: ['en.ts', 'zh-CN.ts', 'zh-CN.objects.generated.ts'] }; + const label = read(fixture({ files: ['packages/platform-objects/src/objects/account.object.ts'], git: { added, trees } })); + t('⭐ a new locale under a label PR is merge main first at K = 3', [label.exit, label.merge.length, label.merge[0].startsWith('a new locale pack landed after PRBASE (pt-BR in packages/platform-objects/src/apps/translations)')], [EXIT_MERGE_MAIN_FIRST, 1, true]); + const notLabel = read(fixture({ files: ['scripts/pm/x.mjs'], git: { added, trees } })); + t('…and the same pack under a PR off the label surface is clear', [notLabel.exit, notLabel.locale.packs.length, notLabel.locale.label_hits], [EXIT_OK, 1, []]); + const known = read(fixture({ files: ['packages/spec/src/ui/view.zod.ts'], git: { added: { [`${BASE}..${MAIN}`]: [`${dir}/zh-CN.metadata-forms.generated.ts`] }, trees } })); + t('a file added for a locale the directory already held is no new pack', known.locale.packs, []); + t('the label surface: a form module, spec, an example, a translation file and an extract-config package hit; a script does not', ['packages/spec/src/ui/x.form.ts', 'packages/spec/src/data/field.zod.ts', 'examples/app-todo/objectstack.config.ts', 'packages/x/translations/en.ts', 'packages/platform-objects/src/a.ts', 'scripts/pm/x.mjs'].map((p) => Boolean(labelSurfaceReader(['packages/platform-objects/'])(p))), [true, true, true, true, true, false]); + t('the locale is the file name up to its first dot', newLocalePacks(['a/translations/ja-JP.source-hashes.generated.ts', 'a/translations/index.ts', 'a/b.ts'], () => []).packs.map((x) => x.locale), ['ja-JP']); + const unreadFiles = read(fixture({ files: null, git: { added, trees } })); + t('⭐ a new pack with an unread PR file list is exit 3, never a clear leg', [unreadFiles.exit, unreadFiles.gaps.some((g) => g.includes('label leg is unjudged'))], [EXIT_CANT_ANSWER, true]); + } + + battery('the shared-budget leg: the same book on both sides, at any K'); + { + const both = read(fixture({ files: ['skills/objectstack-data/SKILL.md'], git: { names: { [`${BASE}..${MAIN}`]: ['skills/objectstack-ui/SKILL.md'] } } })); + t('⭐ a skills PR under a skills change on main is merge main first at K = 3', [both.exit, both.merge[0]], [EXIT_MERGE_MAIN_FIRST, 'shared budget: this PR and main after PRBASE both touch the skills token ratchet (skills/** : scripts/check-skills-token-ratchet.mjs)']); + const ledger = read(fixture({ files: ['ui/apps/console/src/locales/en.ts'], git: { names: { [`${BASE}..${MAIN}`]: ['ui/scripts/check-eager-closure-budget.mjs'] } } })); + t('the ledger on one side and the input on the other is the same book', [ledger.exit, ledger.merge[0].includes('ui eager-closure budget')], [EXIT_MERGE_MAIN_FIRST, true]); + const other = read(fixture({ files: ['skills/objectstack-data/SKILL.md'], git: { names: { [`${BASE}..${MAIN}`]: ['ui/packages/x/src/locales/en.ts'] } } })); + t('two different books never meet', [other.exit, other.budget], [EXIT_OK, { main: ['ui eager-closure budget'], pr: ['skills token ratchet'] }]); + t('a locales file that is not en.ts is not the ui book', booksTouched(['ui/apps/console/src/locales/zh-CN.ts']), []); + const unread = read(fixture({ files: null, git: { names: { [`${BASE}..${MAIN}`]: ['skills/a/SKILL.md'] } } })); + t('⭐ a book moved on main with an unread PR file list is exit 3', [unread.exit, unread.gaps.some((g) => g.includes('budget leg is unjudged'))], [EXIT_CANT_ANSWER, true]); + } + + battery('fail closed: every unread leg is exit 3, never 0'); + { + const expired = read(fixture({ logs: { 12: null } })); + t('⭐ an expired log is exit 3 with the job named', [expired.exit, expired.gaps[0].includes('could not be read — expired or refused (HTTP 410 Gone)')], [EXIT_CANT_ANSWER, true]); + const noLine = read(fixture({ logs: { 12: 'nothing here' } })); + t('⭐ a log without the line is exit 3', [noLine.exit, noLine.gaps[0].includes('carries no `Affected-set diff base` line')], [EXIT_CANT_ANSWER, true]); + const noGreen = read(fixture({ jobs: { 2: greenJobs.map((j) => ({ ...j, conclusion: 'failure' })) } })); + t('no green Test Core on the PR is exit 3', [noGreen.exit, noGreen.gaps[0].startsWith('no completed pull_request ci.yml run')], [EXIT_CANT_ANSWER, true]); + const skipped = read(fixture({ jobs: { 2: [job(13, TEST_CORE_GATE)] } })); + t('a green aggregate with no shard and no planner printed no base: exit 3', [skipped.exit, skipped.gaps[0].includes('no Test Core shard or planner ran in it')], [EXIT_CANT_ANSWER, true]); + const short = read(fixture({ pr: { ...fixture().pr, changed_files: 4 } })); + t('a PR file list shorter than the PR counts is exit 3', [short.exit, short.gaps[0]], [EXIT_CANT_ANSWER, "the PR's file list returned 1 file(s) and the PR counts 4"]); + const noPr = read(fixture({ pr: null })); + t('an unreadable PR is exit 3, nothing read', [noPr.exit, Boolean(noPr.prerequisite)], [EXIT_CANT_ANSWER, true]); + const both = read(fixture({ logs: { 12: null }, git: { counts: { [`${BASE}..${MAIN}`]: 40 } } })); + t('⭐ an unread PRBASE never yields a K at all, so no merge verdict either: exit 3', [both.exit, both.k], [EXIT_CANT_ANSWER, null]); + } + + battery('the CLI: usage, exits and the footer'); + { + t('--pr is required', Boolean(parseArgs([]).error), true); + t('a malformed --pr is refused', Boolean(parseArgs(['--pr', 'x']).error), true); + t('an unknown flag is refused, never ignored', Boolean(parseArgs(['--pr', '7', '--k', '3']).error), true); + t('both spellings of an option are read, and #N is a PR number', [parseArgs(['--pr=7']).opts.pr, parseArgs(['--pr', '#8']).opts.pr], [7, 8]); + const ok = quiet(main)(['--pr', '7'], { readers: fixtureReaders(fixture(), REPO) }); + t('⭐ every run names the legs it cannot read, and a clean run says OK, exit 0', [ok.code, UNREAD_LEGS.every((l) => ok.out.includes(l)), ok.out.includes('landing-k OK — K = 3 < 15')], [EXIT_OK, true, true]); + const bad = quiet(main)(['--pr', '7'], { readers: fixtureReaders(fixture({ logs: { 12: null } }), REPO) }); + t('⭐ an unread run prints CAN\'T ANSWER and exits 3, never the OK line', [bad.code, bad.out.includes("landing-k CAN'T ANSWER"), bad.out.includes('landing-k OK')], [EXIT_CANT_ANSWER, true, false]); + t('--json carries the exit and the verdict', JSON.parse(quiet(main)(['--pr', '7', '--json'], { readers: fixtureReaders(fixture(), REPO) }).out).exit, EXIT_OK); + } + + const failed = cases.filter((x) => !x.ok); + for (const f of failed) console.error(` ✗ ${f.name} — ${f.detail}`); + const floor = []; + const declared = Object.keys(SELF_TEST_BATTERIES); + if (declared.length < SELF_TEST_BATTERY_FLOOR) floor.push(`the battery ledger declares ${declared.length} batteries, below its floor of ${SELF_TEST_BATTERY_FLOOR}`); + for (const [name, count] of batteryCases) if (!(name in SELF_TEST_BATTERIES)) floor.push(`self-test battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES`); + for (const name of declared) { + const count = batteryCases.get(name) ?? 0; + if (count < SELF_TEST_BATTERIES[name]) floor.push(count === 0 ? `self-test battery "${name}" DID NOT RUN` : `self-test battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]}`); + } + for (const f of floor) console.error(` ✗ ${f}`); + if (failed.length || floor.length) { + console.error(`✗ landing-k self-test: ${failed.length} of ${cases.length} case(s) failed${floor.length ? `, ${floor.length} floor breach(es)` : ''}.`); + selfTestReachedVerdict = true; + return EXIT_SELF_TEST_FAILED; + } + console.log(`✓ landing-k self-test: ${cases.length} cases pass across ${declared.length} batteries — offline, no network.`); + selfTestReachedVerdict = true; + return EXIT_OK; +} + +if (isEntrypoint(import.meta.url)) { + const argv = process.argv.slice(2); + if (argv.includes('--self-test')) { + const code = selfTest(); + if (!selfTestReachedVerdict) { + console.error('\n✗ landing-k self-test: selfTest() returned without reaching its verdict, so no success line was\nprinted. Exiting 0 here would report a self-test that never finished as one that passed.\n'); + process.exit(1); + } + process.exit(code); + } else { + process.exit(main(argv)); + } +} From 61d2b5eb19a316f89be4a25c37a13ba7a2a916ba Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:20:38 +0000 Subject: [PATCH 2/7] feat(pm): pr-state prints one state line per PR from the readings the landing rules name Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- scripts/pm/pr-state.mjs | 600 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 600 insertions(+) create mode 100644 scripts/pm/pr-state.mjs diff --git a/scripts/pm/pr-state.mjs b/scripts/pm/pr-state.mjs new file mode 100644 index 00000000000..5d409a0a820 --- /dev/null +++ b/scripts/pm/pr-state.mjs @@ -0,0 +1,600 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * pr-state — one state line per PR, read the way the landing and reporting rules ask for it. + * + * node scripts/pm/pr-state.mjs --pr 35482 + * node scripts/pm/pr-state.mjs --pr 35482,35532 --json + * node scripts/pm/pr-state.mjs --pr 35482 --fixture pr.json # offline: the fixture answers every read + * node scripts/pm/pr-state.mjs --self-test # offline, no network at all + * + * ## Why this file exists + * + * `references/coordinator.md` (before any PR status goes to the maintainer) and `references/landing-operations.md` + * (every look between open and MERGED) ask every seat, coordinator and director to re-read the same six facts, and + * `references/readings-queue.md` says how each one lies: `mergeable_state` is computed lazily and `unknown` is not a + * reading; queue membership is the timeline's `added_to_merge_queue` / `removed_from_merge_queue`, and the position + * is the `gh-readonly-queue/*` parent-tip chain from the current main; `auto_merge` is unstable. This file is that + * reading. ⛔ It writes nothing. + * + * ## What it reads — REST through `gh api`, every page, and one `git ls-remote` + * + * 1. the PR row; on an OPEN PR whose `mergeable_state` is `unknown`, re-read up to `--rereads` times (bounded); + * 2. every review — the newest per reviewer, and which of them are on the head commit; + * 3. the timeline, every page — the last merge-queue event; + * 4. the queue refs and the base branch's tip (`git ls-remote`, zero quota) — the position, only while a ref exists; + * 5. the head's check-runs (`filter=latest`, every page, the platform's count checked), judged with + * `check-expected-skips.mjs`'s roster (this checkout's workflows), and the head's legacy commit status. + * + * ## What it does NOT read — named in the footer of every run + * + * `UNREAD_LEGS`: `auto_merge` is printed but is not a reading; a queue event can be absent for a short window after an + * enqueue; whether the PR's content is on `main` (read it by content); and the required-set verdict of the enqueue bar + * (the skip judgement here uses this checkout's roster, not the base branch's). + * + * ## Exit codes — capture them BEFORE any pipe + * + * 0 every leg answered for every PR + * 1 `--self-test` failed + * 2 usage + * 3 a PR row could not be read — nothing printed for it but the gap + * 4 INCOMPLETE — a leg did not answer (named on the line), or an open PR's `mergeable_state` was still `unknown` + * after the bounded re-reads; ⛔ never read as a clean line + * + * ## Self-test + * + * `--self-test` drives every leg and the CLI against fixtures, with the floor and the handshake AGENTS.md § "Writing a + * `--self-test`" requires (copied, never imported), and pins the rule text it replaces. + */ + +import { readFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { isEntrypoint } from '../invoked-as.mjs'; +import { DEFAULT_SWEEP_REPO } from './check-half-states.mjs'; +import { expectedSkipRoster, judgeCheckRuns } from './check-expected-skips.mjs'; +import { ghApi } from './gh-pages.mjs'; + +const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)); + +export const EXIT_OK = 0; +export const EXIT_SELF_TEST_FAILED = 1; +export const EXIT_USAGE = 2; +export const EXIT_PR_UNREADABLE = 3; +export const EXIT_INCOMPLETE = 4; + +export const DEFAULT_REREADS = 3; +export const REREAD_DELAY_MS = 3000; +export const QUEUE_EVENTS = Object.freeze(['added_to_merge_queue', 'removed_from_merge_queue']); +/** `gh-readonly-queue//pr--`: `` is the previous entry's tip. */ +export const QUEUE_REF = /^refs\/heads\/gh-readonly-queue\/[^/]+\/pr-(\d+)-([0-9a-f]{40})$/; + +/** Where the rules live, and the phrases this file is built from — the self-test pins each one present. */ +export const RULE_FILES = Object.freeze({ + '.claude/skills/pm-dispatch/references/coordinator.md': [ + '`pr-state.mjs`:merged/draft/auto_merge/在队/reviews/`mergeable_state`', + '无 APPROVED 也可能已被 ready 入队 ⇒ ⛔ 单读 reviews', + ], + '.claude/skills/pm-dispatch/references/landing-operations.md': ['读检查与 `mergeable_state`,`unknown` 重读:`pr-state.mjs`'], + '.claude/skills/pm-dispatch/references/readings-queue.md': [ + '判在不在队列的决断读数是 timeline 事件 `added_to_merge_queue` / `removed_from_merge_queue`', + '`auto_merge` 字段不只是空,是不稳定', + '`mergeable_state` 惰性计算,`unknown` 不是读数', + '队列 ref 在场时还答位置:名形 `…/pr--` 的 `` 是前一条目的 tip', + '从根在当前 `origin/main` 的那条起走父-tip 链即真实排队序', + ], +}); + +/** The legs this file cannot read, printed under every run. */ +export const UNREAD_LEGS = Object.freeze([ + '`auto_merge` — printed as the API answered it; the field is unstable and is never a reading (never re-arm on it)', + 'an enqueue in its first minutes — the queue event has been measured absent for +75 s; a short-window absence is not a reading', + "whether the PR's content is on `main` — read it by content, never by the head sha's ancestry", + "the enqueue bar's required set — the skip judgement here uses this checkout's roster, not the base branch's (`check-expected-skips.mjs --pr N`)", +]); + +// --------------------------------------------------------------------------- +// The pure core +// --------------------------------------------------------------------------- + +/** The newest review per reviewer, and the ones on `head`. */ +export function reviewsAtHead(reviews, head) { + const newest = new Map(); + for (const r of reviews ?? []) { + if (!r?.user?.login || r.state === 'COMMENTED' || r.state === 'PENDING') continue; + const prev = newest.get(r.user.login); + if (!prev || String(r.submitted_at) >= String(prev.submitted_at)) newest.set(r.user.login, r); + } + const at = [...newest.values()].filter((r) => r.commit_id === head); + return { + approved: at.filter((r) => r.state === 'APPROVED').map((r) => r.user.login).sort(), + changes: at.filter((r) => r.state === 'CHANGES_REQUESTED').map((r) => r.user.login).sort(), + dismissed: at.filter((r) => r.state === 'DISMISSED').map((r) => r.user.login).sort(), + older: [...newest.values()].filter((r) => r.commit_id !== head).length, + }; +} + +/** The last merge-queue event on a timeline, or null. */ +export function lastQueueEvent(timeline) { + let last = null; + for (const e of timeline ?? []) if (QUEUE_EVENTS.includes(e?.event)) last = e; + return last ? { event: last.event, at: last.created_at ?? null, actor: last.actor?.login ?? null } : null; +} + +/** The queue order from `ls-remote` rows `{sha, ref}`, walked from the base tip by parent. */ +export function queueChain(rows, baseSha) { + const entries = []; + for (const r of rows ?? []) { + const m = QUEUE_REF.exec(r.ref); + if (m) entries.push({ pr: Number(m[1]), parent: m[2], tip: r.sha, ref: r.ref }); + } + const byParent = new Map(entries.map((e) => [e.parent, e])); + const chain = []; + const seen = new Set(); + let cur = baseSha; + while (byParent.has(cur) && !seen.has(cur)) { + seen.add(cur); + const e = byParent.get(cur); + chain.push(e); + cur = e.tip; + } + return { chain, entries, offChain: entries.filter((e) => !chain.includes(e)) }; +} + +/** The queue leg for one PR: `{ text, gap }`. */ +export function queueLeg({ pr, event, refs, baseSha }) { + if (pr.merged_at) return { text: 'queue: landed' }; + if (pr.state !== 'open') return { text: 'queue: n/a (closed unmerged)' }; + const q = refs ? queueChain(refs, baseSha) : null; + const mine = q ? q.entries.find((e) => e.pr === pr.number) : null; + const pos = mine && q.chain.includes(mine) ? `position ${q.chain.indexOf(mine) + 1} of ${q.chain.length}` : mine ? `a queue ref exists but is off the chain from ${String(baseSha).slice(0, 10)} (position unread)` : null; + if (!event) return { text: mine ? `queue: no queue event on the timeline, yet a queue ref exists (${pos}) — re-read` : 'queue: never queued (no queue event)' }; + if (event.event === 'removed_from_merge_queue') return { text: `queue: not in queue (removed ${event.at})${mine ? ` — yet a queue ref exists (${pos}); re-read` : ''}` }; + if (!q) return { text: `queue: in queue (added ${event.at}), position unread`, gap: 'the queue refs could not be listed, so the position is unread' }; + return { text: `queue: in queue (added ${event.at}), ${pos ?? 'no queue ref for it now (a ref answers a build, not membership) — position unread'}` }; +} + +/** One PR's state, read through `get` / `lsRemote` / `sleep`. `{ number, line, gaps, exit, json }`. */ +export function readPrState({ repo, number, get = ghApi, lsRemote = gitLsRemote, sleep = sleepMs, rereads = DEFAULT_REREADS, roster = null }) { + const gaps = []; + let row = get(`/repos/${repo}/pulls/${number}`); + if (!row.ok) return { number, line: `#${number} · CAN'T READ — the PR row did not answer (${row.error})`, gaps: [row.error], exit: EXIT_PR_UNREADABLE, json: { number, error: row.error } }; + let reads = 1; + while (row.value.state === 'open' && row.value.mergeable_state === 'unknown' && reads <= rereads) { + sleep(REREAD_DELAY_MS); + const again = get(`/repos/${repo}/pulls/${number}`); + reads++; + if (!again.ok) break; + row = again; + } + const pr = row.value; + const head = pr.head?.sha ?? null; + const base = pr.base?.ref ?? 'main'; + const state = pr.merged_at ? `MERGED ${pr.merged_at}` : pr.state === 'open' ? 'OPEN' : 'CLOSED unmerged'; + let mergeable; + if (pr.state !== 'open') mergeable = `mergeable_state n/a (${pr.merged_at ? 'merged' : 'closed'})`; + else if (pr.mergeable_state === 'unknown') { + mergeable = `mergeable_state unknown after ${reads} read(s) — not a reading`; + gaps.push(`mergeable_state still unknown after ${reads} read(s)`); + } else mergeable = `mergeable_state ${pr.mergeable_state}${reads > 1 ? ` (read ${reads}×)` : ''}`; + + const reviews = readPaged(get, `/repos/${repo}/pulls/${number}/reviews`); + let reviewText; + let rv = null; + if (!reviews.ok) { + reviewText = 'reviews unread'; + gaps.push(`reviews could not be read (${reviews.error})`); + } else { + rv = reviewsAtHead(reviews.value, head); + const parts = [rv.approved.length ? `APPROVED ${rv.approved.join(',')}` : null, rv.changes.length ? `CHANGES_REQUESTED ${rv.changes.join(',')}` : null, rv.dismissed.length ? `DISMISSED ${rv.dismissed.join(',')}` : null].filter(Boolean); + reviewText = `reviews at ${String(head).slice(0, 10)}: ${parts.join('; ') || 'none'}${rv.older ? ` (${rv.older} reviewer(s) newest on an older commit)` : ''}`; + } + + const timeline = readPaged(get, `/repos/${repo}/issues/${number}/timeline`); + let event = null; + if (!timeline.ok) gaps.push(`the timeline could not be read (${timeline.error}), so queue membership is unread`); + else event = lastQueueEvent(timeline.value); + let queue; + if (!timeline.ok && pr.state === 'open' && !pr.merged_at) queue = { text: 'queue: unread' }; + else { + let refs = null; + let baseSha = null; + if (pr.state === 'open' && !pr.merged_at) { + const ls = lsRemote(repo, [`refs/heads/gh-readonly-queue/${base}/*`, `refs/heads/${base}`]); + if (ls.ok) { + baseSha = ls.value.find((r) => r.ref === `refs/heads/${base}`)?.sha ?? null; + refs = baseSha ? ls.value : null; + } + } + queue = queueLeg({ pr: { ...pr, number }, event, refs, baseSha }); + if (queue.gap) gaps.push(queue.gap); + } + + let checksText; + let judged = null; + const runs = readWrappedAll(get, `/repos/${repo}/commits/${head}/check-runs?filter=latest`, 'check_runs'); + if (!runs.ok) { + checksText = 'checks unread'; + gaps.push(`the head's check-runs could not be read (${runs.error})`); + } else if (runs.total !== null && runs.value.length < runs.total) { + checksText = `checks unread (listed ${runs.value.length} of ${runs.total})`; + gaps.push(`the head's check-run listing returned ${runs.value.length} and the platform counts ${runs.total}`); + } else { + judged = judgeCheckRuns({ total_count: runs.value.length, check_runs: runs.value }, roster ?? localRoster()); + if (judged.kind === 'empty') checksText = 'checks: none on the head'; + else if (judged.kind === 'unreadable') { + checksText = 'checks unread'; + gaps.push(judged.reason); + } else { + const failed = judged.other.filter((o) => o.conclusion !== 'neutral'); + checksText = `checks at ${String(head).slice(0, 10)}: ${judged.success} success · ${judged.expected.reduce((s, e) => s + e.count, 0)} expected skip · ${judged.unexpected.length} unexpected skip${judged.unexpected.length ? ` (${judged.unexpected.map((u) => u.name).join(', ')})` : ''} · ${failed.length} failed${failed.length ? ` (${failed.map((f) => `${f.name}=${f.conclusion}`).join(', ')})` : ''} · ${judged.pending.length} pending`; + } + } + const status = get(`/repos/${repo}/commits/${head}/status`); + let statusText; + if (!status.ok) { + statusText = 'commit status unread'; + gaps.push(`the head's commit status could not be read (${status.error})`); + } else statusText = status.value.total_count ? `commit status ${status.value.state} (${status.value.total_count})` : 'no commit status'; + const auto = pr.auto_merge ? `auto_merge set (${pr.auto_merge.merge_method ?? '?'})` : 'auto_merge null'; + const parts = [`#${number}`, state, `draft ${pr.draft ? 'yes' : 'no'}`, mergeable, queue.text, reviewText, checksText, statusText, `${auto} [unreliable field]`]; + const line = parts.join(' · ') + (gaps.length ? ` — INCOMPLETE: ${gaps.join('; ')}` : ''); + return { + number, + line, + gaps, + exit: gaps.length ? EXIT_INCOMPLETE : EXIT_OK, + json: { + number, + state: pr.merged_at ? 'merged' : pr.state, + merged_at: pr.merged_at ?? null, + draft: Boolean(pr.draft), + head, + mergeable_state: pr.state === 'open' ? pr.mergeable_state : null, + mergeable_reads: reads, + queue: queue.text, + queue_event: event, + reviews_at_head: rv, + checks: judged && judged.kind !== 'unreadable' ? { kind: judged.kind, success: judged.success ?? 0, expected_skips: judged.expected?.length ?? 0, unexpected_skips: (judged.unexpected ?? []).map((u) => u.name), other: judged.other ?? [], pending: (judged.pending ?? []).map((p) => p.name) } : null, + commit_status: status.ok ? { state: status.value.state, total_count: status.value.total_count } : null, + auto_merge: pr.auto_merge ?? null, + gaps, + line, + }, + }; +} + +// --------------------------------------------------------------------------- +// Reads +// --------------------------------------------------------------------------- + +function readPaged(get, path, maxPages = 30) { + const rows = []; + for (let page = 1; page <= maxPages; page++) { + const r = get(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + if (!r.ok) return r; + if (!Array.isArray(r.value)) return { ok: false, error: `GET ${path} answered no list` }; + rows.push(...r.value); + if (r.value.length < 100) return { ok: true, value: rows }; + } + return { ok: false, error: `GET ${path} still returned full pages after ${maxPages}` }; +} + +function readWrappedAll(get, path, key, maxPages = 10) { + const rows = []; + let total = null; + for (let page = 1; page <= maxPages; page++) { + const r = get(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + if (!r.ok) return r; + if (!Array.isArray(r.value?.[key])) return { ok: false, error: `GET ${path} answered no \`${key}\` list` }; + total = r.value.total_count ?? total; + rows.push(...r.value[key]); + if (r.value[key].length < 100) return { ok: true, value: rows, total }; + } + return { ok: false, error: `GET ${path} still returned full pages after ${maxPages}` }; +} + +/** `git ls-remote https://github.com/.git ` → `{ ok, value: [{sha, ref}] }`. Zero API quota. */ +export function gitLsRemote(repo, patterns) { + const r = spawnSync('git', ['ls-remote', `https://github.com/${repo}.git`, ...patterns], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }); + if (r.status !== 0) return { ok: false, error: (r.stderr || `git ls-remote exited ${r.status}`).trim().split('\n')[0] }; + return { ok: true, value: r.stdout.split('\n').filter(Boolean).map((l) => { const [sha, ref] = l.split('\t'); return { sha, ref }; }) }; +} + +let rosterCache = null; +/** This checkout's derived skip roster, read once per process (`check-expected-skips.mjs` owns the derivation). */ +export function localRoster() { + rosterCache ??= expectedSkipRoster(REPO_ROOT).roster; + return rosterCache; +} + +export function sleepMs(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +// --------------------------------------------------------------------------- +// Fixture — offline PRs the same reads answer +// --------------------------------------------------------------------------- + +/** + * `{ prs: {N: row | [row, row…] (successive reads)}, reviews: {N: []}, timeline: {N: []}, check_runs: {sha: []}, + * status: {sha: {state, total_count}}, ls_remote: [{sha, ref}] | null, roster: [] }`. Absent → 404; `null` → 502. + */ +export function fixtureReaders(fx, repo) { + const reads = new Map(); + const page = (rows, path) => { + const p = Number(new URLSearchParams(path.split('?')[1] ?? '').get('page') ?? 1); + return rows.slice((p - 1) * 100, p * 100); + }; + const from = (table, key, path, wrap) => { + if (!table || !(key in table)) return { ok: false, error: 'HTTP 404' }; + if (table[key] === null) return { ok: false, error: 'HTTP 502' }; + return { ok: true, value: wrap ? wrap(table[key]) : page(table[key], path) }; + }; + const get = (path) => { + const bare = path.split('?')[0]; + let m = new RegExp(`^/repos/${repo}/pulls/(\\d+)$`).exec(bare); + if (m) { + const v = fx.prs?.[m[1]]; + if (v === undefined || v === null) return { ok: false, error: v === null ? 'HTTP 502' : 'HTTP 404' }; + if (!Array.isArray(v)) return { ok: true, value: v }; + const k = reads.get(m[1]) ?? 0; + reads.set(m[1], k + 1); + return { ok: true, value: v[Math.min(k, v.length - 1)] }; + } + if ((m = new RegExp(`^/repos/${repo}/pulls/(\\d+)/reviews$`).exec(bare))) return from(fx.reviews, m[1], path); + if ((m = new RegExp(`^/repos/${repo}/issues/(\\d+)/timeline$`).exec(bare))) return from(fx.timeline, m[1], path); + if ((m = new RegExp(`^/repos/${repo}/commits/([0-9a-f]+)/check-runs$`).exec(bare))) return from(fx.check_runs, m[1], path, (runs) => ({ total_count: fx.check_runs_total ?? runs.length, check_runs: page(runs, path) })); + if ((m = new RegExp(`^/repos/${repo}/commits/([0-9a-f]+)/status$`).exec(bare))) return from(fx.status, m[1], path, (s) => s); + return { ok: false, error: `HTTP 404 (${bare})` }; + }; + const lsRemote = () => (fx.ls_remote === null ? { ok: false, error: 'fatal: unable to access' } : { ok: true, value: fx.ls_remote ?? [] }); + return { get, lsRemote, sleep: () => {}, roster: fx.roster ?? [] }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +const USAGE = [ + 'pr-state — one state line per PR: merged, draft, mergeable_state, queue, reviews at head, checks (read-only).', + '', + ' node scripts/pm/pr-state.mjs --pr N[,N…] [--repo OWNER/NAME] [--rereads K] [--json] [--fixture FILE]', + ' node scripts/pm/pr-state.mjs --self-test', + '', + ' Exits: 0 complete · 2 usage · 3 a PR row unreadable · 4 INCOMPLETE (a leg unread or mergeable_state still unknown).', +].join('\n'); + +export function parseArgs(argv) { + const opts = { repo: DEFAULT_SWEEP_REPO, prs: [], rereads: DEFAULT_REREADS, json: false, fixture: null, help: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const eq = /^(--[a-z-]+)=(.*)$/.exec(a); + const flag = eq ? eq[1] : a; + const take = () => (eq ? eq[2] : argv[++i]); + if (flag === '--json' && !eq) opts.json = true; + else if ((flag === '--help' || flag === '-h') && !eq) opts.help = true; + else if (flag === '--pr') { + const v = String(take() ?? ''); + const list = v.split(',').map((s) => s.trim().replace(/^#/, '')); + if (!list.every((s) => /^[1-9][0-9]*$/.test(s))) return { error: `--pr must be N or N,N,… (PR numbers), got \`${v}\`` }; + opts.prs.push(...list.map(Number)); + } else if (flag === '--repo') { + opts.repo = String(take() ?? ''); + if (!/^[\w.-]+\/[\w.-]+$/.test(opts.repo)) return { error: `--repo must be OWNER/NAME, got \`${opts.repo}\`` }; + } else if (flag === '--rereads') { + const v = String(take() ?? ''); + if (!/^[0-9]$/.test(v)) return { error: `--rereads must be 0-9, got \`${v}\`` }; + opts.rereads = Number(v); + } else if (flag === '--fixture') { + opts.fixture = take(); + if (!opts.fixture) return { error: '--fixture needs a file' }; + } else return { error: `\`${a}\` is not an argument this tool takes` }; + } + if (!opts.help && opts.prs.length === 0) return { error: '--pr N is required' }; + return { opts }; +} + +export function main(argv, deps = {}) { + const parsed = parseArgs(argv); + if (parsed.error) { + console.error(`pr-state: ${parsed.error}`); + console.error(USAGE); + return EXIT_USAGE; + } + const o = parsed.opts; + if (o.help) { + console.log(USAGE); + return EXIT_OK; + } + let readers = deps.readers ?? {}; + if (o.fixture) { + try { + readers = fixtureReaders(JSON.parse(readFileSync(o.fixture, 'utf8')), o.repo); + } catch (e) { + console.error(`pr-state: --fixture \`${o.fixture}\` could not be read as JSON (${e.message})`); + return EXIT_USAGE; + } + } + const results = o.prs.map((number) => readPrState({ repo: o.repo, number, rereads: o.rereads, ...readers })); + const exit = results.some((r) => r.exit === EXIT_PR_UNREADABLE) ? EXIT_PR_UNREADABLE : results.some((r) => r.exit === EXIT_INCOMPLETE) ? EXIT_INCOMPLETE : EXIT_OK; + if (o.json) console.log(JSON.stringify({ repo: o.repo, prs: results.map((r) => r.json), unread_legs: UNREAD_LEGS, exit }, null, 2)); + else { + for (const r of results) console.log(r.line); + console.log('Not read by this reader — the seat reads these itself:'); + for (const leg of UNREAD_LEGS) console.log(` · ${leg}`); + console.log(exit === EXIT_OK ? `pr-state COMPLETE — ${results.length} PR(s), every leg read.` : `pr-state ${exit === EXIT_PR_UNREADABLE ? "CAN'T READ a PR" : 'INCOMPLETE'} — ⛔ not a clean state line: re-run when the reads answer.`); + } + return exit; +} + +// --------------------------------------------------------------------------- +// Self-test — floor (battery names pinned) + handshake, copied from the landed shape +// --------------------------------------------------------------------------- + +const SELF_TEST_BATTERIES = Object.freeze({ + 'the rule text: every phrase this file is built from is in the file that writes it': 3, + 'mergeable_state: unknown is re-read, bounded, and never printed as a reading': 5, + 'the queue: the timeline decides membership, the parent-tip chain the position': 8, + 'reviews: the newest per reviewer, at the head commit': 4, + 'checks and status: the head, every page, the count checked': 6, + 'the line and the CLI: usage, exits and the footer': 7, +}); +const SELF_TEST_BATTERY_FLOOR = 6; +const UNATTRIBUTED_BATTERY = '(unattributed)'; +const batteryCases = new Map(); +let openBattery = null; +const battery = (name) => { + openBattery = name; +}; +let selfTestReachedVerdict = false; + +const quiet = (fn) => (...args) => { + const log = console.log; + const err = console.error; + const out = []; + console.log = (...a) => out.push(a.join(' ')); + console.error = (...a) => out.push(a.join(' ')); + try { + return { code: fn(...args), out: out.join('\n') }; + } finally { + console.log = log; + console.error = err; + } +}; + +export function selfTest() { + const cases = []; + const t = (name, actual, expected = true) => { + const key = openBattery ?? UNATTRIBUTED_BATTERY; + batteryCases.set(key, (batteryCases.get(key) ?? 0) + 1); + const ok = JSON.stringify(actual) === JSON.stringify(expected); + cases.push({ name, ok, detail: ok ? '' : `got ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}` }); + }; + const REPO = 'objectstack-ai/objectstack'; + const sha = (c) => c.repeat(40); + const HEAD = sha('c'); + const MAIN = sha('a'); + const open = (over = {}) => ({ number: 7, state: 'open', draft: false, merged_at: null, mergeable_state: 'clean', head: { sha: HEAD }, base: { ref: 'main' }, auto_merge: null, ...over }); + const run = (name, conclusion = 'success') => ({ name, status: 'completed', conclusion, check_suite: { id: 1 } }); + const fixture = (over = {}) => ({ prs: { 7: open() }, reviews: { 7: [] }, timeline: { 7: [] }, check_runs: { [HEAD]: [run('Test Core'), run('Lint & Repo Gates')] }, status: { [HEAD]: { state: 'pending', total_count: 0 } }, ls_remote: [{ sha: MAIN, ref: 'refs/heads/main' }], roster: [{ name: 'Build Docs', reason: 'docs filter' }], ...over }); + const read = (fx, opts = {}) => readPrState({ repo: REPO, number: 7, ...fixtureReaders(fx, REPO), ...opts }); + + battery('the rule text: every phrase this file is built from is in the file that writes it'); + { + const missing = Object.entries(RULE_FILES).flatMap(([p, phrases]) => phrases.filter((ph) => !readFileSync(join(REPO_ROOT, p), 'utf8').includes(ph)).map((ph) => `${p}: ${ph}`)); + t('⭐ coordinator.md, landing-operations.md and readings-queue.md still say what this file encodes', missing, []); + t('the queue-ref shape parses PR and parent', QUEUE_REF.exec(`refs/heads/gh-readonly-queue/main/pr-35482-${MAIN}`)?.slice(1), ['35482', MAIN]); + t('the six facts the coordinator rule names are each on the line', ['MERGED', 'draft', 'mergeable_state', 'queue:', 'reviews at', 'auto_merge'].every((w) => read(fixture({ prs: { 7: open({ merged_at: '2026-11-19T13:48:50Z', state: 'closed' }) } })).line.includes(w)), true); + } + + battery('mergeable_state: unknown is re-read, bounded, and never printed as a reading'); + { + const settles = read(fixture({ prs: { 7: [open({ mergeable_state: 'unknown' }), open({ mergeable_state: 'unknown' }), open({ mergeable_state: 'blocked' })] } })); + t('⭐ unknown is re-read until it settles, and the line says how many reads', [settles.exit, settles.line.includes('mergeable_state blocked (read 3×)')], [EXIT_OK, true]); + const stuck = read(fixture({ prs: { 7: [open({ mergeable_state: 'unknown' })] } }), { rereads: 2 }); + t('⭐ unknown after the bound is INCOMPLETE, exit 4, never a reading', [stuck.exit, stuck.line.includes('mergeable_state unknown after 3 read(s) — not a reading')], [EXIT_INCOMPLETE, true]); + let slept = 0; + read(fixture({ prs: { 7: [open({ mergeable_state: 'unknown' })] } }), { rereads: 2, sleep: () => slept++ }); + t('the re-reads are bounded by --rereads and each waits', slept, 2); + const merged = read(fixture({ prs: { 7: open({ state: 'closed', merged_at: '2026-11-19T13:48:50Z', mergeable_state: 'unknown' }) } })); + t('a merged PR is never re-read for mergeable_state and is not incomplete for it', [merged.exit, merged.line.includes('mergeable_state n/a (merged)')], [EXIT_OK, true]); + t('a clean open PR is read once', read(fixture()).json.mergeable_reads, 1); + } + + battery('the queue: the timeline decides membership, the parent-tip chain the position'); + { + const added = { event: 'added_to_merge_queue', created_at: '2026-11-19T10:00:00Z' }; + const removed = { event: 'removed_from_merge_queue', created_at: '2026-11-19T10:05:00Z' }; + const refs = [{ sha: MAIN, ref: 'refs/heads/main' }, { sha: sha('1'), ref: `refs/heads/gh-readonly-queue/main/pr-5-${MAIN}` }, { sha: sha('2'), ref: `refs/heads/gh-readonly-queue/main/pr-7-${sha('1')}` }, { sha: sha('3'), ref: `refs/heads/gh-readonly-queue/main/pr-9-${sha('2')}` }]; + const inQ = read(fixture({ timeline: { 7: [added] }, ls_remote: refs })); + t('⭐ in queue: the position is walked from the base tip by parent, never by name order', inQ.line.includes('queue: in queue (added 2026-11-19T10:00:00Z), position 2 of 3'), true); + t('⭐ the LAST queue event decides: removed after added is not in queue', read(fixture({ timeline: { 7: [added, removed] } })).line.includes('queue: not in queue (removed 2026-11-19T10:05:00Z)'), true); + t('no queue event is never queued', read(fixture()).line.includes('queue: never queued'), true); + const noRef = read(fixture({ timeline: { 7: [added] } })); + t('in queue with no ref: membership stands, the position is unread, and that is not a gap', [noRef.exit, noRef.line.includes('no queue ref for it now (a ref answers a build, not membership) — position unread')], [EXIT_OK, true]); + const contradict = read(fixture({ timeline: { 7: [added, removed] }, ls_remote: refs })); + t('a ref that contradicts the timeline is printed, not resolved', contradict.line.includes('— yet a queue ref exists (position 2 of 3); re-read'), true); + const lsDown = read(fixture({ timeline: { 7: [added] }, ls_remote: null })); + t('⭐ unlisted queue refs on an in-queue PR leave the position unread and make it INCOMPLETE', [lsDown.exit, lsDown.gaps[0]], [EXIT_INCOMPLETE, 'the queue refs could not be listed, so the position is unread']); + const tl = read(fixture({ timeline: { 7: null } })); + t('⭐ an unreadable timeline is INCOMPLETE: membership is never inferred from refs', [tl.exit, tl.line.includes('queue: unread')], [EXIT_INCOMPLETE, true]); + t('a broken chain leaves the stranded entries off it', queueChain(refs.filter((r) => !r.ref.includes('pr-5-')), MAIN).chain.length, 0); + } + + battery('reviews: the newest per reviewer, at the head commit'); + { + const rv = (login, state, commit, at) => ({ user: { login }, state, commit_id: commit, submitted_at: at }); + const r = reviewsAtHead([rv('a', 'CHANGES_REQUESTED', HEAD, '1'), rv('a', 'APPROVED', HEAD, '2'), rv('b', 'APPROVED', sha('d'), '1'), rv('c', 'COMMENTED', HEAD, '3')], HEAD); + t('⭐ the newest review per reviewer counts; an approval on an older commit is not at head', [r.approved, r.changes, r.older], [['a'], [], 1]); + t('a comment-only review is neither', reviewsAtHead([rv('c', 'COMMENTED', HEAD, '3')], HEAD).approved, []); + t('the line names the approvals at head and the older ones', read(fixture({ reviews: { 7: [rv('a', 'APPROVED', HEAD, '2'), rv('b', 'APPROVED', sha('d'), '1')] } })).line.includes(`reviews at ${HEAD.slice(0, 10)}: APPROVED a (1 reviewer(s) newest on an older commit)`), true); + t('unreadable reviews are INCOMPLETE', read(fixture({ reviews: { 7: null } })).exit, EXIT_INCOMPLETE); + } + + battery('checks and status: the head, every page, the count checked'); + { + const runs = [run('Test Core'), run('Build Docs', 'skipped'), run('Lint UI', 'skipped'), run('Type Check UI', 'failure'), { name: 'Build Core', status: 'in_progress', conclusion: null, check_suite: { id: 1 } }]; + const r = read(fixture({ check_runs: { [HEAD]: runs } })); + t('⭐ success, expected and unexpected skips, failures and pending are each counted', r.line.includes('1 success · 1 expected skip · 1 unexpected skip (Lint UI) · 1 failed (Type Check UI=failure) · 1 pending'), true); + const many = Array.from({ length: 130 }, (_, k) => run(`job ${k}`)); + t('every page of check-runs is read', read(fixture({ check_runs: { [HEAD]: many } })).line.includes('130 success'), true); + const gap = read(fixture({ check_runs_total: 9 })); + t('⭐ a listing shorter than the platform count is INCOMPLETE', [gap.exit, gap.line.includes('checks unread (listed 2 of 9)')], [EXIT_INCOMPLETE, true]); + t('a legacy status with entries is printed with its state', read(fixture({ status: { [HEAD]: { state: 'failure', total_count: 1 } } })).line.includes('commit status failure (1)'), true); + t('unreadable check-runs are INCOMPLETE', read(fixture({ check_runs: { [HEAD]: null } })).exit, EXIT_INCOMPLETE); + const live = readPrState({ repo: REPO, number: 7, ...fixtureReaders(fixture({ check_runs: { [HEAD]: [run('Build Docs', 'skipped')] } }), REPO), roster: null }); + t('⭐ with no injected roster the live one is derived from this checkout and judges a skip', [Array.isArray(localRoster()), localRoster().length > 0, live.exit], [true, true, EXIT_OK]); + } + + battery('the line and the CLI: usage, exits and the footer'); + { + t('--pr is required', Boolean(parseArgs([]).error), true); + t('a list of PRs is read, #N included', parseArgs(['--pr', '7,#8']).opts.prs, [7, 8]); + t('an unknown flag is refused, never ignored', Boolean(parseArgs(['--pr', '7', '--fast']).error), true); + const ok = quiet(main)(['--pr', '7'], { readers: fixtureReaders(fixture(), REPO) }); + t('⭐ every run names the legs it cannot read, auto_merge is tagged unreliable, a complete run exits 0', [ok.code, UNREAD_LEGS.every((l) => ok.out.includes(l)), ok.out.includes('auto_merge null [unreliable field]')], [EXIT_OK, true, true]); + const gone = quiet(main)(['--pr', '7,8'], { readers: fixtureReaders(fixture(), REPO) }); + t('⭐ an unreadable PR row is exit 3 and its line says CAN\'T READ', [gone.code, gone.out.includes("#8 · CAN'T READ")], [EXIT_PR_UNREADABLE, true]); + const inc = quiet(main)(['--pr', '7'], { readers: fixtureReaders(fixture({ reviews: { 7: null } }), REPO) }); + t('an incomplete run never prints the COMPLETE verdict', [inc.code, inc.out.includes('pr-state COMPLETE')], [EXIT_INCOMPLETE, false]); + t('--json carries the exit', JSON.parse(quiet(main)(['--pr', '7', '--json'], { readers: fixtureReaders(fixture(), REPO) }).out).exit, EXIT_OK); + } + + const failed = cases.filter((x) => !x.ok); + for (const f of failed) console.error(` ✗ ${f.name} — ${f.detail}`); + const floor = []; + const declared = Object.keys(SELF_TEST_BATTERIES); + if (declared.length < SELF_TEST_BATTERY_FLOOR) floor.push(`the battery ledger declares ${declared.length} batteries, below its floor of ${SELF_TEST_BATTERY_FLOOR}`); + for (const [name, count] of batteryCases) if (!(name in SELF_TEST_BATTERIES)) floor.push(`self-test battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES`); + for (const name of declared) { + const count = batteryCases.get(name) ?? 0; + if (count < SELF_TEST_BATTERIES[name]) floor.push(count === 0 ? `self-test battery "${name}" DID NOT RUN` : `self-test battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]}`); + } + for (const f of floor) console.error(` ✗ ${f}`); + if (failed.length || floor.length) { + console.error(`✗ pr-state self-test: ${failed.length} of ${cases.length} case(s) failed${floor.length ? `, ${floor.length} floor breach(es)` : ''}.`); + selfTestReachedVerdict = true; + return EXIT_SELF_TEST_FAILED; + } + console.log(`✓ pr-state self-test: ${cases.length} cases pass across ${declared.length} batteries — offline, no network.`); + selfTestReachedVerdict = true; + return EXIT_OK; +} + +if (isEntrypoint(import.meta.url)) { + const argv = process.argv.slice(2); + if (argv.includes('--self-test')) { + const code = selfTest(); + if (!selfTestReachedVerdict) { + console.error('\n✗ pr-state self-test: selfTest() returned without reaching its verdict, so no success line was\nprinted. Exiting 0 here would report a self-test that never finished as one that passed.\n'); + process.exit(1); + } + process.exit(code); + } else { + process.exit(main(argv)); + } +} From f4095406435197b57de1aca74112726c3fbe1581 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:23:13 +0000 Subject: [PATCH 3/7] feat(pm): sweep-closed-cards --pr N reads the cards a merge closed against the body's closing keywords Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- scripts/pm/sweep-closed-cards.mjs | 234 +++++++++++++++++++++++++++++- 1 file changed, 231 insertions(+), 3 deletions(-) diff --git a/scripts/pm/sweep-closed-cards.mjs b/scripts/pm/sweep-closed-cards.mjs index 29bd157b656..b127824ad51 100644 --- a/scripts/pm/sweep-closed-cards.mjs +++ b/scripts/pm/sweep-closed-cards.mjs @@ -119,6 +119,32 @@ * population read itself failed, so NO card was judged and this run says * nothing at all about the board. * + * ## `--pr N` — the post-merge silent-close reading (report-only) + * + * `references/landing-operations.md` asks the landing seat, after every merge, to diff the lane's open cards + * against the expected ones: a card that left `open` unexpectedly is one a closing keyword shut silently. `--pr N` + * is that reading for one merged PR. It WRITES NOTHING and takes no other mode: `--write` and `--all-time` beside + * it are refused. The closed-card sweep above is untouched by it. + * + * - Targets: the card numbers the PR body binds with a closing keyword, read with `closingKeywordTargets` (the + * parser H7 uses; a keyword quoted in backticks binds nothing). + * - Closed by the merge: an issue of this repository closed inside `[merged_at - MERGE_CLOSE_LEAD_SECONDS, + * merged_at + MERGE_CLOSE_WINDOW_SECONDS]` (the search API, its count checked), plus every target, whose + * timeline ties it to THIS merge: the `closed` event carries the merge commit, a `referenced` event carries the + * merge commit (a keyword in a squashed commit message), or a `cross-referenced` event comes from this PR and no + * OTHER pull request whose body closes the card merged inside the window, and the close landed within + * `MERGE_AUTO_CLOSE_SECONDS` of the merge (a later one is listed as a hand close). REST carries no closer field (the + * auto-close's `closed` event reads `commit_id: null`), so this tie is the reading — the actor and the seconds + * after the merge are printed so the seat can tell a hand close inside the window from the merge's. + * - Extra = closed by the merge, named by no closing keyword = a SILENT CLOSE, exit 1. A named target still open is + * printed, not an alarm. + * + * Its exits: 0 every card closed by the merge is a named target · 1 a silent close (each named) · 2 a candidate's + * timeline or the search did not answer, so a silent close may be unread (never a 0) · 3 the PR is unreadable or + * not merged. Exit 1 is also this file's usage code; both are a non-zero a seat reads, never a clean answer. + * Not read: issues in OTHER repositories a cross-repo keyword closed (`owner/repo#N` targets are listed by number), + * and a card the search index has not caught up with in the first seconds after a merge (re-run). + * * ## Cost * * Per run: one default-branch read, one listing page per residue label (the @@ -491,6 +517,95 @@ export function summariseRun(rows) { return { counts, exitCode }; } +// --------------------------------------------------------------------------- +// `--pr N` — the post-merge silent-close reading. Pure core; the reads live below. +// --------------------------------------------------------------------------- + +/** The window around `merged_at` a merge's own close lands in: GitHub closes in seconds, so ten minutes is slack. */ +export const MERGE_CLOSE_LEAD_SECONDS = 60; +export const MERGE_CLOSE_WINDOW_SECONDS = 600; +/** + * A close tied to this PR only by its cross-reference counts as the merge's own only this soon after `merged_at`: + * the platform closes keyword targets at the merge (measured 4 s on a queue merge), while a seat's hand close of a + * folded card lands minutes later (measured 112 s on the same merge). A later close is listed, not charged. + */ +export const MERGE_AUTO_CLOSE_SECONDS = 60; +export const SILENT_CLOSE_PHRASE = '预期外从 open 消失的即被闭合关键词静默误关的卡;每次合并读 `sweep-closed-cards.mjs --pr N`。'; +export const LANDING_OPERATIONS_PATH = '.claude/skills/pm-dispatch/references/landing-operations.md'; + +/** + * Is this candidate closed by THIS merge? Pure over the issue row and its full timeline. + * `{ closed: false }` | `{ closed: true, byThisMerge: boolean, why, closedAt, actor, secondsAfter, otherPr? }`. + */ +export function mergeCloseTie(issue, timeline, { prNumber, mergeSha, mergedAtMs }) { + if (issue?.state !== 'closed') return { closed: false }; + const last = lastClosedEvent(timeline); + const closedAtMs = Date.parse(last?.created_at ?? issue.closed_at ?? ''); + const base = { closed: true, closedAt: last?.created_at ?? issue.closed_at ?? null, actor: last?.actor?.login ?? null, secondsAfter: Number.isFinite(closedAtMs) ? Math.round((closedAtMs - mergedAtMs) / 1000) : null }; + const inWindow = Number.isFinite(closedAtMs) && closedAtMs >= mergedAtMs - MERGE_CLOSE_LEAD_SECONDS * 1000 && closedAtMs <= mergedAtMs + MERGE_CLOSE_WINDOW_SECONDS * 1000; + if (!inWindow) return { ...base, byThisMerge: false, why: 'closed outside the merge window' }; + if (last?.commit_id && last.commit_id === mergeSha) return { ...base, byThisMerge: true, why: 'its closed event carries the merge commit' }; + if ((timeline ?? []).some((e) => e?.event === 'referenced' && e.commit_id === mergeSha)) return { ...base, byThisMerge: true, why: 'the merge commit references it' }; + const fromThisPr = (timeline ?? []).some((e) => (e?.event === 'cross-referenced' || e?.event === 'connected') && e?.source?.issue?.number === prNumber); + if (!fromThisPr) return { ...base, byThisMerge: false, why: 'nothing on its timeline ties it to this merge' }; + const others = closingPullRequestRefs(timeline, issue.number).filter((p) => p.number !== prNumber && p.mergedAt && Math.abs(Date.parse(p.mergedAt) - closedAtMs) <= MERGE_CLOSE_WINDOW_SECONDS * 1000); + if (others.length) return { ...base, byThisMerge: false, why: `#${others[0].number}, merged in the window, closes it by its body`, otherPr: others[0].number }; + if (base.secondsAfter > MERGE_AUTO_CLOSE_SECONDS) return { ...base, byThisMerge: false, later: true, why: `closed ${base.secondsAfter}s after the merge — later than the platform closes on a merge (${MERGE_AUTO_CLOSE_SECONDS}s); a hand close, read its close-out` }; + return { ...base, byThisMerge: true, why: 'this PR references it and no other closing PR merged in the window' }; +} + +/** + * The silent-close verdict for one merged PR. Pure. + * `candidates`: `[{ number, issue, timeline, error? }]` (targets and in-window closes, each once). + * `search`: `{ ok, error?, listed, total, incomplete }`. + */ +export function judgeMergeCloses({ pr, candidates, search }) { + const targets = [...closingKeywordTargets(pr.body ?? '').keys()].map(Number).sort((a, b) => a - b); + const crossRepo = [...String(pr.body ?? '').matchAll(/\b(?:clos(?:e|es|ed)|fix(?:es|ed)?|resolv(?:e|es|ed))\b[ \t]*:?[ \t]*([\w.-]+\/[\w.-]+#\d+)/gi)].map((m) => m[1]); + const mergedAtMs = Date.parse(pr.merged_at); + const closedByMerge = []; + const namedOpen = []; + const namedNotByMerge = []; + const laterHandCloses = []; + const unjudged = []; + for (const c of candidates) { + if (c.error) { + unjudged.push({ number: c.number, detail: c.error }); + continue; + } + const tie = mergeCloseTie(c.issue, c.timeline, { prNumber: pr.number, mergeSha: pr.merge_commit_sha, mergedAtMs }); + const named = targets.includes(c.number); + if (!tie.closed) { + if (named) namedOpen.push({ number: c.number }); + continue; + } + if (tie.byThisMerge) closedByMerge.push({ number: c.number, named, title: c.issue.title ?? '', ...tie }); + else if (tie.later) laterHandCloses.push({ number: c.number, named, ...tie }); + else if (named) namedNotByMerge.push({ number: c.number, ...tie }); + } + const silent = closedByMerge.filter((c) => !c.named); + if (!search.ok) unjudged.push({ number: null, detail: `the in-window closed-issue search did not answer (${search.error})` }); + else if (search.incomplete || search.listed < search.total) unjudged.push({ number: null, detail: `the in-window search listed ${search.listed} of ${search.total} closed issue(s)${search.incomplete ? ' (the platform flagged the result incomplete)' : ''}` }); + const exitCode = silent.length ? EXIT_USAGE : unjudged.length ? EXIT_UNJUDGED : EXIT_OK; + return { targets, crossRepo, closedByMerge, silent, namedOpen, namedNotByMerge, laterHandCloses, unjudged, exitCode }; +} + +export function renderMergeCloses(pr, j) { + const L = [`sweep-closed-cards --pr ${pr.number} — merged ${pr.merged_at} as ${String(pr.merge_commit_sha).slice(0, 10)} · REPORT ONLY, nothing written`]; + L.push(`closing-keyword targets in the body: ${j.targets.map((n) => `#${n}`).join(', ') || 'none'}${j.crossRepo.length ? ` · in other repositories (not read): ${j.crossRepo.join(', ')}` : ''}`); + L.push(`closed by this merge: ${j.closedByMerge.length ? '' : 'none'}`); + for (const c of j.closedByMerge) L.push(` · #${c.number} ${c.named ? 'named' : '⚠️ NOT NAMED — silent close'} · closed ${c.closedAt} (${c.secondsAfter}s after the merge) by ${c.actor ?? '?'} · ${c.why} — ${String(c.title).slice(0, 80)}`); + for (const c of j.namedOpen) L.push(` · #${c.number} named, still OPEN after the merge`); + for (const c of j.namedNotByMerge) L.push(` · #${c.number} named, closed but not by this merge (${c.why})`); + for (const c of j.laterHandCloses) L.push(` · #${c.number} ${c.named ? 'named' : 'not named'}, referenced by this PR, closed by ${c.actor ?? '?'} — ${c.why}`); + for (const u of j.unjudged) L.push(` · UNREAD ${u.number ? `#${u.number}` : ''} — ${u.detail}`); + L.push('Not read by this mode: a card in another repository a cross-repo keyword closed; a card the search index has not caught up with in the first seconds after a merge (re-run).'); + if (j.silent.length) L.push(`✗ SILENT CLOSE — ${j.silent.map((c) => `#${c.number}`).join(', ')} closed by this merge with no closing keyword naming it; reopen and restore its state. Exit ${EXIT_USAGE}.`); + else if (j.unjudged.length) L.push(`⚠️ UNJUDGED — a read did not answer, so a silent close may be unread. ⛔ Not a clean answer. Exit ${EXIT_UNJUDGED}.`); + else L.push(`✓ every card closed by this merge is a named target. Exit ${EXIT_OK}.`); + return L.join('\n'); +} + // --------------------------------------------------------------------------- // Live layer // --------------------------------------------------------------------------- @@ -525,6 +640,52 @@ async function rest(path, { method = 'GET', body = null } = {}) { } /** The board's own default branch — never a hardcoded `main`, so the file stays repo-agnostic. */ +/** Every page of one list read through `rest`, or a thrown error. */ +async function restPages(path, maxPages = 10) { + const rows = []; + for (let page = 1; page <= maxPages; page++) { + const batch = await rest(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + if (!Array.isArray(batch)) throw new Error(`GET ${path} answered no list`); + rows.push(...batch); + if (batch.length < 100) return rows; + } + throw new Error(`GET ${path} still returned full pages after ${maxPages}`); +} + +/** The `--pr N` reads: the PR, the in-window search and each candidate's row and timeline. */ +async function readMergeCloses(repo, number) { + const pr = await rest(`/repos/${repo}/pulls/${number}`); + if (!pr?.merged_at || !pr.merge_commit_sha) return { pr, notMerged: true }; + const t = Date.parse(pr.merged_at); + const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z'); + const range = `${iso(t - MERGE_CLOSE_LEAD_SECONDS * 1000)}..${iso(t + MERGE_CLOSE_WINDOW_SECONDS * 1000)}`; + const search = { ok: true, listed: 0, total: 0, incomplete: false }; + const numbers = new Set([...closingKeywordTargets(pr.body ?? '').keys()].map(Number)); + try { + for (let page = 1; page <= 10; page++) { + const res = await rest(`/search/issues?q=${encodeURIComponent(`repo:${repo} is:issue closed:${range}`)}&per_page=100&page=${page}`); + search.total = res.total_count ?? 0; + search.incomplete ||= Boolean(res.incomplete_results); + for (const it of res.items ?? []) numbers.add(it.number); + search.listed += (res.items ?? []).length; + if ((res.items ?? []).length < 100) break; + } + } catch (err) { + Object.assign(search, { ok: false, error: err.message }); + } + const candidates = []; + for (const n of [...numbers].sort((a, b) => a - b)) { + try { + const issue = await rest(`/repos/${repo}/issues/${n}`); + if (issue?.pull_request) continue; + candidates.push({ number: n, issue, timeline: await restPages(`/repos/${repo}/issues/${n}/timeline`) }); + } catch (err) { + candidates.push({ number: n, error: err.message }); + } + } + return { pr: { ...pr, number }, candidates, search }; +} + async function readDefaultBranch(repo) { const meta = await rest(`/repos/${repo}`); return meta?.default_branch ?? 'main'; @@ -883,8 +1044,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the exit register: nothing to do is never an alarm': 7, 'the report: what a reader is told, and what it refuses to imply': 7, 'the CLI: the one decision a typo must never make': 8, + '--pr N: a card the merge closed that no closing keyword names is a silent close': 13, }); -const SELF_TEST_BATTERY_FLOOR = 9; +const SELF_TEST_BATTERY_FLOOR = 10; const UNATTRIBUTED_BATTERY = '(unattributed)'; let selfTestReachedVerdict = false; @@ -1074,6 +1236,43 @@ export function selfTest() { t('`--all-time` is the null window, and it parses', parseOptions(['--all-time']).options.windowHours === null); t('a bad cap is refused too', parseOptions(['--max-cards=0']).ok === false); + // -- --pr N ---------------------------------------------------------------- + battery('--pr N: a card the merge closed that no closing keyword names is a silent close'); + { + const MERGE = 'f'.repeat(40); + const AT = '2026-11-19T14:56:27Z'; + const pr = { number: 500, merged_at: AT, merge_commit_sha: MERGE, body: 'Fixes #10\n\nPart of #11\n\n`Fixes #12` quoted' }; + const closedEv = (at, extra = {}) => ({ event: 'closed', created_at: at, actor: { login: 'objectstack-fleet[bot]' }, commit_id: null, ...extra }); + const xref = (n, body = '', mergedAt = AT) => ({ event: 'cross-referenced', source: { issue: { number: n, body, state: 'closed', pull_request: { merged_at: mergedAt } } } }); + const closed = (number, timeline) => ({ number, issue: { number, state: 'closed', title: `card ${number}` }, timeline }); + const ok = { ok: true, listed: 2, total: 2, incomplete: false }; + const clean = judgeMergeCloses({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')])], search: ok }); + t('a named target closed by the merge is clean, exit 0', clean.exitCode === EXIT_OK && clean.closedByMerge.length === 1 && clean.silent.length === 0); + const partOf = judgeMergeCloses({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')]), closed(11, [xref(500), closedEv('2026-11-19T14:56:32Z')])], search: ok }); + t('⭐ a `Part of` card the merge closed is a SILENT CLOSE, exit 1, named', partOf.exitCode === EXIT_USAGE && partOf.silent.map((c) => c.number).join() === '11'); + t('the targets are read with the H7 parser: a backticked keyword binds nothing', partOf.targets.join() === '10'); + const viaCommit = judgeMergeCloses({ pr, candidates: [closed(13, [{ event: 'referenced', commit_id: MERGE }, closedEv('2026-11-19T14:56:33Z')])], search: ok }); + t('⭐ a keyword in the squashed commit message (a referenced event on the merge commit) is tied to the merge', viaCommit.silent.map((c) => c.number).join() === '13' && viaCommit.silent[0].why === 'the merge commit references it'); + const byCommitId = mergeCloseTie({ number: 14, state: 'closed' }, [closedEv('2026-11-19T14:56:33Z', { commit_id: MERGE })], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); + t('a closed event carrying the merge commit is tied to it', byCommitId.byThisMerge === true); + const other = mergeCloseTie({ number: 15, state: 'closed' }, [xref(500), xref(501, 'Fixes #15'), closedEv('2026-11-19T14:56:40Z')], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); + t('⭐ a card another PR merged in the same window closes by its body is not charged to this merge', other.byThisMerge === false && other.otherPr === 501); + const late = mergeCloseTie({ number: 16, state: 'closed' }, [xref(500), closedEv('2026-11-19T16:00:00Z')], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); + t('a close outside the window is not this merge\'s', late.byThisMerge === false); + const hand = judgeMergeCloses({ pr, candidates: [closed(18, [xref(500), closedEv('2026-11-19T14:58:19Z')])], search: ok }); + t('⭐ a card this PR only cross-references, closed minutes after the merge, is a listed hand close, not a silent close', hand.exitCode === EXIT_OK && hand.laterHandCloses.length === 1 && renderMergeCloses(pr, hand).includes('#18 not named, referenced by this PR')); + const untied = mergeCloseTie({ number: 17, state: 'closed' }, [closedEv('2026-11-19T14:56:40Z')], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); + t('a card closed in the window with nothing tying it to this merge is not charged to it', untied.byThisMerge === false); + const openTarget = judgeMergeCloses({ pr, candidates: [{ number: 10, issue: { number: 10, state: 'open' }, timeline: [] }], search: ok }); + t('a named target still open is printed, not an alarm', openTarget.exitCode === EXIT_OK && openTarget.namedOpen.length === 1 && renderMergeCloses(pr, openTarget).includes('#10 named, still OPEN')); + const unread = judgeMergeCloses({ pr, candidates: [{ number: 11, error: 'GET … -> HTTP 502' }], search: ok }); + t('⭐ an unreadable candidate timeline is UNJUDGED, exit 2, never a clean 0', unread.exitCode === EXIT_UNJUDGED && renderMergeCloses(pr, unread).includes('⛔ Not a clean answer')); + const shortSearch = judgeMergeCloses({ pr, candidates: [], search: { ok: true, listed: 1, total: 3, incomplete: false } }); + t('⭐ a search that listed fewer than it counts is UNJUDGED, exit 2', shortSearch.exitCode === EXIT_UNJUDGED); + t('`--pr N` parses in both spellings, and refuses --write and --all-time beside it', parseOptions(['--pr', '35482']).options.pr === 35482 && parseOptions(['--pr=#7']).options.pr === 7 && parseOptions(['--pr=7', '--write']).ok === false && parseOptions(['--pr=7', '--all-time']).ok === false && parseOptions(['--pr=x']).ok === false && parseOptions([]).options.pr === null); + t('⭐ landing-operations.md still says the rule this mode reads, with the pointer here', readFileSync(new URL(`../../${LANDING_OPERATIONS_PATH}`, import.meta.url), 'utf8').includes(SILENT_CLOSE_PHRASE)); + } + // -- the floor ------------------------------------------------------------- const floorFailure = (message) => { cases.push({ name: message, ok: false }); }; const declared = Object.keys(SELF_TEST_BATTERIES); @@ -1152,7 +1351,7 @@ export function readOption(argv, name, fallback) { /** The flags this tool takes. An argument outside this set is a typo, and a typo is refused. */ export const KNOWN_FLAGS = Object.freeze(['--write', '--dry-run', '--json', '--all-time', '--self-test', '--help', '-h']); -export const KNOWN_OPTIONS = Object.freeze(['since-hours', 'max-cards', 'list-cap', 'provenance']); +export const KNOWN_OPTIONS = Object.freeze(['since-hours', 'max-cards', 'list-cap', 'provenance', 'pr']); /** * Parse argv into the run's options, or refuse. Pure, so the refusals are @@ -1165,7 +1364,12 @@ export const KNOWN_OPTIONS = Object.freeze(['since-hours', 'max-cards', 'list-ca * standing between a typo and a write. */ export function parseOptions(argv, { nowMs = Date.now() } = {}) { - const args = argv ?? []; + // `--pr N` is spelled with a space as well as `--pr=N`; every other option keeps its one spelling. + const args = []; + for (let i = 0; i < (argv ?? []).length; i++) { + if (argv[i] === '--pr' && i + 1 < argv.length) args.push(`--pr=${argv[++i]}`); + else args.push(argv[i]); + } for (const arg of args) { if (KNOWN_FLAGS.includes(arg)) continue; const named = /^--([a-z-]+)=/.exec(arg); @@ -1189,9 +1393,15 @@ export function parseOptions(argv, { nowMs = Date.now() } = {}) { if (!Number.isInteger(listCap) || listCap <= 0) { return { ok: false, error: '--list-cap must be a positive whole number of rows.' }; } + const prRaw = readOption(args, 'pr', null); + if (prRaw !== null) { + if (!/^#?[1-9][0-9]*$/.test(prRaw)) return { ok: false, error: `--pr=${prRaw} is not a pull request number.` }; + if (args.includes('--write') || allTime) return { ok: false, error: '--pr is a report-only reading: it takes no --write and no --all-time.' }; + } return { ok: true, options: { + pr: prRaw === null ? null : Number(prRaw.replace(/^#/, '')), write: args.includes('--write'), json: args.includes('--json'), windowHours, @@ -1208,6 +1418,7 @@ const USAGE = [ '', ' node scripts/pm/sweep-closed-cards.mjs [--write | --dry-run] [--json] [--since-hours=N | --all-time]', ' [--max-cards=N] [--provenance=TEXT]', + ' node scripts/pm/sweep-closed-cards.mjs --pr N [--json] # report-only: cards this merge closed that its body names by no closing keyword', ' node scripts/pm/sweep-closed-cards.mjs --self-test', '', ` default: DRY RUN over cards closed in the last ${DEFAULT_WINDOW_HOURS}h. --write is what acts.`, @@ -1238,6 +1449,23 @@ async function main(argv) { } const options = parsed.options; + if (options.pr !== null) { + let read; + try { + read = await readMergeCloses(repoRes.repo, options.pr); + } catch (err) { + return reportPrerequisiteNotMet(err); + } + if (read.notMerged) { + console.error(`sweep-closed-cards --pr ${options.pr}: the PR is not merged, so no merge closed anything. Exit ${EXIT_PREREQUISITE_NOT_MET}.`); + return EXIT_PREREQUISITE_NOT_MET; + } + const j = judgeMergeCloses(read); + if (options.json) console.log(JSON.stringify({ pr: options.pr, merged_at: read.pr.merged_at, merge_commit_sha: read.pr.merge_commit_sha, ...j, exit_code: j.exitCode }, null, 2)); + else console.log(renderMergeCloses(read.pr, j)); + return j.exitCode; + } + if (options.write && options.windowHours === null) { console.error( '⚠️ --write with --all-time: this is the unbounded backfill the 2026-08-31 maintainer ruling\n' + From 270521e24eb4f2e2b72a9a42e1adfcd65c50765e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:23:32 +0000 Subject: [PATCH 4/7] chore(pm): run the landing-k and pr-state self-tests in the expected-skips chain Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6498540948a..9174030350e 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,7 @@ "check:pm-governed-merges": "node scripts/pm/check-governed-merges.mjs --self-test", "check:pm-governed-prose": "node scripts/pm/check-governed-prose.mjs --self-test && node scripts/pm/check-governed-prose.mjs", "check:pm-settings-deny-roster": "node scripts/pm/check-settings-deny-roster.mjs --self-test && node scripts/pm/check-settings-deny-roster.mjs && node scripts/pm/install-settings-deny-roster.mjs --self-test", - "check:pm-expected-skips": "node scripts/pm/check-expected-skips.mjs --self-test", + "check:pm-expected-skips": "node scripts/pm/check-expected-skips.mjs --self-test && node scripts/pm/landing-k.mjs --self-test && node scripts/pm/pr-state.mjs --self-test", "check:publish-smoke-pin": "node scripts/publish-smoke-pack.mjs --self-test", "check:partof-closing-keyword": "node scripts/check-partof-closing-keyword.mjs --self-test", "check:commit-card-trailers": "node scripts/check-commit-card-trailers.mjs --self-test", From 4d60cb8c06b413ee2ff407be1c4880621b62187d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:35:03 +0000 Subject: [PATCH 5/7] fix(pm): sweep-closed-cards --pr reads targets with the shared parser only Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- scripts/pm/sweep-closed-cards.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/pm/sweep-closed-cards.mjs b/scripts/pm/sweep-closed-cards.mjs index b127824ad51..99f89f495c3 100644 --- a/scripts/pm/sweep-closed-cards.mjs +++ b/scripts/pm/sweep-closed-cards.mjs @@ -142,7 +142,8 @@ * Its exits: 0 every card closed by the merge is a named target · 1 a silent close (each named) · 2 a candidate's * timeline or the search did not answer, so a silent close may be unread (never a 0) · 3 the PR is unreadable or * not merged. Exit 1 is also this file's usage code; both are a non-zero a seat reads, never a clean answer. - * Not read: issues in OTHER repositories a cross-repo keyword closed (`owner/repo#N` targets are listed by number), + * Not read: issues in OTHER repositories a cross-repo keyword closed (the targets are read with the shared parser, + * which binds this repository's numbers only, so no second closing-keyword parser lives here), * and a card the search index has not caught up with in the first seconds after a merge (re-run). * * ## Cost @@ -561,7 +562,6 @@ export function mergeCloseTie(issue, timeline, { prNumber, mergeSha, mergedAtMs */ export function judgeMergeCloses({ pr, candidates, search }) { const targets = [...closingKeywordTargets(pr.body ?? '').keys()].map(Number).sort((a, b) => a - b); - const crossRepo = [...String(pr.body ?? '').matchAll(/\b(?:clos(?:e|es|ed)|fix(?:es|ed)?|resolv(?:e|es|ed))\b[ \t]*:?[ \t]*([\w.-]+\/[\w.-]+#\d+)/gi)].map((m) => m[1]); const mergedAtMs = Date.parse(pr.merged_at); const closedByMerge = []; const namedOpen = []; @@ -587,12 +587,12 @@ export function judgeMergeCloses({ pr, candidates, search }) { if (!search.ok) unjudged.push({ number: null, detail: `the in-window closed-issue search did not answer (${search.error})` }); else if (search.incomplete || search.listed < search.total) unjudged.push({ number: null, detail: `the in-window search listed ${search.listed} of ${search.total} closed issue(s)${search.incomplete ? ' (the platform flagged the result incomplete)' : ''}` }); const exitCode = silent.length ? EXIT_USAGE : unjudged.length ? EXIT_UNJUDGED : EXIT_OK; - return { targets, crossRepo, closedByMerge, silent, namedOpen, namedNotByMerge, laterHandCloses, unjudged, exitCode }; + return { targets, closedByMerge, silent, namedOpen, namedNotByMerge, laterHandCloses, unjudged, exitCode }; } export function renderMergeCloses(pr, j) { const L = [`sweep-closed-cards --pr ${pr.number} — merged ${pr.merged_at} as ${String(pr.merge_commit_sha).slice(0, 10)} · REPORT ONLY, nothing written`]; - L.push(`closing-keyword targets in the body: ${j.targets.map((n) => `#${n}`).join(', ') || 'none'}${j.crossRepo.length ? ` · in other repositories (not read): ${j.crossRepo.join(', ')}` : ''}`); + L.push(`closing-keyword targets in the body (this repository): ${j.targets.map((n) => `#${n}`).join(', ') || 'none'}`); L.push(`closed by this merge: ${j.closedByMerge.length ? '' : 'none'}`); for (const c of j.closedByMerge) L.push(` · #${c.number} ${c.named ? 'named' : '⚠️ NOT NAMED — silent close'} · closed ${c.closedAt} (${c.secondsAfter}s after the merge) by ${c.actor ?? '?'} · ${c.why} — ${String(c.title).slice(0, 80)}`); for (const c of j.namedOpen) L.push(` · #${c.number} named, still OPEN after the merge`); From 3268e1c78341eff7492638ac88b1abe257bedbc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:42:03 +0000 Subject: [PATCH 6/7] fix(pm): landing-k spells the examples surface as a pattern, not a bare root literal Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G Co-authored-by: Claude --- scripts/pm/landing-k.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/pm/landing-k.mjs b/scripts/pm/landing-k.mjs index 657c869ed9b..203ec565b33 100644 --- a/scripts/pm/landing-k.mjs +++ b/scripts/pm/landing-k.mjs @@ -135,7 +135,7 @@ export function labelSurfaceReader(extractRoots) { if (p.includes('/translations/') || p.startsWith('translations/')) return 'a translation bundle'; if (isMetadataFormModulePath(p)) return 'a metadata form module (the metadataForms half)'; if (p.startsWith('packages/spec/src/')) return 'spec-declared labels'; - if (p.startsWith('examples/')) return 'an example config (check:i18n-coverage)'; + if (/^examples\//.test(p)) return 'an example config (check:i18n-coverage)'; const root = extractRoots.find((r) => p.startsWith(r)); return root ? `a package that owns an i18n extract config (${root.slice(0, -1)})` : null; }; From 2aa7331393357f6700acd3d869abdf34ca71e6ce Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 16:46:56 +0000 Subject: [PATCH 7/7] =?UTF-8?q?fix(pm):=20fix=20round=201=20for=20the=20la?= =?UTF-8?q?nding=20readers=20=E2=80=94=20settle=20window,=20wired=20pin,?= =?UTF-8?q?=20older=20reviews,=20queue=20contradictions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sweep-closed-cards --pr: a merge younger than MERGE_SETTLE_SECONDS (300 s) is UNJUDGED (exit 2) with the time to re-run, never the clean verdict; the silent close gets its own exit code, EXIT_SILENT_CLOSE = 4; the --pr battery floor matches its registered count; the line-77 phrase pin reads its file inside the harness, so a moved or split file fails the case instead of throwing. - check:pm-expected-skips now also runs sweep-closed-cards --self-test. - pr-state: reviewers whose newest review is on an older commit are printed with state and login, apart from the at-head ones, in the line and --json; a queue ref that contradicts the timeline's last queue event is a gap, so the run is INCOMPLETE (exit 4). - landing-k: diff base read from the selector step only. - landing-operations.md line 41 names landing-k as the reading of the any-K legs too (line count unchanged). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CaAqjP52wVTzs99H5G --- .../references/landing-operations.md | 2 +- package.json | 2 +- scripts/pm/landing-k.mjs | 70 ++++++++++++++--- scripts/pm/pr-state.mjs | 46 +++++++---- scripts/pm/sweep-closed-cards.mjs | 77 +++++++++++++------ 5 files changed, 146 insertions(+), 51 deletions(-) diff --git a/.claude/skills/pm-dispatch/references/landing-operations.md b/.claude/skills/pm-dispatch/references/landing-operations.md index 010c7603ad7..3ab65e3aaec 100644 --- a/.claude/skills/pm-dispatch/references/landing-operations.md +++ b/.claude/skills/pm-dispatch/references/landing-operations.md @@ -38,7 +38,7 @@ - 该 op 实测离队见 `readings-queue.md`;在队受管面 PR 亦由落地席发(Prime Directive #14)。 - 谁入队谁看护:冲突或自因被踢 ⇒ 一轮巡查内出队修复再入队;他人 flake 照四分支重投。 - PR 侧红(非队列)同在本窗口处置:义务与三步只住 `readings-ci.md`「红检查先读日志」。 -- 挂 auto-merge/入队前读 K = PRBASE 至 origin/main 的首父提交数,现读 `landing-k.mjs --pr N`。 +- 挂 auto-merge/入队前读 K(PRBASE 至 origin/main 首父提交数)与任何 K 两腿,读 `landing-k.mjs --pr N`。 - PRBASE = 末次绿 PR 跑 Test Core 所印 `Affected-set diff base`,⛔ 不取该跑起始时刻。 - K ≥ 15 ⇒ 先 merge main 等重跑绿,`behind` 例外;任何 K 同:标签 PR 的 PRBASE 后 main 落新语种包; - 或共享预算 PR 遇 PRBASE 后 main 碰同本输入或账本;封闭两本,输入:账本: diff --git a/package.json b/package.json index 9174030350e..8923bc854d0 100644 --- a/package.json +++ b/package.json @@ -100,7 +100,7 @@ "check:pm-governed-merges": "node scripts/pm/check-governed-merges.mjs --self-test", "check:pm-governed-prose": "node scripts/pm/check-governed-prose.mjs --self-test && node scripts/pm/check-governed-prose.mjs", "check:pm-settings-deny-roster": "node scripts/pm/check-settings-deny-roster.mjs --self-test && node scripts/pm/check-settings-deny-roster.mjs && node scripts/pm/install-settings-deny-roster.mjs --self-test", - "check:pm-expected-skips": "node scripts/pm/check-expected-skips.mjs --self-test && node scripts/pm/landing-k.mjs --self-test && node scripts/pm/pr-state.mjs --self-test", + "check:pm-expected-skips": "node scripts/pm/check-expected-skips.mjs --self-test && node scripts/pm/landing-k.mjs --self-test && node scripts/pm/pr-state.mjs --self-test && node scripts/pm/sweep-closed-cards.mjs --self-test", "check:publish-smoke-pin": "node scripts/publish-smoke-pack.mjs --self-test", "check:partof-closing-keyword": "node scripts/check-partof-closing-keyword.mjs --self-test", "check:commit-card-trailers": "node scripts/check-commit-card-trailers.mjs --self-test", diff --git a/scripts/pm/landing-k.mjs b/scripts/pm/landing-k.mjs index 203ec565b33..586699eb600 100644 --- a/scripts/pm/landing-k.mjs +++ b/scripts/pm/landing-k.mjs @@ -22,9 +22,9 @@ * 1. K = `git rev-list --count --first-parent PRBASE..origin/main`. * 2. PRBASE = the `Affected-set diff base` that the LAST GREEN PR run's Test Core printed * (`scripts/ci/select-shard-packages.sh` spells the line; every `Test Core (k/N)` shard and the planner print it), - * ⛔ never that run's start time. "Green" = the run's `Test Core` aggregate job concluded `success`; "PR run" = a - * `pull_request` run of `ci.yml` whose head is one of this PR's commits (a branch name is reused across PRs, so - * the branch alone never decides). + * ⛔ never that run's start time; the diff base is read from the selector step only (`SELECTOR_STEP`). "Green" = + * the run's `Test Core` aggregate job concluded `success`; "PR run" = a `pull_request` run of `ci.yml` whose head + * is one of this PR's commits (a branch name is reused across PRs, so the branch alone never decides). * 3. K ≥ 15 ⇒ merge main first and wait for a green re-run. `behind` alone is not a reason (the K decides). * 4. At any K, the locale leg: a label PR, when a new locale pack landed on main after PRBASE. A new locale pack is a * file ADDED under a `translations/` directory in `PRBASE..main` whose locale (the file name up to its first dot) @@ -88,6 +88,12 @@ export const TEST_CORE_PLAN = 'Plan Test Core shards'; /** `select-shard-packages.sh` spells it `Affected-set diff base: ()`; the log prefixes a timestamp. */ export const DIFF_BASE_LINE = /Affected-set diff base: ([0-9a-f]{40})\s+\(([^)\n]*)\)/; export const DIFF_BASE_SOURCE = 'scripts/ci/select-shard-packages.sh'; +/** + * The diff base is read from the selector step only: the job-log section that opens with this step header (the first + * line of the `run:` block of `ci.yml`'s planner and shard steps) and runs to the next step header. + */ +export const SELECTOR_STEP = 'bash scripts/ci/select-shard-packages.sh'; +export const STEP_HEADER = /##\[group\]Run (.*)$/; /** How many run-list pages and runs one reading walks before it says it found no green run. */ export const MAX_RUN_PAGES = 5; export const MAX_RUNS_INSPECTED = 30; @@ -123,12 +129,40 @@ export const UNREAD_LEGS = Object.freeze([ // The pure core // --------------------------------------------------------------------------- -/** The diff base a Test Core log printed, or null. */ +/** The diff base one printed line carries, or null. */ export function parseDiffBase(logText) { const m = DIFF_BASE_LINE.exec(String(logText ?? '')); return m ? { sha: m[1], why: m[2].trim(), line: m[0] } : null; } +/** + * The diff base a Test Core job log printed, read from the selector step only. + * `{ ok: true, base }` | `{ ok: false, why }` — no selector step, no line in it, or more than one distinct base. + */ +export function readSelectorDiffBase(logText) { + const lines = String(logText ?? '').split('\n'); + const inStep = []; + const all = new Set(); + let step = null; + let sawStep = false; + for (const l of lines) { + const h = STEP_HEADER.exec(l); + if (h) { + step = h[1].trim(); + if (step === SELECTOR_STEP) sawStep = true; + continue; + } + const b = parseDiffBase(l); + if (!b) continue; + all.add(b.sha); + if (step === SELECTOR_STEP) inStep.push(b); + } + if (all.size > 1) return { ok: false, why: `prints ${all.size} distinct \`Affected-set diff base\` values (${[...all].map((x) => x.slice(0, 10)).join(', ')}), so none is read` }; + if (!sawStep) return { ok: false, why: `has no \`Run ${SELECTOR_STEP}\` step` }; + if (!inStep.length) return { ok: false, why: 'carries no `Affected-set diff base` line in its selector step' }; + return { ok: true, base: inStep[0] }; +} + /** The surface the two translation gates count, as a predicate over one repo path. */ export function labelSurfaceReader(extractRoots) { return (p) => { @@ -274,9 +308,9 @@ export function readPrBase({ repo, pr, commits, get, getText }) { const job = sources[0]; const log = getText(`/repos/${repo}/actions/jobs/${job.id}/logs`); if (!log.ok) return { ok: false, gap: `the log of \`${job.name}\` (job ${job.id}, run ${run.id}) could not be read — expired or refused (${log.error})` }; - const base = parseDiffBase(log.value); - if (!base) return { ok: false, gap: `the log of \`${job.name}\` (job ${job.id}, run ${run.id}) carries no \`Affected-set diff base\` line` }; - return { ok: true, run, job, base }; + const read = readSelectorDiffBase(log.value); + if (!read.ok) return { ok: false, gap: `the log of \`${job.name}\` (job ${job.id}, run ${run.id}) ${read.why}` }; + return { ok: true, run, job, base: read.base }; } const why = runs.truncated ? ` (the run list was cut at ${MAX_RUN_PAGES} pages)` : ''; return { ok: false, gap: `no completed pull_request ${CI_WORKFLOW} run on this PR's commits has a green \`${TEST_CORE_GATE}\` (${mine.length} run(s) on its commits, ${inspected} inspected)${why}` }; @@ -503,12 +537,12 @@ export function main(argv, deps = {}) { // --------------------------------------------------------------------------- const SELF_TEST_BATTERIES = Object.freeze({ - 'the rule text: every phrase this file is built from is in the file that writes it': 4, - 'PRBASE: the last green Test Core run on this PR, its log line, never a branch alone': 7, + 'the rule text: every phrase this file is built from is in the file that writes it': 5, + 'PRBASE: the last green Test Core run on this PR, its log line, never a branch alone': 10, 'K: the count, the hold at 15, and a clone that cannot count': 6, 'the locale leg: a new pack after PRBASE under a label PR, at any K': 6, 'the shared-budget leg: the same book on both sides, at any K': 5, - 'fail closed: every unread leg is exit 3, never 0': 7, + 'fail closed: every unread leg is exit 3, never 0': 8, 'the CLI: usage, exits and the footer': 7, }); const SELF_TEST_BATTERY_FLOOR = 7; @@ -548,7 +582,9 @@ export function selfTest() { const MAIN = sha('a'); const HEAD = sha('c'); const OLD = sha('d'); - const log = (s = BASE) => `2026-11-19T13:07:09.7414776Z Affected-set diff base: ${s} (merge-base of origin/main and HEAD)\n`; + const stepLine = (cmd) => `2026-11-19T13:07:09.5000000Z ##[group]Run ${cmd}\n`; + const baseLine = (s = BASE) => `2026-11-19T13:07:09.7414776Z Affected-set diff base: ${s} (merge-base of origin/main and HEAD)\n`; + const log = (s = BASE) => `${stepLine(SELECTOR_STEP)}${baseLine(s)}`; const job = (id, name, conclusion = 'success') => ({ id, name, status: 'completed', conclusion }); const greenJobs = [job(11, 'Plan Test Core shards'), job(12, 'Test Core (1/10)'), job(13, TEST_CORE_GATE)]; const fixture = (over = {}) => { @@ -575,6 +611,8 @@ export function selfTest() { t('⭐ landing-operations.md still says what this file encodes (a reworded K block reds here)', RULE_PHRASES.filter((p) => !text(LANDING_PATH).includes(p)), []); t('⭐ the shard selector still prints the line PRBASE is read from', parseDiffBase(text(DIFF_BASE_SOURCE).split('\n').find((l) => l.includes('echo "Affected-set diff base:')).replace('$SCM_BASE', BASE).replace(/^\s*echo "/, '')) !== null, true); t('both closed books still exist where the rule names their ledgers', BUDGET_BOOKS.filter((b) => !existsSync(join(REPO_ROOT, b.ledger))).map((b) => b.ledger), []); + const runFirstLines = text(`.github/workflows/${CI_WORKFLOW}`).split('\n').filter((l, i, all) => /^\s+run: \|\s*$/.test(all[i - 1] ?? '') && l.trim() === SELECTOR_STEP).length; + t('⭐ ci.yml\'s planner and shard steps still open their run block with the selector, the step the diff base is read from', runFirstLines >= 2, true); t('ci.yml still names the aggregate, the shard and the planner jobs this file reads', [TEST_CORE_GATE, 'Test Core (${{ matrix.shard }}/10)', TEST_CORE_PLAN].filter((n) => !text(`.github/workflows/${CI_WORKFLOW}`).includes(`name: ${n}`)), []); } @@ -591,6 +629,12 @@ export function selfTest() { t('with no shard log, the planner of the same run is read (it prints the same line)', planOnly.prbase?.job, TEST_CORE_PLAN); const running = read(fixture({ runs: [{ id: 4, head_sha: HEAD, status: 'in_progress', created_at: '2026-11-19T16:00:00Z' }, ...fixture().runs] })); t('a run still in progress is not the last green run', running.prbase?.run, 2); + const otherStep = read(fixture({ logs: { 12: `${stepLine('pnpm install --frozen-lockfile')}${baseLine()}${stepLine(SELECTOR_STEP)}no line here\n` } })); + t('⭐ the diff base is read from the selector step only: a line another step printed is not read, exit 3', [otherStep.exit, otherStep.prbase, otherStep.gaps[0]?.endsWith('carries no `Affected-set diff base` line in its selector step')], [EXIT_CANT_ANSWER, null, true]); + const twoBases = read(fixture({ logs: { 12: `${stepLine('pnpm install --frozen-lockfile')}${baseLine(sha('e'))}${log()}` } })); + t('⭐ a log that prints two distinct diff bases is exit 3, neither read', [twoBases.exit, twoBases.prbase, twoBases.gaps[0]?.includes('prints 2 distinct `Affected-set diff base` values')], [EXIT_CANT_ANSWER, null, true]); + const sameTwice = read(fixture({ logs: { 12: `${stepLine('pnpm install --frozen-lockfile')}${baseLine()}${log()}${stepLine('node scripts/partition-test-shards.mjs')}` } })); + t('the same base printed again outside the step still reads, from the selector step', [sameTwice.exit, sameTwice.prbase?.sha], [EXIT_OK, BASE]); t('the text names the run, the job and the reason', renderText(ok).includes(`PRBASE ${BASE.slice(0, 10)} (merge-base of origin/main and HEAD) — from \`Test Core (1/10)\` of run 2`), true); } @@ -642,7 +686,9 @@ export function selfTest() { { const expired = read(fixture({ logs: { 12: null } })); t('⭐ an expired log is exit 3 with the job named', [expired.exit, expired.gaps[0].includes('could not be read — expired or refused (HTTP 410 Gone)')], [EXIT_CANT_ANSWER, true]); - const noLine = read(fixture({ logs: { 12: 'nothing here' } })); + const noStep = read(fixture({ logs: { 12: baseLine() } })); + t('⭐ a log with no selector step is exit 3, its line unread', [noStep.exit, noStep.gaps[0]?.endsWith(`has no \`Run ${SELECTOR_STEP}\` step`)], [EXIT_CANT_ANSWER, true]); + const noLine = read(fixture({ logs: { 12: `${stepLine(SELECTOR_STEP)}nothing here` } })); t('⭐ a log without the line is exit 3', [noLine.exit, noLine.gaps[0].includes('carries no `Affected-set diff base` line')], [EXIT_CANT_ANSWER, true]); const noGreen = read(fixture({ jobs: { 2: greenJobs.map((j) => ({ ...j, conclusion: 'failure' })) } })); t('no green Test Core on the PR is exit 3', [noGreen.exit, noGreen.gaps[0].startsWith('no completed pull_request ci.yml run')], [EXIT_CANT_ANSWER, true]); diff --git a/scripts/pm/pr-state.mjs b/scripts/pm/pr-state.mjs index 5d409a0a820..c223d9d860c 100644 --- a/scripts/pm/pr-state.mjs +++ b/scripts/pm/pr-state.mjs @@ -21,7 +21,8 @@ * ## What it reads — REST through `gh api`, every page, and one `git ls-remote` * * 1. the PR row; on an OPEN PR whose `mergeable_state` is `unknown`, re-read up to `--rereads` times (bounded); - * 2. every review — the newest per reviewer, and which of them are on the head commit; + * 2. every review — the newest per reviewer: those on the head commit, and apart from them, with state and login, + * those on an older commit (an APPROVED on any commit counts, AGENTS.md Prime Directive 14); * 3. the timeline, every page — the last merge-queue event; * 4. the queue refs and the base branch's tip (`git ls-remote`, zero quota) — the position, only while a ref exists; * 5. the head's check-runs (`filter=latest`, every page, the platform's count checked), judged with @@ -39,8 +40,9 @@ * 1 `--self-test` failed * 2 usage * 3 a PR row could not be read — nothing printed for it but the gap - * 4 INCOMPLETE — a leg did not answer (named on the line), or an open PR's `mergeable_state` was still `unknown` - * after the bounded re-reads; ⛔ never read as a clean line + * 4 INCOMPLETE — a leg did not answer (named on the line), an open PR's `mergeable_state` was still `unknown` + * after the bounded re-reads, or a queue ref contradicts the timeline's last queue event; ⛔ never read as a + * clean line * * ## Self-test * @@ -100,7 +102,7 @@ export const UNREAD_LEGS = Object.freeze([ // The pure core // --------------------------------------------------------------------------- -/** The newest review per reviewer, and the ones on `head`. */ +/** The newest review per reviewer: the ones on `head`, and apart from them the ones on an older commit. */ export function reviewsAtHead(reviews, head) { const newest = new Map(); for (const r of reviews ?? []) { @@ -113,10 +115,18 @@ export function reviewsAtHead(reviews, head) { approved: at.filter((r) => r.state === 'APPROVED').map((r) => r.user.login).sort(), changes: at.filter((r) => r.state === 'CHANGES_REQUESTED').map((r) => r.user.login).sort(), dismissed: at.filter((r) => r.state === 'DISMISSED').map((r) => r.user.login).sort(), - older: [...newest.values()].filter((r) => r.commit_id !== head).length, + older: [...newest.values()] + .filter((r) => r.commit_id !== head) + .map((r) => ({ login: r.user.login, state: r.state, commit: r.commit_id ?? null })) + .sort((a, b) => a.login.localeCompare(b.login)), }; } +/** The older-commit reviews as the line prints them: `APPROVED b@dddddddddd`. */ +export function olderReviewsText(older) { + return older.map((r) => `${r.state} ${r.login}@${String(r.commit).slice(0, 10)}`).join(', '); +} + /** The last merge-queue event on a timeline, or null. */ export function lastQueueEvent(timeline) { let last = null; @@ -151,8 +161,8 @@ export function queueLeg({ pr, event, refs, baseSha }) { const q = refs ? queueChain(refs, baseSha) : null; const mine = q ? q.entries.find((e) => e.pr === pr.number) : null; const pos = mine && q.chain.includes(mine) ? `position ${q.chain.indexOf(mine) + 1} of ${q.chain.length}` : mine ? `a queue ref exists but is off the chain from ${String(baseSha).slice(0, 10)} (position unread)` : null; - if (!event) return { text: mine ? `queue: no queue event on the timeline, yet a queue ref exists (${pos}) — re-read` : 'queue: never queued (no queue event)' }; - if (event.event === 'removed_from_merge_queue') return { text: `queue: not in queue (removed ${event.at})${mine ? ` — yet a queue ref exists (${pos}); re-read` : ''}` }; + if (!event) return mine ? { text: `queue: no queue event on the timeline, yet a queue ref exists (${pos}) — re-read`, gap: 'a queue ref exists with no queue event on the timeline, so membership is unread' } : { text: 'queue: never queued (no queue event)' }; + if (event.event === 'removed_from_merge_queue') return mine ? { text: `queue: not in queue (removed ${event.at}) — yet a queue ref exists (${pos}); re-read`, gap: 'a queue ref exists after the last queue event removed the PR, so membership is unread' } : { text: `queue: not in queue (removed ${event.at})` }; if (!q) return { text: `queue: in queue (added ${event.at}), position unread`, gap: 'the queue refs could not be listed, so the position is unread' }; return { text: `queue: in queue (added ${event.at}), ${pos ?? 'no queue ref for it now (a ref answers a build, not membership) — position unread'}` }; } @@ -190,7 +200,7 @@ export function readPrState({ repo, number, get = ghApi, lsRemote = gitLsRemote, } else { rv = reviewsAtHead(reviews.value, head); const parts = [rv.approved.length ? `APPROVED ${rv.approved.join(',')}` : null, rv.changes.length ? `CHANGES_REQUESTED ${rv.changes.join(',')}` : null, rv.dismissed.length ? `DISMISSED ${rv.dismissed.join(',')}` : null].filter(Boolean); - reviewText = `reviews at ${String(head).slice(0, 10)}: ${parts.join('; ') || 'none'}${rv.older ? ` (${rv.older} reviewer(s) newest on an older commit)` : ''}`; + reviewText = `reviews at ${String(head).slice(0, 10)}: ${parts.join('; ') || 'none'}${rv.older.length ? ` · newest on an older commit: ${olderReviewsText(rv.older)} (an APPROVED counts on any commit)` : ''}`; } const timeline = readPaged(get, `/repos/${repo}/issues/${number}/timeline`); @@ -257,7 +267,8 @@ export function readPrState({ repo, number, get = ghApi, lsRemote = gitLsRemote, mergeable_reads: reads, queue: queue.text, queue_event: event, - reviews_at_head: rv, + reviews_at_head: rv ? { approved: rv.approved, changes: rv.changes, dismissed: rv.dismissed } : null, + reviews_older: rv ? rv.older : null, checks: judged && judged.kind !== 'unreadable' ? { kind: judged.kind, success: judged.success ?? 0, expected_skips: judged.expected?.length ?? 0, unexpected_skips: (judged.unexpected ?? []).map((u) => u.name), other: judged.other ?? [], pending: (judged.pending ?? []).map((p) => p.name) } : null, commit_status: status.ok ? { state: status.value.state, total_count: status.value.total_count } : null, auto_merge: pr.auto_merge ?? null, @@ -438,8 +449,8 @@ export function main(argv, deps = {}) { const SELF_TEST_BATTERIES = Object.freeze({ 'the rule text: every phrase this file is built from is in the file that writes it': 3, 'mergeable_state: unknown is re-read, bounded, and never printed as a reading': 5, - 'the queue: the timeline decides membership, the parent-tip chain the position': 8, - 'reviews: the newest per reviewer, at the head commit': 4, + 'the queue: the timeline decides membership, the parent-tip chain the position': 9, + 'reviews: the newest per reviewer, at the head commit and apart from it on older ones': 6, 'checks and status: the head, every page, the count checked': 6, 'the line and the CLI: usage, exits and the footer': 7, }); @@ -517,7 +528,9 @@ export function selfTest() { const noRef = read(fixture({ timeline: { 7: [added] } })); t('in queue with no ref: membership stands, the position is unread, and that is not a gap', [noRef.exit, noRef.line.includes('no queue ref for it now (a ref answers a build, not membership) — position unread')], [EXIT_OK, true]); const contradict = read(fixture({ timeline: { 7: [added, removed] }, ls_remote: refs })); - t('a ref that contradicts the timeline is printed, not resolved', contradict.line.includes('— yet a queue ref exists (position 2 of 3); re-read'), true); + t('⭐ a ref after the last event removed the PR contradicts the timeline: printed, not resolved, INCOMPLETE exit 4', [contradict.exit, contradict.line.includes('— yet a queue ref exists (position 2 of 3); re-read'), contradict.line.includes('INCOMPLETE: a queue ref exists after the last queue event removed the PR')], [EXIT_INCOMPLETE, true, true]); + const noEvent = read(fixture({ ls_remote: refs })); + t('⭐ a ref with no queue event on the timeline contradicts it: INCOMPLETE exit 4, never a clean line', [noEvent.exit, noEvent.line.includes('queue: no queue event on the timeline, yet a queue ref exists (position 2 of 3) — re-read'), noEvent.gaps], [EXIT_INCOMPLETE, true, ['a queue ref exists with no queue event on the timeline, so membership is unread']]); const lsDown = read(fixture({ timeline: { 7: [added] }, ls_remote: null })); t('⭐ unlisted queue refs on an in-queue PR leave the position unread and make it INCOMPLETE', [lsDown.exit, lsDown.gaps[0]], [EXIT_INCOMPLETE, 'the queue refs could not be listed, so the position is unread']); const tl = read(fixture({ timeline: { 7: null } })); @@ -525,13 +538,16 @@ export function selfTest() { t('a broken chain leaves the stranded entries off it', queueChain(refs.filter((r) => !r.ref.includes('pr-5-')), MAIN).chain.length, 0); } - battery('reviews: the newest per reviewer, at the head commit'); + battery('reviews: the newest per reviewer, at the head commit and apart from it on older ones'); { const rv = (login, state, commit, at) => ({ user: { login }, state, commit_id: commit, submitted_at: at }); const r = reviewsAtHead([rv('a', 'CHANGES_REQUESTED', HEAD, '1'), rv('a', 'APPROVED', HEAD, '2'), rv('b', 'APPROVED', sha('d'), '1'), rv('c', 'COMMENTED', HEAD, '3')], HEAD); - t('⭐ the newest review per reviewer counts; an approval on an older commit is not at head', [r.approved, r.changes, r.older], [['a'], [], 1]); + t('⭐ the newest review per reviewer counts; an approval on an older commit is not at head, and is kept with its state and login', [r.approved, r.changes, r.older], [['a'], [], [{ login: 'b', state: 'APPROVED', commit: sha('d') }]]); t('a comment-only review is neither', reviewsAtHead([rv('c', 'COMMENTED', HEAD, '3')], HEAD).approved, []); - t('the line names the approvals at head and the older ones', read(fixture({ reviews: { 7: [rv('a', 'APPROVED', HEAD, '2'), rv('b', 'APPROVED', sha('d'), '1')] } })).line.includes(`reviews at ${HEAD.slice(0, 10)}: APPROVED a (1 reviewer(s) newest on an older commit)`), true); + t('the line names the approvals at head and, apart from them, the older ones by state and login', read(fixture({ reviews: { 7: [rv('a', 'APPROVED', HEAD, '2'), rv('b', 'APPROVED', sha('d'), '1')] } })).line.includes(`reviews at ${HEAD.slice(0, 10)}: APPROVED a · newest on an older commit: APPROVED b@${sha('d').slice(0, 10)} (an APPROVED counts on any commit)`), true); + const moved = read(fixture({ reviews: { 7: [rv('m', 'APPROVED', sha('d'), '1'), rv('x', 'CHANGES_REQUESTED', sha('e'), '2')] } })); + t('⭐ approve, then a merge of main moves the head: the line still says who approved, never only a count', [moved.exit, moved.line.includes(`reviews at ${HEAD.slice(0, 10)}: none · newest on an older commit: APPROVED m@${sha('d').slice(0, 10)}, CHANGES_REQUESTED x@${sha('e').slice(0, 10)}`)], [EXIT_OK, true]); + t('--json carries the older reviews apart from the at-head ones', JSON.parse(quiet(main)(['--pr', '7', '--json'], { readers: fixtureReaders(fixture({ reviews: { 7: [rv('m', 'APPROVED', sha('d'), '1')] } }), REPO) }).out).prs[0].reviews_older, [{ login: 'm', state: 'APPROVED', commit: sha('d') }]); t('unreadable reviews are INCOMPLETE', read(fixture({ reviews: { 7: null } })).exit, EXIT_INCOMPLETE); } diff --git a/scripts/pm/sweep-closed-cards.mjs b/scripts/pm/sweep-closed-cards.mjs index 99f89f495c3..42474e89535 100644 --- a/scripts/pm/sweep-closed-cards.mjs +++ b/scripts/pm/sweep-closed-cards.mjs @@ -136,15 +136,17 @@ * `MERGE_AUTO_CLOSE_SECONDS` of the merge (a later one is listed as a hand close). REST carries no closer field (the * auto-close's `closed` event reads `commit_id: null`), so this tie is the reading — the actor and the seconds * after the merge are printed so the seat can tell a hand close inside the window from the merge's. - * - Extra = closed by the merge, named by no closing keyword = a SILENT CLOSE, exit 1. A named target still open is - * printed, not an alarm. + * - Extra = closed by the merge, named by no closing keyword = a SILENT CLOSE, exit `EXIT_SILENT_CLOSE` (4). A named + * target still open is printed, not an alarm. + * - Settling: an unnamed card reaches the candidates only through the search, and neither the platform's close nor + * the search index has landed in the first moments after a merge. While the merge is younger than + * `MERGE_SETTLE_SECONDS` the run is UNJUDGED (exit 2) and names the time to re-run; ⛔ never the clean verdict. * - * Its exits: 0 every card closed by the merge is a named target · 1 a silent close (each named) · 2 a candidate's - * timeline or the search did not answer, so a silent close may be unread (never a 0) · 3 the PR is unreadable or - * not merged. Exit 1 is also this file's usage code; both are a non-zero a seat reads, never a clean answer. + * Its exits: 0 every card closed by the merge is a named target · 4 a silent close (each named) · 2 the merge is + * still inside the settle window, or a candidate's timeline or the search did not answer, so a silent close may be + * unread (never a 0) · 3 the PR is unreadable or not merged · 1 usage. * Not read: issues in OTHER repositories a cross-repo keyword closed (the targets are read with the shared parser, - * which binds this repository's numbers only, so no second closing-keyword parser lives here), - * and a card the search index has not caught up with in the first seconds after a merge (re-run). + * which binds this repository's numbers only, so no second closing-keyword parser lives here). * * ## Cost * @@ -189,6 +191,8 @@ const TOKEN = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? ''; export const EXIT_OK = 0; export const EXIT_USAGE = 1; export const EXIT_UNJUDGED = 2; +/** `--pr N` only: a card the merge closed that no closing keyword names. 3 is `EXIT_PREREQUISITE_NOT_MET`. */ +export const EXIT_SILENT_CLOSE = 4; /** * The re-exec guard, per script rather than shared with the sweeper: two @@ -531,6 +535,11 @@ export const MERGE_CLOSE_WINDOW_SECONDS = 600; * folded card lands minutes later (measured 112 s on the same merge). A later close is listed, not charged. */ export const MERGE_AUTO_CLOSE_SECONDS = 60; +/** + * How old a merge must be before `--pr N` judges it: the auto-close bound above plus four minutes for the search index, + * the one read an unnamed card reaches the candidates through. Younger ⇒ UNJUDGED with the time to re-run. + */ +export const MERGE_SETTLE_SECONDS = 300; export const SILENT_CLOSE_PHRASE = '预期外从 open 消失的即被闭合关键词静默误关的卡;每次合并读 `sweep-closed-cards.mjs --pr N`。'; export const LANDING_OPERATIONS_PATH = '.claude/skills/pm-dispatch/references/landing-operations.md'; @@ -560,9 +569,12 @@ export function mergeCloseTie(issue, timeline, { prNumber, mergeSha, mergedAtMs * `candidates`: `[{ number, issue, timeline, error? }]` (targets and in-window closes, each once). * `search`: `{ ok, error?, listed, total, incomplete }`. */ -export function judgeMergeCloses({ pr, candidates, search }) { +export function judgeMergeCloses({ pr, candidates, search, nowMs = Date.now() }) { const targets = [...closingKeywordTargets(pr.body ?? '').keys()].map(Number).sort((a, b) => a - b); const mergedAtMs = Date.parse(pr.merged_at); + const settleAtMs = mergedAtMs + MERGE_SETTLE_SECONDS * 1000; + const settling = !Number.isFinite(mergedAtMs) || nowMs < settleAtMs; + const rerunAt = Number.isFinite(mergedAtMs) ? new Date(settleAtMs).toISOString().replace(/\.\d{3}Z$/, 'Z') : null; const closedByMerge = []; const namedOpen = []; const namedNotByMerge = []; @@ -586,8 +598,9 @@ export function judgeMergeCloses({ pr, candidates, search }) { const silent = closedByMerge.filter((c) => !c.named); if (!search.ok) unjudged.push({ number: null, detail: `the in-window closed-issue search did not answer (${search.error})` }); else if (search.incomplete || search.listed < search.total) unjudged.push({ number: null, detail: `the in-window search listed ${search.listed} of ${search.total} closed issue(s)${search.incomplete ? ' (the platform flagged the result incomplete)' : ''}` }); - const exitCode = silent.length ? EXIT_USAGE : unjudged.length ? EXIT_UNJUDGED : EXIT_OK; - return { targets, closedByMerge, silent, namedOpen, namedNotByMerge, laterHandCloses, unjudged, exitCode }; + if (settling) unjudged.push({ number: null, settling: true, detail: rerunAt ? `the merge is ${Math.max(0, Math.round((nowMs - mergedAtMs) / 1000))}s old, inside the ${MERGE_SETTLE_SECONDS}s settle window: the platform's close and the search index may not have landed — re-run at or after ${rerunAt} (in ${Math.ceil((settleAtMs - nowMs) / 1000)}s)` : `the merge time \`${pr.merged_at}\` does not parse, so the settle window is unread` }); + const exitCode = silent.length ? EXIT_SILENT_CLOSE : unjudged.length ? EXIT_UNJUDGED : EXIT_OK; + return { targets, closedByMerge, silent, namedOpen, namedNotByMerge, laterHandCloses, unjudged, settling, rerunAt, exitCode }; } export function renderMergeCloses(pr, j) { @@ -599,8 +612,9 @@ export function renderMergeCloses(pr, j) { for (const c of j.namedNotByMerge) L.push(` · #${c.number} named, closed but not by this merge (${c.why})`); for (const c of j.laterHandCloses) L.push(` · #${c.number} ${c.named ? 'named' : 'not named'}, referenced by this PR, closed by ${c.actor ?? '?'} — ${c.why}`); for (const u of j.unjudged) L.push(` · UNREAD ${u.number ? `#${u.number}` : ''} — ${u.detail}`); - L.push('Not read by this mode: a card in another repository a cross-repo keyword closed; a card the search index has not caught up with in the first seconds after a merge (re-run).'); - if (j.silent.length) L.push(`✗ SILENT CLOSE — ${j.silent.map((c) => `#${c.number}`).join(', ')} closed by this merge with no closing keyword naming it; reopen and restore its state. Exit ${EXIT_USAGE}.`); + L.push('Not read by this mode: a card in another repository a cross-repo keyword closed.'); + if (j.silent.length) L.push(`✗ SILENT CLOSE — ${j.silent.map((c) => `#${c.number}`).join(', ')} closed by this merge with no closing keyword naming it; reopen and restore its state. Exit ${EXIT_SILENT_CLOSE}.`); + else if (j.settling && j.rerunAt) L.push(`⚠️ UNJUDGED — the merge is younger than ${MERGE_SETTLE_SECONDS}s, so a silent close may not be readable yet; re-run at or after ${j.rerunAt}. ⛔ Not a clean answer. Exit ${EXIT_UNJUDGED}.`); else if (j.unjudged.length) L.push(`⚠️ UNJUDGED — a read did not answer, so a silent close may be unread. ⛔ Not a clean answer. Exit ${EXIT_UNJUDGED}.`); else L.push(`✓ every card closed by this merge is a named target. Exit ${EXIT_OK}.`); return L.join('\n'); @@ -1044,7 +1058,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the exit register: nothing to do is never an alarm': 7, 'the report: what a reader is told, and what it refuses to imply': 7, 'the CLI: the one decision a typo must never make': 8, - '--pr N: a card the merge closed that no closing keyword names is a silent close': 13, + '--pr N: a card the merge closed that no closing keyword names is a silent close': 19, }); const SELF_TEST_BATTERY_FLOOR = 10; const UNATTRIBUTED_BATTERY = '(unattributed)'; @@ -1246,12 +1260,15 @@ export function selfTest() { const xref = (n, body = '', mergedAt = AT) => ({ event: 'cross-referenced', source: { issue: { number: n, body, state: 'closed', pull_request: { merged_at: mergedAt } } } }); const closed = (number, timeline) => ({ number, issue: { number, state: 'closed', title: `card ${number}` }, timeline }); const ok = { ok: true, listed: 2, total: 2, incomplete: false }; - const clean = judgeMergeCloses({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')])], search: ok }); + const nowMs = Date.parse(AT) + 3600 * 1000; + const judge = (args) => judgeMergeCloses({ nowMs, ...args }); + const clean = judge({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')])], search: ok }); t('a named target closed by the merge is clean, exit 0', clean.exitCode === EXIT_OK && clean.closedByMerge.length === 1 && clean.silent.length === 0); - const partOf = judgeMergeCloses({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')]), closed(11, [xref(500), closedEv('2026-11-19T14:56:32Z')])], search: ok }); - t('⭐ a `Part of` card the merge closed is a SILENT CLOSE, exit 1, named', partOf.exitCode === EXIT_USAGE && partOf.silent.map((c) => c.number).join() === '11'); + const partOf = judge({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')]), closed(11, [xref(500), closedEv('2026-11-19T14:56:32Z')])], search: ok }); + t('⭐ a `Part of` card the merge closed is a SILENT CLOSE, exit 4, named', partOf.exitCode === EXIT_SILENT_CLOSE && partOf.silent.map((c) => c.number).join() === '11' && renderMergeCloses(pr, partOf).includes(`Exit ${EXIT_SILENT_CLOSE}.`)); + t('the silent close has its own exit code, apart from usage, unjudged and the unmet prerequisite', EXIT_SILENT_CLOSE === 4 && new Set([EXIT_OK, EXIT_USAGE, EXIT_UNJUDGED, EXIT_PREREQUISITE_NOT_MET, EXIT_SILENT_CLOSE]).size === 5); t('the targets are read with the H7 parser: a backticked keyword binds nothing', partOf.targets.join() === '10'); - const viaCommit = judgeMergeCloses({ pr, candidates: [closed(13, [{ event: 'referenced', commit_id: MERGE }, closedEv('2026-11-19T14:56:33Z')])], search: ok }); + const viaCommit = judge({ pr, candidates: [closed(13, [{ event: 'referenced', commit_id: MERGE }, closedEv('2026-11-19T14:56:33Z')])], search: ok }); t('⭐ a keyword in the squashed commit message (a referenced event on the merge commit) is tied to the merge', viaCommit.silent.map((c) => c.number).join() === '13' && viaCommit.silent[0].why === 'the merge commit references it'); const byCommitId = mergeCloseTie({ number: 14, state: 'closed' }, [closedEv('2026-11-19T14:56:33Z', { commit_id: MERGE })], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); t('a closed event carrying the merge commit is tied to it', byCommitId.byThisMerge === true); @@ -1259,18 +1276,34 @@ export function selfTest() { t('⭐ a card another PR merged in the same window closes by its body is not charged to this merge', other.byThisMerge === false && other.otherPr === 501); const late = mergeCloseTie({ number: 16, state: 'closed' }, [xref(500), closedEv('2026-11-19T16:00:00Z')], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); t('a close outside the window is not this merge\'s', late.byThisMerge === false); - const hand = judgeMergeCloses({ pr, candidates: [closed(18, [xref(500), closedEv('2026-11-19T14:58:19Z')])], search: ok }); + const hand = judge({ pr, candidates: [closed(18, [xref(500), closedEv('2026-11-19T14:58:19Z')])], search: ok }); t('⭐ a card this PR only cross-references, closed minutes after the merge, is a listed hand close, not a silent close', hand.exitCode === EXIT_OK && hand.laterHandCloses.length === 1 && renderMergeCloses(pr, hand).includes('#18 not named, referenced by this PR')); const untied = mergeCloseTie({ number: 17, state: 'closed' }, [closedEv('2026-11-19T14:56:40Z')], { prNumber: 500, mergeSha: MERGE, mergedAtMs: Date.parse(AT) }); t('a card closed in the window with nothing tying it to this merge is not charged to it', untied.byThisMerge === false); - const openTarget = judgeMergeCloses({ pr, candidates: [{ number: 10, issue: { number: 10, state: 'open' }, timeline: [] }], search: ok }); + const openTarget = judge({ pr, candidates: [{ number: 10, issue: { number: 10, state: 'open' }, timeline: [] }], search: ok }); t('a named target still open is printed, not an alarm', openTarget.exitCode === EXIT_OK && openTarget.namedOpen.length === 1 && renderMergeCloses(pr, openTarget).includes('#10 named, still OPEN')); - const unread = judgeMergeCloses({ pr, candidates: [{ number: 11, error: 'GET … -> HTTP 502' }], search: ok }); + const unread = judge({ pr, candidates: [{ number: 11, error: 'GET … -> HTTP 502' }], search: ok }); t('⭐ an unreadable candidate timeline is UNJUDGED, exit 2, never a clean 0', unread.exitCode === EXIT_UNJUDGED && renderMergeCloses(pr, unread).includes('⛔ Not a clean answer')); - const shortSearch = judgeMergeCloses({ pr, candidates: [], search: { ok: true, listed: 1, total: 3, incomplete: false } }); + const shortSearch = judge({ pr, candidates: [], search: { ok: true, listed: 1, total: 3, incomplete: false } }); t('⭐ a search that listed fewer than it counts is UNJUDGED, exit 2', shortSearch.exitCode === EXIT_UNJUDGED); + const young = judgeMergeCloses({ pr, candidates: [closed(10, [xref(500), closedEv('2026-11-19T14:56:31Z')])], search: ok, nowMs: Date.parse(AT) + 20 * 1000 }); + const youngText = renderMergeCloses(pr, young); + t('⭐ a merge younger than the settle window is UNJUDGED, exit 2, with the time to re-run — never the clean verdict', young.exitCode === EXIT_UNJUDGED && young.rerunAt === '2026-11-19T15:01:27Z' && youngText.includes('re-run at or after 2026-11-19T15:01:27Z') && !youngText.includes('✓ every card'), youngText.split('\n').slice(-1)[0]); + const edge = judgeMergeCloses({ pr, candidates: [], search: ok, nowMs: Date.parse(AT) + MERGE_SETTLE_SECONDS * 1000 }); + t('the window closes at the bound: a run at merged_at + MERGE_SETTLE_SECONDS judges', edge.exitCode === EXIT_OK && edge.settling === false); + const youngSilent = judgeMergeCloses({ pr, candidates: [closed(11, [xref(500), closedEv('2026-11-19T14:56:32Z')])], search: ok, nowMs: Date.parse(AT) + 20 * 1000 }); + t('a silent close already readable inside the window is still the alarm, exit 4', youngSilent.exitCode === EXIT_SILENT_CLOSE); + const noTime = judgeMergeCloses({ pr: { ...pr, merged_at: 'not a time' }, candidates: [], search: ok, nowMs }); + t('a merge time that does not parse leaves the window unread: UNJUDGED, exit 2', noTime.exitCode === EXIT_UNJUDGED); t('`--pr N` parses in both spellings, and refuses --write and --all-time beside it', parseOptions(['--pr', '35482']).options.pr === 35482 && parseOptions(['--pr=#7']).options.pr === 7 && parseOptions(['--pr=7', '--write']).ok === false && parseOptions(['--pr=7', '--all-time']).ok === false && parseOptions(['--pr=x']).ok === false && parseOptions([]).options.pr === null); - t('⭐ landing-operations.md still says the rule this mode reads, with the pointer here', readFileSync(new URL(`../../${LANDING_OPERATIONS_PATH}`, import.meta.url), 'utf8').includes(SILENT_CLOSE_PHRASE)); + let landingText = null; + let landingError = ''; + try { + landingText = readFileSync(new URL(`../../${LANDING_OPERATIONS_PATH}`, import.meta.url), 'utf8'); + } catch (err) { + landingError = `${LANDING_OPERATIONS_PATH} could not be read (${err.code ?? err.message}) — moved or split?`; + } + t('⭐ landing-operations.md still says the rule this mode reads, with the pointer here', landingText !== null && landingText.includes(SILENT_CLOSE_PHRASE), landingError || undefined); } // -- the floor -------------------------------------------------------------