diff --git a/.claude/skills/pm-dispatch/references/coordinator.md b/.claude/skills/pm-dispatch/references/coordinator.md index ccd911f2f82..f877c50d162 100644 --- a/.claude/skills/pm-dispatch/references/coordinator.md +++ b/.claude/skills/pm-dispatch/references/coordinator.md @@ -14,7 +14,7 @@ ## 二、跨车道取卡(coordinator 每次唤醒读) -- 取卡面 = 各车道 open 卡:p0/p1 先,再点名 area 或子专题的下一张;判据照 `execution-duties.md`。 +- 取卡面 = 各车道 open 卡,次序现读 `card-pick.mjs --order <序>`;判据照 `execution-duties.md`。 - 维护者只说改级 ⇒ 只落级,评论照 `filing-gate.md` 引原话;⛔ 不借此开线程,照取卡全序。 - 每张卡交其车道的席位线程;车道无席位线程而座位贴空着 ⇒ 先开席位线程再交卡。 - 维护者 ⛔ 不逐卡点名车道:车道读卡的 `domain:*`;S/M 分流见 `dispatch-runbook.md` 卡线程节。 @@ -24,10 +24,10 @@ - 卡线程上限全项目一个数,由维护者按项目言明;未言明取各席 `batch` 之和。 - 席位攒批交候选,一线程一行:卡/PR、标题、级别、effort、汇报区、要读文件、续做分支。 - 派发令全文随行;⛔ 不等自己的槽位;区与卡线程 ⛔ 不直找 coordinator,经席位。 -- coordinator 一批开完、一次回全部 id:p0/p1 先,余照点名次序;满即排队,交回或合入即释放。 -- 有空槽即开;先后只认卡上 `Blocked-by:` 与席位串行队,⛔ 不自排、不逐张等。 +- coordinator 一批开完、一次回全部 id:p0/p1 先,余照点名次序(队列卡现读 `card-pick.mjs`)。 +- 满即排队;有空槽即开;先后只认卡上 `Blocked-by:` 与席位串行队,⛔ 不自排、不逐张等。 - 槽位只算在建的线程:等人(授权批准、决策卡)或等席位 L1/L2 审核的卡线程不占槽。 -- S 卡的席内子代理只计该席 `batch`,不计本上限。 +- 交回或合入即释放槽位;S 卡的席内子代理只计该席 `batch`,不计本上限。 ## 四、effort 与档位按难度(coordinator 开线程时读;席位请线程时读) diff --git a/.claude/skills/pm-dispatch/references/execution-duties.md b/.claude/skills/pm-dispatch/references/execution-duties.md index 89a224e1117..b5d3fb55356 100644 --- a/.claude/skills/pm-dispatch/references/execution-duties.md +++ b/.claude/skills/pm-dispatch/references/execution-duties.md @@ -9,17 +9,14 @@ - 席改标:卡余项实测路径整落本席包树 ⇒ 本席改 `domain:*`,审计评论列路径与新旧标同笔。 - 席改标限未派发卡;带 `needs-user-decision`、open `Blocked-by:` 或 `security` 的 ⛔ 不改,仍问分诊。 - 每张候选读全文 + 全部评论,写派发词前做决策复读:评论读到最后一页。 -- 写裁决区前 grep 申报文件面(源码与测试)的 `ruling`、`Ruling-ref`、`maintainer`、`⛔`。 +- 裁决区与过时检查先跑 `check-prior-rulings.mjs --card --paths <面>`;引现状 ⛔ 不引裁决旧述。 - 本卡与命中所引裁决逐字入区(id+原句)作约束;零命中才写无裁决,命中无裁决写命中数。 -- 派发前做前提过时检查,裁决同罪,三面都查;动作面:`git log --oneline -20 -- `。 -- 卡引用面:裁决/卡片点名的每张 issue 逐个读现 open/closed/assignee,引现状 ⛔ 不引裁决旧述。 - 工作项面:卡片、裁决与分诊评论列的工作项逐条对树核验是否仍未完成,⛔ 不对卡核验。 - 软顶:本席已验收等人批的 Tier H PR 逾 5 ⇒ 停派 Tier H,S/非受管照常,轮报列积压;两周复测。 - 每轮按现 head 核本席终局四件套 PR:席位记录/`pm:awaiting-merge`/请审/终版速读,缺件同轮补。 - 四件读数器:本地 `node scripts/pm/check-half-states.mjs` H43/H48 只读受管 H;超行无受管 PR 自读。 - single-writer 路径 = `SINGLE_CLAIM_PATHS` 所枚举;共享其它路径是普通并发,后落地方解冲突。 -- 第 N 单派发前读 `scripts/pm/os-verify-lock.sh --status`:到达深度 ≥ `LOCK_DEPTH_HOLD`(= 2)即等。 -- 到达深度 = `queue N:` 行数 + 1(待派 dev 的运行算作到达);`state:` holder 与 `parked` 行不计。 +- 第 N 单派发前跑 `scripts/pm/os-verify-lock.sh --depth`:≥ `LOCK_DEPTH_HOLD`(= 2)即等(exit 1)。 - 同批独立按文件面不相交判,⛔ 不按包/check 名;有效上限随锁宽,⛔ 不是第二个 `batch`。 - p0 无槽或低级在飞 PR 重叠挡住 ⇒ 暂停腾位的最低级 dev:停会话、PR 留 draft、认领不动。 - 卡记 `Paused-for: #`,⛔ 不丢弃、不回退、不 force-push;p0 落地即复活该 dev,同认领同分支。 @@ -47,12 +44,10 @@ - 分诊预见的后续工作是一张卡,触发条件落地时立卡;⛔ 分诊一句话永不授权无卡编辑。 - 阻塞项无主 ⇒ 被挡席认领做掉,不限大小;在该卡走完整认领、尊重其热文件串行队。 - 阻塞项在飞 ⇒ 等;卡 PR 叠未合 PR 或 `Blocked-by:` 未合的,合前 ⛔ 不开线程(维护者令除外)。 -- 取卡次序 = `docs/NORTH-STAR.md`「Priority」第 3 条:本车道队列开放 P0/P1 取卡时现读。 +- 标签序 = NORTH-STAR「Priority」第 3 条(无级殿后),本车道开放卡现读 `card-pick.mjs --order <序>`。 - 开放 = 未派发(无 `pm:dispatched`、无 assignee);在飞的 P0/P1 不挡任何候选,只余取卡全序。 - 取卡全序:维护者直派插队卡(出处三件)> 契约面卡(判据见 `references/lanes/spec.md`)> 标签序。 -- 标签序:`priority:p0` > p1(任何 area,含暂停)> 维护者点名的 area 或子专题里的下一张 > 无级。 - 云车道同按专题派,⛔ 不按 `cloud/ROADMAP.md` 行序;细则照 `lanes/cloud.md` 所指的 cloud 仓文件。 -- 点名范围内:子专题照其子卡次序与 `Blocked-by:`;无子专题先 p2 后 p3;级只决定插队。 - 全序每级现读/现算,零逐卡维护;无级/无 area/无 type 轮报记分诊缺口。 - 同级先非车队卡(作者非 `Bot` 且首行非席位签名),再 `Bug`、卡龄;⛔ 不升级、不越 p0。 - 一车道多席按全序交替取卡:席 1 奇位、席 2 偶位;只为破交替才发 `split`;认领戳仲裁。 diff --git a/.claude/skills/pm-dispatch/references/seat-lifecycle.md b/.claude/skills/pm-dispatch/references/seat-lifecycle.md index 4d94e68382a..0b12e2d87e7 100644 --- a/.claude/skills/pm-dispatch/references/seat-lifecycle.md +++ b/.claude/skills/pm-dispatch/references/seat-lifecycle.md @@ -86,9 +86,8 @@ - 停:队列空或 `rounds` 用尽(仅一次性调用适用);一轮 ≥ 半数派发失败或升级;维护者打断。 - 队列空是待命非退场(按需席除外):巡查跑到收班,只维护者令停;⛔ 不按 N 次无变化即停。 -- 队列空是逐卡表非结论:报无卡可派(维护者/协调者/轮报)即列队列过滤当刻返回的各卡。 -- 逐卡:卡号、同轮现读标签与 assignee(⛔ 不用缓存)、具名卡点;无卡点即候选,⛔ 不得报空。 -- 卡点一份词表:候选定义反面(`execution-duties.md`),open `Blocked-by:`、无分诊审计、他席 `Claim:`。 +- 队列空是逐卡表:报无卡可派即贴 `card-pick.mjs --order <序> --why`;无卡点即候选,⛔ 不得报空。 +- 卡点一份词表:候选定义反面,open `Blocked-by:`、`outside --order`、无分诊审计、他席 `Claim:`。 - 单车道仓 `repo:*` 席:每轮首触 sweep 清空再认领,先于待命五项;cloud 细则见 `lanes/cloud.md`。 - 巡查每轮探针后读信箱、认领满 `batch`,跑待命五项;间隔按 `execution-duties.md` 收集节②。 - 待命五项各以其主节为准,⛔ 此处不另抄:findings 配合;`pm:blocked`/`pm:on-hold` 解锁扫描。 diff --git a/package.json b/package.json index 491a168b878..6498540948a 100644 --- a/package.json +++ b/package.json @@ -84,7 +84,7 @@ "check:pm-half-states": "node scripts/pm/check-half-states.mjs --self-test", "check:issue-citations": "node scripts/check-issue-citations.mjs --self-test", "check:pm-record-recognisers": "node scripts/pm/record-recognisers.mjs --self-test && node scripts/pm/check-owed-reviews.mjs --self-test && node scripts/pm/mailbox-open.mjs --self-test && node scripts/pm/fleet-roster.mjs --self-test", - "check:pm-prior-rulings": "node scripts/pm/check-prior-rulings.mjs --self-test", + "check:pm-prior-rulings": "node scripts/pm/check-prior-rulings.mjs --self-test && node scripts/pm/card-pick.mjs --self-test", "check:pm-write-pace": "node scripts/pm/write-pace.mjs --self-test", "check:pm-fleet-token": "node scripts/pm/fleet-token.mjs --self-test", "check:pm-issue-create": "node scripts/pm/issue-create.mjs --self-test", diff --git a/scripts/pm/card-pick.mjs b/scripts/pm/card-pick.mjs new file mode 100644 index 00000000000..22640fdf077 --- /dev/null +++ b/scripts/pm/card-pick.mjs @@ -0,0 +1,949 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * card-pick — which ready cards a seat takes next, read off the live board under the grade rules. + * + * node scripts/pm/card-pick.mjs --order area:fleet --seat repo:objectstack#5 --why + * node scripts/pm/card-pick.mjs --order epic:#35205,area:ux,area:build --limit 3 --json + * node scripts/pm/card-pick.mjs --order area:ux --fixture board.json # offline, no network + * node scripts/pm/card-pick.mjs --self-test # offline, no network at all + * + * ## Why this file exists + * + * Every executing seat, every fire, and the coordinator on every wake, retyped the pick order by hand: list the + * queue, sort it by grade, walk the maintainer-named areas and epics, drop what is assigned, decided, blocked or + * claimed, and say why each other card is not a candidate. The rule is short; the reading is long, and the reading + * is where a seat sends itself the wrong card. This file is the reading. ⛔ It writes nothing: its output is input to + * a claim, and the claim's own re-read still arbitrates. + * + * ## The rules it encodes — rule text on `main`, pinned by the self-test + * + * `docs/NORTH-STAR.md` "Priority" rule 3 (`RULE_PHRASES`), read with `references/execution-duties.md`'s candidate + * definition and `references/state-machine.md`'s `Blocked-by:` contract: + * + * 1. `priority:p0` first, past every cap (leg `p0`). + * 2. `priority:p1` next, whatever area it belongs to, a paused area included (leg `p1 jump`). + * 3. Then the areas and epics `--order` names, in that order (leg `order k`). Inside an epic, its child order + * whatever the grade (`GET …/issues/N/sub_issues`; leg `epic child k`); inside an area, p2 by the same-grade + * tiebreak, then p3 by the same tiebreak (leg `order k p3 close-out`). + * 4. A card the order reaches that carries no grade comes after every graded leg (leg `ungraded`): the label order + * is p0 > p1 > the named order > ungraded. + * 5. An area's p3 is a pick, ranked after every p2 of that same item and before the next item: "p2 first, p3 left + * for the close-out"; "in an area with no sub-epic, p2 before p3". So an area holding only p3 cards yields its + * p3 as the next pick, never an empty queue. The reader cannot tell whether an area has a sub-epic, so every + * area item ranks this way; a sub-epic is named as an `epic:` item and keeps its child order. + * 6. At one grade: a non-fleet card first (`isFleetCard`), then a `Bug`, then the card opened first. + * 7. Not a candidate: an assignee, `pm:dispatched`, `needs-user-decision`, `pm:retriage`, a second pm state, an + * epic or tracking parent (`pm:epic`, `tracking`), an open line-start `Blocked-by:` target in the body or a + * comment (a PR target holds until it MERGES; closed unmerged keeps the block), a newest `Claim:` (not + * followed by a `Release:`), and a fleet card with no triage audit record (`references/seat-lifecycle.md`'s + * blocking-point vocabulary). + * 8. Leases are not read: a lease guards file overlap, and overlap is checked at claim time (`overlap-check.mjs`). + * + * ## What it does NOT read — named in the footer of every run + * + * The maintainer's direct dispatch (the first leg of 取卡全序, three provenance pieces), the contract-surface leg + * (`references/lanes/spec.md`), a `tooling` card's three-gate admission (triage's reading: only one gate is a + * machine line), the multi-seat odd/even alternation, batching a p3 onto a PR that touches the same files (rule + * ④'s "or batched", a judgement over a diff), lane ownership (a `domain:*` card outside the seat's lane, a cloud + * card or a security card is listed but may not be claimed; each row prints its `domain:*` so the seat can read it) + * and an area item that holds a sub-epic (rule 3 ③ binds that sub-epic's child order; the reader ranks the area p2 + * before p3 unless the sub-epic is named as an `epic:` item). A seat reads those itself; the output says so every + * time, so an absent leg never reads as a leg that found nothing. + * + * ## What it reads — REST through `gh api`, every page + * + * 1. every open issue carrying `pm:queue` (`readAllPages`), pull requests dropped, the count compared with the + * platform's own `GET /search/issues` total — a gap is INCOMPLETE (exit 4), ⛔ never a clean pick list; + * 2. each named epic's row and `GET …/issues/N/sub_issues`, every page, for the child order; + * 3. a card's comment thread, only for a card the order reaches, in rank order — every one with `--why`, and only + * until `--limit` picks without it (the rest are counted as not reached); + * 4. each `Blocked-by:` target's row, cross-repo included (`blockerTargetKey`), once per run; + * 5. a fleet card's sub-issue parent only when its thread carries no triage audit (`h74NeedsParentRead`). + * + * Every reader is borrowed, never re-spelled: `check-half-states.mjs` owns the `Blocked-by:` line, the target row, + * the claim and release markers, the seat signature, the fleet reading, the grade ladder, H67's age order and H74's + * triage audit; `gh-pages.mjs` owns the paging. + * + * ## Exit codes — capture them BEFORE any pipe + * + * 0 complete: every read answered and the walk counted what the platform counts + * 1 `--self-test` failed + * 2 usage + * 3 PREREQUISITE NOT MET — the queue listing or the platform count could not be read; nothing was ranked + * 4 INCOMPLETE — a count gap, an epic that could not be read, or a card whose thread, `Blocked-by:` target or + * sub-issue parent could not be read; the list is printed with each gap named and every card such a read holds + * printed even without `--why`, ⛔ never as a clean answer + * + * ## Self-test + * + * `--self-test` drives the ranking, the exclusions, the reads 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. + */ + +import { readFileSync } from 'node:fs'; + +import { isEntrypoint } from '../invoked-as.mjs'; +import { + CLAIM_COMMENT_MARKER, + DECISION_INBOX_LABEL, + DEFAULT_SWEEP_REPO, + GRADE_LADDER, + H74_PARENT_UNREADABLE, + PM_EXCLUSIVE_STATE_LABELS, + RELEASE_COMMENT_MARKER, + SEAT_SIGNATURE_LINE, + SEAT_SIGNATURE_SEPARATOR, + blockerResolutionFromRow, + blockerTargetsFor, + gradeRung, + h67ReadOrder, + h74NeedsParentRead, + h74QueuedWithoutTriageAudit, + isFleetCard, + labelNames, + markerMatches, + readSignatureLine, + subIssueParentPath, +} from './check-half-states.mjs'; +import { ghApi, readAllPages } from './gh-pages.mjs'; + +const REPO_ROOT = 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_PREREQUISITE = 3; +export const EXIT_INCOMPLETE = 4; + +export const QUEUE_LABEL = 'pm:queue'; +export const DEFAULT_LIMIT = 5; +/** Labels that make a card a parent of work rather than work (H74's exemption list carries both). */ +export const PARENT_LABELS = Object.freeze(['pm:epic', 'tracking']); + +/** Where the rules live, and the phrases this file is built from — the self-test pins each one present. */ +export const NORTH_STAR_PATH = 'docs/NORTH-STAR.md'; +export const RULE_PHRASES = Object.freeze([ + 'A seat takes its next card in this order: ① p0, dispatched in the same round, past every concurrency cap', + '② p1, ahead of the next card of the area being dispatched, whatever area it belongs to, a held or paused area included', + '③ the next card of the area being dispatched, in the order of the areas and sub-epics the maintainer names, and inside one by its own child order and `Blocked-by:`', + '④ inside an area, p2 and p3 are only a reference: p2 first, p3 left for the close-out or batched; in an area with no sub-epic, p2 before p3, and at the same grade the card opened first goes first', +]); +export const DUTIES_PATH = '.claude/skills/pm-dispatch/references/execution-duties.md'; +export const DUTIES_PHRASES = Object.freeze([ + '候选 = open、未 assign、无 `needs-user-decision`、无 `pm:retriage`', + '取卡全序:维护者直派插队卡(出处三件)> 契约面卡(判据见 `references/lanes/spec.md`)> 标签序', + '同级先非车队卡(作者非 `Bot` 且首行非席位签名),再 `Bug`、卡龄', + '本车道开放卡现读 `card-pick.mjs --order <序>`', + '开放 = 未派发(无 `pm:dispatched`、无 assignee)', +]); +export const STATE_MACHINE_PATH = '.claude/skills/pm-dispatch/references/state-machine.md'; +export const STATE_MACHINE_PHRASES = Object.freeze([ + '正典标记 = 行首 `Blocked-by: #N`', + '合并才放,关而未合并 ⛔ 不放', +]); +export const LIFECYCLE_PATH = '.claude/skills/pm-dispatch/references/seat-lifecycle.md'; +export const LIFECYCLE_PHRASES = Object.freeze(['无分诊审计、他席 `Claim:`', '`card-pick.mjs --order <序> --why`', '`outside --order`']); + +/** The legs this file cannot read, printed under every run. */ +export const UNREAD_LEGS = Object.freeze([ + "the maintainer's direct dispatch (取卡全序 leg 1, three provenance pieces) — not on the board as a label", + 'the contract-surface leg (取卡全序 leg 2, `references/lanes/spec.md`) — a judgement over the diff, not a label', + "a `tooling` card's three-gate admission — triage's reading; flagged on the row, not judged", + 'multi-seat odd/even alternation — the seat applies it to this list', + "batching a p3 onto a PR that touches the same files (rule ④'s \"or batched\") — a judgement over a diff; here every area p3 ranks as its close-out", + "lane ownership — a `domain:*` card outside this seat's lane, a cloud card or a security card is listed here but a seat may not claim it; read each row's `domain:*` against your lane", + "an area item that holds a sub-epic — ranked here p2 before p3, but rule 3 ③ binds that sub-epic's child order; name it as `epic:#N` in --order to get it", +]); + +// --------------------------------------------------------------------------- +// The pure core +// --------------------------------------------------------------------------- + +/** `--order` parsed: `epic:#N` / `epic:N` and `area:x`, in the order given. `{ ok, items }` or `{ ok: false, error }`. */ +export function parseOrder(text) { + const items = []; + for (const raw of String(text ?? '').split(',').map((s) => s.trim()).filter(Boolean)) { + const epic = /^epic:#?(\d+)$/.exec(raw); + const area = /^area:([a-z0-9][a-z0-9-]*)$/.exec(raw); + if (epic) items.push({ kind: 'epic', number: Number(epic[1]), name: `epic:#${epic[1]}` }); + else if (area) items.push({ kind: 'area', label: `area:${area[1]}`, name: `area:${area[1]}` }); + else return { ok: false, error: `--order item \`${raw}\` is neither epic:#N nor area:NAME` }; + } + const seen = new Set(); + for (const it of items) { + if (seen.has(it.name)) return { ok: false, error: `--order names \`${it.name}\` twice` }; + seen.add(it.name); + } + return { ok: true, items }; +} + +/** + * `--seat LANE#N` parsed by the seat signature's own grammar (`SEAT_SIGNATURE_LINE`, borrowed, never re-spelled), so + * every lane a signature can carry is accepted, an epic seat's `epic:#N#1` included. Pure. + */ +export function parseSeat(text) { + const v = String(text ?? ''); + if (/\s/.test(v)) return null; + const m = SEAT_SIGNATURE_LINE.exec(`${v}${SEAT_SIGNATURE_SEPARATOR}seat${SEAT_SIGNATURE_SEPARATOR}session_parseseat`); + return m ? { lane: m[1], seat: Number(m[2]), name: `${m[1]}#${m[2]}` } : null; +} + +const GRADE_NAMES = Object.freeze(['p0', 'p1', 'p2', 'p3']); +export const gradeName = (issue) => { + const rung = gradeRung(issue); + return rung === null ? 'ungraded' : GRADE_NAMES[rung]; +}; +export const issueType = (issue) => { + const t = issue?.type; + const name = typeof t === 'string' ? t : t?.name; + return typeof name === 'string' && name.trim() ? name.trim() : null; +}; +const areaOf = (issue) => labelNames(issue).filter((l) => l.startsWith('area:')).join(',') || 'no area'; +/** The card's lane labels, printed on every row: the reader does not judge lane ownership, the seat does. Pure. */ +export const domainOf = (issue) => labelNames(issue).filter((l) => l.startsWith('domain:')).join(',') || 'no domain'; + +/** + * The same-grade order: a non-fleet card first, then a `Bug`, then the card opened first. H67's read order supplies + * rank → fleet → age → number; a STABLE sort on rank → fleet → Bug then slots the Bug tiebreak in above age without + * re-spelling either half. Pure. + */ +export function sameGradeOrder(cards) { + const base = h67ReadOrder(cards, Number.MAX_SAFE_INTEGER).read; + const rank = (i) => { + const r = gradeRung(i); + return r === null ? GRADE_LADDER.length : r; + }; + const fleet = (i) => (isFleetCard(i) ? 1 : 0); + const bug = (i) => (issueType(i) === 'Bug' ? 0 : 1); + return [...base].sort((a, b) => rank(a) - rank(b) || fleet(a) - fleet(b) || bug(a) - bug(b)); +} + +/** + * The reasons a card is not a candidate that its own row can answer — no read. Pure. + * ⚠ The `pm:queue` population is the caller's; a closed card or a PR never reaches here. + */ +export function labelReasons(issue) { + const labels = labelNames(issue); + const out = []; + if (Array.isArray(issue?.assignees) ? issue.assignees.length > 0 : Boolean(issue?.assignee)) { + out.push(`assigned (${(issue.assignees ?? [issue.assignee]).map((a) => a?.login ?? '?').join(', ')})`); + } + if (labels.includes('pm:dispatched')) out.push('pm:dispatched'); + if (labels.includes(DECISION_INBOX_LABEL)) out.push(DECISION_INBOX_LABEL); + if (labels.includes('pm:retriage')) out.push('pm:retriage'); + for (const l of PARENT_LABELS) if (labels.includes(l)) out.push(`${l} parent`); + for (const l of PM_EXCLUSIVE_STATE_LABELS) { + if (![QUEUE_LABEL, 'pm:dispatched', DECISION_INBOX_LABEL].includes(l) && labels.includes(l)) out.push(`second pm state ${l}`); + } + return out; +} + +/** + * Where the order puts a card: `{ leg, legRank, orderIndex, childIndex }` or `null` when nothing reaches it. Pure. + * `children` maps an epic number to its child numbers in the epic's own order. + */ +export function placeCard(issue, items, children) { + const rung = gradeRung(issue); + if (rung === 0) return { leg: 'p0', legRank: 0, orderIndex: -1, childIndex: -1 }; + if (rung === 1) return { leg: 'p1 jump', legRank: 1, orderIndex: -1, childIndex: -1 }; + const labels = labelNames(issue); + for (let k = 0; k < items.length; k++) { + const it = items[k]; + let childIndex = -1; + if (it.kind === 'epic') { + childIndex = (children.get(it.number) ?? []).indexOf(issue.number); + if (childIndex === -1) continue; + } else if (!labels.includes(it.label)) continue; + if (rung === 3 && it.kind === 'area') return { leg: `order ${k + 1} p3 close-out`, legRank: 1.75, orderIndex: k, childIndex, item: it.name }; + if (rung === null && it.kind === 'area') return { leg: 'ungraded', legRank: 2, orderIndex: k, childIndex, item: it.name }; + return { leg: it.kind === 'epic' ? `epic child ${childIndex + 1}` : `order ${k + 1}`, legRank: 1.5, orderIndex: k, childIndex, item: it.name }; + } + return null; +} + +/** + * Rank the in-scope cards: p0, p1, then each order item in turn (an epic by child order whatever the grade; an area + * by the same-grade order, every p2 ahead of every p3), then the ungraded leg. Pure. + */ +export function rankCards(placed) { + const byLeg = (pred) => placed.filter(pred); + const out = []; + out.push(...sameGradeOrder(byLeg((p) => p.place.leg === 'p0').map((p) => p.issue))); + out.push(...sameGradeOrder(byLeg((p) => p.place.leg === 'p1 jump').map((p) => p.issue))); + const orderIndexes = [...new Set(placed.map((p) => p.place.orderIndex).filter((k) => k >= 0))].sort((a, b) => a - b); + for (const k of orderIndexes) { + const inItem = byLeg((p) => p.place.orderIndex === k && p.place.legRank === 1.5); + const epic = inItem.filter((p) => p.place.childIndex >= 0).sort((a, b) => a.place.childIndex - b.place.childIndex); + out.push(...epic.map((p) => p.issue)); + out.push(...sameGradeOrder(inItem.filter((p) => p.place.childIndex < 0).map((p) => p.issue))); + out.push(...sameGradeOrder(byLeg((p) => p.place.orderIndex === k && p.place.legRank === 1.75).map((p) => p.issue))); + } + for (const k of orderIndexes) out.push(...sameGradeOrder(byLeg((p) => p.place.orderIndex === k && p.place.leg === 'ungraded').map((p) => p.issue))); + return { ranked: out }; +} + +/** + * The newest ownership marker on a thread: the newest comment carrying `Claim:` or `Release:` (the shared markers), + * and who signed it. `null` when neither appears. Pure. + */ +export function ownershipOf(comments) { + let newest = null; + for (const c of comments ?? []) { + const body = String(c?.body ?? ''); + const claim = markerMatches(CLAIM_COMMENT_MARKER, body); + const release = markerMatches(RELEASE_COMMENT_MARKER, body); + if (!claim && !release) continue; + const at = Date.parse(c?.created_at ?? ''); + if (newest === null || !Number.isFinite(newest.at) || (Number.isFinite(at) && at >= newest.at)) { + newest = { kind: release && !claim ? 'release' : 'claim', at, signature: readSignatureLine(body) }; + } + } + return newest; +} + +/** The claim reason for a thread, judged against `--seat`: `null` when the card is free. Pure. */ +export function claimReason(comments, seat) { + const own = ownershipOf(comments); + if (own === null || own.kind === 'release') return null; + const sig = own.signature; + if (!sig) return 'Claim: (unsigned) — another session holds it unless the claim names you'; + const who = `${sig.lane}#${sig.seat}`; + if (seat && seat.name === who) return `Claim: by this seat (${who}) — already yours, not a new pick`; + return `Claim: by ${who}`; +} + +const ageDays = (issue, nowMs) => { + const t = Date.parse(issue?.created_at ?? ''); + return Number.isFinite(t) ? `${Math.max(0, Math.floor((nowMs - t) / 86_400_000))}d` : '?d'; +}; + +// --------------------------------------------------------------------------- +// The walk — `get` is injected (`{ ok, value }` / `{ ok: false, error }`, gh-pages' shape) +// --------------------------------------------------------------------------- + +const is404 = (r) => !r.ok && /\b404\b|Not Found/i.test(String(r.error ?? '')); + +export async function pick({ repo, items, seat, limit = DEFAULT_LIMIT, why = false, nowMs = Date.now(), get = ghApi }) { + const incomplete = []; + const reads = { pages: 0, threads: 0, targets: 0, parents: 0, epics: 0 }; + const getCounted = get; + + // 1. the queue, every page, against the platform's count. + const listed = readAllPages(`/repos/${repo}/issues?state=open&labels=${encodeURIComponent(QUEUE_LABEL)}`, { + get: (p) => { + reads.pages += 1; + return getCounted(p); + }, + }); + if (!listed.ok) return { prerequisite: `the ${QUEUE_LABEL} listing could not be read: ${listed.error}` }; + const queue = listed.value.filter((row) => row && !row.pull_request); + const total = getCounted(`/search/issues?q=${encodeURIComponent(`repo:${repo} is:issue is:open label:${QUEUE_LABEL}`)}&per_page=1`); + if (!total.ok || typeof total.value?.total_count !== 'number') return { prerequisite: `the platform count could not be read: ${total.error ?? 'no total_count'}` }; + if (total.value.incomplete_results === true) incomplete.push('the platform count answered incomplete_results'); + if (total.value.total_count !== queue.length) incomplete.push(`the walk returned ${queue.length} ${QUEUE_LABEL} issue(s) and the platform counts ${total.value.total_count}`); + + // 2. each named epic's child order. + const children = new Map(); + const epicRows = new Map(); + for (const it of items.filter((i) => i.kind === 'epic')) { + reads.epics += 1; + const row = getCounted(`/repos/${repo}/issues/${it.number}`); + const subs = readAllPages(`/repos/${repo}/issues/${it.number}/sub_issues`, { get: getCounted }); + if (!subs.ok) { + incomplete.push(`${it.name}'s children could not be read (${subs.error}) — its leg is empty`); + continue; + } + if (row.ok) epicRows.set(it.number, row.value); + children.set(it.number, subs.value.map((s) => s?.number).filter(Number.isInteger)); + } + + // 3. place every card; the label-only reasons first. + const rows = []; + const placed = []; + for (const issue of queue) { + const reasons = labelReasons(issue); + const place = placeCard(issue, items, children); + const row = { issue, place, reasons, flags: [], read: false, gap: false }; + rows.push(row); + if (reasons.length) continue; + if (place === null) { + row.reasons.push(`outside --order (${gradeName(issue)} · ${areaOf(issue)})`); + continue; + } + placed.push(row); + } + for (const row of rows) if (labelNames(row.issue).includes('tooling')) row.flags.push('tooling: three-gate admission unread'); + + // 4. walk in rank order, reading threads lazily. + const { ranked } = rankCards(placed); + const rowOf = new Map(rows.map((r) => [r.issue.number, r])); + const targetCache = new Map(); + const resolveTarget = (t) => { + if (targetCache.has(t.key)) return targetCache.get(t.key); + reads.targets += 1; + const r = getCounted(`/repos/${t.repo}/issues/${t.number}`); + const res = r.ok ? blockerResolutionFromRow(t, r.value) : { ...t, state: 'unresolved', detail: r.error }; + targetCache.set(t.key, res); + return res; + }; + const evaluate = (row) => { + const { issue } = row; + reads.threads += 1; + const thread = readAllPages(`/repos/${repo}/issues/${issue.number}/comments`, { get: getCounted }); + row.read = true; + if (!thread.ok) { + row.reasons.push(`thread unreadable (${thread.error})`); + row.gap = true; + incomplete.push(`#${issue.number}'s thread could not be read`); + return; + } + const comments = thread.value; + const bodies = comments.map((c) => String(c?.body ?? '')); + for (const t of blockerTargetsFor(issue, bodies, repo)) { + const res = resolveTarget(t); + const name = t.local ? `#${t.number}` : t.key; + if (res.state === 'unresolved') { + row.reasons.push(`Blocked-by: ${name} (unreadable — held, never read as closed)`); + row.gap = true; + incomplete.push(`#${issue.number}'s Blocked-by: ${name} could not be read (${res.detail ?? 'no detail'})`); + } + else if (res.state === 'open') row.reasons.push(`Blocked-by: ${name} (open)`); + else if (res.unmerged) row.reasons.push(`Blocked-by: ${name} (PR closed unmerged — the block stays)`); + } + const claim = claimReason(comments, seat); + if (claim) row.reasons.push(claim); + let parent = row.place?.childIndex >= 0 ? epicRows.get(Number(row.place.item.replace(/\D/g, ''))) : undefined; + if (parent === undefined && h74NeedsParentRead(issue, bodies)) { + reads.parents += 1; + const p = getCounted(subIssueParentPath(repo, issue.number)); + parent = p.ok ? p.value : is404(p) ? null : H74_PARENT_UNREADABLE; + } + if (h74QueuedWithoutTriageAudit(issue, bodies, parent) !== null) { + row.reasons.push(parent === H74_PARENT_UNREADABLE ? 'no triage audit (parent unreadable — unjudged, held)' : 'no triage audit — knock triage'); + } + if (parent === H74_PARENT_UNREADABLE) { + row.gap = true; + incomplete.push(`#${issue.number}'s sub-issue parent could not be read`); + } + }; + const picks = []; + let notReached = 0; + for (const issue of ranked) { + const row = rowOf.get(issue.number); + if (picks.length >= limit && !why) { + notReached += 1; + continue; + } + evaluate(row); + if (row.reasons.length === 0) { + if (picks.length < limit) picks.push(row); + else row.reasons.push(`below --limit ${limit} (a candidate)`); + } + } + const pickSet = new Set(picks.map((r) => r.issue.number)); + const others = rows.filter((r) => !pickSet.has(r.issue.number) && r.reasons.length > 0); + const held = others.filter((r) => r.gap); + return { + repo, + items, + seat, + limit, + why, + nowMs, + enumerated: queue.length, + totalCount: total.value.total_count, + reads, + complete: incomplete.length === 0, + incomplete, + picks, + others, + held, + notReached, + }; +} + +// --------------------------------------------------------------------------- +// Rendering +// --------------------------------------------------------------------------- + +function rowLine(row, rank, nowMs) { + const i = row.issue; + const leg = row.place?.leg ?? '—'; + const where = row.place?.item ?? areaOf(i); + const parts = [`#${i.number}`, gradeName(i), where, domainOf(i), issueType(i) ?? 'no type', leg, ageDays(i, nowMs), isFleetCard(i) ? 'fleet' : 'non-fleet']; + const title = String(i.title ?? '').replace(/\s+/g, ' ').slice(0, 90); + const flags = row.flags.length ? ` [${row.flags.join('; ')}]` : ''; + return `${rank === null ? '' : `${rank} · `}${parts.join(' · ')} — ${title}${flags}`; +} + +export function verdictLine(r) { + if (!r.complete) return `card-pick INCOMPLETE — ${r.incomplete.join('; ')}. ⛔ Not a clean pick list: re-run when the reads answer.`; + return `card-pick COMPLETE — ${r.picks.length} pick(s)`; +} + +export function renderText(r) { + const at = new Date(r.nowMs).toISOString().slice(0, 16) + 'Z'; + const L = [`card-pick — ${r.repo} · order ${r.items.map((i) => i.name).join(', ') || '(none: p0/p1 only)'} · seat ${r.seat?.name ?? '(none)'} · ${at}`]; + L.push(`read: ${r.enumerated} open ${QUEUE_LABEL} issue(s) over ${r.reads.pages} page(s) · the platform counts ${r.totalCount} · threads ${r.reads.threads} · Blocked-by targets ${r.reads.targets} · parents ${r.reads.parents} · epics ${r.reads.epics}`); + L.push(`Picks (limit ${r.limit}) — rank · #N · grade · area/epic · domain · type · leg · age · fleet:`); + if (r.picks.length === 0) L.push(' (none — every card the order reaches has a named blocking point; --why lists them)'); + r.picks.forEach((row, k) => L.push(` ${rowLine(row, k + 1, r.nowMs)}`)); + if (r.why) { + L.push(`Not a pick (--why) — ${r.others.length} card(s), each with its blocking point:`); + const sorted = [...r.others].sort((a, b) => (a.place ? 0 : 1) - (b.place ? 0 : 1) || a.issue.number - b.issue.number); + for (const row of sorted) L.push(` · #${row.issue.number} · ${gradeName(row.issue)} · ${row.place?.item ?? areaOf(row.issue)} · ${domainOf(row.issue)} — ${row.reasons.join('; ')}`); + } else { + if (r.held.length > 0) { + L.push(`Held by a read that did not answer — ${r.held.length} card(s), printed without --why (⛔ not a card the order skipped):`); + for (const row of r.held) L.push(` · ${rowLine(row, null, r.nowMs)} — ${row.reasons.join('; ')}`); + } + if (r.notReached > 0) L.push(`Not reached: ${r.notReached} lower-ranked card(s) were not read once --limit filled (--why reads them all).`); + } + 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) { + const card = (row) => ({ + number: row.issue.number, + title: row.issue.title ?? '', + grade: gradeName(row.issue), + area: areaOf(row.issue), + domain: domainOf(row.issue), + type: issueType(row.issue), + leg: row.place?.leg ?? null, + order_item: row.place?.item ?? null, + fleet: isFleetCard(row.issue), + created_at: row.issue.created_at ?? null, + flags: row.flags, + reasons: row.reasons, + thread_read: row.read, + }); + return { + repo: r.repo, + order: r.items.map((i) => i.name), + seat: r.seat?.name ?? null, + complete: r.complete, + incomplete_reasons: r.incomplete, + enumerated: r.enumerated, + total_count: r.totalCount, + reads: r.reads, + picks: r.picks.map(card), + not_a_pick: r.why ? r.others.map(card) : null, + held_on_unread: r.held.map(card), + not_reached: r.notReached, + unread_legs: UNREAD_LEGS, + verdict: verdictLine(r), + }; +} + +// --------------------------------------------------------------------------- +// Fixture — an offline board the same `get` answers +// --------------------------------------------------------------------------- + +/** + * A `get` over a fixture: `{ issues, total_count?, comments?: {N: []}, sub_issues?: {N: []}, rows?: {"o/r#N": row}, + * parents?: {N: row} }`. A path the fixture does not hold answers 404, so a fixture can never read as a board that + * answered; a `null` comment list, row or parent answers HTTP 502, a read that failed. Pure. + */ +export function fixtureGet(fixture, repo) { + const page = (rows, path) => { + const q = new URLSearchParams(path.split('?')[1] ?? ''); + const per = Number(q.get('per_page') ?? 100); + const p = Number(q.get('page') ?? 1); + return rows.slice((p - 1) * per, p * per); + }; + const issues = fixture.issues ?? []; + return (path) => { + const bare = path.split('?')[0]; + if (bare === `/repos/${repo}/issues`) return { ok: true, value: page(issues, path) }; + if (bare === '/search/issues') return { ok: true, value: { total_count: fixture.total_count ?? issues.filter((i) => !i.pull_request).length, incomplete_results: false } }; + let m = /^\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)\/comments$/.exec(bare); + if (m) return fixture.comments?.[m[2]] === null ? { ok: false, error: 'HTTP 502' } : { ok: true, value: page(fixture.comments?.[m[2]] ?? [], path) }; + m = /^\/repos\/[^/]+\/[^/]+\/issues\/(\d+)\/sub_issues$/.exec(bare); + if (m) return fixture.sub_issues?.[m[1]] ? { ok: true, value: page(fixture.sub_issues[m[1]], path) } : { ok: false, error: 'HTTP 404 Not Found' }; + m = /^\/repos\/[^/]+\/[^/]+\/issues\/(\d+)\/parent$/.exec(bare); + if (m) { + if (fixture.parents?.[m[1]] === null) return { ok: false, error: 'HTTP 502' }; + return fixture.parents?.[m[1]] ? { ok: true, value: fixture.parents[m[1]] } : { ok: false, error: 'HTTP 404 Not Found' }; + } + m = /^\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)$/.exec(bare); + if (m) { + if (fixture.rows?.[`${m[1]}#${m[2]}`] === null) return { ok: false, error: 'HTTP 502' }; + const row = fixture.rows?.[`${m[1]}#${m[2]}`] ?? (m[1] === repo ? issues.find((i) => i.number === Number(m[2])) : undefined); + return row ? { ok: true, value: row } : { ok: false, error: 'HTTP 404 Not Found' }; + } + return { ok: false, error: `HTTP 404 Not Found (${bare})` }; + }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +const USAGE = [ + 'card-pick — which ready cards a seat takes next (read-only; the claim re-read still arbitrates).', + '', + ' node scripts/pm/card-pick.mjs --order epic:#N,area:NAME,… [--seat LANE#N] [--repo OWNER/NAME]', + ' [--limit N] [--why] [--json] [--fixture FILE] [--now ISO]', + ' node scripts/pm/card-pick.mjs --self-test', + '', + ' --order the maintainer-named order, epics and areas mixed; p0 and p1 jump it whatever their area.', + ' --seat this seat, so its own Claim: reads as already yours rather than another seat\'s.', + ' --why every other queue card with its named blocking point (reads every thread the order reaches).', + ' Exits: 0 complete · 2 usage · 3 prerequisite (queue unreadable) · 4 INCOMPLETE (a gap, named; held cards printed).', +].join('\n'); + +export function parseArgs(argv) { + const opts = { repo: DEFAULT_SWEEP_REPO, order: null, seat: null, limit: DEFAULT_LIMIT, why: false, json: false, fixture: null, nowMs: 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 === '--why' && !eq) opts.why = true; + else if (flag === '--json' && !eq) opts.json = true; + else if ((flag === '--help' || flag === '-h') && !eq) opts.help = true; + 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 === '--order') { + const v = take(); + if (v === undefined) return { error: '--order needs a value (epic:#N and area:NAME, comma-separated; --order "" for p0/p1 only)' }; + const parsed = parseOrder(v); + if (!parsed.ok) return { error: parsed.error }; + opts.order = parsed.items; + } else if (flag === '--seat') { + const v = take(); + opts.seat = parseSeat(v); + if (!opts.seat) return { error: `--seat must be LANE#N (a seat signature's first part), got \`${v}\`` }; + } else if (flag === '--limit') { + const v = take(); + if (!/^[1-9][0-9]*$/.test(String(v ?? ''))) return { error: `--limit must be a positive integer, got \`${v}\`` }; + opts.limit = Number(v); + } else if (flag === '--fixture') { + opts.fixture = take(); + if (!opts.fixture) return { error: '--fixture needs a file' }; + } else if (flag === '--now') { + const v = take(); + opts.nowMs = Date.parse(String(v ?? '')); + if (!Number.isFinite(opts.nowMs)) return { error: `--now must be an ISO time, got \`${v}\`` }; + } else return { error: `\`${a}\` is not an argument this tool takes` }; + } + if (!opts.help && opts.order === null) return { error: '--order is required (the maintainer-named order: epic:#N and area:NAME, comma-separated); a pick list with no order is p0/p1 only, so say so with --order ""' }; + return { opts }; +} + +export async function main(argv, deps = {}) { + const parsed = parseArgs(argv); + if (parsed.error) { + console.error(`card-pick: ${parsed.error}`); + console.error(USAGE); + return EXIT_USAGE; + } + const o = parsed.opts; + if (o.help) { + console.log(USAGE); + return EXIT_OK; + } + let get = deps.get ?? ghApi; + let nowMs = o.nowMs ?? deps.nowMs ?? Date.now(); + if (o.fixture) { + let fixture; + try { + fixture = JSON.parse(readFileSync(o.fixture, 'utf8')); + } catch (e) { + console.error(`card-pick: --fixture \`${o.fixture}\` could not be read as JSON (${e.message})`); + return EXIT_USAGE; + } + get = fixtureGet(fixture, o.repo); + if (o.nowMs === null && fixture.now) nowMs = Date.parse(fixture.now); + } + const r = await pick({ repo: o.repo, items: o.order, seat: o.seat, limit: o.limit, why: o.why, nowMs, get }); + if (r.prerequisite) { + console.error(`card-pick: PREREQUISITE NOT MET — ${r.prerequisite}. ⛔ No pick list: nothing was ranked.`); + return EXIT_PREREQUISITE; + } + console.log(o.json ? JSON.stringify(renderJson(r), null, 2) : renderText(r)); + return r.complete ? EXIT_OK : EXIT_INCOMPLETE; +} + +// --------------------------------------------------------------------------- +// 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': 5, + 'the grade legs: p0 above everything, p1 jumps the named order, the ungraded leg comes last': 6, + "p3: an area's close-out after every p2 of that item; an epic's children keep their child order": 7, + 'Blocked-by: an open target holds, a closed-unmerged PR holds, a merged PR and a closed issue release, cross-repo is read': 7, + 'the same-grade order and the epic child order': 5, + 'the candidate definition: label reasons, claims and the triage audit': 9, + 'the walk: every page, the count checked, the limit and --why': 11, + 'the CLI: usage, exits and the footer': 12, +}); +const SELF_TEST_BATTERY_FLOOR = 8; +const UNATTRIBUTED_BATTERY = '(unattributed)'; +const batteryCases = new Map(); +let openBattery = null; +const battery = (name) => { + openBattery = name; +}; +let selfTestReachedVerdict = false; + +const quiet = (fn) => async (...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: await fn(...args), out: out.join('\n') }; + } finally { + console.log = log; + console.error = err; + } +}; + +export async 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 NOW = Date.parse('2026-11-19T12:00:00Z'); + const HUMAN = { login: 'someone', type: 'User' }; + const APP = { login: 'objectstack-fleet[bot]', type: 'Bot' }; + const SIG = 'repo:objectstack#1 · os-warren · session_01ABCDEFGH'; + const AUDIT = 'triage#1 · os-tri · session_01TRIAGEXY\n\n## Triage\n\narea · type · severity'; + let n = 100; + const card = (labels, extra = {}) => ({ + number: ++n, + title: `card ${n}`, + labels: [QUEUE_LABEL, ...labels].map((name) => ({ name })), + created_at: '2026-11-10T00:00:00Z', + user: HUMAN, + assignees: [], + body: 'x', + ...extra, + }); + const run = (fixture, opts = {}) => + pick({ repo: REPO, items: parseOrder(opts.order ?? 'area:ux').items, seat: parseSeat(opts.seat ?? 'repo:objectstack#5'), limit: opts.limit ?? 10, why: opts.why ?? true, nowMs: NOW, get: opts.get ?? fixtureGet(fixture, REPO) }); + const nums = (rows) => rows.map((r) => r.issue.number); + + battery('the rule text: every phrase this file is built from is in the file that writes it'); + { + const read = (p) => readFileSync(new URL(p, REPO_ROOT), 'utf8'); + t('⭐ NORTH-STAR "Priority" rule 3 still says what this file encodes (a reworded rule reds here)', RULE_PHRASES.filter((p) => !read(NORTH_STAR_PATH).includes(p)), []); + t('execution-duties.md: the candidate definition, 取卡全序 and the same-grade order are its phrases', DUTIES_PHRASES.filter((p) => !read(DUTIES_PATH).includes(p)), []); + t('state-machine.md: the line-start Blocked-by contract, a PR released by its merge only', STATE_MACHINE_PHRASES.filter((p) => !read(STATE_MACHINE_PATH).includes(p)), []); + t('seat-lifecycle.md: the blocking-point vocabulary, and the pointer here', LIFECYCLE_PHRASES.filter((p) => !read(LIFECYCLE_PATH).includes(p)), []); + t('the grade ladder this file names is the shared one', GRADE_LADDER.join(','), 'priority:p0,priority:p1,priority:p2,priority:p3'); + } + + battery('the grade legs: p0 above everything, p1 jumps the named order, the ungraded leg comes last'); + { + const named2 = card(['area:ux', 'priority:p2'], { created_at: '2026-01-01T00:00:00Z' }); + const other1 = card(['area:build', 'priority:p1']); + const p0 = card(['area:data', 'priority:p0']); + const ungraded = card(['area:ux'], { created_at: '2025-01-01T00:00:00Z' }); + const outside2 = card(['area:build', 'priority:p2']); + const comments = Object.fromEntries([named2, other1, p0, ungraded, outside2].map((c) => [c.number, [{ body: AUDIT }]])); + const r = await run({ issues: [named2, ungraded, outside2, other1, p0], comments }); + t('⭐ p0 is first, past everything', nums(r.picks)[0], p0.number); + t('⭐ an unnamed-area p1 beats a named-area p2', nums(r.picks).indexOf(other1.number) < nums(r.picks).indexOf(named2.number), true); + t('the named-area p2 comes before the ungraded card in that area, however old', nums(r.picks).join(), [p0, other1, named2, ungraded].map((c) => c.number).join()); + t('a p2 outside the order is not a pick, and says why', r.others.find((o) => o.issue.number === outside2.number)?.reasons[0], 'outside --order (p2 · area:build)'); + t('the legs are named on the row', r.picks.map((p) => p.place.leg).join('|'), 'p0|p1 jump|order 1|ungraded'); + const r2 = await run({ issues: [named2, other1], comments }, { order: 'area:build,area:ux' }); + t('the order items are walked in the order given', nums(r2.picks).join(), [other1, named2].map((c) => c.number).join()); + } + + battery("p3: an area's close-out after every p2 of that item; an epic's children keep their child order"); + { + const p3a = card(['area:ux', 'priority:p3'], { created_at: '2025-01-01T00:00:00Z' }); + const p3b = card(['area:ux', 'priority:p3']); + const p2 = card(['area:ux', 'priority:p2']); + const comments = Object.fromEntries([p3a, p3b, p2].map((c) => [c.number, [{ body: AUDIT }]])); + const only = await run({ issues: [p3b, p3a], comments }, { limit: 10 }); + t('⭐ an area holding only p3 cards yields its p3 cards as picks, oldest first — never an empty queue', nums(only.picks).join(), [p3a, p3b].map((c) => c.number).join()); + const r = await run({ issues: [p3b, p2, p3a], comments }, { limit: 10 }); + t('⭐ a p2 ranks ahead of every p3 in the same item, an older p3 included', nums(r.picks).join(), [p2, p3a, p3b].map((c) => c.number).join()); + t('…and the p3 rows name their leg', r.picks.map((p) => p.place.leg).join('|'), 'order 1|order 1 p3 close-out|order 1 p3 close-out'); + const build2 = card(['area:build', 'priority:p2']); + const ungraded = card(['area:ux'], { created_at: '2024-01-01T00:00:00Z' }); + const c2 = { ...comments, [build2.number]: [{ body: AUDIT }], [ungraded.number]: [{ body: AUDIT }] }; + const two = await run({ issues: [build2, p3a, ungraded], comments: c2 }, { order: 'area:ux,area:build' }); + t("an item's p3 closes that item before the next item's p2; the ungraded leg still comes last", nums(two.picks).join(), [p3a, build2, ungraded].map((c) => c.number).join()); + const out = await run({ issues: [p3a], comments }, { order: 'area:build' }); + t('a p3 outside the order is not a pick, and says why', [out.picks.length, out.others[0]?.reasons[0]], [0, 'outside --order (p3 · area:ux)']); + const e3 = card(['priority:p3']); + const e2 = card(['priority:p2']); + const ec = Object.fromEntries([e3, e2].map((c) => [c.number, [{ body: AUDIT }]])); + const er = await run({ issues: [e2, e3], comments: ec, sub_issues: { 600: [e3, e2].map((c) => ({ number: c.number })) }, rows: { [`${REPO}#600`]: { number: 600, labels: [] } } }, { order: 'epic:#600' }); + t("⭐ an epic's children follow child order whatever the grade: a p3 first child ranks ahead of a p2 second child", nums(er.picks).join(), [e3, e2].map((c) => c.number).join()); + t('…under the epic child leg, never the close-out leg', er.picks.map((p) => p.place.leg).join('|'), 'epic child 1|epic child 2'); + } + + battery('Blocked-by: an open target holds, a closed-unmerged PR holds, a merged PR and a closed issue release, cross-repo is read'); + { + const onOpen = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: #900' }); + const onAbandoned = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: #901' }); + const onMerged = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: #902' }); + const onClosed = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: #903' }); + const onComment = card(['area:ux', 'priority:p2']); + const crossRepo = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: objectstack-ai/cloud#77' }); + const rows = { + [`${REPO}#900`]: { number: 900, state: 'open' }, + [`${REPO}#901`]: { number: 901, state: 'closed', pull_request: { merged_at: null } }, + [`${REPO}#902`]: { number: 902, state: 'closed', pull_request: { merged_at: '2026-11-18T00:00:00Z' } }, + [`${REPO}#903`]: { number: 903, state: 'closed' }, + 'objectstack-ai/cloud#77': { number: 77, state: 'open' }, + }; + const all = [onOpen, onAbandoned, onMerged, onClosed, onComment, crossRepo]; + const comments = Object.fromEntries(all.map((c) => [c.number, [{ body: AUDIT }]])); + comments[onComment.number].push({ body: 'Blocked-by: #900', created_at: '2026-11-18T00:00:00Z' }); + const asked = []; + const base = fixtureGet({ issues: all, comments, rows }, REPO); + const r = await run(null, { get: (p) => (asked.push(p), base(p)) }); + const why = (c) => r.others.find((o) => o.issue.number === c.number)?.reasons.join('; ') ?? 'PICKED'; + t('⭐ an open Blocked-by target excludes the card', why(onOpen), 'Blocked-by: #900 (open)'); + t('⭐ a closed-but-unmerged PR target still blocks', why(onAbandoned), 'Blocked-by: #901 (PR closed unmerged — the block stays)'); + t('a merged PR target releases', why(onMerged), 'PICKED'); + t('a closed issue target releases', why(onClosed), 'PICKED'); + t('a Blocked-by: line in a COMMENT holds too', why(onComment), 'Blocked-by: #900 (open)'); + t('⭐ a cross-repo target is read from its own repo', [why(crossRepo), asked.includes('/repos/objectstack-ai/cloud/issues/77')], ['Blocked-by: objectstack-ai/cloud#77 (open)', true]); + t('one target named twice is read once', asked.filter((p) => p === `/repos/${REPO}/issues/900`).length, 1); + } + + battery('the same-grade order and the epic child order'); + { + const fleetOld = card(['area:ux', 'priority:p2'], { user: APP, created_at: '2025-01-01T00:00:00Z' }); + const humanNew = card(['area:ux', 'priority:p2'], { created_at: '2026-11-01T00:00:00Z' }); + const humanBug = card(['area:ux', 'priority:p2'], { created_at: '2026-11-05T00:00:00Z', type: { name: 'Bug' } }); + const humanOld = card(['area:ux', 'priority:p2'], { created_at: '2026-10-01T00:00:00Z' }); + const signed = card(['area:ux', 'priority:p2'], { created_at: '2024-01-01T00:00:00Z', body: `${SIG}\n\nbody` }); + const all = [fleetOld, humanNew, humanBug, humanOld, signed]; + const comments = Object.fromEntries(all.map((c) => [c.number, [{ body: AUDIT }]])); + const r = await run({ issues: all, comments }); + t('⭐ non-fleet first, then Bug, then the card opened first; a seat-signed body reads as the fleet\'s', nums(r.picks).join(), [humanBug, humanOld, humanNew, signed, fleetOld].map((c) => c.number).join()); + const c1 = card(['priority:p2'], { created_at: '2026-11-11T00:00:00Z' }); + const c2 = card(['priority:p2'], { created_at: '2026-01-01T00:00:00Z' }); + const c3 = card([], {}); + const epicIssues = [c1, c2, c3]; + const ec = Object.fromEntries(epicIssues.map((c) => [c.number, [{ body: AUDIT }]])); + const er = await run({ issues: epicIssues, comments: ec, sub_issues: { 500: [c3, c1, c2].map((c) => ({ number: c.number })) }, rows: { [`${REPO}#500`]: { number: 500, labels: [] } } }, { order: 'epic:#500' }); + t('⭐ inside an epic the child order rules, not the age and not the grade', nums(er.picks).join(), [c3, c1, c2].map((c) => c.number).join()); + t('…and the row names its child position', er.picks[0].place.leg, 'epic child 1'); + const jump = card(['priority:p1']); + const jr = await run({ issues: [...epicIssues, jump], comments: { ...ec, [jump.number]: [] }, sub_issues: { 500: [c3, c1, c2, jump].map((c) => ({ number: c.number })) } }, { order: 'epic:#500' }); + t('a p1 child jumps its own epic\'s order', [nums(jr.picks)[0], jr.picks[0].place.leg], [jump.number, 'p1 jump']); + const gone = await run({ issues: epicIssues, comments: ec }, { order: 'epic:#501' }); + t('an epic whose children cannot be read is a named gap, never an empty leg read as clean', [gone.complete, gone.incomplete[0]?.startsWith('epic:#501')], [false, true]); + } + + battery('the candidate definition: label reasons, claims and the triage audit'); + { + t('an assignee is not a candidate', labelReasons(card([], { assignees: [{ login: 'os-bill' }] })), ['assigned (os-bill)']); + t('needs-user-decision and pm:retriage are not candidates', labelReasons(card([DECISION_INBOX_LABEL, 'pm:retriage'])), [DECISION_INBOX_LABEL, 'pm:retriage']); + t('an epic or tracking parent is not a candidate', labelReasons(card(['pm:epic'])), ['pm:epic parent']); + t('a second pm state is named', labelReasons(card(['pm:blocked'])), ['second pm state pm:blocked']); + const claim = (sig, at = '2026-11-18T00:00:00Z') => ({ body: `${sig}\n\nClaim: round 1\nBranch: x`, created_at: at }); + t('⭐ another seat\'s Claim: excludes', claimReason([claim(SIG)], parseSeat('repo:objectstack#5')), 'Claim: by repo:objectstack#1'); + t('this seat\'s own Claim: reads as already yours', claimReason([claim(SIG)], parseSeat('repo:objectstack#1')), 'Claim: by this seat (repo:objectstack#1) — already yours, not a new pick'); + t('a Release: after the Claim: frees the card', claimReason([claim(SIG), { body: 'Release: session gone · back to queue', created_at: '2026-11-18T05:00:00Z' }], null), null); + const fleetCard = card(['area:ux', 'priority:p2'], { user: APP }); + const r = await run({ issues: [fleetCard], comments: { [fleetCard.number]: [{ body: 'just a note' }] } }); + t('⭐ a fleet card with no triage audit record is not a candidate', r.others[0]?.reasons, ['no triage audit — knock triage']); + const r2 = await run({ issues: [{ ...fleetCard }], comments: { [fleetCard.number]: [{ body: AUDIT }] } }); + t('…and its audit record makes it one', nums(r2.picks), [fleetCard.number]); + } + + battery('the walk: every page, the count checked, the limit and --why'); + { + const many = Array.from({ length: 130 }, () => card(['area:ux', 'priority:p2'])); + const comments = Object.fromEntries(many.map((c) => [c.number, [{ body: AUDIT }]])); + const r = await run({ issues: many, comments }, { limit: 3, why: false }); + t('every page is walked (130 cards over two pages)', [r.enumerated, r.reads.pages], [130, 2]); + t('⭐ without --why the walk stops reading at --limit and counts the rest', [r.picks.length, r.reads.threads, r.notReached], [3, 3, 127]); + const w = await run({ issues: many, comments }, { limit: 3, why: true }); + t('with --why every card the order reaches is read and the rest named', [w.reads.threads, w.others.length], [130, 127]); + t('a candidate below the limit says so', w.others[0].reasons[0], 'below --limit 3 (a candidate)'); + const gap = await run({ issues: many.slice(0, 2), comments, total_count: 5 }, { why: false }); + t('⭐ a count gap is INCOMPLETE, never clean', [gap.complete, gap.incomplete[0]], [false, `the walk returned 2 ${QUEUE_LABEL} issue(s) and the platform counts 5`]); + const dead = await run(null, { get: () => ({ ok: false, error: 'HTTP 403' }) }); + t('an unreadable queue is a prerequisite, nothing ranked', Boolean(dead.prerequisite), true); + const unread = await run({ issues: [many[0]], comments: { [many[0].number]: null } }, { why: false }); + t('a thread that cannot be read holds the card, makes the run INCOMPLETE, and the held card is printed without --why', [unread.picks.length, unread.complete, nums(unread.held), renderText(unread).includes(`#${many[0].number} · p2`)], [0, false, [many[0].number], true]); + const onUnread = card(['area:ux', 'priority:p2'], { body: 'Blocked-by: #904' }); + const ur = await run({ issues: [onUnread], comments: { [onUnread.number]: [{ body: AUDIT }] }, rows: { [`${REPO}#904`]: null } }, { why: false }); + t('⭐ an unreadable Blocked-by: target holds the card AND makes the run INCOMPLETE, the gap named', [ur.picks.length, ur.complete, ur.incomplete[0]], [0, false, `#${onUnread.number}'s Blocked-by: #904 could not be read (HTTP 502)`]); + t('⭐ …and the held card is printed without --why', [renderText(ur).includes('Held by a read that did not answer — 1 card(s)'), renderText(ur).includes(`#${onUnread.number} · p2`)], [true, true]); + const orphan = card(['area:ux', 'priority:p2'], { user: APP }); + const pr = await run({ issues: [orphan], comments: { [orphan.number]: [{ body: 'just a note' }] }, parents: { [orphan.number]: null } }, { why: false }); + t('⭐ an unreadable sub-issue parent makes the run INCOMPLETE, the gap named, the held card printed without --why', [pr.complete, pr.incomplete[0], nums(pr.held), renderText(pr).includes('no triage audit (parent unreadable — unjudged, held)')], [false, `#${orphan.number}'s sub-issue parent could not be read`, [orphan.number], true]); + const quietRun = await run({ issues: [many[0]], comments }, { why: false }); + t('a complete run prints no held block', [quietRun.complete, renderText(quietRun).includes('Held by a read')], [true, false]); + } + + battery('the CLI: usage, exits and the footer'); + { + t('--order is required', Boolean(parseArgs([]).error), true); + t('a malformed --order item is refused', Boolean(parseArgs(['--order', 'ux']).error), true); + t('a malformed --seat is refused', Boolean(parseArgs(['--order', 'area:ux', '--seat', 'five']).error), true); + t('an unknown flag is refused, never ignored', Boolean(parseArgs(['--order', 'area:ux', '--lane', 'x']).error), true); + t('both spellings of an option are read', [parseArgs(['--order=area:ux', '--limit=2']).opts.limit, parseArgs(['--order', 'epic:#7']).opts.order[0].number], [2, 7]); + t('--order as the last argument with no value is a usage error; --order "" is the p0/p1-only order', [Boolean(parseArgs(['--order']).error), parseArgs(['--order', '']).opts?.order], [true, []]); + t('--seat reads every lane a seat signature carries, an epic seat\'s epic:#N included', [parseSeat('epic:#35205#1')?.name, parseSeat('domain:ui#2')?.name, parseSeat('area:ux#1'), parseSeat('repo:objectstack#5 x')], ['epic:#35205#1', 'domain:ui#2', null, null]); + t('⭐ the footer names lane ownership and the sub-epic an area item holds, beside the five legs it named before', [UNREAD_LEGS.length, UNREAD_LEGS.some((l) => l.startsWith('lane ownership — ')), UNREAD_LEGS.some((l) => l.startsWith('an area item that holds a sub-epic — '))], [7, true, true]); + const c = card(['area:ux', 'priority:p2', 'domain:ui']); + const ok = await quiet(main)(['--order', 'area:ux'], { get: fixtureGet({ issues: [c], comments: { [c.number]: [] } }, REPO), nowMs: NOW }); + t('a complete run exits 0', ok.code, EXIT_OK); + t('⭐ each row prints its domain:* label, so the seat reads lane ownership off the row', ok.out.includes(`#${c.number} · p2 · area:ux · domain:ui · `), true); + t('⭐ every run names the legs it cannot read', UNREAD_LEGS.every((l) => ok.out.includes(l)), true); + const down = await quiet(main)(['--order', 'area:ux'], { get: () => ({ ok: false, error: 'HTTP 403' }) }); + t('an unread queue exits 3, a usage error 2', [down.code, (await quiet(main)(['--bogus'])).code], [EXIT_PREREQUISITE, EXIT_USAGE]); + } + + 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(`✗ card-pick 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(`✓ card-pick 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')) { + selfTest().then((code) => { + if (!selfTestReachedVerdict) { + console.error('\n✗ card-pick 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 { + main(argv).then((code) => process.exit(code)); + } +} diff --git a/scripts/pm/check-prior-rulings.mjs b/scripts/pm/check-prior-rulings.mjs index dd3d165e4fc..3d09c88f943 100644 --- a/scripts/pm/check-prior-rulings.mjs +++ b/scripts/pm/check-prior-rulings.mjs @@ -10,6 +10,8 @@ * node scripts/pm/check-prior-rulings.mjs --card 16934 --terms single,posture,tenant * node scripts/pm/check-prior-rulings.mjs --terms single,posture,tenant * node scripts/pm/check-prior-rulings.mjs --card 16934 --json + * node scripts/pm/check-prior-rulings.mjs --card 16934 --paths 'scripts/pm/**,packages/core/src/x.ts' + * node scripts/pm/check-prior-rulings.mjs --paths 'scripts/pm/**' * node scripts/pm/check-prior-rulings.mjs --self-test * * `--card` reads the card AND its comment thread from the board (a token, and @@ -28,6 +30,43 @@ * output saying so. The thread corpus is the one corpus that lives on the * board, and it is read from the same board the card is. * + * `--paths` adds the PRE-DISPATCH PREMISE READINGS over a declared file surface + * (pm-dispatch `references/execution-duties.md`'s ruling-area and staleness + * steps, which a seat typed as three command families per candidate card): + * + * ① the surface ruling grep — `SURFACE_RULING_PATTERNS` (`ruling`, + * `Ruling-ref`, `maintainer`, `⛔`) over the paths at the revision, each + * hit `file:line`, the count per pattern, and per file the READING OWED + * (`READING_OWED`): whether a hit cites a ruling is a reading of the hit, + * so ⛔ this file never classifies it and never prints the count outcome. + * A ruling is as often cited by name, date or card number (`ruling A′, + * 2026-09-13`, `ruling A+, #31491`) as by an id, so an id-shape match + * (`ID_SHAPE_HINT_RE`) is printed as a hint only. The one verdict printed + * is 「零命中 → 无裁决」, and only when every declared path matched a file + * at the revision: a path that matched none is named and the clean verdict + * withheld, because zero files read is not zero hits. A word whose hits + * pass `SURFACE_HIT_NAME_CAP` names the rest by count and prints the exact + * `git grep` that lists them; + * ② the action face — `git log -20` on the paths, and the same-day churn + * line verbatim (`SAME_DAY_LINE`, pinned to `dispatch-runbook.md`) when one + * of them is dated today (UTC); + * ③ the card-ref face — every `#N` / `owner/repo#N` the card body and its + * thread name (needs `--card`; without it the face says `not read`, ⛔ + * never `none`), scoped to the swept repository: a ref in it is read NOW + * for its state, merge, assignees and title; a ref in another repository + * of the same owner is read for open/closed and assignees only, no title; + * a ref outside that owner is listed by number only and never fetched; an + * `owner/repo` that is not a plain name (`.`, `..`, anything else outside + * `isPlainRepoName`) is rejected and never fetched; + * ④ the faces this file does NOT read, named under every run (`UNREAD_FACES`): + * the work-item face, a GitHub URL in the card or thread (listed by number), + * and a card a ruling hit in the tree names (listed by number, not followed). + * + * `--paths` alone runs ① and ② and skips the term search; with `--card` or + * `--terms` the term search runs as before and the readings follow it. A git + * read that fails is exit 3; a ref whose row cannot be read is `unresolved` on + * its row and the run exits 3 — never a state it did not read. + * * ## Why this file exists at all * * `references/lanes/director.md:45` already prescribes the search, in as many @@ -915,6 +954,290 @@ export function search({ terms, adrUnits, agentsLines, docblocks, top = DEFAULT_ }; } +// --------------------------------------------------------------------------- +// Premise readings — `--paths` (execution-duties.md's ruling-area and staleness steps) +// --------------------------------------------------------------------------- + +/** The words the ruling-area step greps a declared surface for, exactly as the rule spells them. */ +export const SURFACE_RULING_PATTERNS = Object.freeze(['ruling', 'Ruling-ref', 'maintainer', '⛔']); +/** + * An id SHAPE on a hit line: `ADR-NNN` or a 9 to 11 digit record id. ⚠ A HINT, never the classifier. A ruling is + * as often cited by name, date or card number (`ruling A′, 2026-09-13`, `ruling A+, #31491`), which carries no id + * shape, and a line that carries one may cite no ruling at all. Whether a hit cites a ruling is the seat's reading. + */ +export const ID_SHAPE_HINT_RE = /\bADR-\d{3,4}\b|\b\d{9,11}\b/u; +/** How many hits per pattern the report names before it counts the rest and prints the grep that lists them. */ +export const SURFACE_HIT_NAME_CAP = 12; +export const LOG_DEPTH = 20; +/** How many card refs one run reads; the rest are counted as not read, ⛔ never as clean. */ +export const MAX_REF_READS = 60; +export const ZERO_HIT_VERDICT = '零命中 → 无裁决'; +/** The reading every hit is owed. ⛔ This file prints it and never its outcome: the seat reads the hit. */ +export const READING_OWED = '逐行读:引裁决 ⇒ id+原句入裁决区;不引 ⇒ 计数'; +/** `dispatch-runbook.md`'s same-day churn line, verbatim — the self-test pins it present there. */ +export const SAME_DAY_LINE = '基于合并后的代码工作,issue 引用的片段可能已变,先核对当前 main。'; +export const SAME_DAY_RULE_PATH = '.claude/skills/pm-dispatch/references/dispatch-runbook.md'; +export const PREMISE_RULE_PATH = '.claude/skills/pm-dispatch/references/execution-duties.md'; +export const PREMISE_RULE_PHRASES = Object.freeze([ + '`check-prior-rulings.mjs --card --paths <面>`', + '零命中才写无裁决,命中无裁决写命中数', +]); +/** The premise faces this file does not read, printed under every `--paths` run so an absent face never reads as clean. */ +export const UNREAD_FACES = Object.freeze([ + 'the work-item face (工作项面): each work item the card, a ruling or a triage comment lists, checked against the tree', + 'a GitHub URL in the card or its thread: listed by number below, never read', + 'a card a ruling hit in the tree names: listed by number below, never followed', +]); + +/** A declared path as a git pathspec: `**` needs the glob magic; one already carrying magic is left alone. Pure. */ +export function pathspecOf(path) { + const p = String(path).trim(); + return p.startsWith(':') ? p : `:(glob)${p}`; +} + +/** `--paths a,b` split, empties dropped. Pure. */ +export function parsePaths(text) { + return String(text ?? '').split(',').map((s) => s.trim()).filter(Boolean); +} + +/** One argument quoted for a POSIX shell, so a printed command can be pasted as it stands. Pure. */ +export function shellQuote(s) { + const v = String(s); + return /^[A-Za-z0-9_./:@=-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`; +} + +/** The exact `git grep` that lists every hit of one word over the paths. Pure. */ +export function grepCommandOf(pat, rev, specs) { + return ['git', 'grep', '-n', '-I', '-F', '-e', pat, rev, '--', ...specs].map(shellQuote).join(' '); +} + +/** + * `git grep -n` output at a revision (`REV:file:line:text`) as hits. Pure. + * The revision prefix is stripped by its known length, so a `:` inside a path or a line survives. + */ +export function parseGrepAtRev(out, rev) { + const hits = []; + for (const raw of String(out ?? '').split('\n')) { + if (!raw) continue; + const rest = raw.startsWith(`${rev}:`) ? raw.slice(rev.length + 1) : raw; + const m = /^(.*?):(\d+):(.*)$/.exec(rest); + if (m) hits.push({ file: m[1], line: Number(m[2]), text: m[3] }); + } + return hits; +} + +/** + * The ruling-area reading from the hits. Pure. + * ⛔ It never classifies a hit as citing a ruling or not, and never states the count outcome: every hit line is + * listed under the reading it is owed (`READING_OWED`), grouped by file, an id-shape match flagged as a hint. The + * one verdict is `ZERO_HIT_VERDICT`, withheld while a declared path matched no file (`unmatchedPaths`). + */ +export function surfaceVerdict(byPattern, unmatchedPaths = []) { + const lines = new Map(); + for (const [pat, hits] of Object.entries(byPattern)) { + for (const h of hits) { + const key = `${h.file}:${h.line}`; + const seen = lines.get(key) ?? { ...h, words: [], hint: ID_SHAPE_HINT_RE.test(h.text) }; + seen.words.push(pat); + lines.set(key, seen); + } + } + const all = [...lines.values()]; + const byFile = new Map(); + for (const h of all) byFile.set(h.file, [...(byFile.get(h.file) ?? []), h]); + const files = [...byFile].map(([file, hits]) => ({ file, hits: hits.sort((a, b) => a.line - b.line) })); + const hinted = all.filter((h) => h.hint); + const unread = unmatchedPaths.length + ? `${unmatchedPaths.length} declared path(s) matched no file at the revision (${unmatchedPaths.join(', ')}) — not read; correct or drop them and re-run` + : ''; + if (all.length === 0) { + if (unread) return { lines: 0, files, hinted, clean: false, text: `零命中 on the paths that matched, ⛔ 无裁决 WITHHELD: ${unread}` }; + return { lines: 0, files, hinted, clean: true, text: ZERO_HIT_VERDICT }; + } + const hint = hinted.length + ? `; an id shape (ADR-NNN or a record id) is on ${hinted.length} of them — a hint, ⛔ not the reading` + : '; none carries an id shape, which says nothing: a ruling cited by name, date or card number has none'; + return { + lines: all.length, + files, + hinted, + clean: false, + text: `${all.length} hit line(s) in ${files.length} file(s), each owed the reading, no verdict drawn here: ${READING_OWED}${hint}${unread ? `; and ${unread}` : ''}`, + }; +} + +/** `git log --format=%h%x09%cI%x09%s` lines, and which were committed on `todayUtc` (YYYY-MM-DD, UTC). Pure. */ +export function parseLog(out, todayUtc) { + const commits = String(out ?? '') + .split('\n') + .filter(Boolean) + .map((l) => { + const [sha, at, ...subject] = l.split('\t'); + const ms = Date.parse(at); + return { sha, at, day: Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 10) : null, subject: subject.join('\t') }; + }); + return { commits, sameDay: commits.filter((c) => c.day === todayUtc) }; +} + +const OWNER_NAME_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/u; +const REPO_NAME_RE = /^(?!\.+$)[A-Za-z0-9_.-]+$/u; + +/** `owner/repo` as two plain names: an account name, and a repo name that is not dot-only (`.`, `..`). Pure. */ +export function isPlainRepoName(text) { + const parts = String(text ?? '').split('/'); + return parts.length === 2 && OWNER_NAME_RE.test(parts[0]) && REPO_NAME_RE.test(parts[1]); +} + +const ownerOf = (repo) => String(repo).split('/')[0].toLowerCase(); + +/** + * Every issue or PR a card's body and thread name, in order, deduplicated, the card itself left out. A bare `#N` + * must not touch a word character on its left, so a seat signature's `LANE#N` and a `repo:x#5` name nothing. Each + * ref carries its scope against the swept repository: `local` (that repository), `sameOwner` (another repository of + * its owner), `foreign` (any other owner) or `rejected` (an `owner/repo` that is not two plain names). Pure. + */ +export function cardRefs(texts, repo, self) { + const out = []; + const seen = new Set(); + const re = /(? a - b); +} + +/** One issue row as the card-ref face prints it. Pure. */ +export function refStateOf(row) { + const pr = row?.pull_request != null; + const merged = pr && Boolean(row.pull_request.merged_at); + const state = row?.state === 'closed' ? (pr ? (merged ? 'merged' : 'closed unmerged') : 'closed') : 'open'; + const who = (row?.assignees ?? []).map((a) => a?.login).filter(Boolean); + return { kind: pr ? 'PR' : 'issue', state, assignees: who, title: row?.title ?? '' }; +} + +/** + * The readings. `git` and `getRow` are injected so the self-test drives every branch offline: + * `git(args)` returns stdout or throws (an exit 1 from `git grep` is "no match" and must be passed as `''`); + * `getRow(ref)` answers `{ ok, row }`, `{ ok: false, notFound: true }` or `{ ok: false, error }`, and is called + * only for a `local` or `sameOwner` ref. + */ +export async function premiseReadings({ paths, rev, todayUtc, card = null, thread = null, repo, git: gitImpl, getRow }) { + const specs = paths.map(pathspecOf); + const emptyTree = gitImpl(['hash-object', '-t', 'tree', '/dev/null']).trim(); + const unmatchedPaths = paths.filter((p) => gitImpl(['diff', '--no-renames', '--name-only', emptyTree, rev, '--', pathspecOf(p)]).trim() === ''); + const byPattern = {}; + for (const pat of SURFACE_RULING_PATTERNS) { + byPattern[pat] = parseGrepAtRev(gitImpl(['grep', '-n', '-I', '-F', '-e', pat, rev, '--', ...specs]), rev); + } + const verdict = surfaceVerdict(byPattern, unmatchedPaths); + const log = parseLog(gitImpl(['log', `-${LOG_DEPTH}`, '--format=%h%x09%cI%x09%s', rev, '--', ...specs]), todayUtc); + const texts = card ? [card.body, ...(thread?.comments ?? []).map((c) => c.body)] : []; + const unreadFaces = { urlRefs: card ? urlRefNumbers(texts) : null, hitRefs: hitRefNumbers(byPattern) }; + let refs = null; + if (card) { + const found = cardRefs(texts, repo, card.number); + const toRead = found.filter((r) => r.scope === 'local' || r.scope === 'sameOwner'); + refs = { total: found.length, rows: [], notRead: Math.max(0, toRead.length - MAX_REF_READS), unresolved: 0 }; + const reading = new Set(toRead.slice(0, MAX_REF_READS).map((r) => r.key)); + for (const ref of found) { + if (ref.scope === 'rejected') { + refs.rows.push({ ...ref, kind: '-', state: 'rejected — not a plain owner/repo name; not read', assignees: [], title: '' }); + continue; + } + if (ref.scope === 'foreign') { + refs.rows.push({ ...ref, kind: '-', state: 'outside the swept repository\'s owner — listed by number, not read', assignees: [], title: '' }); + continue; + } + if (!reading.has(ref.key)) continue; + const r = await getRow(ref); + if (r.ok) { + const s = refStateOf(r.row); + refs.rows.push(ref.scope === 'local' + ? { ...ref, ...s } + : { ...ref, kind: '-', state: s.state === 'open' ? 'open' : 'closed', assignees: s.assignees, title: '' }); + } else if (r.notFound) refs.rows.push({ ...ref, kind: '-', state: 'no such issue (404)', assignees: [], title: '' }); + else { + refs.unresolved += 1; + refs.rows.push({ ...ref, kind: '-', state: `unresolved (${r.error})`, assignees: [], title: '' }); + } + } + } + return { paths, specs, rev, todayUtc, byPattern, unmatchedPaths, verdict, log, refs, unreadFaces }; +} + +/** How the card-ref face names a ref: in full inside the swept repository's owner, by number only outside it. */ +const refName = (r) => (r.scope === 'local' ? `#${r.number}` : r.scope === 'sameOwner' ? r.key : `#${r.number}`); + +export function renderPremise(p) { + const L = []; + const specs = p.specs ?? p.paths.map(pathspecOf); + L.push(` Premise readings (--paths ${p.paths.join(',')}) at ${p.rev}:`); + L.push(` ① surface ruling grep — ${SURFACE_RULING_PATTERNS.map((pat) => `\`${pat}\` ${p.byPattern[pat].length}`).join(' · ')}`); + for (const path of p.unmatchedPaths ?? []) L.push(` ⚠️ declared path \`${path}\` matched NO file at ${p.rev} — nothing under it was read`); + for (const pat of SURFACE_RULING_PATTERNS) { + const hits = p.byPattern[pat]; + for (const h of hits.slice(0, SURFACE_HIT_NAME_CAP)) { + L.push(` [${pat}] ${h.file}:${h.line} ${truncate(h.text, 96)}${ID_SHAPE_HINT_RE.test(h.text) ? ' (id-shape hint)' : ''}`); + } + if (hits.length > SURFACE_HIT_NAME_CAP) { + L.push(` [${pat}] +${hits.length - SURFACE_HIT_NAME_CAP} more, owed the same reading — list them all: ${grepCommandOf(pat, p.rev, specs)}`); + } + } + for (const f of p.verdict.files) L.push(` read ${f.file} — ${f.hits.length} hit line(s): ${READING_OWED}`); + L.push(` reading: ${p.verdict.text}`); + L.push(` ② action face — git log -${LOG_DEPTH} -- the paths: ${p.log.commits.length} commit(s)`); + for (const c of p.log.commits) L.push(` ${c.sha} ${c.at.slice(0, 16)} ${truncate(c.subject, 90)}`); + if (p.log.sameDay.length > 0) { + L.push(` same-day churn (${p.todayUtc} UTC): ${p.log.sameDay.map((c) => c.sha).join(', ')} — paste this line:`); + L.push(` ${SAME_DAY_LINE}`); + } else L.push(` same-day churn (${p.todayUtc} UTC): none on these paths — no line owed`); + if (p.refs === null) L.push(' ③ card-ref face: not read — no --card names a card; ⛔ not `none`'); + else { + L.push(` ③ card-ref face — ${p.refs.total} ref(s) named by the body and thread, read now (cite the state, ⛔ never an old account):`); + for (const r of p.refs.rows) { + const who = r.assignees.length ? ` · assignee ${r.assignees.join(', ')}` : r.state === 'open' ? ' · unassigned' : ''; + L.push(` ${refName(r)} ${r.kind === '-' ? '' : `${r.kind} `}${r.state}${who}${r.title ? ` — ${truncate(r.title, 70)}` : ''}`); + } + if (p.refs.notRead > 0) L.push(` +${p.refs.notRead} ref(s) NOT read (cap ${MAX_REF_READS}) — read them by hand`); + if (p.refs.unresolved > 0) L.push(` ⚠️ ${p.refs.unresolved} ref(s) unresolved — their state was NOT read; exit ${EXIT_PREREQUISITE_NOT_MET}`); + } + L.push(' ④ not read by this reader — the seat reads these itself (⛔ an absent face is not a clean one):'); + for (const face of UNREAD_FACES) L.push(` · ${face}`); + const u = p.unreadFaces ?? { urlRefs: null, hitRefs: [] }; + L.push(` URL refs: ${u.urlRefs === null ? 'not looked for — no --card' : u.urlRefs.length ? u.urlRefs.map((n) => `#${n}`).join(', ') : 'none in the card or thread'}`); + L.push(` refs on ruling-hit lines: ${u.hitRefs.length ? u.hitRefs.map((n) => `#${n}`).join(', ') : 'none'}`); + return L.join('\n'); +} + // --------------------------------------------------------------------------- // Card read — ONE request, no retry loop // --------------------------------------------------------------------------- @@ -1022,6 +1345,26 @@ export async function readThread(number, repo, env, fetchImpl = fetch) { return { verdict: classifyCardRead({ hasToken: true, status: 200, what }), thread: { comments, pages, bytes, ms } }; } +/** + * One ref's row for the card-ref face: a single GET in the ref's own repo, no retry (see `classifyCardRead`). + * `premiseReadings` asks only for a ref inside the swept repository's owner; the name is checked again here, so a + * ref that is not two plain names never becomes a request path whatever the caller passes. + */ +export async function readRefRow(ref, env, fetchImpl = fetch) { + if (!isPlainRepoName(ref?.repo) || !Number.isSafeInteger(ref?.number)) return { ok: false, error: 'not a plain owner/repo#N' }; + const token = env.GITHUB_TOKEN || env.GH_TOKEN || ''; + if (!token) return { ok: false, error: 'no token' }; + let res; + try { + res = await fetchImpl(`https://api.github.com/repos/${ref.repo}/issues/${ref.number}`, { headers: boardHeaders(token) }); + } catch (err) { + return { ok: false, error: err?.message ?? 'network' }; + } + if (res.status === 404) return { ok: false, notFound: true }; + if (res.status !== 200) return { ok: false, error: `HTTP ${res.status}` }; + return { ok: true, row: await res.json() }; +} + // --------------------------------------------------------------------------- // Report // --------------------------------------------------------------------------- @@ -1158,7 +1501,7 @@ export function reportPrerequisiteNotMet(verdict, extra = [], corpusRepo = null) // --------------------------------------------------------------------------- export function parseArgs(argv) { - const opts = { card: null, terms: null, rev: DEFAULT_REV, top: DEFAULT_TOP, json: false }; + const opts = { card: null, terms: null, paths: null, rev: DEFAULT_REV, top: DEFAULT_TOP, json: false }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === '--self-test') continue; @@ -1177,6 +1520,12 @@ export function parseArgs(argv) { if (opts.terms.length === 0) return { error: '--terms wants at least one term' }; continue; } + if (a === '--paths') { + const v = take(); + opts.paths = parsePaths(v); + if (opts.paths.length === 0) return { error: '--paths wants a comma-separated list of the declared file surface' }; + continue; + } if (a === '--rev') { const v = take(); if (!v) return { error: '--rev wants a revision' }; @@ -1191,8 +1540,8 @@ export function parseArgs(argv) { } return { error: `unknown argument ${JSON.stringify(a)}` }; } - if (opts.card === null && opts.terms === null) { - return { error: 'nothing to search for — pass --card , or --terms a,b,c' }; + if (opts.card === null && opts.terms === null && opts.paths === null) { + return { error: 'nothing to search for — pass --card , --terms a,b,c, or --paths a/**,b.ts' }; } return { opts }; } @@ -1264,7 +1613,51 @@ async function run(argv) { ' cheapest ruling lives, and the one this corpus was added for.', ], corpusRepo); } - thread = { ...readThreadRulings(th.thread.comments), pages: th.thread.pages, bytes: th.thread.bytes, ms: th.thread.ms }; + thread = { ...readThreadRulings(th.thread.comments), pages: th.thread.pages, bytes: th.thread.bytes, ms: th.thread.ms, commentRows: th.thread.comments }; + } + + // The premise readings (`--paths`), taken before the term search so a git + // failure here is exit 3 with nothing searched, like every refusal above. + let premise = null; + if (opts.paths !== null) { + const premiseGit = (args) => { + try { + return git(args); + } catch (err) { + if (args[0] === 'grep' && err?.status === 1) return ''; + throw err; + } + }; + try { + premise = await premiseReadings({ + paths: opts.paths, + rev: opts.rev, + todayUtc: new Date().toISOString().slice(0, 10), + card, + thread: card ? { comments: thread?.commentRows ?? [] } : null, + repo: sweep.repo, + git: premiseGit, + getRow: (ref) => readRefRow(ref, process.env), + }); + premise.shallow = git(['rev-parse', '--is-shallow-repository']).trim() === 'true'; + } catch (err) { + return reportPrerequisiteNotMet( + { kind: 'premise-git', headline: `the premise readings could not read git at ${opts.rev} (${err?.message ?? 'unknown'})` }, + [], + corpusRepo, + ); + } + } + const premiseExit = premise?.refs?.unresolved > 0 ? EXIT_PREREQUISITE_NOT_MET : EXIT_OK; + const premiseText = () => { + if (!premise) return ''; + const text = renderPremise(premise); + return premise.shallow ? `${text}\n ⚠️ shallow checkout: the log above may stop short of ${LOG_DEPTH} — deepen before reading it as complete` : text; + }; + if (premise && opts.card === null && opts.terms === null) { + if (opts.json) console.log(JSON.stringify({ rev: opts.rev, tip, corpusRepo, premise }, null, 2)); + else console.log(`check-prior-rulings: ${corpusRepo ?? 'an unresolved repo'} at ${opts.rev} (${tip})\n\n${premiseText()}\n\n Report-only: this file writes nothing and decides nothing.`); + return premiseExit; } const built = buildTermSet({ title: card?.title ?? '', body: card?.body ?? '', override: opts.terms }); @@ -1320,11 +1713,13 @@ async function run(argv) { })), accepted: result.accepted, pasteLine: result.pasteLine, + premise, }, null, 2)); } else { console.log(renderReport(result, meta)); + if (premise) console.log(`\n${premiseText()}`); } - return EXIT_OK; + return premiseExit; } // --------------------------------------------------------------------------- @@ -1680,6 +2075,85 @@ export async function selfTest() { t('…and having re-armed once, does not loop', proxyRearmPlan({ env: { HTTPS_PROXY: 'http://127.0.0.1:1', [PROXY_REARM_GUARD]: '1' }, flagSupported: true }).rearm, false); t('an unproxied environment plans nothing', proxyRearmPlan({ env: {}, flagSupported: true }).rearm, false); + // ---- premise readings: --paths (execution-duties.md's ruling-area and staleness steps) ---- + { + const J = (v) => JSON.stringify(v); + const ROOT = new URL('../../', import.meta.url); + t('--paths: the ruling-area rule still names this command and its verdict words (a reworded rule reds here)', PREMISE_RULE_PHRASES.every((ph) => readFileSync(new URL(PREMISE_RULE_PATH, ROOT), 'utf8').includes(ph)), true); + t('--paths: the same-day churn line is dispatch-runbook.md\'s, verbatim', readFileSync(new URL(SAME_DAY_RULE_PATH, ROOT), 'utf8').includes(`该行原文:${SAME_DAY_LINE}`), true); + t('--paths: the grep words are the rule\'s four', SURFACE_RULING_PATTERNS.join(' '), 'ruling Ruling-ref maintainer ⛔'); + t('--paths: a ** path becomes a glob pathspec; one carrying magic is left alone', J([pathspecOf('scripts/pm/**'), pathspecOf(':(top)x.ts')]), J([':(glob)scripts/pm/**', ':(top)x.ts'])); + t('--paths: a grep line at a revision keeps a colon inside the text', J(parseGrepAtRev('origin/main:a/b.ts:12:x: ruling 6181973363\n', 'origin/main')), J([{ file: 'a/b.ts', line: 12, text: 'x: ruling 6181973363' }])); + t('--paths: ⭐ zero hits over paths that all matched read 零命中 → 无裁决', J([surfaceVerdict({ ruling: [], '⛔': [] }).text, surfaceVerdict({ ruling: [] }).clean]), J([ZERO_HIT_VERDICT, true])); + + // ⭐ The rule's own worked example: `screen-input-contract.ts` cites its rulings by name, date and card number, + // never by an id shape. Every such hit is listed for the seat's reading and none gets a count verdict. + const sic = 'packages/x/src/screen-input-contract.ts'; + const sicHits = { + ruling: [ + { file: sic, line: 67, text: '// ruling A+, #31491 — the screen keeps its declared inputs' }, + { file: sic, line: 164, text: '// ruling A′, 2026-09-13: an undeclared input is refused at save' }, + ], + maintainer: [{ file: sic, line: 164, text: '// ruling A′, 2026-09-13: an undeclared input is refused at save' }], + }; + const sicVerdict = surfaceVerdict(sicHits); + t('--paths: ⭐ hits citing a ruling by name, date or card number get NO count verdict and no 无裁决 (the reader never classifies a hit)', J([sicVerdict.text.includes('写命中数'), sicVerdict.text.includes('无裁决'), sicVerdict.clean, sicVerdict.text.includes(READING_OWED)]), J([false, false, false, true])); + t('--paths: a line two words hit is one hit line, and both lines sit under their file for reading', J([sicVerdict.lines, sicVerdict.files.map((f) => [f.file, f.hits.map((h) => h.line)])]), J([2, [[sic, [67, 164]]]])); + const sicText = renderPremise({ paths: ['packages/x/**'], rev: 'origin/main', todayUtc: '2000-01-01', byPattern: { ...sicHits, 'Ruling-ref': [], '⛔': [] }, unmatchedPaths: [], verdict: sicVerdict, log: { commits: [], sameDay: [] }, refs: null }); + t('--paths: ⭐ the render lists every hit line and prints the reading owed per file, never 写命中数', J([sicText.includes(`${sic}:67`), sicText.includes(`${sic}:164`), sicText.includes(`read ${sic} — 2 hit line(s): ${READING_OWED}`), sicText.includes('写命中数')]), J([true, true, true, false])); + const h = (line, text) => ({ file: 'a.ts', line, text }); + const hinted = surfaceVerdict({ ruling: [h(1, 'ruling record 6181973363'), h(2, 'ruling')], '⛔': [h(3, '⛔ ADR-0131 D8')] }); + t('--paths: an id shape is a HINT on its line, the reading owed is the same for every hit', J([hinted.hinted.length, hinted.text.includes(READING_OWED), 'cited' in hinted]), J([2, true, false])); + const log = parseLog('abc1234\t2026-11-19T10:03:00+00:00\tfeat: today\ndef5678\t2026-11-19T07:00:00+08:00\tfix: yesterday in UTC\n', '2026-11-19'); + t('--paths: ⭐ same-day is the UTC day of the commit, an offset date converted', J(log.sameDay.map((c) => c.sha)), J(['abc1234'])); + + // A declared path that matches no file: zero files read is not zero hits. + const unmatched = surfaceVerdict({ ruling: [] }, ['scripts/pmm/**']); + t('--paths: ⭐ a declared path that matched no file withholds 零命中 → 无裁决 and names the path', J([unmatched.clean, unmatched.text === ZERO_HIT_VERDICT, unmatched.text.includes('WITHHELD'), unmatched.text.includes('scripts/pmm/**')]), J([false, false, true, true])); + + const asked = []; + const fakeGit = (args) => { + asked.push(args); + if (args[0] === 'hash-object') return 'EMPTYTREE\n'; + if (args[0] === 'diff') return args.at(-1) === ':(glob)gone/**' ? '' : 'x/a.ts\n'; + if (args[0] === 'grep') return args[5] === 'ruling' ? 'origin/main:x.ts:3:a ruling (#31491)\n' : ''; + return 'abc1234\t2026-11-19T10:03:00Z\tfeat: today\n'; + }; + const fetched = []; + const rows = { + 'o/r#12': { ok: true, row: { state: 'open', assignees: [], title: 'local title' } }, + 'o/r#13': { ok: false, notFound: true }, + 'o/r#14': { ok: false, error: 'HTTP 502' }, + 'o/sib#15': { ok: true, row: { state: 'closed', pull_request: { merged_at: 'x' }, assignees: [{ login: 'os-bill' }], title: 'sibling title' } }, + }; + const card = { number: 500, body: 'needs #12 and #13, o/sib#15, evil/x#3, ../x#1 and https://github.com/evil/x/issues/77' }; + const pr = await premiseReadings({ paths: ['x/**', 'gone/**'], rev: 'origin/main', todayUtc: '2026-11-19', card, thread: { comments: [{ body: 'and #14' }] }, repo: 'o/r', git: fakeGit, getRow: (ref) => (fetched.push(ref.key), rows[ref.key]) }); + t('--paths: ⭐ the unmatched path is found against the revision\'s tree and its clean verdict withheld, the matched one is not named', J([pr.unmatchedPaths, pr.verdict.clean]), J([['gone/**'], false])); + t('--paths: every word is grepped fixed-string over the glob pathspecs at the revision', J(asked.filter((a) => a[0] === 'grep').map((a) => [a[4], a[5], a.at(-1)])), J(SURFACE_RULING_PATTERNS.map((w) => ['-e', w, ':(glob)gone/**']))); + t('--paths: the log is -20 at the revision on the same paths', J(asked.find((a) => a[0] === 'log').slice(0, 2).concat(asked.find((a) => a[0] === 'log').slice(-2))), J(['log', '-20', ':(glob)x/**', ':(glob)gone/**'])); + const text = renderPremise(pr); + t('--paths: the render names the path that matched no file', text.includes('declared path `gone/**` matched NO file'), true); + t('--paths: the same-day line is printed verbatim when one commit is today', text.includes(SAME_DAY_LINE), true); + t('--paths: refs read from the body AND the thread; a 404 is a reading, an unreadable row is unresolved', J([pr.refs.rows.filter((r) => r.scope === 'local').map((r) => r.state), pr.refs.unresolved]), J([['open', 'no such issue (404)', 'unresolved (HTTP 502)'], 1])); + t('--paths: ⭐ a ref outside the swept repository\'s owner is never fetched and is listed by number only', J([fetched.includes('evil/x#3'), pr.refs.rows.find((r) => r.number === 3)?.scope, text.includes('evil/x')]), J([false, 'foreign', false])); + t('--paths: ⭐ a `../x#1` ref is rejected and never fetched', J([pr.refs.rows.find((r) => r.number === 1)?.scope, fetched.some((k) => k.includes('..'))]), J(['rejected', false])); + t('--paths: a ref in another repository of the same owner is read for open/closed and assignees only, no title', J([fetched.includes('o/sib#15'), pr.refs.rows.find((r) => r.number === 15)?.state, text.includes('sibling title'), text.includes('local title')]), J([true, 'closed', false, true])); + t('--paths: a plain owner/repo name is two plain names, never a dot-only segment', J(['o/.github', '../x', './x', 'o/..', 'o/.', 'o/r/x', 'a b/c'].map(isPlainRepoName)), J([true, false, false, false, false, false, false])); + const calls = []; + const refused = await readRefRow({ repo: '..', number: 1 }, { GITHUB_TOKEN: 't' }, (u) => (calls.push(u), Promise.reject(new Error('never')))); + t('--paths: readRefRow refuses a name that is not plain without a request', J([refused.ok, calls.length]), J([false, 0])); + t('--paths: ⭐ the unread faces are named under the run, URL refs and refs on ruling-hit lines by number', J([UNREAD_FACES.every((f) => text.includes(f)), text.includes('URL refs: #77'), text.includes('refs on ruling-hit lines: #31491')]), J([true, true, true])); + t('--paths: card refs — a signature\'s LANE#N names nothing, dedup, scope per ref, the card itself out', J(cardRefs(['repo:objectstack#5 · os-bill · session_01ABCDEF\nsee #12 and #12, epic:#35205#1, objectstack-ai/cloud#7, PR #99 and #500 itself'], 'objectstack-ai/objectstack', 500).map((r) => [r.key, r.scope])), J([['objectstack-ai/objectstack#12', 'local'], ['objectstack-ai/objectstack#35205', 'local'], ['objectstack-ai/cloud#7', 'sameOwner'], ['objectstack-ai/objectstack#99', 'local']])); + t('--paths: a PR is read as merged, closed unmerged or open; an issue names its assignees', J([refStateOf({ state: 'closed', pull_request: { merged_at: 'x' } }).state, refStateOf({ state: 'closed', pull_request: { merged_at: null } }).state, refStateOf({ state: 'open', assignees: [{ login: 'os-bill' }] }).assignees]), J(['merged', 'closed unmerged', ['os-bill']])); + const cap = Array.from({ length: SURFACE_HIT_NAME_CAP + 3 }, (_, k) => h(k + 1, 'a ruling')); + const capText = renderPremise({ paths: ['a/**'], rev: 'origin/main', todayUtc: '2000-01-01', byPattern: { ruling: cap, 'Ruling-ref': [], maintainer: [], '⛔': [] }, unmatchedPaths: [], verdict: surfaceVerdict({ ruling: cap }), log: { commits: [], sameDay: [] }, refs: null }); + t('--paths: past the per-word cap the rest are counted and the exact git grep that lists them is printed', capText.includes(`[ruling] +3 more, owed the same reading — list them all: git grep -n -I -F -e ruling origin/main -- ':(glob)a/**'`), true); + const noCard = await premiseReadings({ paths: ['x'], rev: 'origin/main', todayUtc: '2000-01-01', repo: 'o/r', git: (a) => (a[0] === 'diff' ? 'x\n' : ''), getRow: () => ({ ok: false }) }); + t('--paths: without a card the ref face says not read, ⛔ never none; no hits over a matched path read 零命中', [noCard.refs, renderPremise(noCard).includes('③ card-ref face: not read'), renderPremise(noCard).includes(ZERO_HIT_VERDICT)].join('|'), '|true|true'); + t('--paths: alone is a legal run (no card, no terms)', J(parseArgs(['--paths', 'a/**,b.ts']).opts?.paths), J(['a/**', 'b.ts'])); + t('--paths: an empty list is refused', parseArgs(['--paths', ' , ']).error !== undefined, true); + } + // ---- structural: this file has no write path --------------------------- // The report-only property, held mechanically rather than promised. A `POST` // to the API from here would make it a tool that mutates the board, and the @@ -1740,7 +2214,7 @@ export async function selfTest() { 'content-line anchoring, the fixture thread with its two rulings oldest-first, `none` against ' + '`not read` against the whole-line `unresolved`, and the offline board read (paged to a short ' + 'page with bytes and ms measured, a refusal, no token, the page bound, a network failure, a ' + - 'malformed page); the THIRD (fallback) decision shape on objectui\'s real `## Decision` structure, with its empty-anchor, prose-sentence, already-carries-a-D-unit and non-ADR-path controls; the corpus repo named in BOTH arms of the paste line; the structural no-write-path, no-retry-loop and no-Link-walk assertions; and ' + + 'malformed page); the THIRD (fallback) decision shape on objectui\'s real `## Decision` structure, with its empty-anchor, prose-sentence, already-carries-a-D-unit and non-ADR-path controls; the corpus repo named in BOTH arms of the paste line; the structural no-write-path, no-retry-loop and no-Link-walk assertions; the --paths premise readings (the rule\'s four grep words, the zero-hit verdict and its withholding for a path that matched no file, every hit listed for the seat\'s reading with no count verdict on the rule\'s own worked example, the id-shape hint, the per-word cap\'s re-run grep, the UTC same-day line pinned to dispatch-runbook.md, the card-ref face scoped to the swept repository with its 404, unresolved, same-owner, foreign and rejected rows, and the unread faces); and ' + 'the one live-tree D8 existence pin).', ); return { code: EXIT_OK, verdict: SELF_TEST_VERDICT }; diff --git a/scripts/pm/os-verify-lock.sh b/scripts/pm/os-verify-lock.sh index 10318de089a..809db7b46ed 100755 --- a/scripts/pm/os-verify-lock.sh +++ b/scripts/pm/os-verify-lock.sh @@ -6,6 +6,7 @@ # scripts/pm/os-verify-lock.sh -- pnpm --filter @objectstack/core test # scripts/pm/os-verify-lock.sh --status # holder, how long it has held, the queue, # # and whether each recorded process still exists +# scripts/pm/os-verify-lock.sh --depth # arrival depth vs LOCK_DEPTH_HOLD: exit 0 go, 1 wait # scripts/pm/os-verify-lock.sh --show-budget # the acquisition budget this call would use # scripts/pm/os-verify-lock.sh --self-test # verify this script # @@ -19,7 +20,8 @@ # `--status` is the one mode with an exit code of its own: 3 means the liveness # control at the foot of its output failed, so it printed no reading at all # rather than one it cannot stand behind. It takes no lock, so 99 is not -# something it can ever mean. +# something it can ever mean. `--depth` shares that 3 and adds 0 (go) and 1 +# (wait) -- see `mode_depth`. # # A host with no usable `flock` runs in DECLARED UNLOCKED MODE (see the block # below): the command runs and its own exit code passes through, so 99 keeps @@ -2288,6 +2290,8 @@ usage: os-verify-lock.sh -c '' run it under the shared verify lock os-verify-lock.sh -- same, without a shell os-verify-lock.sh --status who holds the lock, for how long, who is queued + os-verify-lock.sh --depth arrival depth vs LOCK_DEPTH_HOLD before the next + dispatch: exit 0 go, 1 wait, 3 cannot read os-verify-lock.sh --show-budget the acquisition budget this call would use os-verify-lock.sh --report aggregate the ledger: waits, holds, queue depth, which commands own the lock-seconds, and the @@ -2617,6 +2621,78 @@ mode_status() { return 0 } +# --- depth ------------------------------------------------------------------ + +# The dispatching seat's hold: before the 2nd and every later dev of a batch, +# it waits while the arrival depth is at or above this. pm-dispatch +# `references/execution-duties.md` names the value, and the self-test holds the +# two equal. +readonly LOCK_DEPTH_HOLD=2 + +# `--depth`: the arrival depth a dispatching seat used to count by eye off +# `--status`. Depth = live `queue N:` tickets + 1, the dev about to be +# dispatched counting as an arrival; the `state:` holder and every parked slot +# are NOT counted -- the holder has arrived already and a parked place blocks +# nobody. Exit 0 go (depth below the hold), 1 wait, 3 when the liveness probe +# that decides which tickets are live is not lit, or the lock cannot operate +# on this host: ⛔ an unread depth is never read as 1. +# +# ⭐ IT COUNTS WITHOUT PRUNING. `queue_live` deletes every ticket it judges +# dead, and `--status` takes `liveness_snapshot` first for exactly that reason: +# a dev whose turn ended while waiting leaves its evidence in a dead ticket. +# This mode runs before every dispatch, so pruning here would delete that +# evidence where no seat ever reads it. It judges each ticket with the same +# `ticket_state`, leaves the dead ones in place, and names them, so the next +# `--status` still prints their liveness verdicts. +mode_depth() { + local q=0 p=0 d=0 file pid start stamp label + if ! liveness_control; then + printf '%s\n' "$LIVENESS_CONTROL_LINE" + printf 'depth: CANNOT READ — the probe that decides which tickets are live is not lit; ⛔ never read as depth 1.\n' + return "$LIVENESS_REFUSAL_EXIT" + fi + if ! preflight; then + printf 'depth: CANNOT READ — this host cannot operate the lock (`--status` names why); ⛔ never read as depth 1.\n' + return "$LIVENESS_REFUSAL_EXIT" + fi + local dead_lines='' + if [[ -d "$QUEUE_DIR" ]]; then + shopt -s nullglob + for file in "$QUEUE_DIR"/*; do + [[ -f "$file" ]] || continue + case "$(ticket_state "$file")" in + active) q=$((q + 1)) ;; + parked) p=$((p + 1)) ;; + *) + d=$((d + 1)) + pid='' + start='' + stamp='' + label='' + read -r pid start stamp label < "$file" 2> /dev/null || true + dead_lines="${dead_lines}dead ${d}: ticket ${file##*/}, pid ${pid:--} — ${label:-?}"$'\n' + ;; + esac + done + shopt -u nullglob + fi + local depth=$((q + 1)) verdict=go + ((depth >= LOCK_DEPTH_HOLD)) && verdict=wait + printf 'depth %d (queue %d + 1) · hold at %d → %s · not counted: the holder, %d parked slot(s), %d dead ticket(s)\n' \ + "$depth" "$q" "$LOCK_DEPTH_HOLD" "$verdict" "$p" "$d" + if ((d > 0)); then + printf 'dead tickets LEFT IN PLACE, not pruned — `--status` prints their liveness verdicts and then prunes them:\n' + printf '%s' "$dead_lines" + fi + if ((PREFLIGHT_NO_FLOCK == 1)); then + printf 'host: NO USABLE flock — a run here takes no ticket and runs in DECLARED UNLOCKED MODE, with no\n' + printf ' mutual exclusion, so this depth counts nothing a run on this host waits behind.\n' + printf ' · %s\n' "$PREFLIGHT_NO_FLOCK_NOTE" + fi + [[ "$verdict" == go ]] && return 0 + return 1 +} + # --- report ----------------------------------------------------------------- # Percentile of a numeric column, by sorting it. `sort -n` rather than an awk @@ -4333,6 +4409,55 @@ FAKEDATE "$(printf '%s\n' "$lvout" | grep -cE '^liveness (holder|waiter|parked)')" 0 rm -rf "$lvq" "${lvl}"* + # `--depth` — the arrival depth a dispatching seat counted by eye off + # `--status`. Driven as a CHILD against a private lock, like the liveness + # cases above, because the surface a seat runs is what is owed. + local dl dq dout drc dstart + dl="${tmp}/depth-lock" + dq="${dl}.q" + mkdir -p "$dq" + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth on an empty queue reads depth 1 (the dev about to be dispatched) and goes' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c '^depth 1 (queue 0 + 1) · hold at 2 → go')" '0|1' + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" OS_VERIFY_LOCK_FLOCK="${tmp}/no-such-flock" bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth on a host with no usable flock still reads, and discloses DECLARED UNLOCKED MODE as --status does' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c 'DECLARED UNLOCKED MODE')" '0|1' + dstart="$(proc_starttime "$$")" + printf '%s %s %s depth-holder\n' "$$" "$dstart" "$(now_s)" > "${dl}.holder" + printf '0 %s %s depth-parked\n' "$(now_s)" "$(now_s)" > "${dq}/00000000000000000001-sdepthslot" + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth counts neither the holder nor a parked slot' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c '^depth 1 (queue 0 + 1) .* 1 parked slot')" '0|1' + printf '%s %s %s depth-waiter\n' "$$" "$dstart" "$(now_s)" > "${dq}/00000000000000000002-$$" + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth counts a live waiter: depth 2 reaches the hold and exits 1 (wait)' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c '^depth 2 (queue 1 + 1) · hold at 2 → wait')" '1|1' + # ⭐ A dead ticket is the evidence a dev whose turn ended while waiting + # leaves behind. `--depth` runs before every dispatch, so it must neither + # count that ticket nor delete it: it names it and leaves it for `--status`. + local ddead="${dq}/00000000000000000003-999999" + printf '%s %s %s depth-dead-waiter\n' 999999 12345 "$(now_s)" > "$ddead" + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth does not count a dead ticket, names it, and leaves it in place' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c '^depth 2 (queue 1 + 1) .* 1 dead ticket')|$(printf '%s\n' "$dout" | grep -c '^dead 1: ticket 00000000000000000003-999999, pid 999999')|$([[ -f "$ddead" ]] && printf kept)" \ + '1|1|1|kept' + st_case '…so the next --status still prints that dead ticket'"'"'s liveness verdict' \ + "$(OS_VERIFY_LOCK_FILE="$dl" bash "$SELF" --status 2>&1 | grep -c '^liveness waiter ticket 00000000000000000003-999999: pid 999999 DOES NOT EXIST')" 1 + drc=0 + dout="$(OS_VERIFY_LOCK_FILE="$dl" OS_VERIFY_LOCK_SIM_LIVENESS=alive bash "$SELF" --depth 2>&1)" || drc=$? + st_case '--depth with an unlit probe exits 3 and is never read as depth 1' \ + "${drc}|$(printf '%s\n' "$dout" | grep -c '^depth: CANNOT READ')|$(printf '%s\n' "$dout" | grep -c '^depth [0-9]')" '3|1|0' + local duties + duties="$(dirname "$SELF")/../../.claude/skills/pm-dispatch/references/execution-duties.md" + st_case 'LOCK_DEPTH_HOLD equals the value the dispatch rule names, and the rule points at --depth' \ + "$(grep -c "os-verify-lock.sh --depth\`.*LOCK_DEPTH_HOLD\`(= ${LOCK_DEPTH_HOLD})" "$duties" 2> /dev/null)" 1 + rm -rf "$dq" "${dl}"* + # arrival stamps sort lexically in arrival order — the FIFO claim rests on it. # A host with only whole-second stamps (no EPOCHREALTIME, no GNU `date +%N`, # no perl) cannot promise STRICTLY increasing, and says so via --status rather @@ -4679,6 +4804,10 @@ main() { mode_status exit $? ;; + --depth) + mode_depth + exit $? + ;; --show-budget) mode_show_budget exit 0