diff --git a/.claude/agents/os-dev.md b/.claude/agents/os-dev.md index 99c2b4bacb8..a3a0b7970fa 100644 --- a/.claude/agents/os-dev.md +++ b/.claude/agents/os-dev.md @@ -276,6 +276,8 @@ model: opus - 认领的 `Clause-②:`、`Metadata-protocol:` 两行照抄进 PR 正文行首;无则零写,⛔ 不自造。 - 两行同抄进 changeset 正文行首;`Check Changeset` 读 PR 正文:kind 即 `minor`,`none` 即 `patch`。 - 种类非 `none` 或带 `(narrowing)` ⇒ 按 diff 加写 `Skills-docs:` 行;拼法与分工住认领模板。 +- diff 触根 `.claude/**` ⇒ PR 正文写行首 `Rule-change:` 行,按 diff 自判。 +- `none` 未改车队规则(agent 不经维护者可做什么、做什么与先后、什么须交他);`yes` 改了;`ruled` 照抄已裁条文,写行首 `Ruling-ref:` 引维护者原话、出处、时间。缺行同 `yes`:Tier H。 - ⛔ 永不 `Fixes` 一张还在决策箱的卡:合并会静默关掉它,而收件箱过滤只读 open。 - ⛔ 不写否定式的关单句,它照样关掉点名的卡:解析器无视否定,只匹配关键词 + `#`。 - 关键词是 `fix/fixes/fixed/close/closes/closed` 与 `resolve/resolves/resolved`;让它们远离其它卡号。 @@ -340,11 +342,9 @@ model: opus - 两条合法出路:在轮内同步等它(资源纪律的排队条款:限时获取 ⇒ 无锁工作 ⇒ 再取)。 - 或者收窄这次检查的范围并在报告里申报:已申报的收窄是被接受的偏差,CI 跑满农场。 - PM L1 审核的是 CI 收敛,不是你本地的覆盖面;未申报的收窄不在此列,那是漏跑。 - - 唯一同时反轮询又不停轮的形状是一次前台阻塞等待:前台跑完,或 `tail --pid` 等它退出。 - 比回合长的门禁在写报告那一刻读日志(重定向目标);未完成的记 NOT MEASURED 并写原因。 - 自检是机械的,不看你怎么形容这次等待:终消息只能是报告 JSON 或 `blocked` 报告。 - 结束一轮之前自检:最后一条消息是否在描述你不拥有的进程给你的唤醒? - - 排队的锁、别的 agent 的 build、脱管的 watcher 都不会来;保持这一轮活着,自己收退出码。 ## 何时停手不写码 @@ -397,8 +397,7 @@ model: opus - 不是 NUL 的控制字节也不是把门禁命中读成误报的理由。 - 危害的论证在 `scripts/check-nul-bytes.mjs` 头部,引用它,别重推;push 前跑它。 - 改动只要提到控制字符,就在门禁之外自扫:`grep -naP '[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]' `。 -- GitHub 正文 sanitizer 是同一纪律的另一半:形状、触发条件与作者纪律归 AGENTS.md。 -- 归属条款是 AGENTS.md 的 GitHub mutates body BYTES 条;署名页脚两形如下。 +- GitHub 正文 sanitizer 的作者纪律归 AGENTS.md 的 GitHub mutates body BYTES 条;署名页脚两形如下。 ```text --- ← 规则线,前留一空行;平台只认整块 diff --git a/.claude/skills/pm-dispatch/SKILL.md b/.claude/skills/pm-dispatch/SKILL.md index 59faec670dc..adebe90db75 100644 --- a/.claude/skills/pm-dispatch/SKILL.md +++ b/.claude/skills/pm-dispatch/SKILL.md @@ -187,19 +187,17 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → ## 路径分叉 -- **ACCEPT 之后的路径分叉**:翻 ready / 挂 auto-merge / 入队前先取一次 PR 的路径面。 -- 路径面用 `get_files` 取,⛔ 不看报告自述;动手之前先分,不是事后对照。 -- governed 面(定 Tier,非车道):`docs/adr/**`+`.claude/**`+`skills/**`+`docs/NORTH-STAR.md`+`.github/workflows/**`。 -- governed 面同含 `AGENTS.md`+`CLAUDE.md`;`GOVERNED_REPOS` 同治理、行可限仓,执行席恒随落地仓车道。 -- 另含 `ui/docs/adr/**`+`ui/.claude/**`+`ui/skills/**`+`ui/AGENTS.md`+`ui/CLAUDE.md`+`ui/.github/workflows/**`。 +- **ACCEPT 之后的路径分叉**:翻 ready/挂 auto-merge/入队前 `get_files` 取路径面,⛔ 不看报告自述。 +- governed 面(定 Tier,非车道):`docs/adr/**`+`.claude/**`+`skills/**`+`docs/NORTH-STAR.md`+`.github/workflows/**`+`AGENTS.md`+`CLAUDE.md`+`ui/docs/adr/**`+`ui/.claude/**`+`ui/skills/**`+`ui/AGENTS.md`+`ui/CLAUDE.md`+`ui/.github/workflows/**`。 +- `GOVERNED_REPOS` 同治理、行可限仓,执行席恒随落地仓车道。 +- 恒 H:守卫仪器 `scripts/pm/check-governed-merges.mjs`+`scripts/pm/check-governed-queue-guard.mjs`+`scripts/pm/record-recognisers.mjs`+`scripts/pm/dispatch-gates.mjs`+守卫 workflow+settings+hooks。 - 定档 Tier H ⇒ ACCEPT 换终局四件套,混合 diff ⛔ 不按比例判;要拆让 dev 单独开 PR。 -- 改动 >3000 行(含生成物)同换终局四件套含③请审,⛔ 无 Tier S 例外;读数=PR additions+deletions。 +- >3000 行(含生成物,additions+deletions)或申报收窄同换终局四件套含③请审,⛔ 无 Tier S 例外。 - ① 席位记录落 PR 先于 `pr_ready`/入队且钉 head:速读四行+席位意见,其下 `## 席位核对`。 - ② PR 悬着等人批,同笔挂 `pm:awaiting-merge`;人工直合即审核记录,授权批准 ⇒ 席位落地。 - 指针 `ACCEPT → PR #n comment `;受管/spec 面欠 ①–④,席只达档补审现 head 记录未盖处。 - 核对六项:形态/前提实测/门禁 check-runs/接受的偏差/范围外去向+`Skills-docs:`/落地条款。 -- 草稿归 dev:PR 正文带 `## 维护者速读` 四行(见 os-dev.md),中文业务话,不写席位意见。 -- 终稿 = 席位对照自己读的 diff 校正四行、加席位意见行,置顶席位记录;维护者只读评论。 +- 终稿 = 席位照自己读的 diff 校正 dev 草稿、加席位意见行,置顶席位记录;维护者只读评论。 - `pm:awaiting-merge` 只挂 PR、不入六态,与请审同为等人批清单,随获批或撤回判决离开。 - 批准后再推亦不过期;席位落地 = 过落地前检、清标、ready、auto-merge,踢出/变基同法。 - ③ 请审 = 席位交棒:ACCEPT 与现 head 同形 PASS 俱在案,同轮中继 `pr_request_reviewers` 请审批人。 @@ -207,8 +205,8 @@ PM 的工作是循环:选卡 → 认领 → 派发 → 收集 → L1 审核 → - `pr_create` 派不请;`pr_ready` 只补交棒漏;非例外 head 移 ⇒ 撤挂回等;脱中继 PR 自读请/派。 - 速读「要你做什么」求批点名 PASS 评论 id+`Head-sha`;无 PASS ⇒ 写 contract review owed 不求批。 - ④ 轮报单列 awaiting a human merge 并现读请审人;⛔ 未请审不在 chat 报「等你批」,先补请。 -- skills 车道自有 PR:纯代码面如 `scripts/pm/` 由本席自读(清单不减)后落地。 -- 受管面两层:Tier S = `.claude/**`+下行 S 面(该面独占),余皆 Tier H;S 经达档 PASS 后 ready→入队。 +- skills 车道自有 PR:纯代码面如 `scripts/pm/` 由本席自读(清单不减)后落地,守卫除外。 +- Tier S = `Rule-change: none`/`ruled` 记录核过的 `.claude/**`+下行面,余皆 H;达档 PASS 后 ready→入队。 - 本仓 workflows 读 `readWorkflowDiff`(发布面/C2/拒读⇒H),技能与只增 ADR `lowRiskArmVerdict`,未读⇒H。 - 入队资格:每 check 绿或预期 skip,⛔ 非必查子集;名单 check-expected-skips.mjs 只判 objectstack。 - 非必查红是真缺陷或坏门,归 PM 入队前处置;第三种按设计而红,三条全立才可带红入队: diff --git a/.claude/skills/pm-dispatch/references/contract-review.md b/.claude/skills/pm-dispatch/references/contract-review.md index 8204a55fd21..ed1bb208213 100644 --- a/.claude/skills/pm-dispatch/references/contract-review.md +++ b/.claude/skills/pm-dispatch/references/contract-review.md @@ -42,7 +42,7 @@ - 另记作者:PR `user.login` 非 `objectstack-fleet[bot]` ⇒ ③ 注点名该 login(脱中继写),落地前读。 - ③ 恒查(席位自读同):SQL 可下推处新增 id 物化或应用内 join 而无因由 ⇒ 记发现(AGENTS.md)。 - 简报从 `record-recognisers.mjs --brief-template` 起稿:只读条款与输入集内建,⛔ 不删 ⛔ 行。 -- 独立性对与低风险臂读的 `Security-touching:` 行,取值同见 `--template`;子代理记采纳它的席位。 +- 独立性对、`Security-touching:`、`Rule-change-verified:` 行取值见 `--template`;子代理记采纳席位。 - ④ 恒由起草者之外的 agent 达档跑,起草已达档不免;喂入同上,⛔ 不喂起草者的结论。 - 卡线程隔离子代理照上落现 head 记录并贴简报 ⇒ 席核简报、`Scope:` 与独立性对后采纳, ACCEPT 点名其评论 id;`Scope:` 窄于 `hits` 不采纳;席的补缺记录只管缺口,⛔ 不单充 head 记录。 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 492c07c1e4a..d30e52214aa 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -19,7 +19,10 @@ # `node scripts/pm/check-governed-queue-guard.mjs --self-test` reads this file # (`codeownersMirrorVerdict`) and reds when a Tier H row has no line here, when # any line names fewer or other owners than that constant, or when a Tier S row -# (`.claude/**`, which lands on a seat's review of record) is routed here. A +# (`.claude/**`, which lands on a seat's review of record) is routed here. That +# row splits by declaration since 2026-11-19, and the two paths under it that +# no declaration moves to a seat — the hooks and the settings files — each +# carry a line of their own, which the same self-test demands. A # Tier H row carrying the register's low-risk arm (`lowRisk`: the two skills # catalogs and the root ADR tree) has NO line here and reds if one is added: # the relay's per-pull review plan reads the arm and decides who is asked @@ -48,7 +51,9 @@ # The enforcement chain is routed the same way, deliberately: a PR that edits # the audit script, the approver constant or this file is a governance change — # without these entries the rule could be lifted by editing the enforcers -# instead of the surfaces. +# instead of the surfaces. Since 2026-11-19 the four guard scripts are register +# rows themselves (Tier H) and sit with the surfaces below; this file is the one +# enforcer still routed as a chain row. # Tier H governed surfaces — the register's rows with tier H, less the # low-risk arm's `/docs/adr/` and `/skills/` rows (see the header) @@ -56,6 +61,15 @@ /CLAUDE.md @os-zhuang /docs/NORTH-STAR.md @os-zhuang /.github/workflows/ @os-zhuang +/scripts/pm/check-governed-merges.mjs @os-zhuang +/scripts/pm/check-governed-queue-guard.mjs @os-zhuang +/scripts/pm/record-recognisers.mjs @os-zhuang +/scripts/pm/dispatch-gates.mjs @os-zhuang + +# Always Tier H under the root `.claude/` row, whatever a pull declares — the +# row itself has no line, since its other paths can land on a seat's record +/.claude/hooks/ @os-zhuang +/.claude/settings*.json @os-zhuang # Tier H governed surfaces of the nested `ui/` workspace (#25712) — the same # register rows, under `ui/`; `ui/.claude/` is Tier H, unlike the root tree; @@ -68,5 +82,3 @@ # The enforcement chain /.github/CODEOWNERS @os-zhuang -/scripts/pm/check-governed-merges.mjs @os-zhuang -/scripts/pm/check-governed-queue-guard.mjs @os-zhuang diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 2f73d8cc837..9df9de4daa2 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,6 +13,11 @@ _Keep one value on each of the two lines above, each line starting with its key. [Human Minimum](https://github.com/objectstack-ai/objectstack/blob/main/CONTRIBUTING.md#human-minimum) item 5 says what they mean._ +_Only when this pull request changes a file under `.claude/`: add one more line there. It starts with the key +word `Rule-change` and a colon, then `none` (no fleet rule changes), `yes` (one does) or `ruled` (it copies a +maintainer ruling, quoted on a second line that starts with `Ruling-ref` and a colon). Every other pull request +leaves it out._ + ## Human Minimum Each item is one rule from diff --git a/AGENTS.md b/AGENTS.md index 60e675203f0..8278786fcda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -273,40 +273,40 @@ See `ui/AGENTS.md` for the app-id / localStorage / auth gotchas. 14. **⛔ A governed surface lands only the way its tier allows — Tier H by the maintainer's hand (merge or enqueue) or an authorized approval, Tier S by the owning seat on a contract-tier review of record; before that record no AI seat merges, queues, or arms auto-merge on a PR whose diff touches one.** The governed surfaces are `docs/adr/**`, - `docs/NORTH-STAR.md`, `.claude/**` (agents, hooks and settings — not only skills), `skills/**`, `AGENTS.md`, - `CLAUDE.md` and `.github/workflows/**`, and under `ui/` `ui/docs/adr/**`, `ui/.claude/**`, `ui/skills/**`, - `ui/AGENTS.md`, `ui/CLAUDE.md` and `ui/.github/workflows/**`. The register is `GOVERNED_SURFACES` in - `scripts/pm/check-governed-merges.mjs`, each row carrying its tier; adding a surface is an edit *there*, never here, - and `pnpm check:pm-governed-prose` reds per-PR when this paragraph names fewer surfaces than the register — or - more. A fork PR (head repo ≠ base repo) is a proposal, never a delivery, whatever its paths: no AI seat readies, + `docs/NORTH-STAR.md`, `.claude/**`, `skills/**`, `AGENTS.md`, `CLAUDE.md`, `.github/workflows/**`, under `ui/` + `ui/docs/adr/**`, `ui/.claude/**`, `ui/skills/**`, `ui/AGENTS.md`, `ui/CLAUDE.md` and `ui/.github/workflows/**`, and + the guard itself: `scripts/pm/check-governed-queue-guard.mjs`, `scripts/pm/record-recognisers.mjs`, + `scripts/pm/dispatch-gates.mjs` and the register, `GOVERNED_SURFACES` in `scripts/pm/check-governed-merges.mjs`, + each row carrying its tier; adding a surface is an edit *there*, never here (`pnpm check:pm-governed-prose` pins the + list). A fork PR (head repo ≠ base repo) is a proposal, never a delivery, whatever its paths: no AI seat readies, queues, arms auto-merge on or approves it; the owning seat adopts the diff onto an internal branch and lands that. **Authoring stays open to every seat** — drafting, pushing, opening and revising the PR. What is reserved is the - **landing**: on a PR whose diff touches a governed surface ⛔ never merge, ⛔ never queue, ⛔ never arm - auto-merge, ⛔ never flip it out of draft to make any of those possible — judged on the PR's **file list**, not - its description; a **mixed diff is not a proportion question**, one path hit is enough; to land the rest, split off - the governed files. **The landing is tiered by the register; one Tier H path makes the whole PR Tier H.** **Tier H** - (人合: every row outside Tier S): those four lift only for an authorized APPROVED review by an account in - `GOVERNED_APPROVERS`, on ANY commit and not dismissed; that word is spent once per PR — the OWNING seat then lands - it, later pushes included; the click stays the maintainer's. **Tier S** (席内达档 L2 审核落地: `.claude/**`, - objectstack workflow edits (`readWorkflowDiff`), skills-only wording and add-only ADR notes (`lowRiskArmVerdict`, on - a `Security-touching: no` record, no named card ever labelled `security`; the seat labels unnamed security teaching) - read as S): those four lift once the PR thread or its card carries a PASS `## Contract review` record for the PR's - current head with `Served-tier: CONTRACT_REVIEW_TIER` and every check is green — the owning seat queues it. A PR - whose only governed paths are register rows the queue leg regenerates byte-exact clears with zero approvals — an - uncertified recompute, drift or a hand-authored sibling keeps it governed. ⛔ **No agent seat submits an approving - review on a governed-surface PR, under any account** — an authorized account is agent-operated too; "CI is green" - says nothing about a governance change. An authorized account's enqueue is a review record too: ⛔ never a seat's. + **landing**: on such a PR ⛔ never merge, ⛔ never queue, ⛔ never arm auto-merge, ⛔ never flip it out of draft + to make any of those possible — judged on the PR's **file list**, not its description; a **mixed diff is not a + proportion question**, one path hit is enough; to land the rest, split off the governed files. **One Tier H path + makes the whole PR Tier H.** **Tier H** (人合: every row outside Tier S): those four lift only for an authorized + APPROVED review by an account in `GOVERNED_APPROVERS`, on ANY commit and not dismissed; that word is spent once per + PR — the OWNING seat then lands it, later pushes included; the click stays the maintainer's. **Tier S** + (席内达档 L2 审核落地: `.claude/**`, objectstack workflow edits (`readWorkflowDiff`), skills-only wording + and add-only ADR notes (`lowRiskArmVerdict`, on a `Security-touching: no` record, no named card ever labelled + `security`; the seat labels unnamed security teaching) read as S): those four lift once the PR thread or its card + carries a PASS `## Contract review` record for the PR's current head with `Served-tier: CONTRACT_REVIEW_TIER` and + every check is green — the owning seat queues it. `.claude/**` is S only on a line-start `Rule-change: none` in + the PR body (or `ruled` with a `Ruling-ref:` line quoting the maintainer) repeated on the record's + `Rule-change-verified:` line; no line, `yes`, settings and hooks are Tier H. A PR whose only governed paths are + register rows the queue leg regenerates byte-exact clears with zero approvals — an uncertified recompute, drift or + a hand-authored sibling keeps it governed. ⛔ **No agent seat submits an approving review on a governed-surface PR, + under any account**. An authorized account's enqueue is a review record too: ⛔ never a seat's. **Already armed or queued when you read this?** Disable auto-merge AND convert it back to **draft**, which disarms - an unqueued PR; a queued one's landing seat sends the relay's `pr_dequeue` (measured live, comment 6902190812); any - other seat, or a stroke that does not land, asks the maintainer at once — then confirm from the remote that it is - in neither the queue nor `origin/main`. **Draft is no barrier by itself — the barrier is this directive**, and a - spent approval or a standing record IS the review record, ⛔ not a relaxation. Behind it: the queue guard refuses a - governed diff without its tier's record; CODEOWNERS routes every Tier H surface but the low-risk arm's rows to the - approvers, the relay asks per pull on drafts (no barrier); the post-merge audit (`check-governed-merges.mjs`) lists - every governed-surface merge with its approver and merger — a merger the maintainer does not recognise, any agent - approval, or a Tier S merge without a PASS record is a seat violation, filed and rolled back. No seat judges this. + an unqueued PR; a queued one's landing seat sends the relay's `pr_dequeue`; any other seat, or a stroke that does + not land, asks the maintainer at once — then confirm from the remote that it is in neither the queue nor + `origin/main`. **Draft is no barrier by itself — the barrier is this directive**, and a spent approval or a + standing record IS the review record, ⛔ not a relaxation. Behind it: the queue guard refuses a governed diff + without its tier's record; the post-merge audit (`check-governed-merges.mjs`) lists every governed-surface merge + with its approver and merger — a merger the maintainer does not recognise, any agent approval, or a Tier S merge + without a PASS record is a seat violation, filed and rolled back. No seat judges this. 15. **⛔ A version release is performed by the maintainer, by hand — no AI seat publishes, tags, cuts a Release, or triggers a release, and none merges the Version Packages PR.** A rule that binds every seat lives here, diff --git a/scripts/pm/check-governed-merges.mjs b/scripts/pm/check-governed-merges.mjs index e4b5d6dc2da..fbe521ed46e 100644 --- a/scripts/pm/check-governed-merges.mjs +++ b/scripts/pm/check-governed-merges.mjs @@ -115,7 +115,14 @@ * governs, a row with none governs every repository in `GOVERNED_REPOS`, and * the `workflows` row lists `objectstack`, `objectui` and `cloud` — the two * ruled, plus cloud because its own table already carries the row, so the - * central audit and cloud's table agree. + * central audit and cloud's table agree. `hotcrm` joined the row on 2026-11-19 + * (card #35321, item 4): the audit mirror, so a merged hotcrm workflow change + * produces a row in this sweep. `objectos` and `mobile` stay out. + * + * The same card scoped four rows to objectstack alone — the guard instruments + * (`guard-register`, `guard-queue`, `guard-records`, `guard-tiers`): this file, + * the queue guard, the record recognisers and the tier constants live in this + * repository and nowhere else. * * Consequence for every reader: the register's question has a repository in * it. `governedPathsIn(paths, repo)`, `governedTierFor`, `testVerdict` and @@ -421,7 +428,9 @@ * them. What moved is the LANDING each row waits for, carried as `tier` on the * row and derived per PR by `governedTierFor`: * - * H 人合 — every register row except objectstack's `.claude/**`, and the split + * H 人合 — every register row except objectstack's `.claude/**` where its + * declaration split holds (section "The `.claude/**` row splits by + * declaration" below), and the split * rows where their reading says S (today: `docs/adr/**`, * `docs/NORTH-STAR.md`, `skills/**`, `AGENTS.md`, `CLAUDE.md`, and since * the B2 ruling of 2026-10-13 the `workflows` row, `.github/workflows/**`, @@ -430,13 +439,16 @@ * below): the maintainer's hand, or * an authorized APPROVED review by `GOVERNED_APPROVERS` and then the * owning seat lands it. The tier ruling left this landing as it was; the - * list itself grew by one row on 2026-10-13. The `.claude/**` row of every + * list itself grew by one row on 2026-10-13 and by the four guard + * instruments on 2026-11-19 (card #35321, item 1: the files that DECIDE a + * landing are not landed by the seats they judge). The `.claude/**` row of every * repository but objectstack lands here too (#25199): its `tierRepos` names * objectstack alone, because no other repository's own queue guard has a * Tier S arm (objectui's, measured, refuses `.claude/**` without an * authorized approval; cloud's, objectos' and hotcrm's are unread and fail * closed to H). - * S 席内达档 L2 审核落地 — objectstack's whole `.claude/**` tree: the owning seat lands it + * S 席内达档 L2 审核落地 — objectstack's `.claude/**` tree, since 2026-11-19 only where the + * pull request declares it changes no fleet rule and the record verifies that: the owning seat lands it * through the queue once the PR thread (or its card) carries a * `## Contract review` record for the PR's CURRENT head with * `Served-tier: CONTRACT_REVIEW_TIER` and `**VERDICT: PASS**` and every @@ -451,10 +463,51 @@ * and the whole PR is Tier H; an empty or ungoverned list answers H (fail * closed — the tier of nothing is never the cheaper one), and the tier is * recomputed on the LIFTED slice, since a certified regeneration under - * `skills/**` can be the only Tier H hit in a diff. `.claude/settings.json` is - * the permission set itself and lands under Tier S by the amendment; the - * auto-mode classifier still refuses AI writes to it, so the maintainer's hand - * stays its writer and the tier removes only the approval click. + * `skills/**` can be the only Tier H hit in a diff. `.claude/settings*.json` and + * `.claude/hooks/**` — the permission set and the hooks that enforce it — landed + * under Tier S by the 2026-09-18 amendment and are Tier H by path again since + * 2026-11-19 (next section). + * + * ## The `.claude/**` row splits by declaration (maintainer ruling 2026-11-19, card #35321) + * + * The maintainer, in the review-split discussion thread: 03:17Z 「北极星、AGENTS.md、 + * 改车队规则的技能条文(谁能做什么、怎么定级、怎么合并)也需要fable 吧」, then 04:24Z + * 「1+2+4」 — whose point 1 returns fleet RULE TEXT to him, overriding the + * 2026-09-18 ruling above where it handed all of `.claude/**` to the seats — and + * 04:30Z 「「已裁定的照抄只核对、不再审」 同意」. Rule text is what an agent may do + * without him (merge, bypass checks, change repository settings), what gets done + * and in what order (grading, dispatch, scope), and what must go to him + * (decisions, maintainer actions). Process steps, scripts, wording, slimming and + * file moves stay with the reviewer. + * + * A path list cannot tell the two apart, so the pull request DECLARES and the + * reviewer VERIFIES. The row keeps `tier: S` — the landing it has when both + * hold — and carries `ruleChange`; `applyRuleChangeSplit` runs last in the + * chain and answers Tier H unless: + * + * 1. no changed path is `.claude/settings*.json` or under `.claude/hooks/` + * (`RULE_CHANGE_TIER_H_PATHS` — always Tier H, whatever is declared); + * 2. the PR body carries ONE bare line-start `Rule-change: none`, or + * `Rule-change: ruled` with ONE bare `Ruling-ref:` line quoting the + * maintainer's words, their source and time; + * 3. the PASS `## Contract review` record for the current head carries + * `Rule-change-verified:` with the SAME value. + * + * A missing line, `Rule-change: yes`, a quoted, fenced or doubled line, or a + * record that does not verify is Tier H. ⛔ Fail closed: a caller of + * `governedTierFor` or `testVerdict` that hands in no reading of the pull + * (`--test`, `--branch`) gets Tier H; the record is staged like the low-risk + * arm's (`pending`, read, asked again), and the queue guard — whose own record + * leg judges the record — says so (`RULE_CHANGE_RECORD_LEG_DEFERRED`) and + * enforces 3 there. `ui/.claude/**` and every other repository's `.claude/**` + * are Tier H as before. + * + * ⛔ Two readers do NOT chain the split and still read the raw row's Tier S: + * the relay's review-request plan (`fleet-write/execute.mjs`) and the + * half-states patrol's landing row, both through `landingTierOf` on the + * matched slice. Neither decides a landing — the queue guard does — so a + * `Rule-change: yes` pull is refused at the queue but is not auto-routed to + * the maintainer by the relay; CODEOWNERS routes the settings and hooks paths. * * Published `skills/**` stays a Tier H ROW: the 2026-09-18 seat did not propose * moving it, and no row moved since. What moved on 2026-11-14 is a READING on @@ -1205,14 +1258,16 @@ const SELF_TEST_BATTERIES = Object.freeze({ '⚖️ #33603: the sweep lists a low-risk arm landing APART and judges it on a same-head at-tier PASS record': 71, '⭐ the weekly audit card: every reading the job files on, both ways (#33814)': 54, '⚖️ #33539: the ADR leg of the low-risk arm — an add-only note lands Tier S, any other ADR change stays H': 52, + '⚖️ #35321: the guard instruments are Tier H, and `.claude/**` splits by declaration': 40, }); // DELETING an entry silences that battery's floor exactly as effectively as // zeroing it, so the roster's own size is pinned too. Raised 35 → 36 with the // workflows split battery (ruling record 6722205630): one battery, one row. // Raised 36 → 37 with the low-risk skills arm battery (#33501), 37 → 38 with its post-merge leg (#33603), -// 38 → 39 with the weekly audit card's battery (#33814), 39 → 40 with the arm's ADR leg (#33539). -const SELF_TEST_BATTERY_FLOOR = 40; +// 38 → 39 with the weekly audit card's battery (#33814), 39 → 40 with the arm's ADR leg (#33539), +// 40 → 41 with the guard-instrument rows and the `.claude/**` declaration split (#35321). +const SELF_TEST_BATTERY_FLOOR = 41; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -1346,7 +1401,8 @@ export const HUMAN_MERGE_LINE_THRESHOLD = 3000; * that declares no `repos` key carries the default; `surfaceRepos` is the one * reader of that default. The `workflows` row is scoped to the two public * repositories the ruling 「两仓加治理行」 names plus `cloud`, whose own table - * already carries the same row: `objectos` and `hotcrm` are NOT governed by + * already carries the same row, plus `hotcrm` since 2026-11-19 (the audit + * mirror, card #35321): `objectos` and `mobile` are NOT governed by * it — no ruling names them, and a new gate defaults to no. Every reader of * this table therefore asks for ONE repository (`governedPathsIn(paths, * repo)`), and a call that names none is refused, never answered for "all". @@ -1357,7 +1413,14 @@ export const HUMAN_MERGE_LINE_THRESHOLD = 3000; * and `governedSurfacesFor` hands every matcher the tier for its repository. * The `claude-tree` row's Tier S holds in objectstack alone: the tier is the * landing the repository's own queue guard enforces, and only objectstack's - * has a Tier S arm (#25199). + * has a Tier S arm (#25199). That row also carries `ruleChange`: its Tier S is + * the landing it has when the pull request's declaration and the record hold + * (header section "The `.claude/**` row splits by declaration"), and every + * reader that decides a landing chains `applyRuleChangeSplit`. + * + * The four `guard-*` rows are the instruments that decide a landing — this + * file, the queue guard, the record recognisers, the tier constants — exact + * paths, Tier H, scoped to objectstack (2026-11-19, card #35321). * * The six `ui-*` rows are objectui's own register, carried under `ui/` now * that objectui's tree is this repository's `ui/` workspace (#25677, #25712): @@ -1373,12 +1436,16 @@ export const WORKFLOWS_PREFIX = '.github/workflows/'; export const GOVERNED_SURFACES = Object.freeze([ Object.freeze({ id: 'adr', prefix: 'docs/adr/', glob: 'docs/adr/**', tier: GOVERNED_TIER_H, lowRisk: Object.freeze({ repos: Object.freeze(['objectstack']), addOnly: true }), what: 'architecture decision records' }), - Object.freeze({ id: 'claude-tree', prefix: '.claude/', glob: '.claude/**', tier: GOVERNED_TIER_S, tierRepos: Object.freeze(['objectstack']), what: 'the agent instruction tree (skills, agents, hooks, settings)' }), + Object.freeze({ id: 'claude-tree', prefix: '.claude/', glob: '.claude/**', tier: GOVERNED_TIER_S, tierRepos: Object.freeze(['objectstack']), ruleChange: Object.freeze({ repos: Object.freeze(['objectstack']) }), what: 'the agent instruction tree (skills, agents, hooks, settings)' }), Object.freeze({ id: 'skills-catalog', prefix: 'skills/', glob: 'skills/**', tier: GOVERNED_TIER_H, lowRisk: Object.freeze({ repos: Object.freeze(['objectstack']) }), what: 'the published skills catalog' }), Object.freeze({ id: 'agents-md', exact: 'AGENTS.md', glob: 'AGENTS.md', tier: GOVERNED_TIER_H, what: 'the repo-root agent instruction file' }), Object.freeze({ id: 'claude-md', exact: 'CLAUDE.md', glob: 'CLAUDE.md', tier: GOVERNED_TIER_H, what: 'the repo-root Claude instruction file' }), Object.freeze({ id: 'north-star', exact: 'docs/NORTH-STAR.md', glob: 'docs/NORTH-STAR.md', tier: GOVERNED_TIER_H, what: "the maintainer's North Star — the law above AGENTS.md" }), - Object.freeze({ id: 'workflows', prefix: '.github/workflows/', glob: '.github/workflows/**', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack', 'objectui', 'cloud']), split: Object.freeze({ repos: Object.freeze(['objectstack']), reader: 'readWorkflowDiff' }), what: 'CI, deploy and release workflows: what runs on every push, what deploys, what gates the queue' }), + Object.freeze({ id: 'workflows', prefix: '.github/workflows/', glob: '.github/workflows/**', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack', 'objectui', 'cloud', 'hotcrm']), split: Object.freeze({ repos: Object.freeze(['objectstack']), reader: 'readWorkflowDiff' }), what: 'CI, deploy and release workflows: what runs on every push, what deploys, what gates the queue' }), + Object.freeze({ id: 'guard-register', exact: 'scripts/pm/check-governed-merges.mjs', glob: 'scripts/pm/check-governed-merges.mjs', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: 'the governed register and its tier predicate (this file)' }), + Object.freeze({ id: 'guard-queue', exact: 'scripts/pm/check-governed-queue-guard.mjs', glob: 'scripts/pm/check-governed-queue-guard.mjs', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: 'the merge-queue guard that enforces the register' }), + Object.freeze({ id: 'guard-records', exact: 'scripts/pm/record-recognisers.mjs', glob: 'scripts/pm/record-recognisers.mjs', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: 'the recognisers of the review of record a Tier S landing stands on' }), + Object.freeze({ id: 'guard-tiers', exact: 'scripts/pm/dispatch-gates.mjs', glob: 'scripts/pm/dispatch-gates.mjs', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: 'the dispatch gates and the contract-review tier they declare' }), Object.freeze({ id: 'ui-adr', prefix: 'ui/docs/adr/', glob: 'ui/docs/adr/**', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: "the ui workspace's architecture decision records" }), Object.freeze({ id: 'ui-claude-tree', prefix: 'ui/.claude/', glob: 'ui/.claude/**', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), what: "the ui workspace's agent instruction tree" }), Object.freeze({ id: 'ui-skills-catalog', prefix: 'ui/skills/', glob: 'ui/skills/**', tier: GOVERNED_TIER_H, repos: Object.freeze(['objectstack']), lowRisk: Object.freeze({ repos: Object.freeze(['objectstack']) }), what: "the ui workspace's published skills catalog" }), @@ -1717,7 +1784,7 @@ export function landingTierOf(matched) { */ export function governedTierFor(paths, repo, register = GOVERNED_SURFACES, workflowDiff = null, lowRisk = null) { const id = assertGovernedRepo(repo, 'governedTierFor'); - return landingTierOf(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, id, register), id, workflowDiff), id, lowRisk)); + return landingTierOf(applyRuleChangeSplit(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, id, register), id, workflowDiff), id, lowRisk), id, lowRisk)); } // ── the `workflows` row's content-aware tier (ruling record 6722205630, letter C) ── @@ -1748,6 +1815,10 @@ export const WORKFLOW_TIER_H_FILES = Object.freeze([ Object.freeze({ path: '.github/workflows/docs-deploy.yml', why: 'deploys the docs site (`vercel deploy --prebuilt`, the deploy token)' }), Object.freeze({ path: '.github/workflows/checklist-status.yml', why: 'publishes the checklist status pages to the wiki (`contents: write`)' }), Object.freeze({ path: '.github/workflows/fleet-write.yml', why: "the fleet's write relay and its App key (biased to H: the credential, not a release)" }), + // 2026-11-19 (card #35321): the workflow that RUNS the queue guard. Measured before the row landed: the + // content classifier read seven of eight edits to it as Tier S, a step ahead of the guard and its + // self-test swapped for an echo among them — so the file is H by path, like the instruments it runs. + Object.freeze({ path: '.github/workflows/governed-surface-guard.yml', why: 'runs the merge-queue guard that enforces this register (an edit can stop the guard reading anything)' }), ]); /** The patterns an ADDED line may not carry without Tier H (biased cases: each can turn a check off or skip a gate). */ @@ -2978,6 +3049,282 @@ export function renderLowRiskLines(matched) { return ` ⚖️ low-risk skills arm (${LOW_RISK_ARM_RULING}): Tier H —\n${v.reasons.map((r) => ` - ${r}\n`).join('')}`; } +// ── the `.claude/**` row's declaration split (maintainer ruling 2026-11-19, card #35321) ── + +/** + * Where the split is ruled (header section "The `.claude/**` row splits by declaration"), printed on every + * reading so a queue log names what kept an instruction-tree PR at Tier H or let a seat land it. + */ +export const RULE_CHANGE_RULING = 'maintainer ruling 2026-11-19 on #35321, 「1+2+4」'; + +/** + * The PR body's declaration and the record's verification of it — the two lines the split reads, each ONE + * bare line (`readOneBareLine`). + * + * `Rule-change: none` the diff moves no fleet rule text: process steps, scripts, wording, slimming, file moves; + * `Rule-change: ruled` it copies a ruling the maintainer already gave, and a bare `Ruling-ref:` line beside it + * quotes his words, their source and their time — 「已裁定的照抄只核对、不再审」; + * `Rule-change: yes` it changes what an agent may do without the maintainer, what gets done and in what + * order, or what must go to him. Tier H. + * + * The record's `Rule-change-verified:` line is the reviewer's own reading of the same diff, and Tier S holds only + * where it reads the value the body declares. `yes` there is the reviewer finding rule text the body did not own + * up to; it is the value a template prints by default, so a record nobody filled in keeps the PR at Tier H. + */ +export const RULE_CHANGE_KEY = 'Rule-change'; +export const RULE_CHANGE_VALUES = Object.freeze(['none', 'ruled', 'yes']); +/** The declared values a seat may land on; any other reading is the maintainer's. */ +export const RULE_CHANGE_SEAT_VALUES = Object.freeze(['none', 'ruled']); +export const RULING_REF_KEY = 'Ruling-ref'; +export const RULE_CHANGE_VERIFIED_KEY = 'Rule-change-verified'; + +/** + * Tier H by PATH under the split row, decided BEFORE any declaration is read: the permission set and the + * hooks that enforce it. No declaration and no record moves one of these to Tier S — the 2026-09-18 + * amendment that handed them to the seats is the half the 2026-11-19 ruling takes back first. + * `pattern` is the CODEOWNERS spelling below the root (`codeownersMirrorVerdict` demands a line at each). + */ +export const RULE_CHANGE_TIER_H_PATHS = Object.freeze([ + Object.freeze({ id: 'settings', pattern: '.claude/settings*.json', test: /^\.claude\/settings[^/]*\.json$/, what: 'the harness permission set' }), + Object.freeze({ id: 'hooks', pattern: '.claude/hooks/', test: /^\.claude\/hooks\//, what: 'a harness hook' }), +]); + +/** Does this matched row carry the declaration split in `repo`? */ +function ruleChangeIn(surface, repo) { + return Boolean(surface?.ruleChange) && Array.isArray(surface.ruleChange.repos) && surface.ruleChange.repos.includes(repo); +} + +/** The lead a declaration line may sit behind: quote marks, a heading mark, a list bullet, emphasis, a code span. */ +const BARE_LINE_LEAD = '^[ \\t]*(?:>[ \\t]*)*(?:#{1,6}[ \\t]+)?(?:[-*+][ \\t]+)?`?[*_]{0,3}'; + +/** + * The ONE bare `: ` line of `text`, read the way the record's `Security-touching:` line is + * (`contractReviewSecurityTouching`, `check-half-states.mjs` — which this file cannot import, see + * `proxyRearmPlan`; the self-test drives both over the same specimens): + * + * missing no declaration line at all; + * read the one bare line, with its value; + * unreadable anything else, with the reason. + * + * Every line that leads with the key and a colon counts — fenced, quoted and code-indented ones included, + * in any case — and exactly ONE may exist: outside any code fence and any `>` quote, indented at most three + * spaces, the key outside any code span. With its list bullet and bold stripped it must read EXACTLY + * `: ` for a value in `values`; with `values` null the value is free text and must not be empty. + * So a second declaration, trailing words, another value, a near-miss key and a line that only mentions + * the key are each `unreadable`. ⛔ No reading here defaults to a value. Pure. + */ +export function readOneBareLine(text, key, values = null) { + const spelled = String(key).split('-').map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[-_ \\t]*'); + const declaration = new RegExp(`${BARE_LINE_LEAD}${spelled}[*_\`]{0,3}[ \\t]*[::]`, 'i'); + const hits = []; + let fence = null; // the open fence — its character and run length — or null outside one + for (const line of String(text ?? '').split(/\r?\n/)) { + if (fence !== null) { + if (declaration.test(line)) hits.push({ line, fenced: true }); + const close = /^[ ]{0,3}(`{3,}|~{3,})[ \t]*$/.exec(line); + if (close !== null && close[1][0] === fence.ch && close[1].length >= fence.len) fence = null; + continue; + } + const open = /^[ ]{0,3}(`{3,}(?!.*`)|~{3,})/.exec(line); + if (open !== null) { + fence = { ch: open[1][0], len: open[1].length }; + continue; + } + if (declaration.test(line)) hits.push({ line, fenced: false }); + } + if (hits.length === 0) return { state: 'missing' }; + const unreadable = (reason) => ({ state: 'unreadable', reason }); + if (hits.length > 1) return unreadable(`${hits.length} \`${key}:\` lines, where exactly one is read`); + const [{ line, fenced }] = hits; + if (fenced) return unreadable(`its one \`${key}:\` line sits inside a code fence`); + if (/^[ \t]*>/.test(line)) return unreadable(`its one \`${key}:\` line is a quote (${quoteLine(line)})`); + if (/^(?: {4,}| *\t)/.test(line)) return unreadable(`its one \`${key}:\` line is indented as code (${quoteLine(line)})`); + const stated = line.replace(/^[ \t]*(?:[-*+][ \t]+)?/, '').replace(/\*\*/g, ''); + if (/^[^::]*`/.test(stated)) return unreadable(`its one \`${key}:\` line holds the key inside a code span (${quoteLine(line)}), which mentions the line and states nothing`); + const bare = stated.replace(/`/g, '').replace(/[ \t]+/g, ' ').trim(); + if (values === null) { + const value = bare.startsWith(`${key}: `) ? bare.slice(key.length + 2).trim() : ''; + if (value === '') return unreadable(`its \`${key}:\` line reads ${quoteLine(line)}, which states nothing after the key`); + return { state: 'read', value }; + } + const value = values.find((v) => bare === `${key}: ${v}`); + if (value === undefined) return unreadable(`its \`${key}:\` line reads ${quoteLine(line)}, not exactly ${values.map((v) => `\`${key}: ${v}\``).join(' or ')}`); + return { state: 'read', value }; +} + +/** The record's `Rule-change-verified:` line, off a whole comment body: `{ state, value?, reason? }`. Pure. */ +export function readRuleChangeVerified(body) { + return readOneBareLine(body, RULE_CHANGE_VERIFIED_KEY, RULE_CHANGE_VALUES); +} + +/** + * The record stage a caller with a record leg of its OWN may ask for, as `reading.recordLeg`: the body's declaration + * decides the tier, and the record conjunct is owed to that leg instead of to this predicate. ⛔ One caller may say + * it — the queue guard's queue leg, whose record leg holds the record of such an entry to the line + * (`ruleChangeRecordVerdict` there: stands, reads PASS, and reads `Rule-change-verified:` as declared, by + * `ruleChangeRecordReasons` below) and so keeps a missing record, an unsigned one and an unreadable thread the three + * different refusals they always were. Every other caller leaves it out and gets `pending`: Tier H. + */ +export const RULE_CHANGE_RECORD_LEG_DEFERRED = 'deferred'; + +/** The reason a `pending` record stage of the split reads Tier H on: the record was not read. */ +export const RULE_CHANGE_RECORD_STAGE_PENDING_REASON = + `its contract-review record was not read, so no \`${RULE_CHANGE_VERIFIED_KEY}:\` line is established`; + +/** + * Why the record keeps the split at Tier H, or [] — the split's last conjunct. Pure. + * + * `record` is the reading the low-risk arm's record stage already takes (`lowRiskRecordStage`, the queue guard), + * with two keys of this split's own: `ruleChangeVerified` (`readRuleChangeVerified` of the located comment) and + * `ruleChangeCarried` (`null`, or `{ from, ok, reason }` for a record carried from an older head — it stands only + * when the hops moved nothing under the split row). The conjunct holds only for a record FOUND on this head whose + * line was READ and reads the value the body `declared`: missing, unreadable, `yes`, or the other seat value are + * each a reason, as is a record that is absent, unsigned or unread. + */ +export function ruleChangeRecordReasons(record, declared) { + const want = `${RULE_CHANGE_VERIFIED_KEY}: ${declared}`; + if (!record || record.measured !== true) { + return [`its contract-review record was not read (${record?.reason ?? 'no reading'}), so no \`${want}\` line is established`]; + } + if (record.located !== 'found') { + return [record.located === 'unsigned' + ? `its contract-review record on this head names no reviewer, so its \`${RULE_CHANGE_VERIFIED_KEY}:\` line does not count` + : `no contract-review record names this head, so no \`${want}\` line is established`]; + } + const reasons = []; + const which = `its contract-review record (${record.where ?? 'a'} comment ${record.id ?? '(no id)'})`; + const carried = record.ruleChangeCarried; + if (carried && carried.ok !== true) reasons.push(`${which} ${carried.reason ?? 'was carried from an older head over hops that could not be read'}`); + const line = record.ruleChangeVerified; + if (!line || line.state === 'missing') reasons.push(`${which} carries no \`${RULE_CHANGE_VERIFIED_KEY}:\` line`); + else if (line.state !== 'read') reasons.push(`the \`${RULE_CHANGE_VERIFIED_KEY}:\` line of ${which} is unreadable: ${line.reason ?? 'no reason recorded'}`); + else if (line.value !== declared) reasons.push(`${which} reads \`${RULE_CHANGE_VERIFIED_KEY}: ${String(line.value)}\`, and the PR body declares \`${RULE_CHANGE_KEY}: ${declared}\``); + return reasons; +} + +/** + * The split's verdict over the files of ONE matched split row, from the same READING of the pull request the + * low-risk arm takes (`pullLowRiskReading`; here only its `body` and, second, its `record` are read). Pure. + * + * In order, and the order is the rule: + * 1. a file on `RULE_CHANGE_TIER_H_PATHS` — Tier H by path, nothing else read (`byPath`); + * 2. no reading, or one not measured — Tier H, NOT MEASURED: a path list cannot say what a body declares; + * 3. the body's ONE bare `Rule-change:` line — missing, unreadable or `yes` is Tier H, and `ruled` also + * owes ONE bare `Ruling-ref:` line that states something; + * 4. the RECORD STAGE, as the low-risk arm stages it (`LOW_RISK_RECORD_STAGE`): no `record` handed in is + * `pending`, Tier H, and the caller reads it and asks again; one handed in is judged + * (`ruleChangeRecordReasons`). A caller whose own record leg judges it says so + * (`RULE_CHANGE_RECORD_LEG_DEFERRED`) and reads `deferred`: Tier S on the declaration, the record owed there. + * ⛔ Fail closed: Tier S only with zero reasons, and nothing a caller leaves out is read as `none`. + */ +export function ruleChangeVerdict(files, reading = null) { + const list = (Array.isArray(files) ? files : []).filter((p) => typeof p === 'string' && p !== ''); + const more = (items, n) => `${items.slice(0, n).join(', ')}${items.length > n ? ` (+${items.length - n} more)` : ''}`; + const hot = RULE_CHANGE_TIER_H_PATHS.map((row) => ({ row, files: list.filter((p) => row.test.test(p)) })).filter((x) => x.files.length > 0); + if (hot.length > 0) { + return { + tier: GOVERNED_TIER_H, + measured: true, + byPath: true, + reason: null, + reasons: hot.map(({ row, files: hits }) => `${more(hits, 4)} — ${row.what} (\`${row.pattern}\`), Tier H whatever the pull request declares`), + declared: null, + recordStage: LOW_RISK_RECORD_STAGE.notReached, + }; + } + if (!reading || reading.measured !== true) { + return { + tier: GOVERNED_TIER_H, + measured: false, + byPath: false, + reason: reading?.reason ?? 'no reading of the pull request was handed in — a path list alone cannot say what its body declares', + reasons: [], + declared: null, + recordStage: LOW_RISK_RECORD_STAGE.notReached, + }; + } + const reasons = []; + let declared = null; + const line = readOneBareLine(reading.body, RULE_CHANGE_KEY, RULE_CHANGE_VALUES); + if (line.state === 'missing') reasons.push(`the PR body carries no \`${RULE_CHANGE_KEY}:\` line`); + else if (line.state !== 'read') reasons.push(`the PR body: ${line.reason}`); + else if (!RULE_CHANGE_SEAT_VALUES.includes(line.value)) reasons.push(`the PR body declares \`${RULE_CHANGE_KEY}: ${line.value}\` — it changes fleet rule text, which lands by the maintainer`); + else declared = line.value; + if (declared === 'ruled') { + const ref = readOneBareLine(reading.body, RULING_REF_KEY, null); + if (ref.state === 'missing') reasons.push(`the PR body declares \`${RULE_CHANGE_KEY}: ruled\` and carries no \`${RULING_REF_KEY}:\` line quoting the ruling it copies`); + else if (ref.state !== 'read') reasons.push(`the PR body: ${ref.reason}`); + } + let recordStage = LOW_RISK_RECORD_STAGE.notReached; + if (reasons.length === 0) { + if (reading.record == null && reading.recordLeg === RULE_CHANGE_RECORD_LEG_DEFERRED) { + recordStage = RULE_CHANGE_RECORD_LEG_DEFERRED; + } else if (reading.record == null) { + recordStage = LOW_RISK_RECORD_STAGE.pending; + reasons.push(RULE_CHANGE_RECORD_STAGE_PENDING_REASON); + } else { + recordStage = LOW_RISK_RECORD_STAGE.read; + reasons.push(...ruleChangeRecordReasons(reading.record, declared)); + } + } + return { tier: reasons.length === 0 ? GOVERNED_TIER_S : GOVERNED_TIER_H, measured: true, byPath: false, reason: null, reasons, declared, recordStage }; +} + +/** + * The matched slice with every split row's tier read off the pull request, in `repo`. A row without + * `ruleChange`, or a repository its `ruleChange.repos` does not name, passes through as the same object. + * Run LAST in the chain (`governedPathsIn` → `applyWorkflowSplit` → `applyLowRiskArm` → here), on the one + * reading the low-risk arm takes. ⛔ A caller that skips this step reads the row's own `tier`, which is the + * landing the row has WHEN the declaration and the record hold — so every reader that decides a landing + * chains it: `governedTierFor`, `testVerdict`, and the queue guard's two tier reads. Pure. + */ +export function applyRuleChangeSplit(matched, repo, reading = null) { + return (Array.isArray(matched) ? matched : []).map((surface) => { + if (!ruleChangeIn(surface, repo)) return surface; + const verdict = ruleChangeVerdict(surface.files, reading); + return Object.freeze({ ...surface, tier: verdict.tier, ruleChangeVerdict: verdict }); + }); +} + +/** Is the split's record stage the one thing still unread on this matched slice — every other row already Tier S? Pure. */ +export function ruleChangeRecordStagePending(matched) { + const list = Array.isArray(matched) ? matched : []; + const pending = (s) => s?.ruleChangeVerdict?.recordStage === LOW_RISK_RECORD_STAGE.pending; + return list.some(pending) && list.every((s) => pending(s) || s?.tier === GOVERNED_TIER_S); +} + +/** + * Does any path sit under a row that splits by declaration — the register's own test, for the record + * template and the brief (`record-recognisers.mjs`), which print the `Rule-change-verified:` line on it. Pure. + */ +export function ruleChangeRowHit(paths) { + const list = Array.isArray(paths) ? paths : []; + return GOVERNED_SURFACES.some((s) => s.ruleChange && list.some((p) => typeof p === 'string' && p.startsWith(s.prefix))); +} + +/** The split's words under a verdict, once per split row hit, or '' when none was. Pure. */ +export function renderRuleChangeLines(matched) { + return (Array.isArray(matched) ? matched : []) + .filter((s) => s?.ruleChangeVerdict) + .map(({ glob, ruleChangeVerdict: v }) => { + const head = ` ⚖️ ${glob} declaration split (${RULE_CHANGE_RULING})`; + if (!v.measured) { + return ( + `${head}: NOT MEASURED — ${v.reason}.\n` + + ` Tier H, fail closed. \`--pr \` reads the PR body's \`${RULE_CHANGE_KEY}:\` line and its record; the queue guard reads both on the queue leg.\n` + ); + } + if (v.tier === GOVERNED_TIER_S && v.recordStage === RULE_CHANGE_RECORD_LEG_DEFERRED) { + return `${head}: Tier S — the PR body declares \`${RULE_CHANGE_KEY}: ${v.declared}\`; its record on this head must read \`${RULE_CHANGE_VERIFIED_KEY}: ${v.declared}\`, which the record leg below reads.\n`; + } + if (v.tier === GOVERNED_TIER_S) { + return `${head}: Tier S — the PR body declares \`${RULE_CHANGE_KEY}: ${v.declared}\` and the record on this head reads \`${RULE_CHANGE_VERIFIED_KEY}: ${v.declared}\`.\n`; + } + return `${head}: Tier H${v.byPath ? ' by path' : ''} —\n${v.reasons.map((r) => ` - ${r}\n`).join('')}`; + }) + .join(''); +} + /** `owner/name` out of any git remote spelling, or null. Pure. */ export function slugFromRemote(url) { const m = /(?:github\.com[:/])([\w.-]+\/[\w.-]+?)(?:\.git)?\/*\s*$/.exec(String(url ?? '')); @@ -3126,7 +3473,8 @@ export function testVerdict(paths, { repo, size = null, fork = null, checks = nu const list = (Array.isArray(paths) ? paths : []).filter((p) => typeof p === 'string' && p !== ''); // The `workflows` row's tier is read off the diff where a reading was handed in (the split): H otherwise. // The low-risk skills rows' tier is read off the pull request's body, labels and whole path list: H otherwise. - const matched = applyLowRiskArm(applyWorkflowSplit(governedPathsIn(list, repo), repo, workflowDiff), repo, lowRisk); + // The `.claude/**` row's tier is read off the body's `Rule-change:` line and the record that verifies it: H otherwise. + const matched = applyRuleChangeSplit(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(list, repo), repo, workflowDiff), repo, lowRisk), repo, lowRisk); const hit = new Set(matched.flatMap((s) => s.files)); const sized = sizeVerdict(size, approval); const forked = fork && typeof fork === 'object' ? fork : forkVerdict(null); // the FORK limb, or NOT MEASURED @@ -3330,6 +3678,7 @@ export function renderTestVerdict(verdict) { `${lines.join('\n')}${clear}\n` + renderWorkflowSplitLines(verdict.matched) + renderLowRiskLines(verdict.matched) + + renderRuleChangeLines(verdict.matched) + `${intake}${renderSizeLines(size)}` + renderExceptionLines(verdict) ); @@ -3343,6 +3692,7 @@ export function renderTestVerdict(verdict) { `${lines.join('\n')}${clear}\n` + renderWorkflowSplitLines(verdict.matched) + renderLowRiskLines(verdict.matched) + + renderRuleChangeLines(verdict.matched) + `${intake}${renderSizeLines(size)}` + renderExceptionLines(verdict) ); @@ -4885,8 +5235,10 @@ export async function fetchTimelineOver({ fetchImpl, url, channel, pageCap = PUL */ export async function pullRecordStage({ lowRisk, paths, repo, workflowDiff = null, pullHead, derivation, readers, fetchers = {}, runGit = null }) { if (!lowRisk) return lowRisk; - const surfaces = applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, repo), repo, workflowDiff), repo, lowRisk); - if (!surfaces.some((s) => s?.lowRiskVerdict?.recordStage === LOW_RISK_RECORD_STAGE.pending)) return lowRisk; + const surfaces = applyRuleChangeSplit(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, repo), repo, workflowDiff), repo, lowRisk), repo, lowRisk); + // Two stages share the one record read: the arm's (record line and card labels) and the `.claude/**` split's (record line alone). + const armPending = surfaces.some((s) => s?.lowRiskVerdict?.recordStage === LOW_RISK_RECORD_STAGE.pending); + if (!armPending && !ruleChangeRecordStagePending(surfaces)) return lowRisk; const loaded = typeof readers === 'function' ? await readers() : readers; if (loaded?.available !== true) { const reason = loaded?.reason ?? 'the queue guard readers were not loaded'; @@ -4905,8 +5257,9 @@ export async function pullRecordStage({ lowRisk, paths, repo, workflowDiff = nul fetchComments: built?.fetchComments ?? null, fetchLabels: built?.fetchLabels ?? null, fetchTimeline: built?.fetchTimeline ?? null, + withCardLabels: armPending, }); - return { ...lowRisk, record: stage.record, cardLabels: stage.cardLabels }; + return { ...lowRisk, record: stage.record, ...(armPending ? { cardLabels: stage.cardLabels } : {}) }; } /** @@ -7065,6 +7418,11 @@ async function selfTest() { // is ABOUT the scope and names another one: this checkout's own. The scope // battery pins that the matchers refuse a call that names none. const REPO = SELF_REPO_ID; + // The reading the `.claude/**` declaration split (2026-11-19) lands Tier S on: the body's one bare line, and a + // record FOUND on this head whose own line verifies it. `ruleReading` moves one half at a time for the controls. + const ruleRecord = (value = 'none', over = {}) => ({ measured: true, reason: null, located: 'found', where: 'PR', id: 7, carried: null, ruleChangeCarried: null, ruleChangeVerified: value === null ? { state: 'missing' } : { state: 'read', value }, ...over }); + const ruleReading = (body = 'Rule-change: none', record = ruleRecord()) => ({ measured: true, reason: null, body, ...(record === null ? {} : { record }) }); + const RULE_NONE = ruleReading(); // Report fixtures take a REAL window from the real resolver, never a // hand-built object: a shape drifting from `resolveWindow`'s would render // green here and print nothing an operator could read. @@ -7073,7 +7431,7 @@ async function selfTest() { // ── the governed predicate: the 2026-08-18 unified list, exactly ────────── battery('the governed predicate: the 2026-08-18 unified list, exactly'); const ids = (paths) => governedPathsIn(paths, REPO).map((s) => s.id); - assert('all-thirteen-surfaces-declared-in-order', GOVERNED_SURFACES.map((s) => s.id).join(',') === 'adr,claude-tree,skills-catalog,agents-md,claude-md,north-star,workflows,ui-adr,ui-claude-tree,ui-skills-catalog,ui-agents-md,ui-claude-md,ui-workflows', GOVERNED_SURFACES.map((s) => s.id).join(',')); + assert('all-seventeen-surfaces-declared-in-order', GOVERNED_SURFACES.map((s) => s.id).join(',') === 'adr,claude-tree,skills-catalog,agents-md,claude-md,north-star,workflows,guard-register,guard-queue,guard-records,guard-tiers,ui-adr,ui-claude-tree,ui-skills-catalog,ui-agents-md,ui-claude-md,ui-workflows', GOVERNED_SURFACES.map((s) => s.id).join(',')); assert('adr-prefix', ids(['docs/adr/0001-x.md']).join() === 'adr'); assert('whole-claude-tree-not-only-skills', ids(['.claude/hooks/guard-main-checkout.sh', '.claude/agents/os-dev.md', '.claude/settings.json']).join() === 'claude-tree'); assert('published-skills-catalog-is-governed', ids(['skills/objectstack-ui/SKILL.md']).join() === 'skills-catalog'); @@ -7096,8 +7454,8 @@ async function selfTest() { battery('the per-row repository scope (ruled B2, 2026-10-13)'); const everyRepo = GOVERNED_REPOS.map((r) => r.id); const workflowsRow = GOVERNED_SURFACES.find((s) => s.id === 'workflows'); - assert('the-six-pre-existing-rows-declare-no-scope-and-so-govern-every-repository', GOVERNED_SURFACES.filter((s) => s.id !== 'workflows' && !s.id.startsWith('ui-')).every((s) => s.repos === undefined && surfaceRepos(s).join() === everyRepo.join()), JSON.stringify(GOVERNED_SURFACES.map((s) => [s.id, s.repos ?? null]))); - assert('the-workflows-row-is-scoped-to-objectstack-objectui-and-cloud-exactly', surfaceRepos(workflowsRow).join() === 'objectstack,objectui,cloud' && workflowsRow.tier === GOVERNED_TIER_H && workflowsRow.glob === '.github/workflows/**', JSON.stringify(workflowsRow)); + assert('the-six-pre-existing-rows-declare-no-scope-and-so-govern-every-repository', GOVERNED_SURFACES.filter((s) => s.id !== 'workflows' && !s.id.startsWith('ui-') && !s.id.startsWith('guard-')).every((s) => s.repos === undefined && surfaceRepos(s).join() === everyRepo.join()), JSON.stringify(GOVERNED_SURFACES.map((s) => [s.id, s.repos ?? null]))); + assert('the-workflows-row-is-scoped-to-objectstack-objectui-cloud-and-hotcrm-exactly', surfaceRepos(workflowsRow).join() === 'objectstack,objectui,cloud,hotcrm' && workflowsRow.tier === GOVERNED_TIER_H && workflowsRow.glob === '.github/workflows/**', JSON.stringify(workflowsRow)); assert('every-declared-scope-is-a-non-empty-duplicate-free-subset-of-GOVERNED_REPOS-ids', GOVERNED_SURFACES.every((s) => s.repos === undefined || (Array.isArray(s.repos) && s.repos.length > 0 && new Set(s.repos).size === s.repos.length && s.repos.every((id) => everyRepo.includes(id)))), JSON.stringify(GOVERNED_SURFACES.map((s) => [s.id, s.repos ?? null]))); assert('the-workflows-row-is-a-prefix-row-with-a-separator-so-it-reaches-dispatch-gates-as-written-and-declares-no-hint', workflowsRow.prefix === '.github/workflows/' && !ROOT_FILE_WATCH_HINTS.some((h) => h.startsWith('.github/'))); const wf = '.github/workflows/lint.yml'; @@ -7105,10 +7463,11 @@ async function selfTest() { assert('an-objectui-workflow-path-is-governed-Tier-H', governedPathsIn([wf], 'objectui').map((s) => s.id).join() === 'workflows' && governedTierFor([wf], 'objectui') === GOVERNED_TIER_H); assert('a-cloud-workflow-path-is-governed-Tier-H', governedPathsIn([wf], 'cloud').map((s) => s.id).join() === 'workflows' && governedTierFor([wf], 'cloud') === GOVERNED_TIER_H && testVerdict([wf], { repo: 'cloud' }).governed === true); assert('an-objectos-workflow-path-is-NOT-governed', governedPathsIn([wf], 'objectos').length === 0 && testVerdict([wf], { repo: 'objectos' }).governed === false && testVerdict([wf], { repo: 'objectos' }).clearPaths.join() === wf); - assert('a-hotcrm-workflow-path-is-NOT-governed', governedPathsIn([wf], 'hotcrm').length === 0 && testVerdict([wf], { repo: 'hotcrm' }).governed === false); + assert('a-hotcrm-workflow-path-is-governed-Tier-H-the-audit-mirror-of-2026-11-19', governedPathsIn([wf], 'hotcrm').map((s) => s.id).join() === 'workflows' && governedTierFor([wf], 'hotcrm') === GOVERNED_TIER_H && testVerdict([wf], { repo: 'hotcrm' }).governed === true); + assert('control-the-row-still-leaves-objectos-and-mobile-out-and-no-reading-moves-a-hotcrm-workflow-to-S', ['objectos', 'mobile'].every((r) => governedPathsIn([wf], r).length === 0) && !workflowsRow.split.repos.includes('hotcrm')); assert('the-default-rows-still-govern-objectos-and-hotcrm-the-scope-narrows-one-row-not-the-register', ['objectos', 'hotcrm'].every((r) => governedPathsIn(['AGENTS.md', 'docs/adr/0001-x.md', '.claude/agents/os-dev.md'], r).map((s) => s.id).join() === 'adr,claude-tree,agents-md')); assert('the-near-misses-for-the-workflows-row-stay-out', ids(['.github/ISSUE_TEMPLATE/bug.md', '.github/workflows.bak/x.yml', '.github/workflowsx/y.yml', 'github/workflows/z.yml', '.github/CODEOWNERS', 'packages/x/.github/workflows/w.yml']).length === 0); - assert('surfacesChecked-counts-the-rows-that-govern-the-repository-not-the-table', testVerdict(['README.md'], { repo: 'objectstack' }).surfacesChecked === 13 && testVerdict(['README.md'], { repo: 'objectos' }).surfacesChecked === 6 && governedSurfacesFor('cloud').length === 7 && governedSurfacesFor('hotcrm').map((s) => s.id).join() === 'adr,claude-tree,skills-catalog,agents-md,claude-md,north-star'); + assert('surfacesChecked-counts-the-rows-that-govern-the-repository-not-the-table', testVerdict(['README.md'], { repo: 'objectstack' }).surfacesChecked === 17 && testVerdict(['README.md'], { repo: 'objectos' }).surfacesChecked === 6 && governedSurfacesFor('cloud').length === 7 && governedSurfacesFor('hotcrm').map((s) => s.id).join() === 'adr,claude-tree,skills-catalog,agents-md,claude-md,north-star,workflows'); assert('the-verdict-carries-the-repository-it-answered-for', testVerdict([wf], { repo: 'cloud' }).repo === 'cloud' && JSON.parse(JSON.stringify(testVerdict([wf], { repo: 'objectui' }))).repo === 'objectui'); const refuses = (fn) => { try { fn(); return null; } catch (error) { return error; } }; const noRepo = refuses(() => governedPathsIn([wf])); @@ -7198,10 +7557,11 @@ async function selfTest() { assert('the-split-repositories-are-a-subset-of-the-rows-own', row.split.repos.every((r) => surfaceRepos(row).includes(r))); assert('the-reader-parses-the-fixture-and-the-baseline-is-S-against-itself', workflowFacts(BASE_WF).ok === true && isS(tierOf(BASE_WF)) && isS(tierOf(`${BASE_WF}\n`)), show(tierOf(BASE_WF))); - // Tier H by PATH: the six release, publish and deploy files, each on disk under its own name. + // Tier H by PATH: the six release, publish and deploy files and the workflow that runs the queue guard, each on disk under its own name. const PINNED = WORKFLOW_TIER_H_FILES.map((f) => f.path); - assert('six-files-are-Tier-H-by-path-release-docker-base-image-docs-wiki-and-the-write-relay', PINNED.join() === ['release', 'docker-publish', 'framework-build-base', 'docs-deploy', 'checklist-status', 'fleet-write'].map((n) => `${WORKFLOWS_PREFIX}${n}.yml`).join(), PINNED.join()); + assert('seven-files-are-Tier-H-by-path-release-docker-base-image-docs-wiki-the-write-relay-and-the-guards-own-workflow', PINNED.join() === ['release', 'docker-publish', 'framework-build-base', 'docs-deploy', 'checklist-status', 'fleet-write', 'governed-surface-guard'].map((n) => `${WORKFLOWS_PREFIX}${n}.yml`).join(), PINNED.join()); assert('every-pinned-path-is-a-real-workflow-file-of-this-repository', PINNED.every((p) => existsSync(resolve(scriptDir, '..', '..', p))), PINNED.filter((p) => !existsSync(resolve(scriptDir, '..', '..', p))).join()); + assert('⛔ the-guards-own-workflow-is-H-by-path-on-an-edit-the-content-classifier-reads-S-anywhere-else', isH(tierOf(`# a comment\n${BASE_WF}`, { path: `${WORKFLOWS_PREFIX}governed-surface-guard.yml` }), /Tier H by path/) && isS(tierOf(`# a comment\n${BASE_WF}`)), show(tierOf(`# a comment\n${BASE_WF}`, { path: `${WORKFLOWS_PREFIX}governed-surface-guard.yml` }))); assert('a-pinned-file-is-H-even-on-a-comment-only-edit', PINNED.every((p) => isH(classifyWorkflowChange({ path: p, base: BASE_WF, head: `# a comment\n${BASE_WF}`, inventory: INVENTORY }), /Tier H by path/))); // Tier H by DIFF: one pin per C2 trigger. @@ -7333,7 +7693,7 @@ async function selfTest() { // The verdict: the split reaches testVerdict and governedTierFor, ALL-not-ANY still holds, and the scope holds. assert('a-Tier-S-reading-makes-a-workflow-only-PR-Tier-S-still-GOVERNED-exit-3', (({ governed, tier, humanMerge }) => governed && tier === GOVERNED_TIER_S && humanMerge)(testVerdict([WF], { repo: REPO, workflowDiff: readS })) && governedTierFor([WF], REPO, GOVERNED_SURFACES, readS) === GOVERNED_TIER_S); - assert('beside-a-claude-path-it-stays-S-beside-AGENTS-md-it-is-H', testVerdict([WF, '.claude/agents/os-dev.md'], { repo: REPO, workflowDiff: readS }).tier === GOVERNED_TIER_S && testVerdict([WF, 'AGENTS.md'], { repo: REPO, workflowDiff: readS }).tier === GOVERNED_TIER_H); + assert('beside-a-declared-and-verified-claude-path-it-stays-S-beside-an-undeclared-one-or-AGENTS-md-it-is-H', testVerdict([WF, '.claude/agents/os-dev.md'], { repo: REPO, workflowDiff: readS, lowRisk: RULE_NONE }).tier === GOVERNED_TIER_S && testVerdict([WF, '.claude/agents/os-dev.md'], { repo: REPO, workflowDiff: readS }).tier === GOVERNED_TIER_H && testVerdict([WF, 'AGENTS.md'], { repo: REPO, workflowDiff: readS }).tier === GOVERNED_TIER_H); assert('the-same-reading-moves-nothing-in-objectui-or-cloud-whose-guards-have-no-split-arm', ['objectui', 'cloud'].every((r) => testVerdict([WF], { repo: r, workflowDiff: readS }).tier === GOVERNED_TIER_H)); assert('no-reading-is-byte-identical-to-before-for-a-path-only-caller', testVerdict([WF], { repo: REPO }).tier === GOVERNED_TIER_H && (() => { const m = governedPathsIn(['AGENTS.md', '.claude/x.md'], REPO); return applyWorkflowSplit(m, REPO, readS).every((s, i) => s === m[i]); })()); const textS = renderTestVerdict(testVerdict([WF], { repo: REPO, workflowDiff: readS })); @@ -7415,7 +7775,7 @@ async function selfTest() { // The scope: the arm moves nothing outside objectstack, and nothing without a catalog hit. assert('the-same-S-reading-moves-nothing-in-objectui-cloud-or-hotcrm', tier([SK, CS], read([SK, CS])) === GOVERNED_TIER_S && ['objectui', 'cloud', 'hotcrm'].every((r) => tier([SK, CS], read([SK, CS]), r) === GOVERNED_TIER_H)); - assert('a-slice-with-no-catalog-row-is-returned-as-is-byte-identical', (() => { const m = governedPathsIn(['AGENTS.md', '.claude/x.md'], REPO); return applyLowRiskArm(m, REPO, read(['AGENTS.md', '.claude/x.md'])) === m && renderLowRiskLines(m) === ''; })() && tier(['.claude/agents/os-dev.md'], read(['.claude/agents/os-dev.md'])) === GOVERNED_TIER_S); + assert('a-slice-with-no-catalog-row-is-returned-as-is-byte-identical', (() => { const m = governedPathsIn(['AGENTS.md', '.claude/x.md'], REPO); return applyLowRiskArm(m, REPO, read(['AGENTS.md', '.claude/x.md'])) === m && renderLowRiskLines(m) === ''; })() && tier(['.claude/agents/os-dev.md'], RULE_NONE) === GOVERNED_TIER_S && tier(['.claude/agents/os-dev.md'], read(['.claude/agents/os-dev.md'])) === GOVERNED_TIER_H); // ── The RECORD STAGE: the arm's last two conditions — the review's own `Security-touching: no` line and a card // that never carried `security` — one row per piece. Every row holds the pull-read conditions fixed (`read`). @@ -7721,7 +8081,7 @@ async function selfTest() { const ROOT_ROWS = Object.freeze(GOVERNED_SURFACES.filter((s) => !s.id.startsWith('ui-'))); const UI_SPECIMENS = { 'ui-adr': 'ui/docs/adr/0001-master-detail-subform.md', 'ui-claude-tree': 'ui/.claude/skills/verify/SKILL.md', 'ui-skills-catalog': 'ui/skills/objectui/SKILL.md', 'ui-agents-md': 'ui/AGENTS.md', 'ui-claude-md': 'ui/CLAUDE.md', 'ui-workflows': 'ui/.github/workflows/ci.yml' }; assert('the-ui-rows-are-six-well-formed-register-rows', UI_ROWS.length === 6 && UI_ROWS.every((r) => (r.prefix ? r.prefix.endsWith('/') && r.glob === `${r.prefix}**` && r.exact === undefined : r.glob === r.exact) && r.tier === GOVERNED_TIER_H && r.tierRepos === undefined && surfaceRepos(r).join() === 'objectstack') && new Set(GOVERNED_SURFACES.map((r) => r.id)).size === GOVERNED_SURFACES.length, JSON.stringify(UI_ROWS.map((r) => r.id))); - assert('the-ui-rows-mirror-the-six-rows-objectui-governs-each-under-ui', UI_ROWS.map((r) => r.glob).join() === ROOT_ROWS.filter((s) => s.id !== 'north-star').map((s) => `ui/${s.glob}`).join(), UI_ROWS.map((r) => r.glob).join()); + assert('the-ui-rows-mirror-the-six-rows-objectui-governs-each-under-ui', UI_ROWS.map((r) => r.glob).join() === ROOT_ROWS.filter((s) => s.id !== 'north-star' && !s.id.startsWith('guard-')).map((s) => `ui/${s.glob}`).join(), UI_ROWS.map((r) => r.glob).join()); for (const row of UI_ROWS) { assert(`the-${row.id}-specimen-is-governed-by-its-own-row-alone`, ids([UI_SPECIMENS[row.id]]).join() === row.id, ids([UI_SPECIMENS[row.id]]).join()); } @@ -7732,7 +8092,7 @@ async function selfTest() { assert('the-root-rows-do-not-reach-into-ui-and-the-ui-rows-do-not-reach-the-root', ids(['ui/.github/workflows/ci.yml', '.github/workflows/lint.yml', 'ui/AGENTS.md', 'AGENTS.md']).join() === 'agents-md,workflows,ui-agents-md,ui-workflows'); assert('the-ui-rows-govern-objectstack-alone', ['objectui', 'cloud', 'objectos', 'hotcrm'].every((r) => governedPathsIn(Object.values(UI_SPECIMENS), r).length === 0) && governedSurfacesFor('objectui').length === 7); assert('a-register-handed-in-is-counted-by-the-same-reader', governedSurfacesFor(REPO, ROOT_ROWS).length === governedSurfacesFor(REPO).length - UI_ROWS.length && governedPathsIn(Object.values(UI_SPECIMENS), REPO, ROOT_ROWS).length === 0); - assert('the-register-knows-ui-the-rows-are-live', ids(Object.values(UI_SPECIMENS)).length === UI_ROWS.length && governedSurfacesFor(REPO).length === 13); + assert('the-register-knows-ui-the-rows-are-live', ids(Object.values(UI_SPECIMENS)).length === UI_ROWS.length && governedSurfacesFor(REPO).length === 17); // ── the dispatch-gates declaration (#9979) ─────────────────────────────── // @@ -7771,16 +8131,16 @@ async function selfTest() { assert('every-row-carries-a-tier-and-it-is-H-or-S', GOVERNED_SURFACES.every((s) => s.tier === GOVERNED_TIER_H || s.tier === GOVERNED_TIER_S), JSON.stringify(GOVERNED_SURFACES.map((s) => [s.id, s.tier]))); assert('the-tier-values-are-distinct-single-letters-a-reader-greps', GOVERNED_TIER_H === 'H' && GOVERNED_TIER_S === 'S' && Object.keys(GOVERNED_TIERS).join() === 'H,S'); assert('Tier-S-is-exactly-the-whole-claude-tree-row', GOVERNED_SURFACES.filter((s) => s.tier === GOVERNED_TIER_S).map((s) => s.id).join() === 'claude-tree'); - assert('Tier-H-is-the-law-adr-north-star-skills-catalog-agents-md-claude-md-the-workflows-row-and-the-six-ui-rows', GOVERNED_SURFACES.filter((s) => s.tier === GOVERNED_TIER_H).map((s) => s.id).join() === 'adr,skills-catalog,agents-md,claude-md,north-star,workflows,ui-adr,ui-claude-tree,ui-skills-catalog,ui-agents-md,ui-claude-md,ui-workflows'); - assert('settings-and-hooks-are-Tier-S-by-the-amendment', governedTierFor(['.claude/settings.json', '.claude/hooks/guard-main-checkout.sh'], REPO) === GOVERNED_TIER_S); - assert('skills-agents-and-the-fact-layer-are-Tier-S', governedTierFor(['.claude/skills/pm-dispatch/SKILL.md', '.claude/agents/os-dev.md', '.claude/skills/pm-dispatch/references/contract-review.md'], REPO) === GOVERNED_TIER_S); + assert('Tier-H-is-the-law-adr-north-star-skills-catalog-agents-md-claude-md-the-workflows-row-the-four-guard-instruments-and-the-six-ui-rows', GOVERNED_SURFACES.filter((s) => s.tier === GOVERNED_TIER_H).map((s) => s.id).join() === 'adr,skills-catalog,agents-md,claude-md,north-star,workflows,guard-register,guard-queue,guard-records,guard-tiers,ui-adr,ui-claude-tree,ui-skills-catalog,ui-agents-md,ui-claude-md,ui-workflows'); + assert('settings-and-hooks-are-Tier-H-by-path-the-amendment-is-taken-back', ['.claude/settings.json', '.claude/settings.local.json', '.claude/hooks/guard-main-checkout.sh'].every((p) => governedTierFor([p], REPO, GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_H && governedTierFor([p, '.claude/agents/os-dev.md'], REPO, GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_H)); + assert('skills-agents-and-the-fact-layer-are-Tier-S-on-a-declared-and-verified-reading-and-H-on-the-path-list-alone', ((paths) => governedTierFor(paths, REPO, GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_S && governedTierFor(paths, REPO) === GOVERNED_TIER_H)(['.claude/skills/pm-dispatch/SKILL.md', '.claude/agents/os-dev.md', '.claude/skills/pm-dispatch/references/contract-review.md'])); assert('each-Tier-H-surface-answers-H-alone', ['docs/adr/0001-x.md', 'docs/NORTH-STAR.md', 'skills/objectstack-ui/SKILL.md', 'AGENTS.md', 'CLAUDE.md'].every((p) => governedTierFor([p], REPO) === GOVERNED_TIER_H)); assert('ALL-not-ANY-one-Tier-H-path-makes-the-whole-list-Tier-H', governedTierFor(['.claude/agents/os-dev.md', '.claude/settings.json', 'AGENTS.md'], REPO) === GOVERNED_TIER_H); - assert('an-ungoverned-rider-neither-demotes-a-Tier-H-list-nor-promotes-a-Tier-S-one', governedTierFor(['README.md', 'AGENTS.md'], REPO) === GOVERNED_TIER_H && governedTierFor(['README.md', '.claude/agents/os-dev.md'], REPO) === GOVERNED_TIER_S); + assert('an-ungoverned-rider-neither-demotes-a-Tier-H-list-nor-promotes-a-Tier-S-one', governedTierFor(['README.md', 'AGENTS.md'], REPO) === GOVERNED_TIER_H && governedTierFor(['README.md', '.claude/agents/os-dev.md'], REPO, GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_S); assert('an-EMPTY-or-UNGOVERNED-list-answers-H-fail-closed', governedTierFor([], REPO) === GOVERNED_TIER_H && governedTierFor(undefined, REPO) === GOVERNED_TIER_H && governedTierFor(['README.md'], REPO) === GOVERNED_TIER_H); assert('the-published-skills-catalog-stays-Tier-H-the-seat-did-not-propose-moving-it', tierOf('skills-catalog') === GOVERNED_TIER_H); - assert('--test-carries-the-tier-and-null-when-nothing-is-governed', testVerdict(['.claude/agents/os-dev.md'], { repo: REPO }).tier === GOVERNED_TIER_S && testVerdict(['AGENTS.md'], { repo: REPO }).tier === GOVERNED_TIER_H && testVerdict(['README.md'], { repo: REPO }).tier === null); - const tierSCase = testVerdict(['packages/spec/src/index.ts', '.claude/agents/os-dev.md'], { repo: REPO }); + assert('--test-carries-the-tier-and-null-when-nothing-is-governed', testVerdict(['.claude/agents/os-dev.md'], { repo: REPO, lowRisk: RULE_NONE }).tier === GOVERNED_TIER_S && testVerdict(['AGENTS.md'], { repo: REPO }).tier === GOVERNED_TIER_H && testVerdict(['README.md'], { repo: REPO }).tier === null); + const tierSCase = testVerdict(['packages/spec/src/index.ts', '.claude/agents/os-dev.md'], { repo: REPO, lowRisk: RULE_NONE }); const tierHCase = testVerdict(['packages/spec/src/index.ts', '.claude/agents/os-dev.md', 'AGENTS.md'], { repo: REPO }); const tierSText = renderTestVerdict(tierSCase); const tierHText = renderTestVerdict(tierHCase); @@ -7794,7 +8154,7 @@ async function selfTest() { // recomputed on the lifted slice, never read off the pre-lift one. const liftPath = 'skills/objectstack-ui/references/_index.md'; const lifted = new Map([[liftPath, { pureRegeneration: true, reason: 'byte-equal to the generator' }]]); - const preLift = testVerdict([liftPath, '.claude/agents/os-dev.md'], { repo: REPO }); + const preLift = testVerdict([liftPath, '.claude/agents/os-dev.md'], { repo: REPO, lowRisk: RULE_NONE }); const postLift = applyGeneratedExceptions(preLift, lifted); assert('the-tier-is-recomputed-on-the-LIFTED-slice', preLift.tier === GOVERNED_TIER_H && postLift.tier === GOVERNED_TIER_S && postLift.governed === true, JSON.stringify([preLift.tier, postLift.tier])); const allLifted = applyGeneratedExceptions(testVerdict([liftPath], { repo: REPO }), lifted); @@ -7812,12 +8172,13 @@ async function selfTest() { battery('a row\'s tier is scoped per repository (#25199)'); const claudeRow = GOVERNED_SURFACES.find((s) => s.id === 'claude-tree'); const HOOK = '.claude/hooks/x.sh'; + const TREE = '.claude/agents/x.md'; const PR_13320 = ['guard-main-checkout-bash', 'guard-shared-stash', 'guard-tree-enum'].flatMap((h) => [`.claude/hooks/${h}.selftest.sh`, `.claude/hooks/${h}.sh`]); const elsewhere = everyRepo.filter((r) => r !== 'objectstack'); assert('the-claude-tree-row-holds-Tier-S-in-objectstack-alone', claudeRow.tier === GOVERNED_TIER_S && claudeRow.tierRepos?.join() === 'objectstack' && claudeRow.repos === undefined, JSON.stringify(claudeRow)); assert('it-is-the-only-row-that-scopes-its-tier', GOVERNED_SURFACES.filter((s) => s.tierRepos !== undefined).map((s) => s.id).join() === 'claude-tree'); assert('every-tier-scope-is-a-non-empty-duplicate-free-subset-of-the-rows-own-repositories-on-a-Tier-S-row', GOVERNED_SURFACES.every((s) => s.tierRepos === undefined || (s.tier === GOVERNED_TIER_S && Array.isArray(s.tierRepos) && s.tierRepos.length > 0 && new Set(s.tierRepos).size === s.tierRepos.length && s.tierRepos.every((id) => surfaceRepos(s).includes(id))))); - assert('an-objectstack-claude-path-is-Tier-S-unchanged', governedTierFor([HOOK], 'objectstack') === GOVERNED_TIER_S && testVerdict([HOOK], { repo: 'objectstack' }).tier === GOVERNED_TIER_S); + assert('an-objectstack-claude-path-is-Tier-S-on-its-declaration-and-record-and-the-row-keeps-S-for-them', governedTierFor([TREE], 'objectstack', GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_S && testVerdict([TREE], { repo: 'objectstack', lowRisk: RULE_NONE }).tier === GOVERNED_TIER_S && governedTierFor([TREE], 'objectui', GOVERNED_SURFACES, null, RULE_NONE) === GOVERNED_TIER_H); assert('an-objectui-claude-path-is-governed-by-the-same-row-and-lands-Tier-H', governedPathsIn([HOOK], 'objectui').map((s) => `${s.id}:${s.tier}`).join() === 'claude-tree:H' && governedTierFor([HOOK], 'objectui') === GOVERNED_TIER_H && testVerdict([HOOK], { repo: 'objectui' }).governed === true); assert('cloud-objectos-and-hotcrm-read-Tier-H-their-guards-unread-so-fail-closed', elsewhere.every((r) => governedTierFor([HOOK], r) === GOVERNED_TIER_H && governedPathsIn([HOOK], r).map((s) => s.id).join() === 'claude-tree')); assert('a-repository-the-scope-does-not-name-answers-H-including-one-added-later', surfaceTierIn(claudeRow, 'objectstack') === GOVERNED_TIER_S && surfaceTierIn(claudeRow, 'a-future-repo') === GOVERNED_TIER_H && GOVERNED_SURFACES.filter((s) => s.tierRepos === undefined).every((s) => everyRepo.every((r) => surfaceTierIn(s, r) === s.tier))); @@ -7826,9 +8187,131 @@ async function selfTest() { const ui13320 = testVerdict(PR_13320, { repo: 'objectui' }); const ui13320Text = renderTestVerdict(ui13320); assert('the-objectui-13320-replay-reads-GOVERNED-Tier-H-and-says-so', ui13320.governed === true && ui13320.tier === GOVERNED_TIER_H && ui13320.hitPaths.length === 6 && /landing tier: H/.test(ui13320Text) && !/Tier S/.test(ui13320Text), ui13320Text); - assert('and-the-same-six-paths-in-objectstack-still-read-Tier-S', testVerdict(PR_13320, { repo: 'objectstack' }).tier === GOVERNED_TIER_S && /Tier S/.test(renderTestVerdict(testVerdict(PR_13320, { repo: 'objectstack' })))); + assert('and-the-same-six-hook-paths-in-objectstack-read-Tier-H-by-path-since-2026-11-19', ((v) => v.tier === GOVERNED_TIER_H && /declaration split .*Tier H by path/.test(renderTestVerdict(v)) && !/Tier S\(/.test(renderTestVerdict(v)))(testVerdict(PR_13320, { repo: 'objectstack', lowRisk: RULE_NONE }))); assert('an-objectui-mixed-diff-stays-H-and-the-exit-stays-the-shared-3', governedTierFor([HOOK, 'README.md'], 'objectui') === GOVERNED_TIER_H && governedTierFor([HOOK, 'AGENTS.md'], 'objectui') === GOVERNED_TIER_H && runTestModeExitFor([HOOK], 'objectui') === EXIT_TEST_GOVERNED); + // ── the guard instruments and the `.claude/**` declaration split (2026-11-19, card #35321) ── + // + // Each branch of the card's "done when" is one assertion, and each carries its own control: the input one + // step away that must read the OTHER way, so no branch is green because everything reads H. + battery('⚖️ #35321: the guard instruments are Tier H, and `.claude/**` splits by declaration'); + { + const tier = (paths, reading = null, repo = REPO) => governedTierFor(paths, repo, GOVERNED_SURFACES, null, reading); + const split = (paths, reading = null) => applyRuleChangeSplit(governedPathsIn(paths, REPO), REPO, reading).find((s) => s.ruleChangeVerdict)?.ruleChangeVerdict; + const why = (paths, reading = null) => (split(paths, reading)?.reasons ?? []).join(' | '); + const WORDING = '.claude/skills/pm-dispatch/SKILL.md'; + const GUARDS = ['scripts/pm/check-governed-merges.mjs', 'scripts/pm/check-governed-queue-guard.mjs', 'scripts/pm/record-recognisers.mjs', 'scripts/pm/dispatch-gates.mjs']; + + // Item 1: the four instruments, Tier H, objectstack alone. + assert('⛔ guard-file-is-Tier-H-each-of-the-four-alone-and-beside-a-verified-claude-path', + GUARDS.every((p) => tier([p]) === GOVERNED_TIER_H && tier([p], RULE_NONE) === GOVERNED_TIER_H && tier([p, WORDING], RULE_NONE) === GOVERNED_TIER_H && testVerdict([p], { repo: REPO }).governed === true), + GUARDS.map((p) => `${p}:${tier([p])}`).join()); + assert('control-a-sibling-script-is-not-governed-and-the-four-rows-govern-objectstack-alone', + ['scripts/pm/check-governed-prose.mjs', 'scripts/pm/check-half-states.mjs', 'scripts/pm/dispatch-gates.self-test.mjs', 'ui/scripts/check-governed-queue-guard.mjs', 'scripts/pm/check-governed-merges.mjs.bak'].every((p) => governedPathsIn([p], REPO).length === 0) && + GOVERNED_REPOS.filter((r) => r.id !== REPO).every((r) => governedPathsIn(GUARDS, r.id).length === 0)); + assert('the-four-rows-are-exact-rows-whose-path-is-this-repositorys-own-file', + GOVERNED_SURFACES.filter((s) => s.id.startsWith('guard-')).map((s) => s.exact).join() === GUARDS.join() && + GOVERNED_SURFACES.filter((s) => s.id.startsWith('guard-')).every((s) => s.glob === s.exact && s.prefix === undefined && s.tier === GOVERNED_TIER_H && s.repos.join() === REPO && s.tierRepos === undefined && s.lowRisk === undefined && existsSync(resolve(scriptDir, '..', '..', s.exact)))); + + // Item 2: `.claude/` wording with both lines. + assert('⭐ claude-wording-with-both-lines-is-Tier-S', + tier([WORDING], RULE_NONE) === GOVERNED_TIER_S && testVerdict([WORDING, 'README.md'], { repo: REPO, lowRisk: RULE_NONE }).tier === GOVERNED_TIER_S && split([WORDING], RULE_NONE).declared === 'none' && split([WORDING], RULE_NONE).recordStage === LOW_RISK_RECORD_STAGE.read, + why([WORDING], RULE_NONE)); + assert('control-the-same-path-with-no-reading-is-Tier-H-NOT-MEASURED-and-the-row-moves-nowhere-else', + tier([WORDING]) === GOVERNED_TIER_H && split([WORDING]).measured === false && tier([WORDING], { measured: false, reason: 'x' }) === GOVERNED_TIER_H && + ['objectui', 'cloud', 'hotcrm'].every((r) => tier([WORDING], RULE_NONE, r) === GOVERNED_TIER_H) && tier(['ui/.claude/skills/x.md'], RULE_NONE) === GOVERNED_TIER_H); + assert('⭐ a-ruled-copy-with-its-Ruling-ref-and-a-record-that-verifies-ruled-is-Tier-S', + tier([WORDING], ruleReading('Rule-change: ruled\nRuling-ref: 「同意」 — the maintainer, review thread, 2026-11-19 04:30Z', ruleRecord('ruled'))) === GOVERNED_TIER_S, + why([WORDING], ruleReading('Rule-change: ruled\nRuling-ref: 「同意」 — the maintainer, review thread, 2026-11-19 04:30Z', ruleRecord('ruled')))); + assert('control-ruled-without-a-Ruling-ref-or-with-an-empty-one-is-Tier-H', + [ruleReading('Rule-change: ruled', ruleRecord('ruled')), ruleReading('Rule-change: ruled\nRuling-ref:', ruleRecord('ruled')), ruleReading('Rule-change: ruled\n> Ruling-ref: x', ruleRecord('ruled'))].every((r) => tier([WORDING], r) === GOVERNED_TIER_H) && + /carries no `Ruling-ref:` line/.test(why([WORDING], ruleReading('Rule-change: ruled', ruleRecord('ruled'))))); + + // Item 2: the missing line, `yes`, and a record that does not verify. + assert('⛔ missing-line-is-Tier-H', + tier([WORDING], ruleReading('Fixes #1\n\nClause-②: no\nMetadata-protocol: none\n')) === GOVERNED_TIER_H && /carries no `Rule-change:` line/.test(why([WORDING], ruleReading(''))) && split([WORDING], ruleReading('')).recordStage === LOW_RISK_RECORD_STAGE.notReached, + why([WORDING], ruleReading(''))); + assert('⛔ Rule-change-yes-is-Tier-H-whatever-the-record-says', + tier([WORDING], ruleReading('Rule-change: yes', ruleRecord('none'))) === GOVERNED_TIER_H && tier([WORDING], ruleReading('Rule-change: yes', ruleRecord('yes'))) === GOVERNED_TIER_H && /declares `Rule-change: yes`/.test(why([WORDING], ruleReading('Rule-change: yes'))), + why([WORDING], ruleReading('Rule-change: yes'))); + const unverified = { + 'no line on the record': ruleRecord(null), + 'the record reads yes': ruleRecord('yes'), + 'the record verifies the other value': ruleRecord('ruled'), + 'an unreadable line': ruleRecord('none', { ruleChangeVerified: { state: 'unreadable', reason: 'two lines' } }), + 'no record on this head': { measured: true, reason: null, located: 'absent', where: null, id: null, carried: null, ruleChangeVerified: null }, + 'an unsigned record': ruleRecord('none', { located: 'unsigned' }), + 'a record that was not read': { measured: false, reason: 'the PR thread answered 502' }, + 'a record carried over a hop that moved the tree': ruleRecord('none', { ruleChangeCarried: { from: 'a'.repeat(40), ok: false, reason: 'was carried over hops that moved .claude/x.md' } }), + }; + for (const [name, record] of Object.entries(unverified)) { + assert(`⛔ unverified-is-Tier-H: ${name}`, tier([WORDING], ruleReading('Rule-change: none', record)) === GOVERNED_TIER_H && split([WORDING], ruleReading('Rule-change: none', record)).reasons.length === 1, why([WORDING], ruleReading('Rule-change: none', record))); + } + assert('control-a-carried-record-whose-hops-moved-nothing-under-the-row-still-verifies', + tier([WORDING], ruleReading('Rule-change: none', ruleRecord('none', { ruleChangeCarried: { from: 'a'.repeat(40), ok: true, reason: null } }))) === GOVERNED_TIER_S); + assert('⛔ the-record-not-handed-in-is-PENDING-Tier-H-never-none', + ((v) => v.tier === GOVERNED_TIER_H && v.recordStage === LOW_RISK_RECORD_STAGE.pending && v.reasons.join() === RULE_CHANGE_RECORD_STAGE_PENDING_REASON && v.declared === 'none')(split([WORDING], ruleReading('Rule-change: none', null))) && + ruleChangeRecordStagePending(applyRuleChangeSplit(governedPathsIn([WORDING], REPO), REPO, ruleReading('Rule-change: none', null))) === true && + ruleChangeRecordStagePending(applyRuleChangeSplit(governedPathsIn([WORDING, 'AGENTS.md'], REPO), REPO, ruleReading('Rule-change: none', null))) === false && + ruleChangeRecordStagePending(applyRuleChangeSplit(governedPathsIn([WORDING], REPO), REPO, ruleReading('Rule-change: yes', null))) === false); + + const deferred = (body) => ({ measured: true, reason: null, body, recordLeg: RULE_CHANGE_RECORD_LEG_DEFERRED }); + assert('a-caller-with-its-own-record-leg-reads-DEFERRED-Tier-S-on-the-declaration-alone-and-nothing-else-moves', + ((v) => v.tier === GOVERNED_TIER_S && v.recordStage === RULE_CHANGE_RECORD_LEG_DEFERRED && v.declared === 'none' && v.reasons.length === 0)(split([WORDING], deferred('Rule-change: none'))) && + [deferred(''), deferred('Rule-change: yes'), deferred('Rule-change: ruled'), { ...deferred('Rule-change: none'), measured: false }].every((r) => tier([WORDING], r) === GOVERNED_TIER_H) && + tier(['.claude/settings.json'], deferred('Rule-change: none')) === GOVERNED_TIER_H && tier([WORDING], { ...deferred('Rule-change: none'), record: ruleRecord('yes') }) === GOVERNED_TIER_H && + ruleChangeRecordStagePending(applyRuleChangeSplit(governedPathsIn([WORDING], REPO), REPO, deferred('Rule-change: none'))) === false); + + // Item 2: settings and hooks, decided before any declaration is read. + const HOT = ['.claude/settings.json', '.claude/settings.local.json', '.claude/hooks/guard-main-checkout.sh', '.claude/hooks/lib/x.mjs']; + assert('⛔ settings-and-hooks-are-Tier-H-by-path-on-a-reading-that-would-land-anything-else', + HOT.every((p) => tier([p], RULE_NONE) === GOVERNED_TIER_H && split([p], RULE_NONE).byPath === true && split([p], RULE_NONE).declared === null && tier([p, WORDING], RULE_NONE) === GOVERNED_TIER_H), + HOT.map((p) => `${p}:${tier([p], RULE_NONE)}`).join()); + assert('control-the-near-misses-beside-them-land-Tier-S-on-the-same-reading', + ['.claude/settings.md', '.claude/skills/settings.json', '.claude/skills/hooks/x.sh', '.claude/hooks.md', '.claude/settings/x.json'].every((p) => tier([p], RULE_NONE) === GOVERNED_TIER_S), + ['.claude/settings.md', '.claude/skills/settings.json', '.claude/skills/hooks/x.sh', '.claude/hooks.md', '.claude/settings/x.json'].map((p) => `${p}:${tier([p], RULE_NONE)}`).join()); + assert('the-by-path-list-is-two-rows-each-with-the-pattern-CODEOWNERS-routes', + RULE_CHANGE_TIER_H_PATHS.map((r) => `${r.id}=${r.pattern}`).join() === 'settings=.claude/settings*.json,hooks=.claude/hooks/' && Object.isFrozen(RULE_CHANGE_TIER_H_PATHS) && RULE_CHANGE_TIER_H_PATHS.every((r) => Object.isFrozen(r))); + + // The one-bare-line reader the two declarations and the record's line are read with. + const read = (text) => readOneBareLine(text, RULE_CHANGE_KEY, RULE_CHANGE_VALUES); + assert('the-line-reads-bare-bulleted-bold-and-with-its-value-in-a-code-span', + ['Rule-change: none', '- Rule-change: none', '**Rule-change: none**', 'Rule-change: `none`', 'intro\n\nRule-change: none \n\ntail'].every((t) => read(t).state === 'read' && read(t).value === 'none') && read('Rule-change: ruled').value === 'ruled' && read('Rule-change: yes').value === 'yes'); + const unread = { + doubled: 'Rule-change: none\nRule-change: none', + 'a quoted yes beside a bare none': '> Rule-change: yes\n\nRule-change: none', + fenced: '```\nRule-change: none\n```', + quoted: '> Rule-change: none', + 'indented as code': ' Rule-change: none', + 'trailing words': 'Rule-change: none — wording only', + 'another value': 'Rule-change: no', + 'the key in a code span': '`Rule-change`: none', + 'a near-miss key': 'Rule change: none', + 'an empty value': 'Rule-change:', + }; + for (const [name, text] of Object.entries(unread)) { + assert(`⛔ the-line-is-unreadable-and-Tier-H: ${name}`, read(text).state === 'unreadable' && tier([WORDING], ruleReading(text)) === GOVERNED_TIER_H, JSON.stringify(read(text))); + } + assert('a-mention-off-the-line-start-and-the-records-own-key-are-not-this-line', + read('This PR carries Rule-change: yes in prose.').state === 'missing' && read('Rule-change-verified: none').state === 'missing' && read('').state === 'missing' && + readRuleChangeVerified('Rule-change: none').state === 'missing' && readRuleChangeVerified('Rule-change-verified: ruled').value === 'ruled' && readRuleChangeVerified('Rule-change-verified: maybe').state === 'unreadable'); + assert('the-vocabulary-is-three-values-two-of-them-a-seats-and-the-keys-are-the-three-the-prose-names', + RULE_CHANGE_VALUES.join() === 'none,ruled,yes' && RULE_CHANGE_SEAT_VALUES.join() === 'none,ruled' && [RULE_CHANGE_KEY, RULING_REF_KEY, RULE_CHANGE_VERIFIED_KEY].join() === 'Rule-change,Ruling-ref,Rule-change-verified'); + + // The words, and the chain. + const words = (reading) => renderTestVerdict(testVerdict([WORDING], { repo: REPO, lowRisk: reading })); + assert('the-words-name-the-ruling-and-each-of-the-three-readings', + /declaration split .*NOT MEASURED/.test(words(null)) && words(null).includes(RULE_CHANGE_RULING) && /landing tier: H/.test(words(null)) && + /declaration split .*: Tier S — the PR body declares `Rule-change: none`/.test(words(RULE_NONE)) && /Tier S\(席内达档 L2 审核落地\)/.test(words(RULE_NONE)) && + /declaration split .*: Tier H —\n {8}- the PR body declares `Rule-change: yes`/.test(words(ruleReading('Rule-change: yes'))) && renderRuleChangeLines(governedPathsIn(['AGENTS.md'], REPO)) === ''); + assert('a-slice-with-no-split-row-is-returned-row-for-row-and-a-path-only-reader-of-the-raw-row-still-reads-S', + (() => { const m = governedPathsIn(['AGENTS.md', 'skills/x/SKILL.md'], REPO); return applyRuleChangeSplit(m, REPO, RULE_NONE).every((s, i) => s === m[i]); })() && + landingTierOf(governedPathsIn([WORDING], REPO)) === GOVERNED_TIER_S && GOVERNED_SURFACES.find((s) => s.id === 'claude-tree').ruleChange.repos.join() === REPO && GOVERNED_SURFACES.filter((s) => s.ruleChange).length === 1); + assert('--test-on-a-claude-path-exits-3-as-before-and-prints-Tier-H-until-the-PR-is-read', runTestModeExitFor([WORDING], REPO) === EXIT_TEST_GOVERNED && testVerdict([WORDING], { repo: REPO }).tier === GOVERNED_TIER_H); + assert('ruleChangeRowHit-is-the-registers-own-test-for-where-the-record-template-prints-the-verified-line', + ruleChangeRowHit([WORDING]) && ruleChangeRowHit(['AGENTS.md', '.claude/hooks/x.sh']) && !ruleChangeRowHit(['AGENTS.md', 'skills/x/SKILL.md', 'ui/.claude/x.md']) && !ruleChangeRowHit([]) && !ruleChangeRowHit(null)); + } + // ── --since parsing ─────────────────────────────────────────────────────── battery('since parsing'); const now = new Date('2026-08-18T12:00:00Z'); @@ -8711,9 +9194,9 @@ async function selfTest() { const mixedCase = testVerdict(['packages/spec/src/index.ts', '.claude/agents/os-dev.md', 'README.md'], { repo: REPO }); assert('--test-on-a-mixed-diff-answers-GOVERNED-on-one-hit', mixedCase.governed === true && mixedCase.hitPaths.join() === '.claude/agents/os-dev.md', JSON.stringify(mixedCase.hitPaths)); assert('--test-lists-the-paths-that-are-NOT-on-the-register-too', mixedCase.clearPaths.join() === 'packages/spec/src/index.ts,README.md', JSON.stringify(mixedCase.clearPaths)); - const clearCase = testVerdict(['packages/spec/src/index.ts', 'scripts/pm/check-governed-merges.mjs'], { repo: REPO }); + const clearCase = testVerdict(['packages/spec/src/index.ts', 'scripts/pm/check-governed-prose.mjs'], { repo: REPO }); assert('--test-on-an-ordinary-diff-answers-NOT-governed', clearCase.governed === false && clearCase.hitPaths.length === 0, JSON.stringify(clearCase)); - assert('this-very-file-is-not-itself-a-governed-surface', testVerdict(['scripts/pm/check-governed-merges.mjs'], { repo: REPO }).governed === false); + assert('this-very-file-IS-a-governed-surface-Tier-H-since-2026-11-19-and-a-sibling-script-is-not', ((v) => v.governed === true && v.tier === GOVERNED_TIER_H && v.matched.map((s) => s.id).join() === 'guard-register')(testVerdict(['scripts/pm/check-governed-merges.mjs'], { repo: REPO })) && testVerdict(['scripts/pm/check-governed-prose.mjs'], { repo: REPO }).governed === false); assert('--test-not-governed-renders-the-re-run-on-the-final-list-warning', renderTestVerdict(clearCase).includes('NOT governed') && renderTestVerdict(clearCase).includes('recall'), renderTestVerdict(clearCase)); // Near misses on the predicate, the class the incident turns on: the seat // reasoned about a name, not a register. @@ -9253,13 +9736,13 @@ async function selfTest() { const liftedHead = renderTestVerdict(liftedTest).split('\n')[0]; assert( '⭐ the-test-head-no-longer-reports-a-post-lift-zero-as-if-nothing-had-hit-the-register', - liftedHead === 'governed-surface predicate: 0 of 4 path(s) hit the register after 1 generated-artifact lift(s) (13 surfaces govern objectstack).', + liftedHead === 'governed-surface predicate: 0 of 4 path(s) hit the register after 1 generated-artifact lift(s) (17 surfaces govern objectstack).', liftedHead, ); const plainHead = renderTestVerdict(testVerdict(['packages/spec/src/ui/view.zod.ts'], { repo: REPO })).split('\n')[0]; assert( 'and-a-verdict-with-no-lift-keeps-its-head-line-byte-for-byte', - plainHead === 'governed-surface predicate: 0 of 1 path(s) hit the register (13 surfaces govern objectstack).', + plainHead === 'governed-surface predicate: 0 of 1 path(s) hit the register (17 surfaces govern objectstack).', plainHead, ); @@ -9842,12 +10325,12 @@ async function selfTest() { const sameRepo = wordsOf(['packages/spec/src/index.ts'], { fork: forkOf('o/r'), size: { additions: 1, deletions: 0 } }); assert('a-same-repo-head-on-ordinary-paths-is-unchanged-NOT-governed-ordinary-queue-landing-and-no-fork-line', forkOf('o/r').isFork === false && forkOf('o/r').measured === true && landsByHumanMerge(testVerdict(['x.ts'], { repo: REPO, fork: forkOf('o/r') })) === false && sameRepo.includes('ordinary queue landing applies') && !sameRepo.includes('head repo') && !sameRepo.includes('FORK'), sameRepo); - const forkTierOf = (path, headRepo) => testVerdict([path], { repo: REPO, fork: forkOf(headRepo) }); + const forkTierOf = (path, headRepo) => testVerdict([path], { repo: REPO, fork: forkOf(headRepo), lowRisk: RULE_NONE }); const S_PATH = '.claude/agents/os-dev.md'; assert('a-same-repo-governed-head-keeps-its-tier-H-or-S-word-for-word-while-a-fork-head-on-a-Tier-S-path-still-prints-the-fork-sentence-the-seat-adopts-it-never-lands-it', forkTierOf('AGENTS.md', 'o/r').tier === GOVERNED_TIER_H && !wordsOf(['AGENTS.md'], { fork: forkOf('o/r') }).includes('FORK') && wordsOf(['AGENTS.md'], { fork: forkOf('o/r') }).includes('H(人合)') && - forkTierOf(S_PATH, 'o/r').tier === GOVERNED_TIER_S && wordsOf([S_PATH], { fork: forkOf('o/r') }).includes('Tier S') && !wordsOf([S_PATH], { fork: forkOf('o/r') }).includes('head repo') && - forkTierOf(S_PATH, 'someone/r').tier === GOVERNED_TIER_S && forkTierOf(S_PATH, 'someone/r').humanMerge === true && wordsOf([S_PATH], { fork: forkOf('someone/r') }).includes('FORK PR'), wordsOf([S_PATH], { fork: forkOf('someone/r') })); + forkTierOf(S_PATH, 'o/r').tier === GOVERNED_TIER_S && wordsOf([S_PATH], { fork: forkOf('o/r'), lowRisk: RULE_NONE }).includes('Tier S') && !wordsOf([S_PATH], { fork: forkOf('o/r'), lowRisk: RULE_NONE }).includes('head repo') && + forkTierOf(S_PATH, 'someone/r').tier === GOVERNED_TIER_S && forkTierOf(S_PATH, 'someone/r').humanMerge === true && wordsOf([S_PATH], { fork: forkOf('someone/r'), lowRisk: RULE_NONE }).includes('FORK PR'), wordsOf([S_PATH], { fork: forkOf('someone/r'), lowRisk: RULE_NONE })); const zeroChecks = wordsOf(['src/x.ts'], { fork: forkOf('someone/r'), checks: { sha: 'feedface0001', total: 0, reason: null } }); assert('⭐ ZERO-check-runs-on-the-head-read-NOT-MEASURED-never-green-a-head-whose-checks-ran-prints-no-such-line-an-unread-count-is-NOT-MEASURED-too-and-so-is-a-fork-limb-with-no-PR-object', forkVerdict(null).measured === false && forkVerdict(null).isFork === false && forkVerdict({}).measured === false && wordsOf(['src/x.ts']).includes('head repo: NOT MEASURED') && diff --git a/scripts/pm/check-governed-queue-guard.mjs b/scripts/pm/check-governed-queue-guard.mjs index 37b6fe2f237..d8b1d36934e 100644 --- a/scripts/pm/check-governed-queue-guard.mjs +++ b/scripts/pm/check-governed-queue-guard.mjs @@ -462,6 +462,28 @@ * revival of the retired sha pin — it is the RECORD's own identity test, and it * applies to nothing but this tier. * + * ### The `.claude/**` declaration split on this leg (maintainer ruling 2026-11-19, card #35321) + * + * Since 「1+2+4」 (point 1: fleet rule text lands by the maintainer) the `.claude/**` + * row is Tier S only on a DECLARED pull request with a VERIFYING record — the + * register's header section "The `.claude/**` row splits by declaration" has the + * ruling and the rule. What this leg does with it: + * + * - the tier read hands the PR body in (`readLowRiskTier`, the read the head + * already costs) and says its own record leg judges the record + * (`RULE_CHANGE_RECORD_LEG_DEFERRED`): `Rule-change: none`, or `ruled` with + * its `Ruling-ref:`, is Tier S; a missing line, `yes`, a settings file or a + * hook is Tier H and waits for the authorized approval like any Tier H row; + * - the record leg then requires, on top of stands + PASS, a + * `Rule-change-verified:` line equal to the declared value + * (`ruleChangeRecordVerdict`), and a record carried across a head move must + * not have crossed a `.claude/**` hunk (`ruleChangeCarryRefusal`); + * - the four guard instruments and this guard's own workflow file are plain + * Tier H rows of the register, so nothing here names them; + * - the `pull_request` early-warning leg reads no body, so it names such a + * diff "Tier H UNTIL the PR body is read" (`declarationUnread`) and never + * reddens; `CODEOWNERS` must carry a line for each always-Tier-H path. + * * ## The FOURTH leg: the SIZE line (#19036, maintainer ruling 2026-09-18) * * Everything above is keyed on PATHS or on a LABEL. On 2026-09-18 the @@ -562,6 +584,42 @@ * payload carries `additions` / `deletions` for free; a forecast there is a * one-line maintainer decision, not taken here.) * + * ## The FIFTH leg: a declared NARROWING (maintainer ruling 2026-11-19, card #35321) + * + * The maintainer, 03:17Z in the review-split discussion thread, verbatim: + * 「spec:收紧作者能写的东西(会让现有应用报错),也需要fable 吧?」, confirmed by + * 「1+2+4」 at 04:24Z. A change that narrows what an author may write breaks + * applications that exist, so it lands like Tier H whatever paths it touches. + * + * A path cannot say "narrowing"; the DECLARATION does. On `merge_group`, for + * every queued pull request, this leg reads the PR body and every + * `.changeset/*.md` the queued commit carries, line by line with the fleet's + * two readers (`readClause2Line`, `readMetadataProtocolLine`): a line reading + * `Metadata-protocol: narrowed`, or a `Clause-②:` line with the `(narrowing)` + * arm on either value, is a declared narrowing. `added`, `semantic`, `none` + * and a bare `Clause-②:` declare none and cost one pull read, already memoized + * (`oncePerPull`) when another leg read it. + * + * A declared narrowing is REFUSED until BOTH halves are on record: + * + * - the human half — an authorized APPROVED review (the predicate of the + * governed leg, reused when that leg already read it), or the maintainer's + * own enqueue from an authorized account, which the 2026-10-26 ruling made + * the same act for every landing this file judges; + * - the record half — a `## Contract review` record on the current head that + * stands at its tier and reads PASS, located on the narrowing face + * (`reviewFace` with the declaration texts handed in). The face is HELD + * there once the leg found a declaration, on either line: `reviewFace` + * reads the `Clause-②:` arm alone, so the narrowed kind of the + * `Metadata-protocol:` line is handed to it in the one spelling it reads + * (`NARROWING_FACE_LINE`). A schema or governed path still decides first. + * + * ⛔ Fail closed: an unreadable pull, changeset, review list or thread is a + * refusal on its own code, and a near-arm spelling (`(narrowed)`) counts as + * declared — all but the pull-request template's own unfilled menu line, which + * chose nothing (`UNFILLED_PROTOCOL_MENU`). ⛔ Not read: a narrowing nobody declared — that stays the contract + * review's finding. `pull_request` leg: silent, like the SIZE leg. + * * ## Exit codes — the refusal is impossible to read as clean * * 0 CLEAR — nothing governed in the diff (no API call was made), or every @@ -604,13 +662,20 @@ * pull read failed, or the object carries no pair), or the merge * group names no pull request to read it from. Split from 8 the * way 4 is split from 3. + * 10 REFUSED — a queued pull request DECLARES a narrowing (its body or a + * changeset) and lacks the authorized approval or enqueue, the + * PASS contract review on its head, or both. The NARROWED leg. + * 11 REFUSED — the NARROWED leg could not READ a queued pull request, a + * changeset it carries, its review list or its record threads, + * or the merge group names no pull request. Split from 10 the + * same way. * 1 CANNOT RUN — unusable event payload, unsupported event, unreadable git. * Still non-zero, still red: this file has no green that means * "did not look". * - * ⭐ TWO legs, ONE exit, and the precedence is pinned: every leg's block is + * ⭐ THREE predicates, ONE exit, and the precedence is pinned: every leg's block is * always printed, and the code is the GOVERNED leg's when it refuses, else - * the SIZE leg's (`groupExitCode`). The governed refusal sits on top because + * the SIZE leg's, else the NARROWED leg's (`groupExitCode`). The governed refusal sits on top because * its remedy is the stricter one; the size refusal's remedy (an authorized * approval, or a human merge) is the same terminal as Tier H — a group that * is both governed-unsatisfied and oversized prints both limbs and exits 3. @@ -643,11 +708,14 @@ import { LOW_RISK_ARM_RULING, LOW_RISK_CHANGESET_PATH, LOW_RISK_RECORD_STAGE, + RULE_CHANGE_RECORD_LEG_DEFERRED, + RULE_CHANGE_TIER_H_PATHS, SELF_REPO_ID, WORKFLOWS_PREFIX, addOnlyDiffArgv, applyGeneratedExceptions, applyLowRiskArm, + applyRuleChangeSplit, applyWorkflowSplit, assertGovernedRepo, forkVerdict, @@ -662,13 +730,17 @@ import { pullNumberFromSubject, pullSizeFrom, recomputeProvenanceFor, + readRuleChangeVerified, readWorkflowDiff, renderLiftApprovals, renderLowRiskLines, + renderRuleChangeLines, renderWorkflowSplitLines, + ruleChangeRecordReasons, repoIdForSlug, testVerdict, } from './check-governed-merges.mjs'; +import { CLAUSE2_ARMS, CLAUSE2_VALUES, METADATA_PROTOCOL_KINDS, readClause2Line, readMetadataProtocolLine } from './clause2-line.mjs'; import { gitFreeEnv } from '../git-env.mjs'; import { isEntrypoint } from '../invoked-as.mjs'; @@ -732,6 +804,11 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 12 → 13 with the arm's record stage on the ADR leg: a record without the line, a `security`-labelled card; // 13 → 14 with a second card the note names. '⚖️ the ADR leg at the queue: an add-only note clears on its PASS record, any other ADR change is H (#33539)': 14, + // The declaration split at the queue (maintainer ruling 2026-11-19 on #35321): the four instruments and the guard's + // own workflow are H; `.claude/**` is S only on the declared body line AND the record's verified line. + '⚖️ #35321 at the queue: guard instruments are Tier H, `.claude/**` splits by declaration': 26, + // The narrowed leg (same ruling): a declared narrowing needs BOTH halves; `added`, `semantic`, `none` are untouched. + '⚖️ #35321: a declared narrowing lands like Tier H — an authorized approval AND a PASS record': 24, }); // DELETING an entry silences that battery's floor exactly as effectively as @@ -746,7 +823,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 29 → 30 with the workflows split battery (ruling record 6722205630): one battery, one row. // Raised 30 → 31 with the low-risk skills arm battery (#33501): one battery, one row. // Raised 31 → 32 with its ADR leg battery (#33539): one battery, one row. -const SELF_TEST_BATTERY_FLOOR = 32; +// Raised 32 → 34 with the two #35321 batteries (the declaration split at the queue, the narrowed leg): two rows. +const SELF_TEST_BATTERY_FLOOR = 34; // The key an assertion is filed under when no battery is open. It is not a // declared battery, so it reds by the same set difference rather than silently @@ -771,6 +849,13 @@ export const EXIT_REFUSED_UNATTRIBUTED = 5; */ export const EXIT_REFUSED_OVERSIZED = 8; export const EXIT_REFUSED_SIZE_UNREADABLE = 9; +/** + * The NARROWED leg's two refusals (card #35321, the 2026-11-19 ruling), split the same way: a queued pull + * request that declares a narrowing without both halves on record (10), and one whose declaration, review + * list or record could not be read (11). ⛔ Neither folds into the other, nor into any code above. + */ +export const EXIT_REFUSED_NARROWED = 10; +export const EXIT_REFUSED_NARROWED_UNREADABLE = 11; /** * The check-run name branch protection would pin, and the wiring it belongs @@ -871,6 +956,15 @@ export function codeownersMirrorVerdict({ text, approvers = GOVERNED_APPROVERS, const armed = governing.filter((s) => s.tier === GOVERNED_TIER_H && armedIn(s)); const tierHPatterns = tierH.map(codeownersPatternFor); const armPatterns = armed.map(codeownersPatternFor); + // The declaration split's always-Tier-H sub-paths (2026-11-19): the split row itself is routed nowhere (it can + // land on a seat's record), so each path under it that NEVER can owes a line of its own — the register's list. + const splitHere = governing.some((s) => Boolean(s.ruleChange) && Array.isArray(s.ruleChange.repos) && s.ruleChange.repos.includes(repo)); + const splitPatterns = splitHere ? RULE_CHANGE_TIER_H_PATHS.map((row) => `/${row.pattern}`) : []; + for (const pattern of splitPatterns) { + const row = rows.find((r) => r.pattern === pattern); + if (!row) problems.push(`the always-Tier-H path \`${pattern.slice(1)}\` under a declaration-split row has no CODEOWNERS line at \`${pattern}\` — a pull touching it summons nobody when opened ready`); + else if (!sameOwners(row.owners)) problems.push(`CODEOWNERS line ${row.line} \`${pattern}\` names ${row.owners.join(' ') || 'nobody'}, not every GOVERNED_APPROVERS account (${wanted.join(' ')}) — a Tier H pull then waits on an approver who is never asked`); + } for (const surface of tierH) { const pattern = codeownersPatternFor(surface); const row = rows.find((r) => r.pattern === pattern); @@ -881,7 +975,7 @@ export function codeownersMirrorVerdict({ text, approvers = GOVERNED_APPROVERS, if (!sameOwners(row.owners)) problems.push(`CODEOWNERS line ${row.line} \`${pattern}\` names ${row.owners.join(' ') || 'nobody'}, not every GOVERNED_APPROVERS account (${wanted.join(' ')}) — a Tier H pull then waits on an approver who is never asked`); } for (const row of rows) { - if (tierHPatterns.includes(row.pattern)) continue; + if (tierHPatterns.includes(row.pattern) || splitPatterns.includes(row.pattern)) continue; const arm = armed.find((s) => codeownersPatternFor(s) === row.pattern); if (arm) { problems.push(`CODEOWNERS line ${row.line} routes \`${row.pattern}\`, a Tier H row (\`${arm.id}\`) carrying the low-risk arm in this repository — the relay's per-pull plan decides who is asked there, and a static line summons both approvers on every pull, the low-risk ones too`); @@ -892,7 +986,7 @@ export function codeownersMirrorVerdict({ text, approvers = GOVERNED_APPROVERS, else if (!sameOwners(row.owners)) problems.push(`CODEOWNERS line ${row.line} \`${row.pattern}\` (an enforcement-chain row) names ${row.owners.join(' ') || 'nobody'}, not every GOVERNED_APPROVERS account (${wanted.join(' ')})`); } if (!/GOVERNED_APPROVERS/.test(String(text ?? ''))) problems.push('the file never names `GOVERNED_APPROVERS` — its header must say which constant the owner list mirrors'); - return { ok: problems.length === 0, problems, tierHPatterns, armPatterns, rows }; + return { ok: problems.length === 0, problems, tierHPatterns, armPatterns, splitPatterns, rows }; } // ── the landing TIER: Tier S lands on a review of record, Tier H on an approval ─ @@ -1147,7 +1241,15 @@ export function recordVerdict({ pair, recognisers, cardNote = null }) { 'and with it the one tier the record must stand at — is unknown', }; } - const face = recognisers.reviewFace(pair.paths, pair.repo); + // `declaredOn` (the narrowed leg hands it in): the texts a `Clause-②:` line is read from, which decide the face + // where the paths decide none. Absent on every governed entry, whose paths already decided — the call is unchanged. + // ⭐ `narrowingDeclared` (the narrowed leg sets it, having FOUND a declaration with its own readers): the face is + // held to the narrowing one wherever the paths decide none. `reviewFace` reads the `Clause-②:` arm alone, so a + // narrowing declared on the `Metadata-protocol:` line — beside a bare, an absent or a malformed clause line — would + // otherwise land on the declaration face's cheaper tier, or on no face at all. It is handed the one spelling it + // reads as that arm; a narrowing arm on any text decides before a malformed line is looked at. + const declaredOn = Array.isArray(pair.declaredOn) ? (pair.narrowingDeclared === true ? [NARROWING_FACE_LINE, ...pair.declaredOn] : pair.declaredOn) : null; + const face = declaredOn === null ? recognisers.reviewFace(pair.paths, pair.repo) : recognisers.reviewFace(pair.paths, pair.repo, { declaredOn }); const located = recognisers.locate(pair); if (located.state === 'unreadable') { return { @@ -1353,6 +1455,8 @@ export function decomposeGovernedWork(rows, repo) { // The low-risk skills arm (#33501) needs the PR body and labels, which no // row carries: here it is NOT MEASURED, so a catalog path is Tier H; the // queue leg re-reads the tier with `readLowRiskTier` once the pull is read. + // The `.claude/**` declaration split (2026-11-19) reads the same body and, second, the + // record: NOT MEASURED here, so an instruction-tree path is Tier H until that read. return { pr: entry.pr, shas: entry.shas, @@ -1360,7 +1464,7 @@ export function decomposeGovernedWork(rows, repo) { allPaths: [...(allByPull.get(entry.pr) ?? entry.paths)], changesetRefs: changesetsByPull.get(entry.pr) ?? [], workflowDiff, - surfaces: applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, repo), repo, workflowDiff), repo, null), + surfaces: applyRuleChangeSplit(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(paths, repo), repo, workflowDiff), repo, null), repo, null), tier: governedTierFor(paths, repo, GOVERNED_SURFACES, workflowDiff, null), }; }) @@ -1574,7 +1678,21 @@ export function satisfiedBy(entry) { */ export function entryUnreadable(entry) { if (entry?.approval?.state === 'unreadable') return true; - return entry?.tier === TIER_S && entry?.record?.state === 'unreadable'; + if (entry?.tier === TIER_S && entry?.record?.state === 'unreadable') return true; + // The declaration split (2026-11-19): a body this leg could not read decides nothing, which is not a `no`. + return declarationUnread(entry); +} + +/** + * Is this entry Tier H ONLY because the `.claude/**` declaration split had no body to read — no reading at all on + * the early-warning leg, or a pull request the queue leg could not read — every other row hit being Tier S? Such + * an entry's tier is not yet known: the words say so, and on the queue leg it refuses as UNREADABLE. An entry a + * hook, a settings file or any Tier H row decides is not one: its tier was read. Pure. + */ +export function declarationUnread(entry) { + const surfaces = Array.isArray(entry?.surfaces) ? entry.surfaces : []; + const unread = (s) => s?.ruleChangeVerdict?.measured === false; + return entry?.tier !== TIER_S && surfaces.some(unread) && surfaces.every((s) => unread(s) || s?.tier === TIER_S); } /** @@ -1643,7 +1761,18 @@ export function renderGuardVerdict(verdict) { // the early warning names the tier as the card requires. The queue leg's // record block follows it where the record key exists. const tierLines = (entry) => - entry.tier === TIER_S + declarationUnread(entry) + ? [ + ' ⚖️ landing tier: H(人合) UNTIL the PR body is read — nothing here read it. Every governed path above lies under', + ` ${tierSGlobs()}, which splits by declaration (2026-11-19): it lands Tier S(席内达档 L2 审核落地) when the body`, + ' carries one bare `Rule-change: none` (or `Rule-change: ruled` beside a `Ruling-ref:` line quoting the ruling)', + ` and a \`## Contract review\` comment on ${REVIEW_OF_RECORD_LOCATION} naming the CURRENT head — \`Served-tier:`, + ' CONTRACT_REVIEW_TIER`, `**VERDICT: PASS**` — reads the same value on its `Rule-change-verified:` line.', + ' A missing line or `Rule-change: yes` is Tier H: the maintainer\'s hand or an authorized APPROVED review', + ` (GOVERNED_APPROVERS: ${GOVERNED_APPROVERS.join(', ')}). The queue leg reads the body and the record;`, + ' `node scripts/pm/check-governed-merges.mjs --pr ` reads them now.', + ] + : entry.tier === TIER_S ? [ ` ⚖️ landing tier: S(席内达档 L2 审核落地) — every governed path above lies under a Tier S surface (${tierSGlobs()}),`, ' so a review of record on the CURRENT head lands it in place of an authorized approval: a `## Contract', @@ -1731,6 +1860,7 @@ export function renderGuardVerdict(verdict) { lines.push(...surfaceLines(entry)); lines.push(...renderWorkflowSplitLines(entry.surfaces).split('\n').filter((l) => l !== '').map((l) => ` ${l}`)); lines.push(...renderLowRiskLines(entry.surfaces).split('\n').filter((l) => l !== '').map((l) => ` ${l}`)); + lines.push(...renderRuleChangeLines(entry.surfaces).split('\n').filter((l) => l !== '').map((l) => ` ${l}`)); // The pre-#19133 `pull_request` byte-identity constraint (2026-08-27) is // superseded by that ruling's own requirement: the early warning names the // tier and what it waits for. @@ -2077,8 +2207,8 @@ export function renderGuardVerdict(verdict) { * `applyLowRiskArm` — no second predicate here. Mutates `entry` (its `surfaces` * and `tier`); returns it. */ -export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = null, record = null, cardLabels = null } = {}) { - if (!entry || !(entry.surfaces ?? []).some((s) => s?.lowRiskVerdict)) return entry; +export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = null, record = null, cardLabels = null, recordLeg = null } = {}) { + if (!entry || !(entry.surfaces ?? []).some((s) => s?.lowRiskVerdict || s?.ruleChangeVerdict)) return entry; const refs = Array.isArray(entry.changesetRefs) ? entry.changesetRefs : []; const changesets = typeof runGit !== 'function' ? { measured: false, reason: 'no git reader was handed to the queue leg', files: [] } @@ -2107,13 +2237,30 @@ export function readLowRiskTier(entry, repo, pull, { timeline = null, runGit = n changesets, ...(record == null ? {} : { record }), ...(cardLabels == null ? {} : { cardLabels }), + // The `.claude/**` declaration split (2026-11-19): the queue leg says its own record leg judges the record + // (`RULE_CHANGE_RECORD_LEG_DEFERRED`), so the split reads the body here and `ruleChangeRecordVerdict` the line. + ...(recordLeg == null ? {} : { recordLeg }), } : { measured: false, reason: 'its pull request could not be read, so its body and labels are unknown' }; - entry.surfaces = applyLowRiskArm(applyWorkflowSplit(governedPathsIn(entry.paths, repo), repo, entry.workflowDiff ?? null), repo, reading); + entry.surfaces = applyRuleChangeSplit(applyLowRiskArm(applyWorkflowSplit(governedPathsIn(entry.paths, repo), repo, entry.workflowDiff ?? null), repo, reading), repo, reading); entry.tier = governedTierFor(entry.paths, repo, GOVERNED_SURFACES, entry.workflowDiff ?? null, reading); return entry; } +/** + * A reader that answers each key from its first SUCCESSFUL read. A rejection is not cached: the next caller + * reads again, so one leg's transient failure is never another leg's verdict. + */ +export function oncePerPull(read) { + const seen = new Map(); + return async (key) => { + if (seen.has(key)) return seen.get(key); + const value = await read(key); + seen.set(key, value); + return value; + }; +} + /** `git diff-tree --raw` status letters, spelled as the arm reads them. */ const RAW_STATUS = Object.freeze({ M: 'modified', A: 'added', D: 'deleted', T: 'type-changed', R: 'renamed', C: 'copied' }); @@ -2200,6 +2347,27 @@ export function lowRiskCarryRefusal(carriedFrom, pair) { return null; } +/** + * Why a record CARRIED from an older head does not stand for the `.claude/**` declaration split, as a predicate + * phrase, or null when it does: the hops may touch no path under a split row. The carry admits prose faces by + * NAME at any depth (a `CHANGELOG.md`), so one under the instruction tree could otherwise move after the reviewer + * wrote `Rule-change-verified:`. A diff that cannot be read refuses too. Pure but for `runGit`. + */ +export function ruleChangeCarryRefusal(carriedFrom, pair) { + const from = `\`${String(carriedFrom).slice(0, 12)}\``; + if (typeof pair?.runGit !== 'function' || !pair?.headSha) return `was carried from ${from} and this leg could not diff the hops`; + let moved; + try { + moved = String(pair.runGit(['diff', '-z', '--name-only', '--no-renames', carriedFrom, pair.headSha])).split('\0').filter(Boolean); + } catch (error) { + return `was carried from ${from} and the hops could not be diffed (${String(error?.message ?? error).split('\n')[0]})`; + } + const rows = GOVERNED_SURFACES.filter((s) => s.ruleChange && s.prefix).map((s) => s.prefix); + const touched = moved.filter((p) => rows.some((prefix) => p.startsWith(prefix))); + if (touched.length > 0) return `was carried from ${from} over hops that moved ${touched.slice(0, 3).join(', ')}${touched.length > 3 ? ` (+${touched.length - 3} more)` : ''}, which its \`Rule-change-verified:\` line was read from, after the review`; + return null; +} + /** * The arm's reading of the review of record on this head — the `record` half of its record stage * (`lowRiskRecordStageReasons`, the register). Built from the SAME threads and the SAME locator the @@ -2235,6 +2403,10 @@ export function lowRiskRecordStage({ pair, recognisers }) { id: located.id, carried: located.carriedFrom ? { from: located.carriedFrom, ok: why === null, reason: why } : null, securityTouching: recognisers.reading(comment.body)?.securityTouching ?? null, + // The `.claude/**` declaration split (2026-11-19) reads its own line off the SAME comment, with the + // register's reader, and holds a carried record to its own rule: the hops moved nothing under the row. + ruleChangeVerified: readRuleChangeVerified(comment.body), + ruleChangeCarried: located.carriedFrom ? ((refusal) => ({ from: located.carriedFrom, ok: refusal === null, reason: refusal }))(ruleChangeCarryRefusal(located.carriedFrom, pair)) : null, }; } @@ -2365,7 +2537,7 @@ export function namedCardsOf(recognisers, pull) { * which the arm reads as Tier H. * Returns `{ record, cardLabels, card, apiCalls }`. Never throws. */ -export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, runGit = null, baseRef = null, recognisers, fetchComments = null, fetchLabels = null, fetchTimeline = null }) { +export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, runGit = null, baseRef = null, recognisers, fetchComments = null, fetchLabels = null, fetchTimeline = null, withCardLabels = true }) { if (recognisers?.available !== true) { return { record: { measured: false, reason: recognisers?.reason ?? 'the contract-review recognisers were not loaded' }, @@ -2382,6 +2554,8 @@ export async function readLowRiskRecordStage({ pr, pull, headSha, paths, repo, r ? await readRecordThreads({ pair, recognisers, fetchComments }) : { unreadable: 'no comment reader was supplied to this leg, so no thread was read', apiCalls: 0 }; const record = threads.unreadable !== null ? { measured: false, reason: threads.unreadable } : lowRiskRecordStage({ pair, recognisers }); + // The card labels are the ARM's conjunct: a caller reading the stage for the `.claude/**` split alone leaves them unread. + if (withCardLabels !== true) return { record, cardLabels: null, card, apiCalls: threads.apiCalls }; const labelled = await readCardLabels({ card, named: namedCardsOf(recognisers, pull), fetchLabels, fetchTimeline }); return { record, cardLabels: labelled.reading, card, apiCalls: threads.apiCalls + labelled.apiCalls }; } @@ -2459,6 +2633,38 @@ export function lowRiskRecordVerdict(record, pair, recognisers) { return recordPassVerdict(record, pair, recognisers); } +/** + * The value a Tier S entry's `.claude/**` paths were DECLARED with (`none` or `ruled`), or null for an entry with + * no split row at Tier S: the value its record's `Rule-change-verified:` line must read. Pure. + */ +export function ruleChangeDeclaredOn(entry) { + if (entry?.tier !== TIER_S) return null; + return (entry.surfaces ?? []).find((s) => s?.ruleChangeVerdict?.tier === TIER_S)?.ruleChangeVerdict?.declared ?? null; +} + +/** + * The record leg's verdict for an entry the declaration split put at Tier S (2026-11-19, card #35321): the carry + * rule (`ruleChangeCarryRefusal`), `recordPassVerdict` like every other Tier S entry, and then the LINE — the + * comment the locator chose must carry one bare `Rule-change-verified:` line reading the value the PR body + * declared. Read with the register's reader and judged with the register's own reasons (`readRuleChangeVerified`, + * `ruleChangeRecordReasons`; ⛔ no second rule here): missing, unreadable, `yes` or the other value is `not-pass`, + * a refusal naming the comment. A record that does not stand keeps the state it had. Pure but for `runGit`. + */ +export function ruleChangeRecordVerdict(record, pair, recognisers, declared) { + if (record?.state !== 'stands') return record; + if (record.carriedFrom) { + const why = ruleChangeCarryRefusal(record.carriedFrom, pair); + if (why !== null) return { ...record, state: 'not-pass', verdict: null, verdictReason: `it ${why}` }; + } + const passed = recordPassVerdict(record, pair, recognisers); + if (passed.state !== 'stands') return passed; + const rows = (recognisers?.threads ?? []).flatMap((thread) => (Array.isArray(pair?.[thread.rows]) ? pair[thread.rows] : [])); + const comment = rows.find((r) => r?.id === record.id) ?? null; + const reasons = ruleChangeRecordReasons({ measured: true, reason: null, located: 'found', where: record.where ?? null, id: record.id ?? null, ruleChangeCarried: null, ruleChangeVerified: comment === null ? null : readRuleChangeVerified(comment.body) }, declared); + if (reasons.length > 0) return { ...passed, state: 'not-pass', verdict: null, verdictReason: `the \`.claude/**\` declaration split is not verified — ${reasons.join('; ')}` }; + return passed; +} + /** * The orchestrator, with its one IO dependency injected. * @@ -2562,7 +2768,10 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet // off the pull object this leg already holds — body, labels, fork — the // timeline the enqueue leg read, the changesets at their commits and the whole // path list of its commits. An unread pull is NOT MEASURED: Tier H. - for (const entry of governed) readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit }); + // ⭐ The `.claude/**` declaration split (2026-11-19) is read off the same body, here: missing, unreadable or + // `yes` is Tier H; `none` or `ruled` is Tier S on the DEFERRED record stage, which this leg's own record + // leg settles below (`ruleChangeRecordVerdict`). + for (const entry of governed) readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit, recordLeg: RULE_CHANGE_RECORD_LEG_DEFERRED }); let recognisers = null; for (const entry of governed) { // ⭐ The arm's RECORD STAGE: an entry whose pull-read arm conditions all hold is Tier H until the @@ -2582,7 +2791,7 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet } // The arm's second read of this entry's tier, with the record stage as far as it was read. const readRecordStage = (record, cardLabels) => - readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit, record, cardLabels }); + readLowRiskTier(entry, repo, pulls.get(entry.pr) ?? null, { timeline: timelines.get(entry.pr) ?? null, runGit, record, cardLabels, recordLeg: RULE_CHANGE_RECORD_LEG_DEFERRED }); if (recognisers.available !== true) { // ⛔ No recognisers, no record reading: the pending entry stays Tier H on that reason, and the // record leg is never consulted for it. @@ -2637,7 +2846,11 @@ export async function runGuard({ event, repo, rows, fetchReviews, fetchPull, fet const record = recordVerdict({ pair, recognisers, cardNote }); // ⭐ Every Tier S entry lands on a record that READS PASS, never on one that merely exists (#33541); // the low-risk arm adds its carry rule first (#33501). - const verdicted = landsOnLowRiskArm(entry) ? lowRiskRecordVerdict(record, pair, recognisers) : recordPassVerdict(record, pair, recognisers); + // The declaration split holds its record to the line the body's declaration owes (2026-11-19). + const declaredRule = ruleChangeDeclaredOn(entry); + const verdicted = landsOnLowRiskArm(entry) + ? lowRiskRecordVerdict(record, pair, recognisers) + : declaredRule !== null ? ruleChangeRecordVerdict(record, pair, recognisers, declaredRule) : recordPassVerdict(record, pair, recognisers); records.set(entry.pr, ignoredAuthors.length > 0 ? { ...verdicted, ignoredAuthors } : verdicted); } } @@ -3010,9 +3223,317 @@ export function renderSizeVerdict(verdict) { return lines.join('\n'); } +// ── the NARROWED leg: a declared narrowing lands like Tier H (2026-11-19) ──── + +/** The leg's own name in a log — the third predicate inside the same check run. */ +export const NARROWED_LEG_NAME = 'Narrowed Spec Change (2026-11-19 ruling)'; + +/** + * Where the leg is ruled, as a log line carries it. The maintainer's own words are quoted in the header section + * ("The FIFTH leg"); ⛔ not here — this string is printed on every refusal, and the quotation names a tier by + * its value, which a runtime message never carries. + */ +export const NARROWED_RULING = 'maintainer ruling 2026-11-19 on #35321: a spec change that narrows what an author may write lands by the maintainer'; + +/** + * Every line of `text` that DECLARES a narrowing, read with the fleet's two line readers one line at a time + * (`readMetadataProtocolLine`, `readClause2Line` — ⛔ never a second parser): a `Metadata-protocol: narrowed` + * line, or a `Clause-②:` line carrying the `(narrowing)` arm on either value. Line by line rather than + * first-match, so a `none` written above a `narrowed` does not hide it; a line that only QUOTES the spelling + * is the readers' own `describing` near miss and declares nothing. ⛔ One direction fails closed: a line that + * IS the key, reads `malformed` and spells `narrow` anywhere (`no (narrowed)`, `narrowing`) counts as declared — + * the readers collapse a near-arm into `malformed` exactly so it cannot read as no narrowing. `added`, + * `semantic`, `none`, a bare `yes`/`no` and `yes (widening)` declare none. + * ⛔ ONE malformed line that spells `narrow` declares nothing: the pull-request template's own UNFILLED line, the + * whole menu with no value chosen (`UNFILLED_PROTOCOL_MENU`, built from the readers' closed set). A body that + * left the template as it came chose nothing, and reading it as a narrowing would refuse every such pull — + * the maintainer's own included. Exactly that menu: a partial one (`narrowed | none`) still counts. Pure. + */ +export const UNFILLED_PROTOCOL_MENU = METADATA_PROTOCOL_KINDS.join(' | '); + +/** + * The ONE spelling `reviewFace` reads as the narrowing arm, built from the readers' closed sets. `recordVerdict` + * hands it in for a pull request this leg found a declared narrowing on, so the record half is held to the + * narrowing face's tier whichever line carried the declaration. ⛔ Never written to a body or a record. + */ +export const NARROWING_FACE_LINE = `Clause-②: ${CLAUSE2_VALUES[1]} (${CLAUSE2_ARMS[1]})`; +export function narrowingDeclarationsIn(text) { + const unfilled = (value) => String(value ?? '').replace(/[ \t]+/g, ' ').trim() === UNFILLED_PROTOCOL_MENU; + const out = []; + for (const line of String(text ?? '').split(/\r?\n/)) { + const kind = readMetadataProtocolLine(line); + if (kind?.kind === 'declared' && kind.value === 'narrowed') out.push({ key: 'Metadata-protocol', line: kind.line }); + else if (kind?.kind === 'malformed' && /narrow/i.test(line) && !unfilled(kind.value)) out.push({ key: 'Metadata-protocol', line: kind.line }); + const clause = readClause2Line(line); + if (clause?.kind === 'declared' && clause.arm === 'narrowing') out.push({ key: 'Clause-②', line: clause.line }); + else if (clause?.kind === 'malformed' && /narrow/i.test(line)) out.push({ key: 'Clause-②', line: clause.line }); + } + return out; +} + +/** Every changeset each queued pull request's commits touch, with the commit it is read at: `Map(pr → [{ sha, path }])`. Pure. */ +export function changesetRefsByPull(rows) { + const byPull = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + if (typeof row?.pr !== 'number' || !Number.isInteger(row.pr) || row.pr <= 0) continue; + const refs = byPull.get(row.pr) ?? []; + for (const p of Array.isArray(row.paths) ? row.paths : []) { + if (typeof p === 'string' && LOW_RISK_CHANGESET_PATH.test(p)) refs.push({ sha: row.sha ?? null, path: p }); + } + byPull.set(row.pr, refs); + } + return byPull; +} + +/** + * The committed text of each changeset ref, read with `runGit` at the commit that touched it: + * `{ measured, reason, files: [{ path, text }] }`. A changeset the commit DELETED has no text to declare + * anything and is left out — told apart from a failed read by `git ls-tree`, which answers nothing for a path + * the commit does not hold. No git reader, a ref with no commit, or a read that fails for a path the commit + * DOES hold is NOT MEASURED. Never throws. + */ +export function readChangesetTexts(refs, runGit) { + const unmeasured = (reason) => ({ measured: false, reason, files: [] }); + const list = Array.isArray(refs) ? refs : []; + if (list.length === 0) return { measured: true, reason: null, files: [] }; + if (typeof runGit !== 'function') return unmeasured('no git reader was handed to this leg, so its changesets were not read'); + const files = []; + for (const { sha, path } of list) { + if (!sha) return unmeasured(`\`${path}\` names no commit to read it at`); + try { + files.push({ path, text: String(runGit(['show', `${sha}:${path}`])) }); + } catch (error) { + let held; + try { + held = String(runGit(['ls-tree', sha, '--', path])).trim() !== ''; + } catch { + held = true; + } + if (held) return unmeasured(`\`${path}\` could not be read at ${String(sha).slice(0, 12)} (${String(error?.message ?? error).split('\n')[0]})`); + } + } + return { measured: true, reason: null, files }; +} + +/** + * ONE queued pull request, judged. Pure. + * + * not-declared neither its body nor a changeset its commits touch declares a narrowing — nothing is owed here; + * cleared it declares one, AND a human half holds (an authorized APPROVED review, or the maintainer's own + * enqueue from an authorized account — the 2026-10-26 ruling, as on a Tier H entry), AND the record + * half holds (a `## Contract review` record for the current head that stands at its face's tier and + * reads PASS — `recordVerdict` then `recordPassVerdict`, the Tier S leg's own two readers); + * refused it declares one and a half is missing, each named in `reasons`; + * unreadable its body or a changeset could not be read, or a half that would decide could not be. + * + * ⛔ BOTH halves, never either: the approval is who lands it, the record is the review the narrowing face owes. + */ +export function narrowedReading({ pr, body = null, changesets = null, approval = null, enqueue = null, record = null }) { + if (typeof body !== 'string') return { pr, state: 'unreadable', declarations: [], reasons: ['its pull request body could not be read, so what it declares is unknown'] }; + if (!changesets || changesets.measured !== true) return { pr, state: 'unreadable', declarations: [], reasons: [`its changesets were not read (${changesets?.reason ?? 'no reading'}), so what they declare is unknown`] }; + const declarations = [ + ...narrowingDeclarationsIn(body).map((d) => ({ ...d, where: 'the PR body' })), + ...changesets.files.flatMap((f) => narrowingDeclarationsIn(f.text).map((d) => ({ ...d, where: `\`${f.path}\`` }))), + ]; + if (declarations.length === 0) return { pr, state: 'not-declared', declarations, reasons: [] }; + const reasons = []; + let unreadable = false; + const human = approval?.state === 'approved' ? 'review' : enqueue?.state === 'authorized' ? 'enqueue' : null; + if (human === null) { + if (approval?.state === 'unreadable') { + unreadable = true; + reasons.push(`the review list could not be read (${approval.reason ?? 'unknown error'})`); + } else { + const outside = (approval?.unauthorizedApprovers ?? []).length > 0 ? `; APPROVED only by ${approval.unauthorizedApprovers.join(', ')}, outside GOVERNED_APPROVERS` : ''; + reasons.push(`no authorized APPROVED review is on record (authorized: ${GOVERNED_APPROVERS.join(', ')})${outside}, and no authorized account enqueued it`); + } + } + if (record?.state !== 'stands' || record?.verdict !== 'PASS') { + if (!record || record.state === 'unreadable') { + unreadable = true; + reasons.push(`its contract-review record could not be read (${record?.reason ?? 'no record reading was recorded'})`); + } else if (record.state === 'absent') reasons.push(`no \`## Contract review\` record names its current head (${record.readSummary ?? 'no thread summary'})`); + else if (record.state === 'not-pass') reasons.push(`its contract-review record does not read a clean PASS: ${record.verdictReason ?? 'no reason recorded'}`); + else reasons.push(`its contract-review record does not stand (${record.state})`); + } + return { pr, state: reasons.length === 0 ? 'cleared' : unreadable ? 'unreadable' : 'refused', declarations, reasons, by: human, record: record ?? null }; +} + +/** + * The narrowed verdict, as data. Pure, the same shape as `sizeGuardVerdict`. ⚠️ `merge_group` ONLY: the + * `pull_request` leg returns `not-applicable` and renders the empty string, so that leg's output stays + * byte-identical and makes no read for it. A group that names no pull request has no body to read and refuses; + * a reading that never arrived is `unreadable`, never `not-declared`. + */ +export function narrowedGuardVerdict({ event, repo, pulls = [], readings = new Map(), apiCalls = 0 }) { + assertGovernedRepo(repo, 'narrowedGuardVerdict'); + const base = { event, repo, entries: [], apiCalls, legName: NARROWED_LEG_NAME }; + if (event !== EVENT_MERGE_GROUP) return { ...base, conclusion: 'not-applicable', exitCode: EXIT_CLEAR, refusalKind: null }; + if (pulls.length === 0) return { ...base, conclusion: 'refused', exitCode: EXIT_REFUSED_NARROWED_UNREADABLE, refusalKind: 'no-pull' }; + const entries = pulls.map((pr) => readings.get(pr) ?? { pr, state: 'unreadable', declarations: [], reasons: ['no reading was recorded for this pull request'] }); + const out = { ...base, entries }; + if (entries.some((e) => e.state === 'unreadable')) return { ...out, conclusion: 'refused', exitCode: EXIT_REFUSED_NARROWED_UNREADABLE, refusalKind: 'unreadable' }; + if (entries.some((e) => e.state === 'refused')) return { ...out, conclusion: 'refused', exitCode: EXIT_REFUSED_NARROWED, refusalKind: 'narrowed' }; + return { ...out, conclusion: 'clear', exitCode: EXIT_CLEAR, refusalKind: null }; +} + +/** + * The narrowed orchestrator, IO injected — the SAME readers the other two legs use. Every queued pull request + * is read (`queuedPullsInGroup`, so a bare sibling cannot carry a declared narrowing through): one pull read + * for its body, and its changesets off the committed trees. ⭐ Everything past that is read ONLY for a pull + * request that declares a narrowing: the review list (reused from the governed leg's `approvals` where that leg + * read it), the timeline when no approval holds, and the record threads. A throw is caught into an + * `unreadable` reading, never a pass and never an escaping rejection. + */ +export async function runNarrowedGuard({ event, repo, rows, namedPull = null, fetchPull, fetchReviews = null, fetchTimeline = null, fetchComments = null, loadRecognisers = loadRecordRecognisers, approvals = new Map(), runGit = null, baseRef = null }) { + assertGovernedRepo(repo, 'runNarrowedGuard'); + if (event !== EVENT_MERGE_GROUP) return narrowedGuardVerdict({ event, repo }); + const pulls = queuedPullsInGroup(rows, namedPull); + const refsByPull = changesetRefsByPull(rows); + const pathsByPull = new Map(); + for (const row of Array.isArray(rows) ? rows : []) { + if (typeof row?.pr !== 'number') continue; + pathsByPull.set(row.pr, [...new Set([...(pathsByPull.get(row.pr) ?? []), ...(Array.isArray(row.paths) ? row.paths.filter((p) => typeof p === 'string' && p !== '') : [])])]); + } + const why = (error) => String(error?.message ?? error).split('\n')[0]; + const readings = new Map(); + let recognisers = null; + let apiCalls = 0; + for (const pr of pulls) { + let pull; + try { + apiCalls += 1; + pull = await fetchPull(pr); + } catch (error) { + readings.set(pr, { pr, state: 'unreadable', declarations: [], reasons: [`its pull request could not be read (${why(error)}), so what its body declares is unknown`] }); + continue; + } + const body = typeof pull?.body === 'string' ? pull.body : null; + const changesets = readChangesetTexts(refsByPull.get(pr) ?? [], runGit); + const first = narrowedReading({ pr, body, changesets }); + if (first.state === 'not-declared' || first.declarations.length === 0) { + readings.set(pr, first); + continue; + } + // ── it declares a narrowing: the human half, then the record half ── + let approval = approvals.get(pr) ?? null; + if (approval === null) { + if (typeof fetchReviews !== 'function') approval = unreadableApproval('no review reader was supplied to the narrowed leg'); + else { + try { + apiCalls += 1; + approval = authorizedApprovalVerdict(await fetchReviews(pr), pull?.sha ?? null); + } catch (error) { + approval = unreadableApproval(why(error)); + } + } + } + let enqueue = approval.enqueue ?? null; + if (approval.state !== 'approved' && enqueue === null) { + if (typeof fetchTimeline !== 'function') enqueue = undeterminedEnqueue('no timeline reader was supplied to the narrowed leg'); + else { + try { + apiCalls += 1; + enqueue = authorizedEnqueueVerdict(enqueuerFromTimeline(await fetchTimeline(pr))); + } catch (error) { + enqueue = undeterminedEnqueue(`the timeline could not be read (${why(error)})`); + } + } + } + if (recognisers === null) { + try { + recognisers = await loadRecognisers(); + } catch (error) { + recognisers = { available: false, reason: `the recogniser load threw: ${why(error)}` }; + } + } + let record; + if (recognisers.available !== true) record = recordVerdict({ pair: null, recognisers }); + else { + const row = { number: pr, body: body ?? '', head: { ref: pull?.headRef ?? '' } }; + const card = recognisers.deliveredCard(row); + const cardNote = card.card === null ? `⚠️ no card thread was searched — ${card.reason}` : `card #${card.card}, ${card.evidence}`; + // ⭐ `declaredOn` and `narrowingDeclared` are what put a narrowing with no schema and no governed path on the + // narrowing FACE, so the record must stand at that face's tier (`reviewFace`), never at the declaration face's + // cheaper one — on either declaration line: this point is reached only with a declaration found above. + const pair = { pr, card: card.card, headSha: pull?.sha ?? null, runGit, baseRef, paths: pathsByPull.get(pr) ?? [], repo, declaredOn: [body ?? '', ...changesets.files.map((f) => f.text)], narrowingDeclared: true }; + const threads = typeof fetchComments === 'function' + ? await readRecordThreads({ pair, recognisers, fetchComments }) + : { ignoredAuthors: [], unreadable: 'no comment reader was supplied to the narrowed leg, so no thread was read', apiCalls: 0 }; + apiCalls += threads.apiCalls; + record = threads.unreadable !== null + ? { state: 'unreadable', reason: threads.unreadable, cardNote } + : recordPassVerdict(recordVerdict({ pair, recognisers, cardNote }), pair, recognisers); + } + readings.set(pr, narrowedReading({ pr, body, changesets, approval, enqueue, record })); + } + return narrowedGuardVerdict({ event, repo, pulls, readings, apiCalls }); +} + +/** + * The words a reader acts on for this leg. Returns '' on the `pull_request` leg. A pull request that declares + * nothing costs one line for the whole group; one that declares a narrowing prints the declaring line(s), where + * each sits, and what cleared it or what is still owed. The refusal quotes the ruling untranslated and names + * the two halves. ⛔ It does not advise rewording the declaration — a guard that suggests how to stop being + * asked is a guard that gets routed around. + */ +export function renderNarrowedVerdict(verdict) { + if (verdict.conclusion === 'not-applicable') return ''; + const lines = [`${NARROWED_LEG_NAME} — ${verdict.event} — ${verdict.entries.length} queued pull request(s), ${verdict.apiCalls} API read(s).`]; + const declared = (e) => e.declarations.slice(0, 4).map((d) => ` - ${d.where}: ${d.line}`); + for (const entry of verdict.entries) { + if (entry.state === 'not-declared') continue; + if (entry.state === 'cleared') { + lines.push('', ` #${entry.pr} — ✅ declares a narrowing, and both halves are on record: ${entry.by === 'review' ? 'an authorized APPROVED review' : "the maintainer's own enqueue from an authorized account"}, and a PASS contract review for its head (${entry.record?.where ?? 'a'} comment ${entry.record?.id ?? '(no id)'}).`, ...declared(entry)); + } else { + lines.push('', ` #${entry.pr} — ⛔ ${entry.declarations.length > 0 ? 'declares a narrowing and is NOT cleared' : 'could NOT be read'}:`, ...declared(entry), ...entry.reasons.map((r) => ` ⛔ ${r}`)); + } + } + if (verdict.conclusion === 'clear') { + const cleared = verdict.entries.filter((e) => e.state === 'cleared').length; + lines.push( + '', + cleared === 0 + ? ' ✅ CLEAR — no queued pull request declares a narrowing (`Metadata-protocol: narrowed`, or a `Clause-②:` line with' + : ` ✅ CLEAR — ${cleared} queued pull request(s) declare a narrowing and each carries both halves; no other declares one (\`Metadata-protocol: narrowed\`, or a \`Clause-②:\` line with`, + ' the `(narrowing)` arm), read off each PR body and each changeset its commits touch. `added`, `semantic` and `none` are not this leg\'s.', + ); + return lines.join('\n'); + } + lines.push('', ' ⛔ REFUSED — this merge group must not land.'); + if (verdict.refusalKind === 'no-pull') { + lines.push(' This merge group names NO pull request, so there is no body to read a declaration from. Fail closed.'); + } else if (verdict.refusalKind === 'unreadable') { + lines.push( + ' A reading this leg decides on could not be taken for at least one queued pull request above. ⛔ A refusal and', + ' not a pass: "nobody declares a narrowing" and "we could not find out" are different facts (exit 10 vs 11).', + ); + } else { + lines.push( + ' At least one queued pull request above declares that it NARROWS what an author may write — a key removed or', + ' tombstoned, a value refused, a requirement tightened: metadata that validated yesterday is rejected after it —', + ` and lands like Tier H (${NARROWED_RULING}).`, + ); + } + lines.push( + '', + ' What satisfies this check — BOTH, on the pull request:', + ` 1. the human half: an APPROVED review by an account in GOVERNED_APPROVERS (${GOVERNED_APPROVERS.join(', ')}), on any commit, or the`, + ' maintainer\'s own "Merge when ready" from such an account (2026-10-26); a dismissed, superseded or', + ' unauthorized approval never counts, and ⛔ no seat enqueues under such an account in its place;', + ` 2. the record half: a \`## Contract review\` comment on ${REVIEW_OF_RECORD_LOCATION} naming the CURRENT head, standing at the`, + ' tier its face maps to (`Served-tier:`), one `**VERDICT: PASS**`, no FAIL and no open must-fix or should-fix.', + ' Until both hold the pull request waits OUT of the queue, in draft (the pull-back of AGENTS.md Prime Directive #14).', + ' ⛔ "Edit this check" and rewording the declaration are not ways through: the declaration is what the release', + ' level and the release notes are read from.', + ); + return lines.join('\n'); +} + /** - * TWO legs, ONE exit code. Pure, and pinned: the governed leg's refusal - * wins, then the size leg's. The governed refusal sits on top because its + * THREE legs, ONE exit code. Pure, and pinned: the governed leg's refusal + * wins, then the size leg's, then the narrowed leg's (2026-11-19; a caller + * that ran no narrowed leg hands none in and the two-leg answer stands). The governed refusal sits on top because its * remedy is the stricter one (no landing at all without an authorized * approval, a record, or the maintainer's own direct merge); the size * refusal's remedy is the same terminal as Tier H (an authorized approval, or @@ -3020,9 +3541,10 @@ export function renderSizeVerdict(verdict) { * oversized prints both limbs and exits on the governed one. ⛔ No leg's code is swallowed silently: every block is always * printed, whichever code the run exits on. */ -export function groupExitCode({ governed, size }) { +export function groupExitCode({ governed, size, narrowed = null }) { if (governed?.exitCode !== EXIT_CLEAR) return governed.exitCode; - return size.exitCode; + if (size.exitCode !== EXIT_CLEAR || narrowed === null) return size.exitCode; + return narrowed.exitCode; } @@ -3595,7 +4117,9 @@ async function main() { token: env.GITHUB_TOKEN || env.GH_TOKEN || null, }; const fetchReviews = makeReviewReader(reader); - const fetchPull = makePullReader(reader); + // ONE network read per pull request for the three legs that each read it; a failed read is not kept, so a + // leg that asks again reads again. + const fetchPull = oncePerPull(makePullReader(reader)); const fetchComments = makeCommentReader(reader); const fetchTimeline = makeTimelineReader(reader); const fetchLabels = makeLabelReader(reader); @@ -3621,11 +4145,28 @@ async function main() { approvals: new Map(verdict.entries.map((e) => [e.pr, e.enqueue === undefined ? e.approval : { ...e.approval, enqueue: e.enqueue }])), }); const sizeBlock = renderSizeVerdict(size); + // The NARROWED leg (2026-11-19): every queued pull request's body and changesets, and for one that declares a + // narrowing the same approval, enqueue and record readers. `merge_group` only, '' on the other leg. + const narrowed = await runNarrowedGuard({ + event: context.event, + repo, + rows, + namedPull: context.namedPull, + fetchPull, + fetchReviews, + fetchTimeline, + fetchComments, + approvals: new Map(verdict.entries.map((e) => [e.pr, e.enqueue === undefined ? e.approval : { ...e.approval, enqueue: e.enqueue }])), + runGit, + baseRef: context.baseSha ?? null, + }); + const narrowedBlock = renderNarrowedVerdict(narrowed); const report = [ `${context.label} — ${commitsInRange(read.rows)} commit(s) in range`, ...notes, renderGuardVerdict(verdict), ...(sizeBlock === '' ? [] : ['', sizeBlock]), + ...(narrowedBlock === '' ? [] : ['', narrowedBlock]), ].join('\n'); console.log(report); @@ -3644,7 +4185,7 @@ async function main() { // or the maintainer's own direct merge, Prime Directive #14), the size // refusal's is the same human terminal. ⛔ No leg's code is swallowed // silently — every block states its refusal in full either way. - return groupExitCode({ governed: verdict, size }); + return groupExitCode({ governed: verdict, size, narrowed }); } // ⛔ NOT `process.exitCode = await main()`, and this is not a style choice. @@ -3754,8 +4295,15 @@ export async function selfTest() { // The same authorized approval, on a commit that is no longer the head. Under // the retired sha pin this exact fixture was the REFUSAL case. const authorizedPassOnOlder = (login = GOVERNED_APPROVERS[0]) => authorizedApprovalVerdict([approvedAt(login, OLD)], HEAD); + // The `.claude/**` declaration split (2026-11-19) as the queue leg leaves it once the body declares `none` and the + // record on the head verifies it. The pure-verdict cases below are about the legs AFTER the tier, so `run` hands + // every split entry that reading on the queue leg — the early-warning leg reads no body, exactly as the live one. + const VERIFIED_STAGE = Object.freeze({ measured: true, reason: null, located: 'found', where: 'PR', id: 1, carried: null, securityTouching: null, ruleChangeVerified: Object.freeze({ state: 'read', value: 'none' }), ruleChangeCarried: null }); + const VERIFIED = Object.freeze({ measured: true, reason: null, body: 'Rule-change: none', record: VERIFIED_STAGE }); + const declared = (entry) => readLowRiskTier(entry, REPO, pull(HEAD, { body: 'Rule-change: none' }), { record: VERIFIED_STAGE }); const run = (event, rows, approvals = new Map(), records = new Map()) => { const { governed, unattributed } = decomposeGovernedWork(rows, REPO); + if (event === EVENT_MERGE_GROUP) for (const entry of governed) if (!entry.surfaces.some((s) => s.lowRiskVerdict)) declared(entry); return guardVerdict({ repo: REPO, event, governed, unattributed, approvals, records, apiCalls: governed.length }); }; // The record reading a Tier S entry gets when the thread was READ and held @@ -3788,13 +4336,14 @@ export async function selfTest() { const wfWork = decomposeGovernedWork([row(23043, [WF])], REPO); assert('a-workflow-path-in-this-queue-with-NO-reading-decomposes-to-ONE-governed-entry-Tier-H', wfWork.governed.length === 1 && wfWork.governed[0].tier === TIER_H && wfWork.governed[0].surfaces.map((s) => s.id).join() === 'workflows' && wfWork.governed[0].paths.join() === WF, JSON.stringify(wfWork)); assert('the-same-path-is-governed-in-objectui-and-cloud', ['objectui', 'cloud'].every((r) => decomposeGovernedWork([row(1, [WF])], r).governed.length === 1 && governedTierFor([WF], r) === TIER_H)); - assert('and-NOT-in-objectos-or-hotcrm-the-scope-is-the-rows-not-the-guards', ['objectos', 'hotcrm'].every((r) => decomposeGovernedWork([row(1, [WF])], r).governed.length === 0 && governedPathsIn([WF], r).length === 0)); + assert('and-NOT-in-objectos-or-mobile-the-scope-is-the-rows-not-the-guards', ['objectos', 'mobile'].every((r) => decomposeGovernedWork([row(1, [WF])], r).governed.length === 0 && governedPathsIn([WF], r).length === 0)); + assert('hotcrm-is-governed-by-the-row-since-2026-11-19-the-audit-mirror-Tier-H', decomposeGovernedWork([row(1, [WF])], 'hotcrm').governed.length === 1 && governedTierFor([WF], 'hotcrm') === TIER_H); assert('a-github-tree-sibling-outside-workflows-is-clear', decomposeGovernedWork([row(2, ['.github/ISSUE_TEMPLATE/bug.md', '.github/CODEOWNERS', '.github/workflowsx/y.yml'])], REPO).governed.length === 0); const wfRefused = run('merge_group', [row(23043, [WF])], new Map([[23043, authorizedApprovalVerdict([], HEAD)]])); assert('an-unapproved-workflow-PR-is-REFUSED-at-the-queue-on-the-Tier-H-terminal', wfRefused.exitCode === EXIT_REFUSED_UNAPPROVED && renderGuardVerdict(wfRefused).includes(WF) && /landing tier: H/.test(renderGuardVerdict(wfRefused)), renderGuardVerdict(wfRefused)); assert('and-an-authorized-approval-on-the-head-clears-it', run('merge_group', [row(23043, [WF])], new Map([[23043, authorizedPass()]])).exitCode === EXIT_CLEAR); const wfClearText = renderGuardVerdict(run('merge_group', [row(3, ['.github/ISSUE_TEMPLATE/bug.md'])])); - assert('the-clear-words-count-the-rows-that-govern-THIS-repository-and-name-it', /13 surfaces govern objectstack/.test(wfClearText), wfClearText); + assert('the-clear-words-count-the-rows-that-govern-THIS-repository-and-name-it', /17 surfaces govern objectstack/.test(wfClearText), wfClearText); const threw = (fn) => { try { fn(); return null; } catch (error) { return error; } }; assert('⛔ decomposeGovernedWork-without-a-repository-is-an-ERROR-never-a-clear', threw(() => decomposeGovernedWork([row(1, [WF])])) instanceof TypeError && /decomposeGovernedWork wants the repository/.test(threw(() => decomposeGovernedWork([row(1, [WF])])).message)); const liftRejects = await liftGeneratedExceptions('/w', 'base', [], []).then(() => null, (error) => error); @@ -4131,9 +4680,9 @@ export async function selfTest() { const warnedS = run('pull_request', [row(9528, ['.claude/agents/os-dev.md'])], new Map([[9528, approvalVerdict([])]])); const warnedSText = renderGuardVerdict(warnedS); assert( - 'the-early-warning-names-Tier-S-and-the-record-it-waits-for-and-asks-for-no-approval', - warnedS.conclusion === 'warned' && /landing tier: S/.test(warnedSText) && /## Contract review/.test(warnedSText) && /CONTRACT_REVIEW_TIER/.test(warnedSText) && - !/What a seat DOES do once an account in GOVERNED_APPROVERS/.test(warnedSText), + 'the-early-warning-reads-no-body-so-it-names-Tier-H-UNTIL-it-is-read-the-declaration-and-the-record-Tier-S-waits-for', + warnedS.conclusion === 'warned' && warnedS.entries[0].tier === TIER_H && declarationUnread(warnedS.entries[0]) && /landing tier: H\(人合\) UNTIL the PR body is read/.test(warnedSText) && /## Contract review/.test(warnedSText) && /CONTRACT_REVIEW_TIER/.test(warnedSText) && + /`Rule-change: none`/.test(warnedSText) && /`Rule-change-verified:`/.test(warnedSText) && /declaration split .*NOT MEASURED/.test(warnedSText) && !/No review of record\n? *substitutes here/.test(warnedSText), warnedSText, ); const warnedHText = renderGuardVerdict(warnedV); @@ -4161,7 +4710,7 @@ export async function selfTest() { // thread carried no record — the reading is ABSENT, and the refusal is the // same "unapproved" the incident deserved. A Tier S entry with NO reading // at all refuses as UNREADABLE instead: "could not find out" never clears. - const tier = governedTierFor(replay.files, REPO); + const tier = governedTierFor(replay.files, REPO, GOVERNED_SURFACES, null, VERIFIED); const queued = run('merge_group', rows, new Map([[replay.pr, authorizedApprovalVerdict([], HEAD)]]), tier === TIER_S ? absentRecord(replay.pr) : new Map()); assert(`replay-REFUSES-at-the-queue: ${replay.name}`, queued.exitCode === EXIT_REFUSED_UNAPPROVED, JSON.stringify([queued.conclusion, tier])); if (tier === TIER_S) { @@ -5443,17 +5992,20 @@ export async function selfTest() { const RULES_PATH = 'AGENTS.md'; const TIER_H_PATHS = ['AGENTS.md', 'CLAUDE.md', 'docs/adr/0001-x.md', 'docs/NORTH-STAR.md', 'skills/objectstack-ui/SKILL.md']; - assert('a-Tier-S-only-path-set-is-Tier-S', governedTierFor([REF_A, REF_B, SKILL_PATH, AGENT_PATH, HOOK_PATH, SETTINGS_PATH], REPO) === TIER_S); - assert('⛔ the-old-references-boundary-is-GONE-SKILL-md-and-a-references-draft-sibling-are-Tier-S-alike', governedTierFor([SKILL_PATH], REPO) === TIER_S && governedTierFor(['.claude/skills/pm-dispatch/references-draft/x.md'], REPO) === TIER_S); + assert('a-Tier-S-only-path-set-is-Tier-S-on-a-declared-and-verified-reading-and-Tier-H-on-its-path-list-alone', governedTierFor([REF_A, REF_B, SKILL_PATH, AGENT_PATH], REPO, GOVERNED_SURFACES, null, VERIFIED) === TIER_S && governedTierFor([REF_A, REF_B, SKILL_PATH, AGENT_PATH], REPO) === TIER_H); + assert('⛔ a-hook-or-the-settings-file-in-the-set-is-Tier-H-by-path-on-that-same-reading', [HOOK_PATH, SETTINGS_PATH].every((p) => governedTierFor([REF_A, p], REPO, GOVERNED_SURFACES, null, VERIFIED) === TIER_H && governedTierFor([p], REPO, GOVERNED_SURFACES, null, VERIFIED) === TIER_H)); + assert('⛔ the-old-references-boundary-is-GONE-SKILL-md-and-a-references-draft-sibling-are-Tier-S-alike', governedTierFor([SKILL_PATH], REPO, GOVERNED_SURFACES, null, VERIFIED) === TIER_S && governedTierFor(['.claude/skills/pm-dispatch/references-draft/x.md'], REPO, GOVERNED_SURFACES, null, VERIFIED) === TIER_S); assert('ONE-Tier-H-path-makes-the-WHOLE-entry-Tier-H', governedTierFor([REF_A, REF_B, RULES_PATH], REPO) === TIER_H); assert('each-Tier-H-surface-alone-is-Tier-H', TIER_H_PATHS.every((p) => governedTierFor([p], REPO) === TIER_H), TIER_H_PATHS.join()); assert('an-EMPTY-path-set-defaults-to-Tier-H-never-to-S', governedTierFor([], REPO) === TIER_H && governedTierFor(undefined, REPO) === TIER_H); assert('the-tier-constants-are-the-registers-own-two-distinct-values', TIER_H === GOVERNED_TIER_H && TIER_S === GOVERNED_TIER_S && TIER_H !== TIER_S); assert( 'the-tier-travels-on-the-decomposed-entry-so-the-verdict-never-re-derives-it', - decomposeGovernedWork([row(5, [REF_A])], REPO).governed[0].tier === TIER_S && - decomposeGovernedWork([row(5, [AGENT_PATH])], REPO).governed[0].tier === TIER_S && - decomposeGovernedWork([row(5, [REF_A, RULES_PATH])], REPO).governed[0].tier === TIER_H, + declared(decomposeGovernedWork([row(5, [REF_A])], REPO).governed[0]).tier === TIER_S && + declared(decomposeGovernedWork([row(5, [AGENT_PATH])], REPO).governed[0]).tier === TIER_S && + // ⛔ ...and before the body and the record are read the decomposed entry is Tier H (2026-11-19), like one beside the law. + decomposeGovernedWork([row(5, [REF_A])], REPO).governed[0].tier === TIER_H && + declared(decomposeGovernedWork([row(5, [REF_A, RULES_PATH])], REPO).governed[0]).tier === TIER_H, ); // The real recognisers, and the tier VALUE read from the constant's one home @@ -5477,7 +6029,7 @@ export async function selfTest() { // the one the live loader assembled from `check-handover.mjs`, ⛔ never typed here. const RELAY = live.trustedAuthors?.[0]; assert('the-live-loader-trusts-the-relay-identity-first-then-GOVERNED_APPROVERS-and-nothing-else', typeof RELAY === 'string' && RELAY.endsWith('[bot]') && JSON.stringify(live.trustedAuthors) === JSON.stringify([RELAY, ...GOVERNED_APPROVERS]), JSON.stringify(live.trustedAuthors)); - const recordComment = ({ sha = REF_HEAD.slice(0, 12), signed = true, tierLine = `Served-tier: 75/75 \`${TIER_TOKEN}\``, id = 900, at = '2026-09-13T13:00:00Z', verdictWord = '**VERDICT: PASS**', prose = [], by = RELAY } = {}) => ({ + const recordComment = ({ sha = REF_HEAD.slice(0, 12), signed = true, tierLine = `Served-tier: 75/75 \`${TIER_TOKEN}\``, id = 900, at = '2026-09-13T13:00:00Z', verdictWord = '**VERDICT: PASS**', prose = [], by = RELAY, ruleVerified = 'none' } = {}) => ({ id, created_at: at, ...(by === null ? {} : { user: { login: by } }), @@ -5487,6 +6039,8 @@ export async function selfTest() { `Head-sha: \`${sha}\``, ...(signed ? ['Reviewed-by: `session_01SEAT`'] : []), ...(tierLine ? [tierLine] : []), + // The `.claude/**` declaration split's line (2026-11-19): every fixture record verifies `none` unless a case moves it. + ...(ruleVerified === null ? [] : [`Rule-change-verified: ${ruleVerified}`]), ...prose, '', verdictWord, @@ -5528,7 +6082,10 @@ export async function selfTest() { // Per-card answers for a pull that names more than one card: `{ [number]: list | 'throw' }`, over the two above. cardLabelsBy = {}, cardTimelineBy = {}, + // The body's `Rule-change:` declaration (2026-11-19), appended to whatever body a case writes; `null` leaves it out. + ruleChange = 'none', } = {}) => { + const declaredBody = ruleChange === null ? prBody : `${prBody}\n\nRule-change: ${ruleChange}`; tierApiCalls = 0; tierThreadsRead = []; tierLabelsRead = []; @@ -5537,7 +6094,7 @@ export async function selfTest() { event, rows: [{ ...row(pr, files, 'c'.repeat(40), `x (#${pr})`), ...(workflowDiff ? { workflowDiff } : {}) }, ...extraRows], fetchReviews: async () => { tierApiCalls += 1; return reviews; }, - fetchPull: async () => { tierApiCalls += 1; if (headThrows) throw new Error('head unreadable'); return pull(head, { body: prBody, headRef: branch, labels, fork }); }, + fetchPull: async () => { tierApiCalls += 1; if (headThrows) throw new Error('head unreadable'); return pull(head, { body: declaredBody, headRef: branch, labels, fork }); }, ...(timeline === null ? {} : { fetchTimeline: async (n) => { if (n !== pr) tierApiCalls += 1; const read = n === pr ? timeline : (cardTimelineBy[n] ?? cardTimeline); if (read === 'throw') throw new Error('HTTP 403'); return read; } }), ...(cardLabels === null ? {} : { fetchLabels: async (n) => { tierApiCalls += 1; tierLabelsRead.push(n); const read = cardLabelsBy[n] ?? cardLabels; if (read === 'throw') throw new Error('HTTP 403'); return read; } }), fetchComments: async (n) => { @@ -5580,13 +6137,13 @@ export async function selfTest() { // ⭐ #19133, end to end: the generalised tier. An agents + settings diff lands // on the same record — and its lit control, the same diff with NO record, is // refused (the card's own acceptance line). - const agentPass = await tierRun({ files: [AGENT_PATH, SETTINGS_PATH], comments: [recordComment()] }); + const agentPass = await tierRun({ files: [AGENT_PATH, SKILL_PATH], comments: [recordComment()] }); assert( - 'a-claude-agents-plus-settings-PR-with-a-valid-record-PASSES-with-zero-approvals-Tier-S-generalised', + 'a-claude-agents-plus-skill-PR-with-a-valid-record-PASSES-with-zero-approvals-Tier-S-generalised', agentPass.exitCode === EXIT_CLEAR && agentPass.conclusion === 'cleared' && agentPass.entries[0].tier === TIER_S && agentPass.entries[0].record.state === 'stands', JSON.stringify(agentPass.entries[0].record), ); - const agentNoRecord = await tierRun({ files: [AGENT_PATH, SETTINGS_PATH], comments: [] }); + const agentNoRecord = await tierRun({ files: [AGENT_PATH, SKILL_PATH], comments: [] }); assert( '⛔ CONTROL: the-same-Tier-S-PR-with-NO-record-is-REFUSED', agentNoRecord.exitCode === EXIT_REFUSED_UNAPPROVED && agentNoRecord.entries[0].tier === TIER_S && agentNoRecord.entries[0].record.state === 'absent', @@ -5867,7 +6424,7 @@ export async function selfTest() { event: EVENT_MERGE_GROUP, rows: [row(71, [REF_A])], fetchReviews: async () => [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)], - fetchPull: async () => REF_HEAD, + fetchPull: async () => pull(REF_HEAD, { body: 'Rule-change: none' }), fetchComments: async () => { throw new Error('the thread must not be read when an approval already satisfies the entry'); }, loadRecognisers: async () => { throw new Error('the recognisers must not be loaded when an approval already satisfies the entry'); }, }); @@ -5895,7 +6452,7 @@ export async function selfTest() { const tierNoThread = await tierRun({ commentsThrow: true }); assert('⛔ an-UNREADABLE-thread-is-exit-4-never-a-record-that-is-absent', tierNoThread.exitCode === EXIT_REFUSED_UNREADABLE && tierNoThread.entries[0].record.state === 'unreadable'); const tierNoHead = await tierRun({ headThrows: true, comments: [recordComment()] }); - assert('⛔ an-UNREADABLE-head-is-exit-4-on-THIS-tier-because-a-record-names-a-head', tierNoHead.exitCode === EXIT_REFUSED_UNREADABLE && tierNoHead.entries[0].record.state === 'unreadable'); + assert('⛔ an-UNREADABLE-head-is-exit-4-on-THIS-row-its-body-is-what-the-declaration-is-read-from', tierNoHead.exitCode === EXIT_REFUSED_UNREADABLE && tierNoHead.entries[0].tier === TIER_H && tierNoHead.entries[0].record === undefined && declarationUnread(tierNoHead.entries[0]) && /declaration split .*NOT MEASURED — its pull request could not be read/.test(renderGuardVerdict(tierNoHead)), renderGuardVerdict(tierNoHead)); const tierNoRecognisers = await tierRun({ recognisers: { available: false, reason: 'a rename' }, comments: [recordComment()] }); assert('⛔ recognisers-that-did-not-load-are-exit-4-fail-CLOSED', tierNoRecognisers.exitCode === EXIT_REFUSED_UNREADABLE); const tierLoaderThrew = await tierRun({ loaderThrows: true, comments: [recordComment()] }); @@ -6277,13 +6834,13 @@ export async function selfTest() { const live = codeownersMirrorVerdict({ text: onDisk }); assert('⭐ the-file-on-disk-mirrors-the-register-and-the-approver-list', live.ok, live.problems.join(' | ')); assert('every-Tier-H-row-that-governs-this-repository-is-a-pattern-the-file-carries-or-an-arm-row-it-leaves-out', live.tierHPatterns.length + live.armPatterns.length === governedSurfacesFor(REPO).filter((s) => s.tier === GOVERNED_TIER_H).length && live.tierHPatterns.every((p) => live.rows.some((r) => r.pattern === p)) && live.armPatterns.every((p) => !live.rows.some((r) => r.pattern === p)), JSON.stringify([live.tierHPatterns, live.armPatterns])); - assert('the-patterns-are-the-register-rows-root-anchored-prefix-or-exact', live.tierHPatterns.join() === '/AGENTS.md,/CLAUDE.md,/docs/NORTH-STAR.md,/.github/workflows/,/ui/docs/adr/,/ui/.claude/,/ui/AGENTS.md,/ui/CLAUDE.md,/ui/.github/workflows/', live.tierHPatterns.join()); + assert('the-patterns-are-the-register-rows-root-anchored-prefix-or-exact', live.tierHPatterns.join() === '/AGENTS.md,/CLAUDE.md,/docs/NORTH-STAR.md,/.github/workflows/,/scripts/pm/check-governed-merges.mjs,/scripts/pm/check-governed-queue-guard.mjs,/scripts/pm/record-recognisers.mjs,/scripts/pm/dispatch-gates.mjs,/ui/docs/adr/,/ui/.claude/,/ui/AGENTS.md,/ui/CLAUDE.md,/ui/.github/workflows/', live.tierHPatterns.join()); // Ruling record 6891850019: the rows carrying the low-risk arm leave the file — read off the register's `lowRisk`, never a list here. assert('⭐ the-arm-patterns-are-the-register-rows-carrying-the-low-risk-arm-here', live.armPatterns.join() === '/docs/adr/,/skills/,/ui/skills/' && live.armPatterns.join() === governedSurfacesFor(REPO).filter((s) => s.tier === GOVERNED_TIER_H && s.lowRisk?.repos?.includes(REPO)).map((s) => `/${s.prefix ?? s.exact}`).join(), live.armPatterns.join()); assert('every-line-on-disk-names-every-approver-spelled-as-a-login', live.rows.every((r) => GOVERNED_APPROVERS.every((a) => r.owners.includes(`@${a}`))) && live.rows.length >= live.tierHPatterns.length, JSON.stringify(live.rows)); assert('the-parser-strips-comments-and-blank-lines-and-splits-owners', JSON.stringify(codeownersRows('# c\n\n/docs/adr/ @a @b # trailing\n /x.md @c\n')) === JSON.stringify([{ pattern: '/docs/adr/', owners: ['@a', '@b'], line: 3 }, { pattern: '/x.md', owners: ['@c'], line: 4 }])); const owners = GOVERNED_APPROVERS.map((a) => `@${a}`).join(' '); - const full = (extra = '') => `# mirrors GOVERNED_APPROVERS\n${live.tierHPatterns.map((p) => `${p} ${owners}`).join('\n')}\n${extra}`; + const full = (extra = '') => `# mirrors GOVERNED_APPROVERS\n${[...live.tierHPatterns, ...live.splitPatterns].map((p) => `${p} ${owners}`).join('\n')}\n${extra}`; assert('a-fixture-carrying-exactly-the-Tier-H-rows-with-every-owner-passes', codeownersMirrorVerdict({ text: full() }).ok); // The root ADR row carries the low-risk arm since #33539 and has no line; the ui/ ADR row is the Tier H ADR row here. const one = codeownersMirrorVerdict({ text: full().replace(`/ui/docs/adr/ ${owners}`, `/ui/docs/adr/ @${RETIRED_APPROVER}`) }); @@ -6342,7 +6899,7 @@ export async function selfTest() { assert('two-commits-of-one-PR-both-read-S-is-Tier-S', decomposeGovernedWork([withRead(9, [WF_PATH], S_READ, '1'.repeat(40)), withRead(9, [WF_PATH], S_READ, '2'.repeat(40))], REPO).governed[0].tier === TIER_S); assert('⛔ a-path-the-reading-did-not-classify-is-Tier-H', decomposeGovernedWork([withRead(9, [WF_PATH, '.github/workflows/lint.yml'], S_READ)], REPO).governed[0].tier === TIER_H); assert('⛔ a-Tier-S-workflow-reading-beside-a-Tier-H-path-is-Tier-H-ALL-not-ANY', decomposeGovernedWork([withRead(9, [WF_PATH, 'AGENTS.md'], S_READ)], REPO).governed[0].tier === TIER_H); - assert('a-Tier-S-workflow-reading-beside-a-Tier-S-path-is-Tier-S', decomposeGovernedWork([withRead(9, [WF_PATH, '.claude/agents/os-dev.md'], S_READ)], REPO).governed[0].tier === TIER_S); + assert('a-Tier-S-workflow-reading-beside-a-declared-and-verified-claude-path-is-Tier-S-and-Tier-H-before-its-body-is-read', declared(decomposeGovernedWork([withRead(9, [WF_PATH, '.claude/agents/os-dev.md'], S_READ)], REPO).governed[0]).tier === TIER_S && decomposeGovernedWork([withRead(9, [WF_PATH, '.claude/agents/os-dev.md'], S_READ)], REPO).governed[0].tier === TIER_H); assert('⛔ objectui-and-cloud-stay-Tier-H-on-the-same-reading-the-split-names-objectstack-alone', ['objectui', 'cloud'].every((r) => decomposeGovernedWork([withRead(9, [WF_PATH], S_READ)], r).governed[0].tier === TIER_H && governedTierFor([WF_PATH], r, GOVERNED_SURFACES, S_READ) === TIER_H)); assert('⛔ the-ui-workflows-row-is-not-split', decomposeGovernedWork([withRead(9, ['ui/.github/workflows/ci.yml'], reading(TIER_S, 'ui/.github/workflows/ci.yml'))], REPO).governed[0].tier === TIER_H); assert('a-reading-on-a-row-with-no-workflow-path-changes-nothing', JSON.stringify(decomposeGovernedWork([withRead(9, ['AGENTS.md'], S_READ)], REPO)) === JSON.stringify(decomposeGovernedWork([row(9, ['AGENTS.md'])], REPO))); @@ -6544,7 +7101,7 @@ export async function selfTest() { const pairOf = (rows) => ({ pr: 70, card: REF_CARD, headSha: REF_HEAD, paths: [SK], repo: REPO, prComments: rows, cardComments: [] }); const found = lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: live }); const absent = lowRiskRecordStage({ pair: pairOf([]), recognisers: live }); - return JSON.stringify(found) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' } }) && + return JSON.stringify(found) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' }, ruleChangeVerified: { state: 'read', value: 'none' }, ruleChangeCarried: null }) && absent.measured === true && absent.located === 'absent' && absent.securityTouching === null && lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: { available: false, reason: 'x' } }).measured === false && lowRiskRecordStage({ pair: pairOf([armRecord()]), recognisers: { ...live, reading: undefined } }).measured === false && @@ -6632,7 +7189,7 @@ export async function selfTest() { const cardless = await stageOf({ pull: { ...pull, body: 'Clause-②: no\nMetadata-protocol: none\n' } }); const unreadPull = await stageOf({ pull: null }); return order === `comments 70,comments ${REF_CARD},labels ${REF_CARD},timeline ${REF_CARD}` && clean.apiCalls === 4 && clean.card.card === REF_CARD && - JSON.stringify(clean.record) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' } }) && + JSON.stringify(clean.record) === JSON.stringify({ measured: true, reason: null, located: 'found', where: 'PR', id: 900, carried: null, securityTouching: { state: 'read', value: 'no' }, ruleChangeVerified: { state: 'read', value: 'none' }, ruleChangeCarried: null }) && JSON.stringify(clean.cardLabels) === JSON.stringify({ measured: true, reason: null, card: REF_CARD, labels: ['tooling'], timeline: { measured: true, reason: null, events: [] }, others: { measured: true, reason: null, cards: [] } }) && noLine.record.securityTouching.state === 'missing' && untrusted.record.located === 'absent' && unloaded.apiCalls === 0 && unloaded.record.measured === false && /would not load: boom/.test(unloaded.record.reason) && unloaded.cardLabels.measured === false && @@ -6859,6 +7416,330 @@ export async function selfTest() { })()); } + // ── the guard instruments and the `.claude/**` declaration split at the queue (2026-11-19, card #35321) ── + // + // The card's "done when", branch by branch, through the REAL orchestrator and the real recognisers: each + // refusal beside the one-fact-away fixture that clears, so no branch is green because everything refuses. + battery('⚖️ #35321 at the queue: guard instruments are Tier H, `.claude/**` splits by declaration'); + { + const split = (v) => v.entries[0].surfaces.find((s) => s.ruleChangeVerdict)?.ruleChangeVerdict; + const words = (v) => renderGuardVerdict(v); + const GUARD_FILES = ['scripts/pm/check-governed-merges.mjs', 'scripts/pm/check-governed-queue-guard.mjs', 'scripts/pm/record-recognisers.mjs', 'scripts/pm/dispatch-gates.mjs']; + + // Item 1: a guard file is Tier H — a valid record lands nothing, an authorized approval does. + for (const file of GUARD_FILES) { + const refused = await tierRun({ files: [file], comments: [recordComment()] }); + const approved = await tierRun({ files: [file], reviews: [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)] }); + assert(`⛔ guard-file-is-Tier-H-a-PASS-record-does-not-land-it-and-an-authorized-approval-does: ${file}`, + refused.exitCode === EXIT_REFUSED_UNAPPROVED && refused.entries[0].tier === TIER_H && refused.entries[0].record === undefined && /landing tier: H/.test(words(refused)) && words(refused).includes(file) && + approved.exitCode === EXIT_CLEAR && approved.conclusion === 'cleared', + words(refused)); + } + assert('control-a-sibling-script-is-not-governed-and-costs-no-read', + await (async () => { const v = await tierRun({ files: ['scripts/pm/check-governed-prose.mjs', 'scripts/pm/check-half-states.mjs'] }); return v.conclusion === 'clear' && v.apiCalls === 0 && tierApiCalls === 0; })()); + assert('⛔ a-guard-file-beside-a-declared-and-verified-claude-path-keeps-the-whole-entry-Tier-H', + await (async () => { const v = await tierRun({ files: [SKILL_PATH, GUARD_FILES[0]], comments: [recordComment()] }); return v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H && v.entries[0].record === undefined; })()); + + // Item 2: `.claude/` wording with both lines. + const both = await tierRun({ files: [SKILL_PATH], comments: [recordComment()] }); + assert('⭐ claude-wording-with-both-lines-is-Tier-S-and-clears-on-its-record', + both.exitCode === EXIT_CLEAR && both.conclusion === 'cleared' && both.entries[0].tier === TIER_S && both.entries[0].record.state === 'stands' && both.entries[0].record.verdict === 'PASS' && + split(both).declared === 'none' && split(both).recordStage === 'deferred' && ruleChangeDeclaredOn(both.entries[0]) === 'none' && /declaration split .*Tier S — the PR body declares `Rule-change: none`/.test(words(both)), + words(both)); + const ruledBody = { prBody: `Fixes #${REF_CARD}\n\nRuling-ref: 「同意」 — the maintainer, the review thread, 2026-11-19 04:30Z`, ruleChange: 'ruled' }; + const ruled = await tierRun({ files: [SKILL_PATH], ...ruledBody, comments: [recordComment({ ruleVerified: 'ruled' })] }); + assert('⭐ a-ruled-copy-with-its-Ruling-ref-clears-on-a-record-that-verifies-ruled', ruled.exitCode === EXIT_CLEAR && ruled.entries[0].tier === TIER_S && ruleChangeDeclaredOn(ruled.entries[0]) === 'ruled', words(ruled)); + assert('⛔ ruled-without-a-Ruling-ref-is-Tier-H-and-a-record-that-verifies-none-does-not-verify-ruled', + await (async () => { + const bare = await tierRun({ files: [SKILL_PATH], ruleChange: 'ruled', comments: [recordComment({ ruleVerified: 'ruled' })] }); + const other = await tierRun({ files: [SKILL_PATH], ...ruledBody, comments: [recordComment({ ruleVerified: 'none' })] }); + return bare.exitCode === EXIT_REFUSED_UNAPPROVED && bare.entries[0].tier === TIER_H && /carries no `Ruling-ref:` line/.test(words(bare)) && + other.exitCode === EXIT_REFUSED_UNAPPROVED && other.entries[0].tier === TIER_S && other.entries[0].record.state === 'not-pass' && /reads `Rule-change-verified: none`, and the PR body declares `Rule-change: ruled`/.test(other.entries[0].record.verdictReason); + })()); + + // Item 2: the missing line and `yes` — Tier H, the record never consulted, an approval still lands it. + const missing = await tierRun({ files: [SKILL_PATH], ruleChange: null, comments: [recordComment()] }); + assert('⛔ missing-line-is-Tier-H-refused-with-a-valid-record-on-the-head', + missing.exitCode === EXIT_REFUSED_UNAPPROVED && missing.entries[0].tier === TIER_H && missing.entries[0].record === undefined && tierThreadsRead.length === 0 && + /declaration split .*Tier H —/.test(words(missing)) && /carries no `Rule-change:` line/.test(words(missing)) && /landing tier: H\(人合\) — waits/.test(words(missing)), + words(missing)); + const yes = await tierRun({ files: [SKILL_PATH], ruleChange: 'yes', comments: [recordComment({ ruleVerified: 'yes' })] }); + assert('⛔ Rule-change-yes-is-Tier-H-refused-whatever-the-record-says', + yes.exitCode === EXIT_REFUSED_UNAPPROVED && yes.entries[0].tier === TIER_H && yes.entries[0].record === undefined && /declares `Rule-change: yes`/.test(words(yes)), words(yes)); + assert('control-an-authorized-approval-lands-each-of-the-two-and-reads-no-thread', + await (async () => { + const out = []; + for (const ruleChange of [null, 'yes']) { const v = await tierRun({ files: [SKILL_PATH], ruleChange, reviews: [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)] }); out.push(v.exitCode === EXIT_CLEAR && tierThreadsRead.length === 0); } + return out.every(Boolean); + })()); + assert('⛔ a-declaration-that-is-quoted-fenced-doubled-or-followed-by-words-is-Tier-H', + await (async () => { + const out = []; + for (const line of ['> Rule-change: none', '```\nRule-change: none\n```', 'Rule-change: none\nRule-change: none', 'Rule-change: none — wording only', '`Rule-change`: none']) { + const v = await tierRun({ files: [SKILL_PATH], ruleChange: null, prBody: `Fixes #${REF_CARD}\n\n${line}`, comments: [recordComment()] }); + out.push(v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H); + } + return out.every(Boolean); + })()); + + // Item 2: a record that does not verify — Tier S on the declaration, refused on the record leg, by name. + const unverified = { 'no line on the record': null, 'the record reads yes': 'yes', 'the record verifies the other value': 'ruled' }; + for (const [name, ruleVerified] of Object.entries(unverified)) { + const v = await tierRun({ files: [SKILL_PATH], comments: [recordComment({ ruleVerified })] }); + assert(`⛔ unverified-is-REFUSED-on-the-record-leg: ${name}`, + v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_S && v.entries[0].record.state === 'not-pass' && /declaration split is not verified/.test(v.entries[0].record.verdictReason) && v.entries[0].record.verdictReason.includes('comment 900'), + JSON.stringify(v.entries[0].record)); + } + assert('⛔ an-unreadable-line-on-the-record-is-REFUSED-too-two-lines-a-quoted-one-trailing-words', + await (async () => { + const out = []; + for (const prose of [['Rule-change-verified: none'], ['> Rule-change-verified: yes']]) { const v = await tierRun({ files: [SKILL_PATH], comments: [recordComment({ prose })] }); out.push(v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].record.state === 'not-pass' && /unreadable/.test(v.entries[0].record.verdictReason)); } + const trailing = await tierRun({ files: [SKILL_PATH], comments: [recordComment({ ruleVerified: 'none — wording only' })] }); + return out.every(Boolean) && trailing.entries[0].record.state === 'not-pass'; + })()); + assert('⛔ a-verified-line-on-a-record-that-does-not-read-PASS-or-names-an-older-head-lands-nothing', + await (async () => { + const fail = await tierRun({ files: [SKILL_PATH], comments: [recordComment({ verdictWord: '**VERDICT: FAIL**' })] }); + const old = await tierRun({ files: [SKILL_PATH], comments: [recordComment({ sha: REF_OLD.slice(0, 12) })] }); + return fail.exitCode === EXIT_REFUSED_UNAPPROVED && fail.entries[0].record.state === 'not-pass' && old.exitCode === EXIT_REFUSED_UNAPPROVED && old.entries[0].record.state === 'absent'; + })()); + assert('ruleChangeRecordVerdict-leaves-a-record-that-does-not-stand-as-it-was-and-refuses-a-carry-it-cannot-diff', + ruleChangeRecordVerdict({ state: 'absent' }, {}, live, 'none').state === 'absent' && ruleChangeRecordVerdict({ state: 'below-tier' }, {}, live, 'none').state === 'below-tier' && + ((v) => v.state === 'not-pass' && /could not diff the hops/.test(v.verdictReason))(ruleChangeRecordVerdict({ state: 'stands', id: 900, carriedFrom: 'a'.repeat(40) }, { headSha: REF_HEAD }, live, 'none')) && + /moved \.claude\/x\.md/.test(ruleChangeCarryRefusal('a'.repeat(40), { headSha: REF_HEAD, runGit: () => '.claude/x.md\0.changeset/a.md\0' })) && + ruleChangeCarryRefusal('a'.repeat(40), { headSha: REF_HEAD, runGit: () => '.changeset/a.md\0CHANGELOG.md\0' }) === null && + ruleChangeDeclaredOn({ tier: TIER_H, surfaces: [] }) === null && ruleChangeDeclaredOn(null) === null); + + // Item 2: settings and hooks — Tier H by path on the reading that lands anything else under the row. + for (const file of [SETTINGS_PATH, '.claude/settings.local.json', HOOK_PATH]) { + const v = await tierRun({ files: [file], comments: [recordComment()] }); + const mixed = await tierRun({ files: [file, SKILL_PATH], comments: [recordComment()] }); + assert(`⛔ settings-and-hooks-are-Tier-H-with-both-lines-on-record: ${file}`, + v.exitCode === EXIT_REFUSED_UNAPPROVED && v.entries[0].tier === TIER_H && v.entries[0].record === undefined && split(v).byPath === true && /declaration split .*Tier H by path/.test(words(v)) && tierThreadsRead.length === 0 && + mixed.exitCode === EXIT_REFUSED_UNAPPROVED && mixed.entries[0].tier === TIER_H, + words(v)); + } + assert('control-the-near-misses-beside-them-clear-on-the-same-body-and-record', + await (async () => { const v = await tierRun({ files: ['.claude/settings.md', '.claude/skills/hooks/x.sh'], comments: [recordComment()] }); return v.exitCode === EXIT_CLEAR && v.entries[0].tier === TIER_S; })()); + assert('the-CODEOWNERS-mirror-demands-a-line-for-each-always-Tier-H-path-and-names-the-one-missing', + (() => { + const onDisk = readFileSync(join(repoRoot, '.github', 'CODEOWNERS'), 'utf8'); + const live2 = codeownersMirrorVerdict({ text: onDisk }); + const short = codeownersMirrorVerdict({ text: onDisk.split('\n').filter((l) => !l.startsWith('/.claude/hooks/')).join('\n') }); + const wrong = codeownersMirrorVerdict({ text: onDisk.replace('/.claude/settings*.json @os-zhuang', '/.claude/settings*.json @someone-else') }); + return live2.ok && live2.splitPatterns.join() === '/.claude/settings*.json,/.claude/hooks/' && !short.ok && short.problems.length === 1 && short.problems[0].includes('`/.claude/hooks/`') && + !wrong.ok && wrong.problems.length === 1 && wrong.problems[0].includes('`/.claude/settings*.json`') && codeownersMirrorVerdict({ text: onDisk, repo: 'objectui' }).splitPatterns.length === 0; + })()); + + // The leg that reads no body, and the one whose read failed. + const early = await tierRun({ files: [SKILL_PATH], event: EVENT_PULL_REQUEST, comments: [recordComment()] }); + assert('the-early-warning-leg-reads-no-body-names-Tier-H-UNTIL-it-is-read-and-never-reddens', + early.exitCode === EXIT_CLEAR && early.conclusion === 'warned' && early.entries[0].tier === TIER_H && declarationUnread(early.entries[0]) && /UNTIL the PR body is read/.test(words(early)) && tierThreadsRead.length === 0, words(early)); + assert('declarationUnread-is-only-the-unread-body-never-a-read-Tier-H', + !declarationUnread(missing.entries[0]) && !declarationUnread(yes.entries[0]) && !declarationUnread(both.entries[0]) && !declarationUnread(null) && + !declarationUnread(decomposeGovernedWork([row(5, [SKILL_PATH, 'AGENTS.md'])], REPO).governed[0]) && !declarationUnread(decomposeGovernedWork([row(5, [HOOK_PATH])], REPO).governed[0]) && declarationUnread(decomposeGovernedWork([row(5, [SKILL_PATH])], REPO).governed[0])); + } + + // ── the NARROWED leg (2026-11-19, card #35321, item 3) ────────────────────── + battery('⚖️ #35321: a declared narrowing lands like Tier H — an authorized approval AND a PASS record'); + { + const SPEC = 'packages/spec/src/data/field.zod.ts'; + const CS = '.changeset/35321-narrow.md'; + const NARROW = `Fixes #${REF_CARD}\n\nClause-②: no\nMetadata-protocol: narrowed\n`; + const ADDED = `Fixes #${REF_CARD}\n\nClause-②: yes\nMetadata-protocol: added\n`; + const changeset = (body) => `---\n'@objectstack/spec': minor\n---\n\n${body}\n`; + let reads = []; + const narrowRun = async ({ body = NARROW, files = [SPEC], changesetText = null, reviews = [], timeline = [], comments = [], event = EVENT_MERGE_GROUP, pullThrows = false, reviewsThrow = false, commentsThrow = false, approvals = new Map(), runGit = undefined, recognisers = live, extraRows = [] } = {}) => { + reads = []; + const paths = changesetText === null ? files : [...files, CS]; + return runNarrowedGuard({ + repo: REPO, + event, + rows: [row(70, paths, 'c'.repeat(40)), ...extraRows], + fetchPull: async (n) => { reads.push(`pull ${n}`); if (pullThrows) throw new Error('HTTP 502'); return pull(REF_HEAD, { body: n === 70 ? body : 'Fixes #1', headRef: `claude/issue-${REF_CARD}-x` }); }, + fetchReviews: async (n) => { reads.push(`reviews ${n}`); if (reviewsThrow) throw new Error('HTTP 403'); return reviews; }, + fetchTimeline: async (n) => { reads.push(`timeline ${n}`); return timeline; }, + fetchComments: async (n) => { reads.push(`comments ${n}`); if (commentsThrow) throw new Error('HTTP 502'); return n === 70 ? comments : []; }, + loadRecognisers: async () => recognisers, + approvals, + runGit: runGit === undefined ? (args) => { reads.push(`git ${args[0]}`); if (args[0] === 'show' && changesetText !== null) return changesetText; throw new Error('not in this tree'); } : runGit, + }); + }; + const approval = [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD)]; + const enqueued = [{ event: 'added_to_merge_queue', actor: { login: GOVERNED_APPROVERS[0] }, created_at: '2026-11-19T05:00:00Z' }]; + + // The card's two branches first. + const bare = await narrowRun(); + assert('⛔ narrowed-declaration-without-approval-is-REFUSED-on-its-own-code', + bare.exitCode === EXIT_REFUSED_NARROWED && bare.conclusion === 'refused' && bare.refusalKind === 'narrowed' && bare.entries[0].state === 'refused' && bare.entries[0].reasons.length === 2 && + renderNarrowedVerdict(bare).includes(NARROWED_RULING) && /declares a narrowing and is NOT cleared/.test(renderNarrowedVerdict(bare)) && renderNarrowedVerdict(bare).includes('Metadata-protocol: narrowed'), + renderNarrowedVerdict(bare)); + const added = await narrowRun({ body: ADDED }); + assert('⭐ added-is-unchanged-CLEAR-on-one-pull-read-with-no-review-timeline-or-thread-read', + added.exitCode === EXIT_CLEAR && added.conclusion === 'clear' && added.entries[0].state === 'not-declared' && reads.join() === 'pull 70' && added.apiCalls === 1 && /no queued pull request declares a narrowing/.test(renderNarrowedVerdict(added)), + reads.join()); + assert('semantic-none-a-bare-Clause-2-and-a-widening-arm-are-unchanged-too', + await (async () => { + const out = []; + for (const body of ['Metadata-protocol: semantic', 'Metadata-protocol: none\nClause-②: no', 'Clause-②: yes', 'Clause-②: yes (widening)\nMetadata-protocol: added', '']) { const v = await narrowRun({ body }); out.push(v.exitCode === EXIT_CLEAR && v.entries[0].state === 'not-declared' && reads.join() === 'pull 70'); } + return out.every(Boolean); + })()); + + // Both halves, never either. + const cleared = await narrowRun({ reviews: approval, comments: [recordComment()] }); + assert('⭐ an-authorized-approval-AND-a-PASS-record-on-the-head-CLEAR-it', + cleared.exitCode === EXIT_CLEAR && cleared.entries[0].state === 'cleared' && cleared.entries[0].by === 'review' && /both halves are on record: an authorized APPROVED review/.test(renderNarrowedVerdict(cleared)) && reads.join() === `pull 70,reviews 70,comments 70,comments ${REF_CARD}`, + renderNarrowedVerdict(cleared) + reads.join()); + const approvalOnly = await narrowRun({ reviews: approval }); + const recordOnly = await narrowRun({ comments: [recordComment()] }); + assert('⛔ an-approval-with-no-record-and-a-record-with-no-approval-are-each-REFUSED-naming-the-missing-half', + approvalOnly.exitCode === EXIT_REFUSED_NARROWED && approvalOnly.entries[0].reasons.length === 1 && /no `## Contract review` record names its current head/.test(approvalOnly.entries[0].reasons[0]) && + recordOnly.exitCode === EXIT_REFUSED_NARROWED && recordOnly.entries[0].reasons.length === 1 && /no authorized APPROVED review is on record/.test(recordOnly.entries[0].reasons[0]), + JSON.stringify([approvalOnly.entries[0].reasons, recordOnly.entries[0].reasons])); + assert('the-maintainers-own-enqueue-from-an-authorized-account-is-the-human-half-and-still-owes-the-record', + await (async () => { + const withRecord = await narrowRun({ timeline: enqueued, comments: [recordComment()] }); + const without = await narrowRun({ timeline: enqueued }); + const seat = await narrowRun({ timeline: [{ ...enqueued[0], actor: { login: 'os-sales' } }], comments: [recordComment()] }); + return withRecord.exitCode === EXIT_CLEAR && withRecord.entries[0].by === 'enqueue' && without.exitCode === EXIT_REFUSED_NARROWED && seat.exitCode === EXIT_REFUSED_NARROWED; + })()); + assert('⛔ an-unauthorized-a-dismissed-and-a-superseded-approval-are-not-the-human-half', + await (async () => { + const out = []; + for (const reviews of [[approvedAt('os-sales', REF_HEAD)], [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD), { state: 'DISMISSED', user: { login: GOVERNED_APPROVERS[0] } }], [approvedAt(GOVERNED_APPROVERS[0], REF_HEAD), { state: 'CHANGES_REQUESTED', user: { login: GOVERNED_APPROVERS[0] } }]]) { + out.push((await narrowRun({ reviews, comments: [recordComment()] })).exitCode === EXIT_REFUSED_NARROWED); + } + return out.every(Boolean); + })()); + assert('⛔ a-record-that-reads-FAIL-names-an-older-head-or-is-unsigned-is-not-the-record-half', + await (async () => { + const out = []; + for (const record of [recordComment({ verdictWord: '**VERDICT: FAIL**' }), recordComment({ sha: REF_OLD.slice(0, 12) }), recordComment({ signed: false }), recordComment({ by: 'some-commenter' })]) { + out.push((await narrowRun({ reviews: approval, comments: [record] })).exitCode === EXIT_REFUSED_NARROWED); + } + return out.every(Boolean); + })()); + + // Where a declaration is read from, and with which readers. + assert('⛔ a-changeset-that-declares-narrowed-under-a-body-that-says-none-is-a-declared-narrowing', + await (async () => { + const v = await narrowRun({ body: `Fixes #${REF_CARD}\n\nMetadata-protocol: none\n`, changesetText: changeset('Metadata-protocol: narrowed') }); + const clean = await narrowRun({ body: ADDED, changesetText: changeset('Metadata-protocol: added') }); + return v.exitCode === EXIT_REFUSED_NARROWED && v.entries[0].declarations[0].where === `\`${CS}\`` && clean.exitCode === EXIT_CLEAR && clean.entries[0].state === 'not-declared'; + })()); + assert('⛔ the-narrowing-arm-on-either-Clause-2-value-is-a-declared-narrowing-in-the-body-or-a-changeset', + await (async () => { + const out = []; + for (const line of ['Clause-②: no (narrowing)', 'Clause-②: yes (narrowing)']) { + out.push((await narrowRun({ body: `Fixes #${REF_CARD}\n\n${line}\nMetadata-protocol: none` })).exitCode === EXIT_REFUSED_NARROWED); + out.push((await narrowRun({ body: 'Fixes #1', changesetText: changeset(line) })).exitCode === EXIT_REFUSED_NARROWED); + } + return out.every(Boolean); + })()); + assert('narrowingDeclarationsIn-reads-line-by-line-with-the-fleets-readers-and-fails-closed-on-a-near-arm', + narrowingDeclarationsIn('Metadata-protocol: none\nMetadata-protocol: narrowed').length === 1 && narrowingDeclarationsIn('- **Metadata-protocol**: narrowed (the `x` key)').length === 1 && + narrowingDeclarationsIn('Clause-②: no (narrowed)').length === 1 && narrowingDeclarationsIn('Clause-②: no (narrowing)\nMetadata-protocol: narrowed').map((d) => d.key).join() === 'Clause-②,Metadata-protocol' && + ['Metadata-protocol: added', 'Metadata-protocol: semantic', 'Metadata-protocol: none', 'Clause-②: yes (widening)', 'Clause-②: no', 'a narrowed spec change, in prose', 'see `Metadata-protocol: narrowed` in the template', '- `Metadata-protocol: narrowed` ⇒ `minor`', '', null].every((t) => narrowingDeclarationsIn(t).length === 0), + JSON.stringify(narrowingDeclarationsIn('- `Metadata-protocol: narrowed` ⇒ `minor`'))); + assert('⛔ the-pull-request-template-left-UNFILLED-declares-no-narrowing-and-a-partial-menu-still-does', + await (async () => { + const template = readFileSync(join(repoRoot, '.github', 'PULL_REQUEST_TEMPLATE.md'), 'utf8'); + const v = await narrowRun({ body: template }); + return template.includes(`\nMetadata-protocol: ${UNFILLED_PROTOCOL_MENU}\n`) && UNFILLED_PROTOCOL_MENU === 'added | narrowed | semantic | none' && narrowingDeclarationsIn(template).length === 0 && + v.exitCode === EXIT_CLEAR && v.entries[0].state === 'not-declared' && reads.join() === 'pull 70' && + narrowingDeclarationsIn('Metadata-protocol: added | narrowed | semantic | none').length === 0 && + ['Metadata-protocol: narrowed | none', 'Metadata-protocol: added | narrowed', 'Metadata-protocol: added | narrowed | semantic | none (narrowed)', 'Metadata-protocol: narrowed.'].every((line) => narrowingDeclarationsIn(line).length === 1); + })()); + assert('a-narrowing-with-no-schema-path-stands-on-the-narrowing-face-its-record-at-the-default-tier-does-not', + await (async () => { + const runtime = { files: ['packages/runtime/src/x.ts'], body: `Fixes #${REF_CARD}\n\nClause-②: no (narrowing)\nMetadata-protocol: none\n`, changesetText: changeset('Clause-②: no (narrowing)'), reviews: approval }; + const atTier = await narrowRun({ ...runtime, comments: [recordComment()] }); + const below = await narrowRun({ ...runtime, comments: [recordComment({ tierLine: 'Served-tier: 75/75 `TIER_DEFAULT`' })] }); + return atTier.exitCode === EXIT_CLEAR && atTier.entries[0].record.face === 'narrowing' && below.exitCode === EXIT_REFUSED_NARROWED && /does not stand \(below-tier\)/.test(below.entries[0].reasons[0]); + })()); + // The declaration this leg found holds the face, whatever the `Clause-②:` line reads: the narrowed KIND alone, the + // kind beside a bare, an absent or a malformed clause line, the kind on a changeset only, and a near-arm clause + // spelling (which no longer reads as a record that does not stand for want of a face). + const kindOnly = await (async () => { + const DEFAULT_TIER = recordComment({ tierLine: 'Served-tier: 75/75 `TIER_DEFAULT`' }); + const RUNTIME = ['packages/runtime/src/x.ts']; + const shapes = { + 'kind beside a bare clause line': { body: NARROW }, + 'kind with no clause line': { body: `Fixes #${REF_CARD}\n\nMetadata-protocol: narrowed\n` }, + 'kind on a changeset only': { body: `Fixes #${REF_CARD}\n\nClause-②: no\nMetadata-protocol: none\n`, changesetText: changeset('Metadata-protocol: narrowed') }, + 'near-arm clause spelling': { body: `Fixes #${REF_CARD}\n\nClause-②: no (narrowed)\nMetadata-protocol: none\n` }, + 'kind beside a malformed clause line': { body: `Fixes #${REF_CARD}\n\nClause-②: maybe\nMetadata-protocol: narrowed\n` }, + }; + const out = {}; + for (const [name, shape] of Object.entries(shapes)) { + const atTier = await narrowRun({ ...shape, files: RUNTIME, reviews: approval, comments: [recordComment()] }); + const below = await narrowRun({ ...shape, files: RUNTIME, reviews: approval, comments: [DEFAULT_TIER] }); + out[name] = { atTier: [atTier.exitCode, atTier.entries[0].state, atTier.entries[0].record?.face ?? null], below: [below.exitCode, below.entries[0].state, below.entries[0].record?.face ?? null, below.entries[0].reasons.join(' | ')] }; + } + // Negative control: with NO declaration found the leg holds nothing and reads no record — the same path and the + // same default-tier record under `added` stay clear on one pull read. + const control = await narrowRun({ body: ADDED, files: RUNTIME, reviews: approval, comments: [DEFAULT_TIER] }); + out.control = [control.exitCode, control.entries[0].state, reads.join()]; + return out; + })(); + assert('⛔ the-narrowed-kind-on-a-runtime-only-path-holds-the-narrowing-faces-tier-a-default-tier-record-is-REFUSED-an-at-tier-one-CLEARS', + ['kind beside a bare clause line', 'kind with no clause line', 'kind on a changeset only', 'near-arm clause spelling', 'kind beside a malformed clause line'].every((name) => + kindOnly[name].atTier.join() === `${EXIT_CLEAR},cleared,narrowing` && kindOnly[name].below[0] === EXIT_REFUSED_NARROWED && kindOnly[name].below[1] === 'refused' && kindOnly[name].below[2] === 'narrowing' && /does not stand \(below-tier\)/.test(kindOnly[name].below[3])) && + kindOnly.control.join() === `${EXIT_CLEAR},not-declared,pull 70` && + NARROWING_FACE_LINE === 'Clause-②: no (narrowing)' && readClause2Line(NARROWING_FACE_LINE)?.kind === 'declared' && readClause2Line(NARROWING_FACE_LINE)?.arm === 'narrowing', + JSON.stringify(kindOnly)); + + // "Could not find out" is its own code, and never a pass. + assert('⛔ an-unreadable-pull-changeset-review-list-or-thread-REFUSES-on-code-11', + await (async () => { + const pullGone = await narrowRun({ pullThrows: true }); + const csGone = await narrowRun({ body: ADDED, changesetText: 'x', runGit: (args) => { if (args[0] === 'ls-tree') return `100644 blob abc\t${CS}`; throw new Error('bad object'); } }); + const noGit = await narrowRun({ body: ADDED, changesetText: 'x', runGit: null }); + const reviewsGone = await narrowRun({ reviewsThrow: true, comments: [recordComment()] }); + const threadGone = await narrowRun({ reviews: approval, commentsThrow: true }); + const unloaded = await narrowRun({ reviews: approval, recognisers: { available: false, reason: 'a rename' } }); + return [pullGone, csGone, noGit, reviewsGone, threadGone, unloaded].every((v) => v.exitCode === EXIT_REFUSED_NARROWED_UNREADABLE && v.refusalKind === 'unreadable' && /could not find out/.test(renderNarrowedVerdict(v))); + })()); + assert('a-changeset-the-commit-DELETED-declares-nothing-and-is-told-apart-from-a-failed-read', + await (async () => { const v = await narrowRun({ body: ADDED, changesetText: 'x', runGit: (args) => { if (args[0] === 'ls-tree') return ''; throw new Error('path does not exist'); } }); return v.exitCode === EXIT_CLEAR && v.entries[0].state === 'not-declared'; })() && + readChangesetTexts([], null).measured === true && readChangesetTexts([{ sha: null, path: CS }], () => '').measured === false && changesetRefsByPull([row(7, [CS, SPEC], 'd'.repeat(40)), row(8, [SPEC])]).get(7)[0].sha === 'd'.repeat(40) && changesetRefsByPull([row(8, [SPEC])]).get(8).length === 0); + assert('⛔ a-clean-sibling-does-not-carry-a-declared-narrowing-through-the-group-and-a-group-naming-no-pull-refuses', + await (async () => { + const group = await narrowRun({ extraRows: [row(71, ['packages/runtime/src/y.ts'], 'd'.repeat(40))] }); + const none = await runNarrowedGuard({ repo: REPO, event: EVENT_MERGE_GROUP, rows: [], fetchPull: async () => pull() }); + return group.entries.map((e) => e.state).join() === 'refused,not-declared' && group.exitCode === EXIT_REFUSED_NARROWED && none.exitCode === EXIT_REFUSED_NARROWED_UNREADABLE && none.refusalKind === 'no-pull'; + })()); + assert('the-leg-reuses-the-approval-the-governed-leg-read-and-reads-no-review-list-of-its-own', + await (async () => { const v = await narrowRun({ approvals: new Map([[70, authorizedPass()]]), comments: [recordComment()] }); return v.exitCode === EXIT_CLEAR && !reads.some((r) => r.startsWith('reviews') || r.startsWith('timeline')); })()); + + // The pull_request leg, the exit contract and the wiring. + const prLeg = await narrowRun({ event: EVENT_PULL_REQUEST }); + assert('the-pull_request-leg-is-not-applicable-renders-nothing-and-reads-nothing', + prLeg.conclusion === 'not-applicable' && prLeg.exitCode === EXIT_CLEAR && renderNarrowedVerdict(prLeg) === '' && reads.length === 0); + const exitOf = (code) => ({ exitCode: code }); + assert('the-two-narrowed-codes-are-distinct-and-collide-with-no-other-code', + new Set([EXIT_CLEAR, EXIT_CANNOT_RUN, EXIT_REFUSED_UNAPPROVED, EXIT_REFUSED_UNREADABLE, EXIT_REFUSED_UNATTRIBUTED, EXIT_REFUSED_OVERSIZED, EXIT_REFUSED_SIZE_UNREADABLE, EXIT_REFUSED_NARROWED, EXIT_REFUSED_NARROWED_UNREADABLE]).size === 9 && EXIT_REFUSED_NARROWED === 10 && EXIT_REFUSED_NARROWED_UNREADABLE === 11); + assert('⭐ precedence-governed-then-size-then-narrowed-and-two-legs-alone-answer-as-before', + groupExitCode({ governed: exitOf(0), size: exitOf(0), narrowed: exitOf(EXIT_REFUSED_NARROWED) }) === EXIT_REFUSED_NARROWED && + groupExitCode({ governed: exitOf(0), size: exitOf(EXIT_REFUSED_OVERSIZED), narrowed: exitOf(EXIT_REFUSED_NARROWED) }) === EXIT_REFUSED_OVERSIZED && + groupExitCode({ governed: exitOf(EXIT_REFUSED_UNAPPROVED), size: exitOf(0), narrowed: exitOf(EXIT_REFUSED_NARROWED) }) === EXIT_REFUSED_UNAPPROVED && + groupExitCode({ governed: exitOf(0), size: exitOf(0), narrowed: exitOf(0) }) === EXIT_CLEAR && groupExitCode({ governed: exitOf(0), size: exitOf(0) }) === EXIT_CLEAR); + const ownSource = readFileSync(fileURLToPath(import.meta.url), 'utf8'); + assert('main-runs-the-narrowed-leg-prints-its-block-and-hands-it-to-the-exit-code', + /const narrowed = await runNarrowedGuard\(\{/.test(ownSource) && /return groupExitCode\(\{ governed: verdict, size, narrowed \}\);/.test(ownSource) && /narrowedBlock === '' \? \[\] : \['', narrowedBlock\]/.test(ownSource) && /const fetchPull = oncePerPull\(makePullReader\(reader\)\);/.test(ownSource)); + assert('oncePerPull-keeps-a-successful-read-and-never-a-failed-one', + await (async () => { + let calls = 0; + const read = oncePerPull(async (n) => { calls += 1; if (calls === 1) throw new Error('HTTP 502'); return { n, calls }; }); + const first = await read(7).then(() => null, (e) => e.message); + const second = await read(7); + const third = await read(7); + return first === 'HTTP 502' && second.calls === 2 && third === second && calls === 2 && (await read(8)).calls === 3; + })()); + assert('the-refusal-names-both-halves-and-never-advises-rewording-the-declaration', + ((t) => /the human half/.test(t) && /the record half/.test(t) && /rewording the declaration are not ways through/.test(t) && t.includes(GOVERNED_APPROVERS[0]) && t.includes(NARROWED_LEG_NAME))(renderNarrowedVerdict(bare))); + } + // ── The floor: every declared battery RAN, and ran its cases (#13489) ──── // // Evaluated after every battery has had its chance and BEFORE the verdict, so diff --git a/scripts/pm/record-recognisers.mjs b/scripts/pm/record-recognisers.mjs index 41ab9301da1..8079cebaf15 100644 --- a/scripts/pm/record-recognisers.mjs +++ b/scripts/pm/record-recognisers.mjs @@ -138,7 +138,11 @@ import { // The governed-rules face is the governed register itself — the same function the queue guard // classifies a merge group's paths with. `dispatch-gates.mjs` already imports this module at module // scope, so the edge adds no new module to this file's graph and no cycle. -import { SELF_REPO_ID, governedPathsIn, lowRiskRowHit } from './check-governed-merges.mjs'; +import { RULE_CHANGE_VALUES, RULE_CHANGE_VERIFIED_KEY, SELF_REPO_ID, governedPathsIn, lowRiskRowHit, readRuleChangeVerified, ruleChangeRowHit } from './check-governed-merges.mjs'; +// The record's `Rule-change-verified:` line — the declaration split's machine line (`.claude/**`, maintainer ruling +// 2026-11-19 on #35321). Its key and its reader are the register's own, re-exported so the template below prints +// exactly what the queue guard takes, ⛔ never a second spelling. +export { RULE_CHANGE_VERIFIED_KEY, readRuleChangeVerified }; // How an unreadable `Served-tier:` line is quoted back — the declaration // line's own quoting helper, one spelling for both. The narrowing face is read // with the fleet's ONE reader of that line, imported, ⛔ never a second parser. @@ -2036,6 +2040,48 @@ export function recordCarriesSecurityTouching(face, tierName, scopeHits) { */ export const RECORD_SECURITY_TOUCHING_DEFAULT = CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES[1]; +/** + * What counts as fleet rule text, in the maintainer's own three heads (ruling 2026-11-19 on #35321): the one + * wording the brief and the template legend both print, so the reviewer who writes the line and the seat who + * reads the legend judge by the same sentence. Process steps, scripts, wording, slimming and file moves are + * the reviewer's, and are named so. + */ +export const RULE_CHANGE_VERIFIED_DUTY = Object.freeze([ + ` Write \`${RULE_CHANGE_VERIFIED_KEY}: none\` ONLY when no changed hunk alters what an agent may do without the maintainer`, + ' (merge, bypass a check, change repository settings), what gets done and in what order (grading, dispatch, scope), or', + ' what must go to him (decisions, maintainer actions); process steps, scripts, wording, slimming and file moves are not rule', + ' changes. Write `ruled` ONLY when every such hunk copies the ruling the PR body quotes on its `Ruling-ref:` line — check the', + ' copy against the quoted words, do not re-rule it. Otherwise `yes`: the pull request then waits for the maintainer.', +]); + +const RULE_CHANGE_VERIFIED_LEGEND = Object.freeze([ + ` · ${RULE_CHANGE_VERIFIED_KEY} read by the queue guard on a pull request touching \`.claude/**\`: it lands on this record`, + ' with no human approval only when this line equals the `Rule-change:` value the PR body declares.', + ...RULE_CHANGE_VERIFIED_DUTY.map((line) => ` ${line}`), + ' A missing line, a second line, a quoted, fenced or code-indented line, or anything after the value', + ` does not verify. The template ships \`${RULE_CHANGE_VALUES[2]}\`, so an unedited paste never lands the pull request.`, +]); + +/** + * Does the record printed for this face carry the `Rule-change-verified:` line — the ONE machine line the + * `.claude/**` declaration split stands on (`ruleChangeVerdict`, `check-governed-merges.mjs`)? The same + * shape as `recordCarriesSecurityTouching`: with the `hits` known, exactly when one sits under a row that + * splits by declaration (`ruleChangeRowHit`); with none known, on every at-tier face a governed path can sit + * on. ⛔ Not on the narrowing or the declaration face. Pure. + */ +export function recordCarriesRuleChangeVerified(face, tierName, scopeHits) { + if (tierName !== CONTRACT_REVIEW_TIER_NAME) return false; + if (scopeHits !== undefined) return ruleChangeRowHit(scopeHits); + return face?.id !== 'narrowing'; +} + +/** + * The value the printed record ships on that line: `yes`. It PARSES through the reader that judges the real + * thing and it fails closed — a record pasted with it left in verifies neither `none` nor `ruled`, so the pull + * request does not land on the record, and `none` or `ruled` is only ever a reviewer's own statement. + */ +export const RECORD_RULE_CHANGE_VERIFIED_DEFAULT = RULE_CHANGE_VALUES[2]; + /** * The record itself — the lines a seat copies, and nothing else. * @@ -2081,6 +2127,10 @@ export const RECORD_SECURITY_TOUCHING_DEFAULT = CONTRACT_REVIEW_SECURITY_TOUCHIN * and keeps the pull request at Tier H unless it reads `no`. It ships `yes` * (`RECORD_SECURITY_TOUCHING_DEFAULT`), so an unedited paste fails closed. * + * ⭐ `Rule-change-verified:` rides the same block, after it, where `recordCarriesRuleChangeVerified` says so: + * the queue guard lands a `.claude/**` pull request on this record only when the line equals the + * `Rule-change:` value the PR body declares (`none` or `ruled`). It ships `yes`, so an unedited paste fails closed. + * * @param {{headSha?: string, implementedBy?: string, reviewedBy?: string, tierName?: string, scopeHits?: string[], faceId?: string}} values * @returns {string[]} */ @@ -2104,6 +2154,7 @@ export function contractReviewRecordLines(values = {}) { 'Local-runs: none', ...(tierName === CONTRACT_REVIEW_TIER_NAME ? [`Scope: ${scopeHits} + ${RECORD_SCOPE_PLACEHOLDERS.cited}`] : []), ...(recordCarriesSecurityTouching(face, tierName, values.scopeHits) ? [`${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY}: ${RECORD_SECURITY_TOUCHING_DEFAULT}`] : []), + ...(recordCarriesRuleChangeVerified(face, tierName, values.scopeHits) ? [`${RULE_CHANGE_VERIFIED_KEY}: ${RECORD_RULE_CHANGE_VERIFIED_DEFAULT}`] : []), '', '### ① Derived judgments', '', @@ -2367,6 +2418,7 @@ export function contractReviewTemplateLines(values = {}) { ` or anything after the value keeps the PR at Tier H. The template ships \`${RECORD_SECURITY_TOUCHING_DEFAULT}\`, so an unedited paste`, ' never lands on the arm: the seat adds the `security` label only once the reviewer confirms a `yes` was meant.', ] : []), + ...(recordCarriesRuleChangeVerified(face, tierName, scopeHits) ? RULE_CHANGE_VERIFIED_LEGEND : []), ' · ③ Boundary flags every dev flag and every `open_questions` entry answered, or escalated; and on', ' every face the SQL push-down check:', ...TEMPLATE_PUSH_DOWN_LINES, @@ -2563,6 +2615,12 @@ export function contractReviewBriefLines(values = {}) { ` The record says so on its \`${CONTRACT_REVIEW_SECURITY_TOUCHING_KEY}:\` line, and the arm lands on \`no\` alone: write \`no\` ONLY when no changed`, ' hunk teaches permission, sharing, credential, token, authentication or other security behaviour, else `yes`.', ]; + // A `hits` path under `.claude/**` lands on this record only when it verifies the PR body's `Rule-change:` line. + const ruleChangeLines = !recordCarriesRuleChangeVerified(face, tierName, scopeHits) ? [] : [ + `Rule change — ${scopeHits !== undefined ? 'a `hits` path sits under `.claude/**`' : 'if a `hits` path is under `.claude/**`'}: the PR body declares \`Rule-change:\` and you verify it against the diff.`, + ...RULE_CHANGE_VERIFIED_DUTY, + '', + ]; const lowRiskLines = !recordCarriesSecurityTouching(face, tierName, scopeHits) ? [] : scopeHits !== undefined ? [ 'Security — a `hits` path sits on the low-risk skills arm: when the change teaches security, auth or permission', securityDuty, @@ -2595,6 +2653,7 @@ export function contractReviewBriefLines(values = {}) { '', ...scopeLines, ...lowRiskLines, + ...ruleChangeLines, '⛔ READ-ONLY. No worktree, no checkout, no build, no test run, no gate re-run, no ablation: the check-runs', ' on the head already answered every derived gate family, and a local run costs more than it returns.', " If ONE probe is unavoidable, the record's `Local-runs:` line says `probe — REASON`; otherwise `none`.", @@ -2777,11 +2836,15 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 32 → 38 with the `Security-touching:` line the low-risk skills arm reads: the record line and its // shipped `yes`, the whole template read through the record reader, the `no` reading, the faces and hits it // prints on, the one predicate, and the legend — six pins. - '#18042: the copyable record TEMPLATE — the one machine-read artefact with nothing to copy': 38, + // Raised 38 → 42 with the `Rule-change-verified:` line the `.claude/**` declaration split reads (maintainer ruling + // 2026-11-19 on #35321): the record line and its shipped `yes`, the whole template through the register's reader, + // where it prints, and the one duty wording in the legend and the brief — four pins. + '#18042: the copyable record TEMPLATE — the one machine-read artefact with nothing to copy': 42, // Raised 17 → 19 by #33541: the template record's one `VERDICT:` line read PASS by the guard, and the same record // posted by an untrusted author not read — two pins, two cases. // Raised 19 → 22 with `namedCardNumbers`, every card a pull names: the low-risk arm reads the label on each. - '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 22, + // Raised 22 → 23 with the unedited-paste pin: the shipped `Rule-change-verified: yes` lands nothing. + '#18701: ONE thread set -- what the template STATES is what the queue guard READS': 23, 'the `Local-runs:` reading — `none` or ONE named probe, judged when present; an absent line is not re-judged': 12, // Raised 23 → 24 with ③'s SQL push-down check on every face's brief: one pin. 'the reviewer BRIEF template — the read-only shape a hand-written brief dropped, built in and printed': 24, @@ -3745,15 +3808,23 @@ export async function selfTest() { t('the printed location is the ONE thread set\'s own words', says(TPL_TEXT, `ONE comment on ${REVIEW_OF_RECORD_LOCATION};`)); // -- the `Security-touching:` line: the low-risk skills arm's machine line, printed where an arm PR can sit -- const ST_LINE = (value) => `Security-touching: ${value}`; + const RV_LINE = (value) => `Rule-change-verified: ${value}`; + const rvOf = (text) => JSON.stringify(readRuleChangeVerified(text)); + const RULE_PATH = ['.claude', 'skills', 'pm-dispatch', 'SKILL.md'].join('/'); const stOf = (text) => contractReviewRecordReading(text)?.securityTouching; const ARM_PATHS = [['skills', 'objectstack-data', 'SKILL.md'].join('/'), ['ui', 'skills', 'objectui-forms', 'SKILL.md'].join('/'), ['docs', 'adr', '0001-x.md'].join('/')]; const OFF_ARM_PATH = ['.claude', 'agents', 'os-dev.md'].join('/'); - t('⭐ the bare record carries ONE `Security-touching:` line, right after `Scope:`, and it ships `yes` — read by the fleet\'s record reader as `yes`, never as `no`', (() => { const rec = contractReviewRecordLines(); const i = rec.indexOf(ST_LINE('yes')); return i > 0 && rec[i - 1].startsWith('Scope: ') && rec[i + 1] === '' && rec.filter((l) => l.startsWith('Security-touching')).length === 1 && JSON.stringify(stOf(TPL_RECORD)) === '{"state":"read","value":"yes"}' && RECORD_SECURITY_TOUCHING_DEFAULT === 'yes'; })()); + t('⭐ the bare record carries ONE `Security-touching:` line, right after `Scope:`, and it ships `yes` — read by the fleet\'s record reader as `yes`, never as `no`', (() => { const rec = contractReviewRecordLines(); const i = rec.indexOf(ST_LINE('yes')); return i > 0 && rec[i - 1].startsWith('Scope: ') && rec[i + 1] === RV_LINE('yes') && rec[i + 2] === '' && rec.filter((l) => l.startsWith('Security-touching')).length === 1 && JSON.stringify(stOf(TPL_RECORD)) === '{"state":"read","value":"yes"}' && RECORD_SECURITY_TOUCHING_DEFAULT === 'yes'; })()); t('⭐ the WHOLE printed template reads that one line too — the legend around the fence carries no second declaration, on any face that prints it', [{}, { face: 'rules' }, { face: 'schema' }, ...ARM_PATHS.map((path) => ({ paths: [path] }))].every((v) => JSON.stringify(stOf(contractReviewTemplateLines(v).join('\n'))) === '{"state":"read","value":"yes"}')); t('…and a reviewer who writes `no` over it is read as `no` — the one value the arm stands on', JSON.stringify(stOf(TPL_RECORD.replace(ST_LINE('yes'), ST_LINE('no')))) === '{"state":"read","value":"no"}' && TPL_RECORD.includes(`\n${ST_LINE('yes')}\n`)); t('⛔ the line prints exactly where an arm PR can sit: with the `hits` known, under a low-risk row (skills, ui/skills, an ADR) and nowhere else; with none known, on the bare, rules and schema faces — never the narrowing or declaration face', ARM_PATHS.every((path) => fenced(contractReviewTemplateLines({ paths: [path] })).includes(`\n${ST_LINE('yes')}\n`)) && !contractReviewTemplateLines({ paths: [OFF_ARM_PATH] }).join('\n').includes('Security-touching') && !contractReviewTemplateLines({ paths: MIXED }).join('\n').includes('Security-touching') && ['rules', 'schema'].every((id) => contractReviewRecordLines({ faceId: id }).includes(ST_LINE('yes'))) && ['narrowing', 'declaration'].every((id) => !contractReviewTemplateLines({ face: id }).join('\n').includes('Security-touching')) && !contractReviewRecordLines({ tierName: TIER_DEFAULT_NAME }).join('\n').includes('Security-touching')); t('the predicate is ONE function over face, tier and hits — below tier never, a narrowing never, known hits by the register\'s own low-risk row test', recordCarriesSecurityTouching(null, CONTRACT_REVIEW_TIER_NAME, undefined) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, undefined) && !recordCarriesSecurityTouching(reviewFaceById('narrowing'), CONTRACT_REVIEW_TIER_NAME, undefined) && recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [ARM_PATHS[0]]) && !recordCarriesSecurityTouching(reviewFaceById('rules'), CONTRACT_REVIEW_TIER_NAME, [OFF_ARM_PATH]) && !recordCarriesSecurityTouching(null, TIER_DEFAULT_NAME, [ARM_PATHS[0]])); t('the notes explain the line where the record carries it — who reads it, when `no` may be written, what keeps Tier H — and the key and values are the reader\'s own constants', ['· Security-touching read by the low-risk skills arm alone', 'only when this line reads `no`', 'Write `no` ONLY when no changed hunk teaches permission, sharing, credential, token,', 'the key inside a code span', 'keeps the PR at Tier H', 'The template ships `yes`', 'adds the `security` label only once the reviewer confirms a `yes` was meant'].every((frag) => says(TPL_TEXT, frag)) && CONTRACT_REVIEW_SECURITY_TOUCHING_KEY === 'Security-touching' && CONTRACT_REVIEW_SECURITY_TOUCHING_VALUES.join() === 'no,yes'); + // -- the `Rule-change-verified:` line: the `.claude/**` declaration split's machine line (maintainer ruling 2026-11-19 on #35321) -- + t('⭐ the bare record carries ONE `Rule-change-verified:` line, in the header block, and it ships `yes` — read by the register\'s own reader as `yes`, never as a value that verifies', (() => { const rec = contractReviewRecordLines(); return rec.filter((l) => l.startsWith('Rule-change-verified')).length === 1 && rec.indexOf(RV_LINE('yes')) < rec.indexOf('### ① Derived judgments') && rvOf(TPL_RECORD) === '{"state":"read","value":"yes"}' && RECORD_RULE_CHANGE_VERIFIED_DEFAULT === 'yes' && RULE_CHANGE_VERIFIED_KEY === 'Rule-change-verified'; })()); + t('⭐ the WHOLE printed template reads that one line too, on every face that prints it, and a reviewer who writes `none` or `ruled` over it is read as that', [{}, { face: 'rules' }, { face: 'schema' }, { paths: [RULE_PATH] }].every((v) => rvOf(contractReviewTemplateLines(v).join('\n')) === '{"state":"read","value":"yes"}') && ['none', 'ruled'].every((value) => rvOf(TPL_RECORD.replace(RV_LINE('yes'), RV_LINE(value))) === `{"state":"read","value":"${value}"}`)); + t('⛔ the line prints exactly where a split PR can sit: with the `hits` known, under `.claude/**` and nowhere else; with none known, on the bare, rules and schema faces — never the narrowing or declaration face, never below tier', fenced(contractReviewTemplateLines({ paths: [RULE_PATH] })).includes(`\n${RV_LINE('yes')}\n`) && fenced(contractReviewTemplateLines({ paths: [OFF_ARM_PATH] })).includes(`\n${RV_LINE('yes')}\n`) && ARM_PATHS.every((path) => !contractReviewTemplateLines({ paths: [path] }).join('\n').includes('Rule-change-verified')) && !contractReviewTemplateLines({ paths: ['AGENTS.md'] }).join('\n').includes('Rule-change-verified') && ['rules', 'schema'].every((id) => contractReviewRecordLines({ faceId: id }).includes(RV_LINE('yes'))) && ['narrowing', 'declaration'].every((id) => !contractReviewTemplateLines({ face: id }).join('\n').includes('Rule-change-verified')) && !contractReviewRecordLines({ tierName: TIER_DEFAULT_NAME }).join('\n').includes('Rule-change-verified') && recordCarriesRuleChangeVerified(null, CONTRACT_REVIEW_TIER_NAME, undefined) && !recordCarriesRuleChangeVerified(null, TIER_DEFAULT_NAME, [RULE_PATH]) && !recordCarriesRuleChangeVerified(reviewFaceById('narrowing'), CONTRACT_REVIEW_TIER_NAME, undefined)); + t('the legend and the brief hand the SAME duty where the record carries the line — the maintainer\'s three heads, the ruled copy checked not re-ruled, `yes` the fail-closed value — and neither names it where it does not', ['· Rule-change-verified read by the queue guard', 'what an agent may do without the maintainer', 'what gets done and in what order (grading, dispatch, scope)', 'what must go to him (decisions, maintainer actions)', 'check the', 'copy against the quoted words, do not re-rule it', 'The template ships `yes`'].every((frag) => says(TPL_TEXT, frag)) && RULE_CHANGE_VERIFIED_DUTY.every((line) => says(TPL_TEXT, line) && says(contractReviewBriefLines().join('\n'), line) && says(contractReviewBriefLines({ paths: [RULE_PATH] }).join('\n'), line)) && says(contractReviewBriefLines({ paths: [RULE_PATH] }).join('\n'), 'a `hits` path sits under `.claude/**`') && says(contractReviewBriefLines().join('\n'), 'if a `hits` path is under `.claude/**`') && [{ paths: ARM_PATHS }, { face: 'declaration' }, { face: 'narrowing' }].every((v) => !says(contractReviewBriefLines(v).join('\n'), 'Rule-change-verified') && !says(contractReviewTemplateLines(v).join('\n'), 'Rule-change-verified'))); // -- item ④: the owner's full-review order rides THIS record as a fourth section ------------ const DJ = '### ④ Design judgment'; const headings = (lines) => lines.filter((line) => line.startsWith('### ')); @@ -3858,13 +3929,16 @@ export async function selfTest() { id: 7701, created_at: '2026-09-16T10:00:00Z', user: { login: PIN_RELAY }, - body: contractReviewRecordLines({ headSha: PIN_HEAD, reviewedBy: 'session_01PINSEAT' }).join('\n'), + // …with the ONE line a reviewer must write over filled in: the template ships `Rule-change-verified: yes`, which + // verifies nothing (the pin below drives the unedited paste), so the reviewer's own `none` is what lands the record. + body: contractReviewRecordLines({ headSha: PIN_HEAD, reviewedBy: 'session_01PINSEAT' }).join('\n').replace(`${RULE_CHANGE_VERIFIED_KEY}: ${RECORD_RULE_CHANGE_VERIFIED_DEFAULT}`, `${RULE_CHANGE_VERIFIED_KEY}: none`), }; - // A Tier S path (the register's `.claude/**` row since #19133). The control - // below asks the register, so a row moving tiers reddens here instead of - // silently driving the approval leg. + const PIN_BODY = `Fixes #${PIN_CARD}\n\nRule-change: none`; + // A Tier S path (the register's `.claude/**` row since #19133) — Tier S on the declared body alone since the + // row splits by declaration (maintainer ruling 2026-11-19 on #35321), which is the reading the queue leg hands in. + // The control below asks the register, so a row moving tiers reddens here instead of silently driving the approval leg. const TIER_S_PATH = '.claude/skills/pm-dispatch/references/contract-review.md'; - t('⛔ CONTROL: the fixture path is Tier S under the register, so the record leg is the one being driven', GUARD.governedTierFor([TIER_S_PATH], GUARD_REPO) === GUARD.TIER_S); + t('⛔ CONTROL: the fixture path is Tier S under the register, so the record leg is the one being driven', GUARD.governedTierFor([TIER_S_PATH], GUARD_REPO, undefined, null, { measured: true, body: PIN_BODY, recordLeg: 'deferred' }) === GUARD.TIER_S && GUARD.governedTierFor([TIER_S_PATH], GUARD_REPO) === GUARD.TIER_H); const pinRun = async (where) => { const threadsRead = []; const verdict = await GUARD.runGuard({ @@ -3872,7 +3946,7 @@ export async function selfTest() { repo: GUARD_REPO, rows: [{ sha: 'e'.repeat(40), subject: `x (#${PIN_PR})`, pr: PIN_PR, paths: [TIER_S_PATH] }], fetchReviews: async () => [], - fetchPull: async () => ({ sha: PIN_HEAD, body: `Fixes #${PIN_CARD}`, headRef: `claude/issue-${PIN_CARD}-x` }), + fetchPull: async () => ({ sha: PIN_HEAD, body: PIN_BODY, headRef: `claude/issue-${PIN_CARD}-x` }), fetchComments: async (n) => { threadsRead.push(n); return (n === PIN_PR ? 'PR' : 'card') === where ? [PIN_RECORD] : []; @@ -3905,6 +3979,7 @@ export async function selfTest() { } })()); t('⛔ #33541: the same template record posted by an author outside the relay and GOVERNED_APPROVERS is not read -- refused as no record', await (async () => { const saved = PIN_RECORD.user; PIN_RECORD.user = { login: 'drive-by-commenter' }; try { const r = await pinRun('PR'); return r.verdict.exitCode !== GUARD.EXIT_CLEAR && r.record?.state === 'absent'; } finally { PIN_RECORD.user = saved; } })()); + t('⛔ #35321: the template pasted UNEDITED — `Rule-change-verified: yes` left in — does not land the pull request; the reviewer\'s own `none` is what the guard reads', await (async () => { const saved = PIN_RECORD.body; PIN_RECORD.body = contractReviewRecordLines({ headSha: PIN_HEAD, reviewedBy: 'session_01PINSEAT' }).join('\n'); try { const r = await pinRun('PR'); return saved.includes('\nRule-change-verified: none\n') && PIN_RECORD.body.includes('\nRule-change-verified: yes\n') && r.verdict.exitCode !== GUARD.EXIT_CLEAR && r.record?.state === 'not-pass' && /declaration split is not verified/.test(r.record?.verdictReason ?? ''); } finally { PIN_RECORD.body = saved; } })()); t('⛔ CONTROL: with the record on NEITHER thread the same run is refused -- the pin can fail', await (async () => { const none = await pinRun('nowhere'); return none.verdict.exitCode !== GUARD.EXIT_CLEAR && none.record?.state === 'absent'; })()); t('the guard prints the location in the WORDS this file owns, so a seat is told one thing', GUARD.REVIEW_OF_RECORD_LOCATION === REVIEW_OF_RECORD_LOCATION && TEMPLATE_TEXT.includes(`ONE comment on ${REVIEW_OF_RECORD_LOCATION}`)); t('⭐ the record the guard cleared carries the at-tier `Scope:` line — the guard reads past it, unchanged (ruling record 6184805932)', PIN_RECORD.body.includes(`\nScope: ${RECORD_SCOPE_PLACEHOLDERS.hits} + ${RECORD_SCOPE_PLACEHOLDERS.cited}\n`) && readSet === THREAD_SET);