From f42bcc18c6de5f44916ac3eee73725d699c48ba3 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sat, 28 Nov 2026 23:32:03 +0000
Subject: [PATCH 001/162] =?UTF-8?q?feat(adr-0087):=20the=20eighth=20dispos?=
=?UTF-8?q?ition=20category=20runtime-member-retyped=20=E2=80=94=20ADR=20t?=
=?UTF-8?q?ext=20(D10)=20and=20the=20registration=20gate=20(#38365)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XHogQ9ogKPxHhiFfT2UQgJi)_
Fixes #38328
Fixes #37447
Claims: #38328 (7240075259) and #37447 (re-posted 7242295202, naming
this branch).
Clause-②: no
Metadata-protocol: none
## 维护者速读
-
用户能看到什么变化:用户无感。「元数据协议升级契约」这份架构决定记录新增第八种申报类别(已发布类型上的成员留着、但声明的类型改了),登记检查同一笔学会核验它。
- 为什么做:你在决策卡上选了「新增第八类」,这里把它写成成文规则;此前这类改动没有一个如实可选的申报类别,写破坏性变更说明的开发者只能卡住。
- 出错会怎样:只有写破坏性变更说明的开发者会照这段文字申报,运行中的系统不受影响;文字有误可以直接撤回这一笔。
- 要你做什么:审阅并批准合并(Tier H)。文字与门禁两半已按座位路由裁定并进本
PR(门禁的词表钉要求两边同一笔,任一半单独合并都会报红);#38366 已并入关闭。
## What changes
Two files, both halves of one decision, combined by the seat's route
ruling (recorded on #37447 and #38328: combine, reason = the #8299
lockstep pin):
- `docs/adr/0087-metadata-protocol-upgrade-contract.md`: +199 −4 (1538
to 1733 lines) — the ADR half (#38328), described below.
- `scripts/check-adr-0087-registration.mjs`: +922 −93 — the gate half
(#37447 item 2), cherry-picked from
`claude/issue-37447-runtime-member-retyped` (closed PR #38366; os-dev
report 7241851254 on #37447) and then reworked on this branch for L2
record 7242485283 and L2 delta record 7243871018 (os-dev reports
7243462155 and 7244464363 on #38328): `runtime-member-retyped` in
`CATEGORIES`, `verifyRuntimeMemberRetyped` with
`RUNTIME_MEMBER_RETYPED_PREDICATES` (`present-at-both-type-differs`,
`no-metadata-surface`, `from-operands-named`), D9's predicates 2–3
lifted into shared helpers with no behaviour change, an explicit
`strictNullChecks`, and the self-test batteries RMR (83) and RMR-N (3).
The rework adds reading (b) of predicate 1 (see the table below).
`type-surface-only` and its predicate 4 are unchanged apart from one
hint line in an existing refusal.
The ADR's changeset disposition vocabulary gains its eighth category,
`runtime-member-retyped`, for a member that stays on a published type
while its declared type changes. Five places move together:
1. **Status line.** The 2026-11-28 amendment entry: the card and its
parent, the decision's own words 「新增第八类」, and where the decision is
recorded.
2. **Vocabulary block** (2026-08-13 addendum). The eighth marker line,
`runtime-member-retyped PACKAGE#TYPE.MEMBER`.
3. **The two prose enumerations beside that block.** The list of
categories resting on a checked fact, which the 2026-11-12 amendment
offers a refused narrowing, and the sentence that names each added
category and the addendum that explains it.
4. **A dated note under D8's predicate 4.** The retyped-member class got
a category of its own instead of a limb on predicate 4, which reads
exactly as it did.
5. **A new addendum (2026-11-28) with D10.** Provenance, the dead end
the category closes (measured), the operands, the three predicates by
name, what the category inherits and what it leaves alone, the worked
example, and what it does not decide.
No untouched text is rewritten, and no existing category's wording
changes.
**The category, as written.** It is D9's sibling. The operand is a
member of a type the package's published entry exports (or a member of
an exported value, read on that value's type as D9's reader reads it),
`PACKAGE#TYPE.MEMBER`, or `PACKAGE/SUBPATH#TYPE.MEMBER` behind a literal
subpath key. An export operand and the whole-package operand are refused
by name. Three predicates, checked by name:
| predicate | what it asks |
|---|---|
| `present-at-both-type-differs` | The type is exported at the merge
base and at HEAD, the member is on it at both, and the type the checker
prints for the member (with its optionality, under `strictNullChecks`)
differs. A vanished member, an added member, and a declaration naming a
type the reader cannot resolve are refused. Reading (b), added in the L2
rework: also refused as unprovable, at either revision, a member whose
printed type names a type with no declaration behind it, or carries more
`any` than the member's own declarations write. An `any` the declaration
writes is still compared as written. The refusal covers what leaves a
trace (the member's own declaration, the printed type); a type that
rests on something unresolved without a trace is compared, on three
named roads carried by #38379. |
| `no-metadata-surface` | D9's predicate 2, asked at both revisions. |
| `from-operands-named` | D9's predicate 3, unchanged. |
It inherits the `no-migration-prescription` refusal as D9 does, it does
not go through D8's text walker, and D8's predicate 4 gains no limb.
**Agreement with the gate half.** The text was first read against the
gate branch for #37447 at `a2b044f1fb` and `e657c303b2`. The gate in
this PR is no longer that file: the L2 reworks changed it on this branch
(blob `e56281db17` first, `15df493f67` at `e2661365c1`, `bc082d7904` at
`8c1017d6d2` and this head), and the ADR changed with it each time:
predicate 1 corrected and scoped to traces, and "What this does not
decide" gaining the trace-less item and one scoped clause. Category
name, operand forms, the three predicate names and each predicate's
reading agree, and neither half departs from the decision's design.
**The vocabulary pin is green on this head.** The gate pins the
categories the ADR documents to the categories it accepts, both ways;
either half alone was red (`documented but not accepted` / `documented
nowhere`), which is why they are one PR.
**Read first** (by risk)
1. The three predicates under D10, from "An author may claim the
category when". Predicate 1's reading is the part the gate has to
implement word for word.
2. The paragraph "D8's predicate 4 is not weakened" and the 2026-11-28
note under D8. The risk is any wording that could be read as a limb on
predicate 4.
3. The table under "The dead end it closes". Two of its rows record
admissions, not refusals: `already-registered` on any old id, and the
two catch-all categories on a body the detector does not read.
**Two-minute check.** Run `node scripts/check-adr-0087-registration.mjs
--self-test` on this branch: it prints 960 assertions (V3 included) and
exits 0.
## Tests
The gate's suite is its own `--self-test` (no test file names the
script). The L2 rework changes behaviour, so it carries new pins and
ablations:
- New pins: RMR-R12 / R12b (inferred `any` at both revisions, refused as
unprovable, not "the SAME"), RMR-R13 (`any` at one revision, refused),
RMR-R14 (annotation naming a local alias over an unresolved name),
RMR-R15 (a mapped type's member), RMR-G4 (a written `any` is still
compared and its retyping admitted); for the nits RMR-G5, R16, G6, R17.
Round 3 adds RMR-C1 (road b, a named compare on the `keyof` shape, to
turn red when the road is closed), RMR-G7 and G7b (a member of an
exported value; the `any` count over an initialiser), RMR-R17's wording
pin with R17b and R17c (the private-package refusal names a retyping;
D9's sentence unchanged), and one pin each on RMR-R12 and R13 for the
remedy line. RMR goes from 44 to 83 cases, its floor with it; the
self-test from 921 to 960 assertions.
- Ablations at `e2661365c1` (accept-set; the arm did not move after it),
direction written before each run, restored each time (`git diff HEAD`
empty): (A) the new arm off: predicted 14, observed 14 red; (C1) the
`any` rule alone off: 8 / 8; (C2) the name rule alone off: 6 / 6; (D)
the written-`any` allowance zeroed: 1 / 1 (RMR-G4); (B) RMR floor at 73:
refused, fixing the battery at exactly 72. At `8c1017d6d2` (the gate
blob of this head): (N7) the wording handed back to D9's: 2 / 2; (N8a)
the merge-base clause off: 1 / 1; (N8b) the clause always on: 1 / 1; (D)
the written-`any` allowance zeroed: 3 / 3 (RMR-G4, G7, G7b); (B) the
floor at 84: refused, fixing the battery at 83.
- On the real `@objectstack/client`, `ObjectStackClient.connect` was
refused as "the SAME at both revisions" at `31596e5b6e` and is now
refused as unprovable, naming `GetDiscoveryResponse`. On the real
`@object-ui/auth`, `AuthClient.updateUser` is still verified and
`AuthClient.signOut` still "the SAME".
- **What predicate 1 does not refuse, stated and carried.** The refusal
covers what leaves a trace. A type that rests on something unresolved
without one is compared, on three roads, each measured through the
shipping gate: (a) the `any` count is a count, not a position, and the
produced `any` arrives through a local alias or by inference; (b) an
operator such as `keyof` consuming an unresolved type behind a local
alias (pinned by RMR-C1 as a named compare); (c) inference through a
local overloaded function. Predicates 2 and 3 hold on all three. The ADR
and the gate header both state this and name the carrier, #38379; until
it lands, that item is the contract. Road b was left stated, not closed:
following every local alias would refuse the by-design named compare.
The dead end, measured: the worked example under every existing
disposition
Method: the net diff of PR #37433 (head `ac218b2489`) applied on
`4cb162bfb9` in a detached comparison worktree, the changeset's marker
and its FROM / TO spelling rewritten per variant, each variant committed
locally and judged by the shipping gate's own `assertInputs` and `scan`.
Nothing from that worktree was pushed.
| variant | marker | how the fix is spelled | outcome |
|---|---|---|---|
| V0 | `type-surface-only`, bare | the PR's own two-line pair | refused,
predicate 4 |
| V1 | `type-surface-only`, dotted member path | two-line pair |
refused, predicate 4 |
| V2 | `no-migration-prescription` | two-line pair | admitted |
| V3 | `runtime-interface-only` | two-line pair | admitted |
| V4 | `runtime-export-retired`, member operand | two-line pair |
refused, predicate 1 |
| V5 | `unpublished` | two-line pair | refused |
| V6 | `registered`, an id not in the diff | two-line pair | refused |
| W1, W3 | the two catch-all categories | one arrowless FROM … TO line |
admitted |
| W2, W4 | the two catch-all categories | an arrow line under no
migration label | admitted |
| W5, W6 | `runtime-export-retired`, member operand | arrowless line,
arrow line | refused, predicate 1 |
| W7 | `already-registered`, a real id older than the merge base |
two-line pair | admitted |
| X1, X2 | the two catch-all categories | a labelled FROM → TO arrow
line | refused by the prescription detector |
| X3 | `type-surface-only`, bare | labelled arrow line | refused,
predicate 4 |
The two halves in one tree: green, and the worked example is
accepted
Joint tree `e121e0e10c`, a local-only merge of the gate branch at
`a2b044f1fb` with this branch at `819cdf7cd0`. This reading predates the
L2 rework: the ADR and the gate both changed at `e2661365c1`, so the 921
below is that tree's number, not this head's (960). R2 and R6 were
re-measured on this head's gate and still hold.
- `node scripts/check-adr-0087-registration.mjs --self-test` printed `✓
check-adr-0087-registration --self-test: 921 assertions over real temp
git repos (real scan()/assertInputs() path)`, exit 0.
- `node scripts/check-adr-0087-registration.mjs --base origin/main` exit
0.
Each half alone:
- This branch: exit 1, `category documented but not accepted:
runtime-member-retyped`; the self-test reports one failure, `V3`.
- The gate branch at `e657c303b2`: exit 1, `category documented nowhere:
runtime-member-retyped`.
The worked example on the joint tree, same driver:
| variant | marker and how the fix is spelled | outcome |
|---|---|---|
| R1 | `runtime-member-retyped @object-ui/auth#AuthClient.updateUser`,
the PR's own two-line pair | refused by predicate 3: the body carries a
vertical FROM / TO pair, which this category does not read |
| R2 | same marker, one FROM … TO … line with `AuthClient.updateUser` on
the FROM side | accepted; the gate prints the member's declared type at
both revisions |
| R3 | same marker, an arrow line | accepted |
| R4 | an export operand | refused by name |
| R5 | the whole-package operand | refused by name |
| R6 | a member the diff did not retype, `AuthClient.signOut` | refused,
predicate 1: the same type at both revisions |
| R7 | `type-surface-only`, bare | still refused by predicate 4 |
The compiler delivers the break (D10's channel
argument)
TypeScript 6.0.3 on the worked example's shape. A caller that reads the
result gets `TS2339` (the property does not exist on type void). A host
that passes its own implementation returning a Promise of AuthUser gets
`TS2322` (not assignable to a Promise of void).
## Acceptance notes
- **Done-when, first bullet.** The ADR names the eighth category with
its three predicates, and every enumeration of the vocabulary carries
it: the marker block and the two prose lists beside it. The status line
carries the amendment entry. Every occurrence of the seventh category's
name was read to find a list that omits the eighth; there is none. The
ADR counts categories by ordinal only (fifth, sixth, seventh, now
eighth), so no count word needed changing.
- **"The two land in either order" does not hold.** This branch alone
fails the vocabulary pin, and the gate half alone fails it in the other
direction. The two agree and are green together, in one merged tree
only.
- **One sentence on the parent card is narrower than it reads.** It says
the two catch-all categories are refused for a body that carries a FROM
→ TO. Measured, that depends on how the pair is spelled: the detector
reads a labelled arrow line and refuses, and it reads neither the
two-line pair PR #37433 carries nor an arrowless line, so both
categories are admitted there. The ADR records the measured outcomes.
Across the 114 pending changesets, two carry a two-line pair the
detector does not read, and both describe behaviour in prose and
prescribe no rewrite. Noted, not filed.
- **PR #37433 needs one edit beyond its marker.** Under the new category
its two-line pair is refused by predicate 3 (R1), and one FROM … TO …
line is accepted (R2). The ADR's worked-example paragraph says so; the
edit itself belongs to that PR.
- **The gate half is no longer carried unchanged.** The L2 reworks
changed it on this branch (blob `e56281db17` before, `bc082d7904` at
this head). Its header now follows the ADR's measured table on the two
catch-all categories: refused on a labelled arrow line the detector
reads; admitted on the two-line pair, an arrowless line, and an arrow
line under no migration label (the ADR's row names the first two). It
also corrects the old reason for the unresolved-name refusal: "two
unresolved names print alike" is measured false on TypeScript 6.0.3; the
true reason is that a name is only its spelling, so one spelling can be
two types at two revisions.
- **Ablations of the gate half** were run by its dev on its branch
(report 7241851254 on #37447): each new refusal reds its own case when
removed. The rework's ablations were run on this branch (see Tests).
- **The private-package refusal names a retyping.** Under this category
it reads "no published entry to retype a member on" (L2 delta N7, L1
item 2); D9's own sentence and its pin REX-R9 are unchanged.
- **Landing pointer for PR #37433.** Under this category #37433's
two-line `FROM:`/`TO:` pair is refused by predicate 3 (R1); it lands
only with one `FROM … TO …` line naming `AuthClient.updateUser` before
TO (R2). The seat posts that pointer on #37433 when this PR lands; the
edit belongs to that PR.
## Verification
Local, head `1f7fcfd66c` (merge base `eef1cbfe4a`, 0 behind main at the
run): the 44 commands of `dispatch-gates --commands` for the two-file
diff, under the shared verify lock (`VERDICT command-exit 0` in two
holds, 976 s and 485 s), each exit captured before any pipe.
- 44 of 44 exit 0, among them `check-adr-0087-registration --base
origin/main`, its `--self-test` (960 assertions), `pnpm
check:changeset-gate-self-tests` (167 + 960 + 456) and `pnpm
check:pm-dispatch-gates` (fast tier, 2385 cases).
- Reconciliation: `dispatch-gates --ran: 44 derived famil(ies) accounted
for - 44 run, 0 NOT-MEASURED`.
- `overlap-check` before the push: `VERDICT clean exit 0`, against
origin/main and 0 PR heads.
NOT MEASURED locally, CI-owned: the slow tier of the dispatch-gates
self-test, the type-check lanes, the governed-merges audit over workflow
variables. No changeset: both files ship in no package.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_
---------
Co-authored-by: Claude
---
...0087-metadata-protocol-upgrade-contract.md | 203 +++-
scripts/check-adr-0087-registration.mjs | 1015 +++++++++++++++--
2 files changed, 1121 insertions(+), 97 deletions(-)
diff --git a/docs/adr/0087-metadata-protocol-upgrade-contract.md b/docs/adr/0087-metadata-protocol-upgrade-contract.md
index 63c598647e4..d71ca788aca 100644
--- a/docs/adr/0087-metadata-protocol-upgrade-contract.md
+++ b/docs/adr/0087-metadata-protocol-upgrade-contract.md
@@ -1,6 +1,6 @@
# ADR-0087: Metadata protocol upgrades for AI consumers — conversion over notification, executable migrations, machine-verifiable upgrades
-**Status**: Accepted (2026-07-04, #2582) · trued up to as-built 2026-07-15 (see Addendum) · **Amended** (2026-09-30, #20390 ruling A — the artifact-ingestion window decides per entry by each retired conversion's `retiredAfter`; see the amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-09, #22449 ruling B′ — the two D4 projections, the per-major section of `spec-changes.json` and the protocol upgrade guide, are generated at publish rather than committed; see the amendment note under D4, which says what is generated where and where each part landed, and the struck clauses in the P2 phase-status bullet) · **Amended** (2026-10-13, #23038 — the artifact-ingestion window's third disjunct, landed as `58f5c90999`: a floor that is the first release of a major replays that major's conversion step, verdict `'converted-major-step'`; see the 2026-10-13 amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-27, #26220, the maintainer's decision A: D8's predicate 4 gains an index-signature limb, and D9's predicate 1 maps a `src/index.tsx` source entry; see the 2026-10-27 amendment notes under D8's predicate 4 and under D9's unmappable-entry paragraph) · **Amended** (2026-10-27, #26220, ruling A on PR #26365, comment `6439038287` — D9 gains a whole-package operand, `#*`, for a published package deleted at HEAD; see the second 2026-10-27 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-11-14, #30598, the maintainer's decision A narrowed, record `6885400963` — D9's three operands take a literal subpath key of the `exports` map, `/#…`, and a wildcard key is refused by name; see the 2026-11-14 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-10-26, #25767 ruling D2 = A, scoped by ruling 6434038284 of 2026-10-27 — a retirement kit (the `retiredKey()` tombstone and its D2 conversion with fixtures) lives one protocol major after the one it retired in and is then removed; a removed key is refused as a strict unknown key whose refusal names the protocol upgrade guide; the kit ages out, the chain's step stays, and the support floor stays 16; see the 2026-10-26 addendum, which also amends the "never deleted" wording in D2 and the conversion "forever" in the 2026-07-31 and 2026-09-13 addenda)
+**Status**: Accepted (2026-07-04, #2582) · trued up to as-built 2026-07-15 (see Addendum) · **Amended** (2026-09-30, #20390 ruling A — the artifact-ingestion window decides per entry by each retired conversion's `retiredAfter`; see the amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-09, #22449 ruling B′ — the two D4 projections, the per-major section of `spec-changes.json` and the protocol upgrade guide, are generated at publish rather than committed; see the amendment note under D4, which says what is generated where and where each part landed, and the struck clauses in the P2 phase-status bullet) · **Amended** (2026-10-13, #23038 — the artifact-ingestion window's third disjunct, landed as `58f5c90999`: a floor that is the first release of a major replays that major's conversion step, verdict `'converted-major-step'`; see the 2026-10-13 amendment note under the 2026-09-13 addendum's window bullet) · **Amended** (2026-10-27, #26220, the maintainer's decision A: D8's predicate 4 gains an index-signature limb, and D9's predicate 1 maps a `src/index.tsx` source entry; see the 2026-10-27 amendment notes under D8's predicate 4 and under D9's unmappable-entry paragraph) · **Amended** (2026-10-27, #26220, ruling A on PR #26365, comment `6439038287` — D9 gains a whole-package operand, `#*`, for a published package deleted at HEAD; see the second 2026-10-27 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-11-14, #30598, the maintainer's decision A narrowed, record `6885400963` — D9's three operands take a literal subpath key of the `exports` map, `/#…`, and a wildcard key is refused by name; see the 2026-11-14 amendment note under D9's unmappable-entry paragraph) · **Amended** (2026-10-26, #25767 ruling D2 = A, scoped by ruling 6434038284 of 2026-10-27 — a retirement kit (the `retiredKey()` tombstone and its D2 conversion with fixtures) lives one protocol major after the one it retired in and is then removed; a removed key is refused as a strict unknown key whose refusal names the protocol upgrade guide; the kit ages out, the chain's step stays, and the support floor stays 16; see the 2026-10-26 addendum, which also amends the "never deleted" wording in D2 and the conversion "forever" in the 2026-07-31 and 2026-09-13 addenda) · **Amended** (2026-11-28, #37447 and its ADR half #38328, the maintainer's decision 「新增第八类」 of 2026-11-26, recorded on PR #37433 as comment `7183687803` — the changeset disposition vocabulary gains an eighth category, `runtime-member-retyped`, for a member that stays on a published type while its declared type changes; it is D9's sibling, proven by the compiler at both revisions, and D8's predicate 4 gains no limb for it; see the 2026-11-28 addendum, D10, and the 2026-11-28 note under D8's predicate 4)
**Deciders**: ObjectStack Protocol Architects
**Builds on**: [ADR-0059](./0059-third-party-backward-compatibility-gates.md) (layered backward-compat gates — this ADR is its consumer-facing sequel), [ADR-0078](./0078-no-silently-inert-metadata.md) (no declarable-but-unenforced metadata — the un-checked `engines.protocol` is exactly this class), [ADR-0025](./0025-plugin-package-distribution.md) (§3.2 `engines.protocol` / `engines.platform` compatibility ranges, §3.10 #3 protocol-first check order), [ADR-0033](./0033-ai-assisted-metadata-authoring.md) (the authoring population this ADR designs for), [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce-or-remove), [ADR-0054](./0054-runtime-proof-for-authorable-surface.md) (prove-it-runs), AGENTS.md Prime Directive #12 (contract-first, no consumer-side dialect fallbacks — §"Why the conversion layer does not violate PD #12" draws the line)
**Consumers**: `@objectstack/spec` (protocol version constant, conversion layer, deprecation/change registries), `@objectstack/cli` (`validate`, `doctor`, `migrate meta`), the runtime metadata loader (handshake + conversion), `@objectstack/mcp` (the AI-native change/migration surface), `@objectstack/create-objectstack`, the Release workflow, and every third-party consumer — whose maintainer is assumed to be an **AI agent**
@@ -754,6 +754,7 @@ gate's log and its `--list` output.
+
```
**The vocabulary is closed, and every exemption is re-verified on every run** — an
@@ -772,14 +773,17 @@ refuses it; whether the fix is written as an arrow, a table or a sentence does n
change that. The fix is a `registered` semantic entry, one file under
`packages/spec/src/migrations/entries/semantic/`, or a category resting on a checked
fact when one is true: `already-registered`, `unpublished`, `runtime-interface-only`,
-`type-surface-only`, `runtime-export-retired`. If the change refuses nothing an author
+`type-surface-only`, `runtime-export-retired` and, since 2026-11-28,
+`runtime-member-retyped`. If the change refuses nothing an author
could write, the `Metadata-protocol:` line is what is wrong, not the disposition.
`added`, `semantic` and `none` keep the exemption, and a changeset already breaking
at the branch point is inherited and never re-judged); `runtime-interface-only` is
the subject of the rest of this addendum; `type-surface-only` — the sixth, added
-2026-08-30 — is the subject of the addendum after it; and `runtime-export-retired` —
+2026-08-30 — is the subject of the addendum after it; `runtime-export-retired` —
the seventh, added 2026-10-12, whose whole-package operand `#*` was added
-2026-10-27 (#26220) — is the subject of the addendum after that. The checks live in
+2026-10-27 (#26220) — is the subject of the addendum after that; and
+`runtime-member-retyped` — the eighth, added 2026-11-28 (#37447) — is the subject of
+the addendum after that one. The checks live in
[`scripts/check-adr-0087-registration.mjs`](../../scripts/check-adr-0087-registration.mjs),
which is also where each one's measured history is written down.
@@ -1025,6 +1029,12 @@ at all. A regression pin in the gate's `--self-test` asserts that the #6048 shap
refused by predicate 4 specifically, so the founding case can never become
claimable.
+> **2026-11-28 note** (#37447) — a member of a published type retyped from one concrete
+> type to another (PR #37433: `AuthClient.updateUser` in `@object-ui/auth`,
+> `Promise` to `Promise`) is refused by predicate 4, and the maintainer's
+> decision 「新增第八类」 gave that class a category of its own, `runtime-member-retyped`
+> (the eighth; see D10), instead of a limb here. Predicate 4 reads exactly as it did.
+
#### What this does not decide
**Whether the HEAD type is the *right* type.** Whether the bound contract is what
@@ -1314,6 +1324,191 @@ refused rather than assumed.
are unchanged; the arrowless line stays outside the detector's reach, stated as such
in the gate's residual-blind-spot paragraph, and is read only by this category.
+## Addendum (2026-11-28) — the eighth category: a published runtime MEMBER retyped (#37447)
+
+The vocabulary above gained an eighth answer:
+
+```text
+
+```
+
+Provenance: the maintainer's decision 「新增第八类」 on a decision card (2026-11-26T05:38Z)
+that asked 「已发布 TS 类型从具体类型收窄,ADR-0087 用哪个处置类别?」. The card's text for that
+option is 「ADR-0087 增补 runtime-member-retyped,另开受管卡教门禁;#37433 保持 draft,等门禁卡合并后带新标记落地」.
+It is recorded on PR #37433 as comment `7183687803` and in the body of #37447.
+
+### The dead end it closes
+
+The worked example is PR #37433. `AuthClient.updateUser` in `@object-ui/auth` declared
+`Promise` while the server answers a receipt, and the member now declares
+`Promise`. The member stays on a published type and its declared type moves from
+one concrete type to another, so the changeset declares `**BREAKING**` truthfully and
+owes the FROM → TO line a breaking changeset carries. Measured at `4cb162bfb9`, with
+that PR's diff (head `ac218b2489`) applied to it and driven through the shipping gate
+under each disposition:
+
+| disposition | outcome |
+|---|---|
+| `registered` | refused — no id is new in the diff, and none could honestly be written: `objectstack migrate meta` has nothing to rewrite in a caller's code. |
+| `not-required (already-registered )` | admitted on any id that pre-dates the merge base, the door D8's table records: the gate checks that the id resolves and is old, never that the entry covers this change. No entry does. |
+| `not-required (unpublished)` | refused — `@object-ui/auth` publishes. |
+| `not-required (type-surface-only …)` | refused by predicate 4, under the bare and the dotted spelling alike — the return annotation was already concrete at the merge base (`Promise`). |
+| `not-required (runtime-export-retired …)` | refused by predicate 1 — `AuthClient` still has the member at HEAD, so nothing retired. |
+| `not-required (no-migration-prescription)` | refused when the fix is written as a labelled `FROM → TO` arrow line, which the detector reads. Admitted on the PR's own body, which writes the pair as `FROM:` and `TO:` on two lines, and on an arrowless `FROM … TO …` line: the detector reads neither. |
+| `not-required (runtime-interface-only …)` | the same two outcomes — it inherits that refusal, and its four predicates read the symbol at HEAD and say nothing about what changed. |
+
+So a changeset that writes its fix where the detector reads it has no category that is
+true of it, and one that does not is held by a detector **miss**: the shape D7 retires,
+and the one D9 closed for a retirement. D8's exit stays shut as well, because the refusal
+by predicate 4 is the one D8 says is never weakened.
+
+### D10 — a published runtime member that is kept and retyped is compiler-carried, and the gate proves the retyping with the compiler
+
+The channel argument is D7's, D8's and D9's: the affected party is a TypeScript
+consumer, and the compiler reports the break at their own site. Measured on the worked
+example's shape, that is `TS2339` at a caller that reads the result and `TS2322` at a
+host that passes in its own implementation. The ledger has no metadata to rewrite.
+
+**The category is D9's sibling.** What D9 proves about a member that left, this category
+proves about a member that stayed. It takes D9's member operand, D9's compiler reading of
+the package's published entry at both revs, and D9's predicates 2 and 3. Only predicate 1
+is its own.
+
+**Operands.** `#.` names a member of a type the package's
+published entry exports, in the canonical spelling D9 fixed (a member of an exported
+value is read too, on that value's type, as D9's reader reads it), and
+`/#.` names one behind a literal subpath key of the
+`exports` map, read as D9's 2026-11-14 amendment reads that key. A member is the only
+operand. `#` and `#*` are refused by name: the decision is
+about a member that is kept, and an export or a package that left the entry is
+`runtime-export-retired`.
+
+An author may claim the category when, for every operand, all three of these hold —
+re-verified on every run and checked by name (`present-at-both-type-differs`,
+`no-metadata-surface`, `from-operands-named`):
+
+1. **present-at-both-type-differs** — the type is exported by the package's published
+ entry at the merge base and at HEAD, the member is on it at both
+ (`getPropertiesOfType`), and the member's declared type differs between the two. The
+ reading is D9's predicate 1 reading: the TypeScript compiler, a Program over the
+ package's source entry at each rev, with the entry located as D9 locates it and an
+ unmappable one refused as D9 refuses it. The declared type is the type the checker
+ prints for the member, with whether the member is optional, and the two printings are
+ compared as text. The Program is compiled with `strictNullChecks`, so `| null` and
+ `| undefined` are part of what is compared. Refused, never guessed: a member that is
+ gone at HEAD (it was retired, and the refusal names `runtime-export-retired`), a
+ member the diff adds (nothing published was retyped), and a member whose type rests,
+ at either rev, on what the reader cannot resolve **where that leaves a trace**. Two
+ traces are read, on the member's own declaration and on the type printed for it: a
+ name that does not resolve, and more `any` in the printing than the member's own
+ declarations write. A bare reference to an unresolved type prints as the name written
+ and an unresolved value prints as `any`, which is how either shows in an inferred
+ type, behind a local alias or on a member with no declaration of its own; SAME and
+ DIFFERS would both be guesses there. An `any` the declaration writes itself is
+ compared as written. A type that rests on something unresolved and leaves neither
+ trace is compared, not refused; "What this does not decide" names the roads.
+2. **no-metadata-surface** — D9's predicate 2, asked at **both** revs because the
+ operand exists at both: neither the type nor the member is declared in a `*.zod.ts`,
+ under `packages/spec/src/contracts/` or in an object definition, the type is not a
+ Zod projection, and no metadata surface references it in code.
+3. **from-operands-named** — D9's predicate 3, unchanged: the FROM → TO block names
+ **exactly** the named operands, each spelled `Type.member` as in the marker. Every
+ FROM operand is a named one, and every named one has a FROM side.
+
+**It inherits the `no-migration-prescription` refusal, as D9 does.** Predicate 3 reads
+the FROM side of every rewrite the body writes, sets exactly those lines aside and runs
+the same prescription detector over what is left, and anything it still finds is
+refused. Nothing the detector refuses today becomes claimable unless every operand it
+rests on was proven retyped by predicate 1 and clear of metadata by predicate 2.
+`type-surface-only` stays the only category exempt from that refusal.
+
+**It does not go through D8's text walker.** `type-surface-only` finds a member by a
+structural walk over a masked projection of one file, which is why its reference is
+`#..`. This category names the package and asks the compiler for the
+member on the exported type, so no file is named and no source text is walked.
+
+⛔ **D8's predicate 4 is not weakened.** The decision adds a category instead of a limb.
+A concrete base is still refused under `type-surface-only`, by predicate 4 and with the
+founding-case refusal, and the gate's `--self-test` keeps asserting that on the worked
+example's own shape: a concretely typed arrow property retyped is not narrowed-from-erased.
+The maintainer's ruling of 2026-08-30 (#13080), 「豁免的安全性由谓词④承载,保持豁免是收窄而非洞」,
+stands as written. This category needs no such payment, because it is not exempt from the
+prescription refusal.
+
+**D9's deviation carries over with its machinery.** A merge base has no build output,
+so the member is read on the **source** entry that generates the public `.d.ts`, not on
+the `.d.ts` itself. For D9's question, which names the entry exports, the two agree. For
+a member's type they can part: a `private` class member is on the source type, and its
+type is absent from the published declaration. The gate reads the source and does not
+tell such a member from a public one.
+
+### The worked example under this category
+
+By the decision, PR #37433 lands carrying this category's marker: one marker,
+`runtime-member-retyped @object-ui/auth#AuthClient.updateUser`, and its fix written in a
+shape predicate 3 reads, with `AuthClient.updateUser` on the FROM side. Its body at head
+`ac218b2489` writes the pair as `FROM:` and `TO:` on two lines, which predicate 3 names
+and refuses rather than reads, so that pair becomes one `FROM … TO …` line. On that line
+every code span between `FROM` and `TO` is read as a FROM operand, so the old type cannot
+stand there in backticks: only `AuthClient.updateUser` does, and both types are written
+after `TO`.
+
+### What this does not decide
+
+**The direction of the change.** The predicate is "differs". Whether the new type is
+narrower, and whether a given consumer stops compiling, is the compiler's to deliver at
+the consumer's own site. The changeset declared the break; the gate proves that the named
+member's declared type is not what it was.
+
+**A change inside a type the member names.** The comparison is of the member's own
+printed type. A member that still declares `Promise` was not retyped when
+`AuthUser` changed shape; the member of `AuthUser` that changed is the operand to name.
+
+**Whether the HEAD type is the right type.** As under D8, that is a question about a
+producer, settled by driving it.
+
+**A member whose type reaches outside the package.** The reader resolves the package's
+own files and `lib.es2022`, and of another workspace package only a root entry the
+package re-exports, as D9 reads it. A member whose declaration names a type imported from
+another package, a DOM type or a React type is refused as unprovable, and so is one whose
+type is inferred through a value from outside where that shows in the printed type (the
+next item names where it does not). On the worked example's own interface,
+`AuthClient.describeDelegableScope` names `DelegableScope` from
+`@objectstack/spec/contracts` and could not be claimed. Resolving such an import at both
+revs waits for its own case.
+
+**A type that rests on something unresolved without a trace.** Predicate 1 reads traces:
+an unresolved name in the member's own declaration or in the printed type, and a surplus
+`any` in the printed type. A type can rest on something unresolved and leave neither. It
+is then compared, and SAME or DIFFERS is a reading of the reader's blindness. Predicates 2
+and 3 hold on all of it, so no metadata prescription gets through; what can be wrong is a
+"same type" refusal or an admitted retyping. Three roads, each measured through the gate:
+
+- **(a) The `any` reading is a count, not a position.** A written `any` that never
+ prints (`keyof any`, a conditional over `any`, the implementation signature under an
+ overload, a setter beside its getter) leaves room for one the reader produced. That one
+ arrives through a local alias or by inference: a method that takes `k: keyof any` and
+ returns an unresolved call writes one `any`, prints one, and is compared.
+- **(b) An operator consumes the unresolved type behind a local alias.** `keyof` of an
+ unresolved type is `string | number | symbol`, so no name and no `any` prints, and no
+ written `any` is needed. A conditional type that checks an unresolved name prints its
+ branches the same way. Written on the member itself, the same `keyof` is refused,
+ because the declaration then names the unresolved type.
+- **(c) Inference consumes it.** An unresolved value passed to a local overloaded
+ function matches the first overload, and the member prints that overload's return type.
+ No reader of traces sees this one.
+
+The three are carried by #38379. Until it lands this item is the contract: on these roads
+the gate compares, and its SAME or DIFFERS proves nothing.
+
+**An export itself, a wildcard subpath key or a static member.** An exported function or
+constant whose own declared type changed is not a member of an exported type and is not
+read; that waits for its own case. The bounds on a subpath key and on a class's static
+side are D9's.
+
+**The completeness of the claim.** Like every category above, the gate judges the
+operands named, not every member the diff retyped.
+
## Addendum (2026-09-13) — the artifact-ingestion door opens a versioned window (#12772)
The addenda above reach authored source and metadata at rest in `sys_metadata`.
diff --git a/scripts/check-adr-0087-registration.mjs b/scripts/check-adr-0087-registration.mjs
index 8317ce8bba5..bc082d7904c 100644
--- a/scripts/check-adr-0087-registration.mjs
+++ b/scripts/check-adr-0087-registration.mjs
@@ -362,7 +362,8 @@
// justification or its body is read (seat decision, option A, on #32601).
// Everything else stays open: `registered`, and the categories that rest on a
// re-checked fact -- `unpublished`, `already-registered`,
-// `runtime-interface-only`, `type-surface-only`, `runtime-export-retired`. Two
+// `runtime-interface-only`, `type-surface-only`, `runtime-export-retired`,
+// `runtime-member-retyped`. Two
// boundaries are deliberate and pinned in the self-test's NP battery:
//
// * The kind is read off `breakingDeclaration().signals` (`NARROWED_SIGNAL`),
@@ -500,6 +501,8 @@ const SELF_TEST_BATTERIES = Object.freeze({
'REX-N: the predicate set is pinned BY NAME, never by count': 3,
'REX-U: unit pins on the operand grammar and the FROM-side reader': 24,
'REX-L: the compiler is loaded only when a marker names the category': 6,
+ 'RMR (#37447): the eighth category `runtime-member-retyped`, D9\'s sibling': 83,
+ 'RMR-N: the eighth category\'s predicate set is pinned BY NAME, never by count': 3,
'WS (#26220): ui workspace packages, `.tsx` modules, aliases and shims': 11,
'IX (#26220): predicate 4 reads an `any` index signature; the entry may be `src/index.tsx`': 52,
'WP (#26220): a deleted published package is retired whole, `#*`': 59,
@@ -609,6 +612,7 @@ export const CATEGORIES = [
'runtime-interface-only',
'type-surface-only',
'runtime-export-retired',
+ 'runtime-member-retyped',
];
/** The ADR whose disposition vocabulary this gate enforces (#8299). */
@@ -4756,7 +4760,9 @@ export function verifyTypeSurfaceOnly(refs, { base, head, cwd, bumps, packages,
' concrete did not move off `any`, and a member removed from it is exactly the class the\n' +
' ledger DOES serve.\n' +
` The index-signature limb (ADR-0087 D8, amended 2026-10-27) does not hold either: ${limb.reason}.\n` +
- ' fix: register the migration.',
+ ' fix: register the migration -- or, if this is a MEMBER of an exported type that a published package\n' +
+ ' KEPT while its declared type changed (concrete to concrete) and no metadata surface reaches it, name\n' +
+ ' it by its package: `not-required (runtime-member-retyped #.)` (#37447).',
);
continue;
}
@@ -5168,7 +5174,8 @@ export async function loadExportReader() {
if (exportReaderKit) return exportReaderKit;
const { requireDefaultExport } = await import('./import-prerequisite.mjs');
const ts = await requireDefaultExport('typescript', () => import('typescript'), import.meta.url, {
- measures: 'whether each export a `runtime-export-retired` marker names really left the package\'s published entry',
+ measures: 'whether each export a `runtime-export-retired` marker names really left the package\'s published entry, ' +
+ 'and whether each member a `runtime-member-retyped` marker names was really retyped',
});
const { createProgramChecked, parseSourceFile } = await import('./ts-parse.mjs');
const { resolveTypesEntry } = await import('./check-published-readme-exports.mjs');
@@ -5205,6 +5212,12 @@ export function wildcardKeysMatching(map, subpath) {
});
}
+/** The end of the private-package refusal, per category: see `sourceEntryAt`. */
+const NO_ENTRY_TO = Object.freeze({
+ retire: 'retire an\n export from',
+ retype: 'retype a\n member on',
+});
+
/**
* The repo-relative SOURCE entry of a workspace package at a rev -- of its root
* entry, or of one LITERAL subpath key -- or a refusal.
@@ -5226,15 +5239,19 @@ export function wildcardKeysMatching(map, subpath) {
* entry is no TypeScript declaration (`./style.css`), and a key that cannot be
* mapped or maps ambiguously.
*
+ * `noEntryTo` is what a PRIVATE package has no published entry FOR, said by the
+ * category that asks (the `fromBlockReads(ordinal)` move): D9 retires an export from
+ * an entry, `runtime-member-retyped` retypes a member on one.
+ *
* @returns {{ refusal: string, keyAbsent?: boolean, noExportsMap?: boolean } | { entry: string, dir: string }}
*/
-export function sourceEntryAt(rev, cwd, pkgName, pkgs, kit, subpath = '.') {
+export function sourceEntryAt(rev, cwd, pkgName, pkgs, kit, subpath = '.', noEntryTo = NO_ENTRY_TO.retire) {
const info = pkgs.get(pkgName);
if (!info) return { refusal: `no workspace manifest at ${rev.slice(0, 12)} is named \`${pkgName}\`` };
if (info.private) {
return {
- refusal: `\`${pkgName}\` is PRIVATE (\`private: true\` in ${info.file}): it has no published entry to retire an\n` +
- ' export from. The disposition that says so is `not-required (unpublished)`',
+ refusal: `\`${pkgName}\` is PRIVATE (\`private: true\` in ${info.file}): it has no published entry to ${noEntryTo}. ` +
+ 'The disposition that says so is `not-required (unpublished)`',
};
}
let manifest;
@@ -5478,16 +5495,29 @@ export function packageReference(pkg, pkgDir, surfaceTexts) {
* are each a pure function of their rev. Relative imports resolve inside the
* rev; a re-export (`export ... from`) of another workspace package's ROOT entry
* resolves through the same mapping, so a cross-package `export *` is followed; any
- * other bare import is left unresolved, which costs nothing for the question asked
- * -- an unresolved `export *` is recorded instead, because a name could hide
- * behind it.
+ * other bare import is left unresolved, which costs nothing for the question D9
+ * asks (which names exist) -- an unresolved `export *` is recorded instead, because
+ * a name could hide behind it. It does cost for the question `runtime-member-retyped`
+ * asks (a member's TYPE): a type that rests on an unresolved import is not read.
+ * `memberTypeAt` reports the traces that leaves and that category refuses those as
+ * unprovable; what leaves none is compared (#38379).
+ *
+ * `noEntryTo` goes to `sourceEntryAt` for the entry this call reads.
+ *
+ * `extraOptions` is spread over the compiler options. Only `runtime-member-retyped`
+ * (#37447) passes one, `strictNullChecks: true`: it compares a member's TYPE, and
+ * with the option off the checker prints `T | null` and `T | undefined` as `T`
+ * (measured). The installed TypeScript 6 already defaults `strict` on, so today the
+ * option restates the default; it is explicit so the reading does not move with a
+ * compiler default. Membership -- the export category's whole question -- does not
+ * depend on it.
*
* @returns {{ refusal: string } | { pkg: string, entry: string, dir: string, sourceFiles: string[], names: Map,
* unresolvedStars: {file: string, specifier: string}[], checker: object, entryFile: object,
* fromVirtual: (f: string) => string|null }}
*/
-function readExportSurface(rev, cwd, pkgName, pkgs, kit, subpath = '.') {
- const mapped = sourceEntryAt(rev, cwd, pkgName, pkgs, kit, subpath);
+function readExportSurface(rev, cwd, pkgName, pkgs, kit, subpath = '.', extraOptions = {}, noEntryTo = NO_ENTRY_TO.retire) {
+ const mapped = sourceEntryAt(rev, cwd, pkgName, pkgs, kit, subpath, noEntryTo);
if (mapped.refusal) return mapped;
const { ts } = kit;
const texts = new Map();
@@ -5507,6 +5537,7 @@ function readExportSurface(rev, cwd, pkgName, pkgs, kit, subpath = '.') {
noEmit: true, skipLibCheck: true, types: [], lib: ['lib.es2022.d.ts'],
jsx: ts.JsxEmit.Preserve,
target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler,
+ ...extraOptions,
};
const real = ts.createCompilerHost(options, true);
const extensionOf = (p) => (p.endsWith('.d.ts') ? ts.Extension.Dts : p.endsWith('.tsx') ? ts.Extension.Tsx : ts.Extension.Ts);
@@ -5628,13 +5659,143 @@ function membersOf(surface, typeName, ts) {
return { state: 'ok', symbol, props, unresolved: [...new Set(unresolved)] };
}
-/** What predicate 3 reads, said once for every message that refuses on it. */
-const FROM_BLOCK_READS =
+/**
+ * What predicate 3 reads, said once for every message that refuses on it. One
+ * function, because `runtime-member-retyped` (#37447) evaluates the SAME predicate
+ * through `fromOperandsNamedProblems`; only the category's ordinal differs.
+ */
+const fromBlockReads = (ordinal) =>
' This category reads the FROM side of a `FROM ... TO ...` line, of an arrow `X -> Y` (or\n' +
' `X -> delete it`), and of the FROM column of a `| FROM | TO |` / `| Wrote | Write instead |`\n' +
' table. Every FROM operand must be a named operand, spelled as the marker spells it, and\n' +
' every named operand must have a FROM side; what the detector still reads after that is\n' +
- ' the `no-migration-prescription` refusal, inherited (ADR-0087, the seventh category).';
+ ` the \`no-migration-prescription\` refusal, inherited (ADR-0087, the ${ordinal} category).`;
+
+/**
+ * Predicate 2, `no-metadata-surface`, for ONE export or member operand read at ONE
+ * rev: its declaration (and the member's) is not a metadata surface, it is not a
+ * Zod projection, and no metadata surface references it in code -- the
+ * `runtime-interface-only` primitives. Lifted out of `verifyRuntimeExportRetired`
+ * unchanged (#37447), because `runtime-member-retyped` asks the same question of
+ * the same operand shape, at BOTH revs where the export category asks it at the
+ * merge base only.
+ *
+ * @param {{ t: string, op: object, surface: object, symbol: object, member: object|null, ts: object,
+ * rev: string, texts: () => Map, pkgs: () => Map }} ctx
+ * `t` opens every message; `rev` names where the declaration was looked for; `texts`
+ * and `pkgs` are thunks, so a claim that fails earlier never reads the surfaces
+ * @returns {{ problem: string } | { problem: null, declared: string }}
+ */
+function exportMetadataSurfaceRead({ t, op, surface, symbol, member, ts, rev, texts, pkgs }) {
+ const files = declarationFiles(surface, symbol);
+ if (files.length === 0) {
+ return { problem: `${t} cannot be verified: the declaration of \`${op.exportName}\` cannot be located at ${rev}.` };
+ }
+ const site = [...files, ...declarationFiles(surface, member)].find((f) => metadataSurfaceKind(f) !== null);
+ if (site) {
+ return {
+ problem:
+ `${t} is false: \`${op.spelling}\` is declared in ${site} (${metadataSurfaceKind(site)}).\n` +
+ ' A metadata surface is what `objectstack migrate meta` reaches, so the ledger IS a channel here.\n' +
+ ' fix: register the migration.',
+ };
+ }
+ const projection = (symbol.declarations ?? []).find((d) => ts.isTypeAliasDeclaration(d) && ZOD_PROJECTION_RE.test(d.type.getText()));
+ if (projection) {
+ return {
+ problem:
+ `${t} is false: \`${op.exportName}\` is a projection of a Zod schema (${projection.type.getText().slice(0, 90)}).\n` +
+ ' Under Prime Directive #1 that is the house spelling of "this type IS metadata".',
+ };
+ }
+ const hit = metadataSurfaceReference(op.exportName, files[0], texts(), pkgs);
+ if (hit) {
+ return {
+ problem:
+ `${t} is false: ${hit.hitPath} (${metadataSurfaceKind(hit.hitPath)}) ` +
+ (hit.kind === 'import'
+ ? `IMPORTS \`${op.exportName}\` from the module that declares it.`
+ : `mentions \`${op.exportName}\` IN CODE while neither declaring nor importing it:\n ${hit.line.slice(0, 140)}`) +
+ '\n An export a metadata surface reaches HAS a metadata surface (comment spans are already excluded).',
+ };
+ }
+ return { problem: null, declared: files[0] };
+}
+
+/**
+ * Predicate 3, `from-operands-named`, shared by `runtime-export-retired` (#22918)
+ * and `runtime-member-retyped` (#37447): the FROM -> TO block names EXACTLY the
+ * named operands, each spelled as the marker spells it, and once those FROM sides
+ * are set aside `findMigrationPrescription` reads nothing more (`readFromBlock`).
+ * Lifted out of `verifyRuntimeExportRetired` unchanged, so the two categories
+ * cannot drift into two readings of one predicate.
+ *
+ * @param {{ ref: string, spelling: string, whole: boolean }[]} operands the parsed, named operands
+ * @param {string} body the changeset body
+ * @param {string} category the marker's category, for the message
+ * @param {string} ordinal the category's ordinal in ADR-0087, for the message
+ * @returns {string[]} one problem per failure
+ */
+function fromOperandsNamedProblems(operands, body, category, ordinal) {
+ const problems = [];
+ const reads = fromBlockReads(ordinal);
+ const t3 = `\`not-required (${category})\` [predicate 3: from-operands-named]`;
+ const named = new Set(operands.map((o) => o.spelling));
+ const block = readFromBlock(body);
+ for (const u of block.unread) {
+ problems.push(`${t3}: the body carries ${u.shape}, which this category does not read:\n ${u.text.slice(0, 160)}\n${reads}`);
+ }
+ // A whole package's FROM side is the package name -- a whole subpath key's, the
+ // specifier `/` (#30598) -- which is no identifier: read it as
+ // that operand's spelling exactly when the marker names it with `#*`.
+ const wholeNames = new Set(operands.filter((o) => o.whole).map((o) => o.spelling));
+ const wholeNote = wholeNames.size === 0 ? '' :
+ '\n A package retired whole (`#*`) is named on ONE FROM line, by the package name, and a\n' +
+ ' subpath key retired whole (`/#*`) by its specifier; its exports take no line of their own.';
+ const seen = new Set();
+ const reported = new Set();
+ for (const raw of block.sides) {
+ const bare = stripTicks(raw.operand).trim();
+ const side = raw.spelling === null && wholeNames.has(bare) ? { ...raw, spelling: bare } : raw;
+ if (side.spelling === null) {
+ if (reported.has(side.operand)) continue;
+ reported.add(side.operand);
+ problems.push(
+ `${t3}: the FROM operand ${side.operand} is not a canonical operand:\n ${side.text.slice(0, 160)}\n` +
+ ' An export is spelled by its name -- a call `name(...)` or `new Name(...)` reads as that name --\n' +
+ ' and a member as `.`. Nothing inside an argument list or an object literal is\n' +
+ ' read (the ruling\'s ⛔ on parsing constructor arguments).',
+ );
+ continue;
+ }
+ seen.add(side.spelling);
+ if (named.has(side.spelling) || reported.has(side.spelling)) continue;
+ reported.add(side.spelling);
+ problems.push(
+ `${t3}: the FROM operand ${side.operand} names \`${side.spelling}\`, which the marker does not name -- out of range:\n` +
+ ` ${side.text.slice(0, 160)}\n` +
+ ' A prescription for anything but the named operands keeps the `no-migration-prescription` refusal.\n' +
+ ` A${category === 'runtime-export-retired' ? ' retired' : ''} MEMBER is named \`.\` in the marker and written the same way on the FROM side.` +
+ wholeNote,
+ );
+ }
+ for (const op of operands) {
+ if (seen.has(op.spelling)) continue;
+ problems.push(
+ `${t3}: the named operand \`${op.ref}\` has no FROM side in the body. The block must name EXACTLY the\n` +
+ ` named operands: write the one-line fix a consumer needs, a line such as\n` +
+ ` - FROM \`${op.spelling}\` TO \n${reads}`,
+ );
+ }
+ if (block.residual) {
+ problems.push(
+ `${t3}: once the named FROM sides are set aside, the body still carries a migration prescription\n` +
+ ` (${block.residual.branch}):\n ${block.residual.line.slice(0, 160)}\n${reads}`,
+ );
+ }
+
+ return problems;
+}
/**
* Verify one `runtime-export-retired` claim: the three predicates, all three, by
@@ -5849,100 +6010,412 @@ export function verifyRuntimeExportRetired(refs, { base, head, cwd, body, packag
verified.push({ ref: op.ref, kind: 'package', declared: r.pkgFile });
continue;
}
- const files = declarationFiles(at, symbol);
- if (files.length === 0) {
- problems.push(`${t} cannot be verified: the declaration of \`${op.exportName}\` cannot be located at the merge base.`);
- continue;
+ const p2 = exportMetadataSurfaceRead({
+ t, op, surface: at, symbol, member, ts, rev: 'the merge base',
+ texts: () => (metadataTexts ??= showManyOrNull(base, surfacePaths, cwd)), pkgs: () => packagesAt(base),
+ });
+ if (p2.problem) { problems.push(p2.problem); continue; }
+ verified.push({ ref: op.ref, kind: op.member === null ? 'export' : 'member', declared: p2.declared });
+ }
+
+ // ---- predicate 3: the FROM -> TO block names exactly the named operands ------
+ P('from-operands-named');
+ problems.push(...fromOperandsNamedProblems(operands, body, 'runtime-export-retired', 'seventh'));
+
+ return { problems, verified, checked };
+}
+
+// ---------------------------------------------------------------------------
+// The eighth category: `runtime-member-retyped` (#37447)
+//
+// ## The class, and why no other category holds it
+//
+// A changeset that RETYPES A PUBLISHED MEMBER -- the member stays on an exported
+// type and its declared type changes from one concrete type to another -- declares
+// `**BREAKING**` truthfully and ships the FROM -> TO line a TypeScript consumer
+// needs. The founding case is `AuthClient.updateUser` in `@object-ui/auth`, whose
+// result narrowed from `Promise` to `Promise` because the server
+// answers a receipt, not the user. No category held it:
+//
+// - `type-surface-only` needs a base of `any` / `unknown` / no annotation, and its
+// predicate 4 is the whole of what pays for its prescription exemption (the
+// maintainer's ruling of 2026-08-30 on #13080: 「豁免的安全性由谓词④承载,保持豁免是收窄而非洞」).
+// It is not weakened, and nothing here touches it.
+// - `runtime-export-retired` needs the member GONE at HEAD;
+// - `no-migration-prescription` / `runtime-interface-only` are refused on a body
+// that writes the fix as a labelled `FROM -> TO` arrow line, which the detector
+// reads, and admitted on a spelling it does not read: the pair written as
+// `FROM:` and `TO:` on two lines, an arrowless `FROM ... TO ...` line, or an
+// arrow line under no migration label. That is an exemption held by a detector
+// MISS, the shape D7 retires (ADR-0087, the measured table of the 2026-11-28
+// addendum, whose row names the first two).
+//
+// The maintainer's decision on #37447 (option 「新增第八类」): 「ADR-0087 增补
+// runtime-member-retyped,另开受管卡教门禁」. The category is modelled as D9's
+// sibling: the same operands, the same compiler reader at both revisions, predicates
+// 2 and 3 unchanged, and predicate 1 swapped. It does NOT go through the text walker
+// `type-surface-only` uses (`resolveSurfaceRef`).
+//
+// ## The operand
+//
+// #. a member of a type the package's entry exports
+// /#. the same, on a LITERAL `exports` key (D9's bound,
+// record 6885400963 on #30598: "only literal subpath keys")
+//
+// A MEMBER only. `#` and `#*` are refused by name: the
+// decision names "a published member kept, its type changed", and the claim is kept
+// exactly as narrow as that.
+//
+// ## The three predicates, BY NAME, re-verified on every run
+//
+// 1. present-at-both-type-differs -- the type is exported by the package's entry
+// at the merge base AND at HEAD, the member is on it at both
+// (`getPropertiesOfType`), and its DECLARED TYPE differs: the checker's printed
+// type of the member (`typeToString`, `NoTruncation`, compiled with
+// `strictNullChecks` so `| null` / `| undefined` are part of it), with its `?`
+// optionality, compared as text. A member that VANISHED is refused and pointed
+// at `runtime-export-retired`; one ADDED at HEAD is refused too.
+//
+// A member whose type rests, at either revision, on what this reader cannot
+// resolve is refused as UNPROVABLE rather than compared, WHERE THAT LEAVES A
+// TRACE. The reader resolves the package's own files, `lib.es2022` and a
+// workspace package root the entry RE-EXPORTS (`readExportSurface`). An import
+// from another package, a DOM global and an `@types` global all stay
+// unresolved. Measured, TypeScript 6.0.3: a bare reference to an unresolved
+// TYPE prints as the name written; an unresolved VALUE prints as `any`, and so
+// does a union with an unresolved type. A name is only its spelling -- one
+// spelling can be two types at two revisions, and two spellings one -- and an
+// `any` the reader produced is its own blindness, so SAME and DIFFERS would
+// both be guesses (#4690). Two readings look for those traces, and either one
+// refuses:
+// a. the member's own declaration names a type that does not resolve;
+// b. the tree the checker prints the member's type from (`typeToTypeNode`,
+// the tree `typeToString` prints) names a type that does not resolve, or
+// carries more `any` than the member's own declarations write. That is
+// how an unresolved value reaches an inferred type (`async connect() {
+// return createClient(); }` prints `() => Promise`), how an
+// unresolved name reaches a member through a local alias, and how either
+// reaches a member with no declaration node of its own (a mapped type's).
+// An `any` the declaration writes is compared as written. An `any` that
+// arrives any other way is not told apart from the reader's own, and is
+// refused with it. A type that rests on something unresolved and leaves
+// NEITHER trace is compared, not refused: the roads are named under "What is
+// deliberately NOT checked".
+// 2. no-metadata-surface -- D9's predicate 2 (`exportMetadataSurfaceRead`),
+// asked at BOTH revisions because the operand exists at both: neither the type
+// nor the member is declared in a metadata surface, the type is no Zod
+// projection, and no metadata surface references it in code.
+// 3. from-operands-named -- D9's predicate 3 (`fromOperandsNamedProblems`),
+// unchanged: the FROM side of every rewrite line names exactly the marker's
+// `Type.member` operands, and the detector reads nothing else in the body. So
+// this is a NARROWING of `no-migration-prescription`, never an escape from it.
+//
+// ## What is deliberately NOT checked
+//
+// **That the new type is narrower.** "Differs" is the predicate; the direction of a
+// TypeScript change is the compiler's to deliver at the consumer's site.
+// **That the claim is complete**, for the reason D9 gives.
+// **A static member of a class**, for the reason D9 gives.
+// **A type that rests on something unresolved WITHOUT A TRACE** (carried by #38379).
+// Predicate 1 reads traces. What leaves none is COMPARED, and "the SAME" or
+// "differs" is then a reading of this reader's blindness. Predicates 2 and 3 hold
+// on all of it, so no metadata prescription gets through. Three roads, each
+// measured through `verifyRuntimeMemberRetyped`; stated, not closed:
+// a. Reading (b)'s `any` rule is a COUNT -- more `any` printed than written -- and
+// not a position. A written `any` the printed type does not carry (`keyof any`,
+// a conditional over `any`, the implementation signature under an overload, a
+// setter beside its getter) leaves room for one produced `any`. That one
+// arrives through a local alias or by INFERENCE: reading (a) reads type names,
+// not calls. `async connect(k: keyof any) { return createClient(); }` writes
+// one `any`, prints one, and is compared.
+// b. An operator CONSUMES the unresolved type behind a local alias. `type K =
+// keyof Routes`, `Routes` unresolved, is `string | number | symbol`: no name
+// and no `any` prints, and no written `any` is needed. RMR-C1 pins the compare.
+// A conditional type that checks an unresolved name prints its two branches
+// the same way. Written on the member itself, `keyof Routes` is refused by
+// reading (a).
+// c. INFERENCE consumes it. An unresolved value passed to a local overloaded
+// function matches the first overload, and the member prints that overload's
+// return type. No reader of traces sees this one.
+// **A local alias that prints by its own name** is compared as that name, whatever
+// its declaration rests on. That is by design: a change inside a type the member
+// names is not a retyping of the member (ADR-0087 D10, "What this does not decide").
+// **What reading (b) refuses beyond the reader's own blindness.** An `any` a lib
+// declaration returns (`JSON.parse`), one behind a local alias (`type X = any`),
+// one written on a mapped type rather than on the member, and `typeof globalThis`
+// (a symbol with no declaration) are refused as unprovable too. That is the
+// direction #4690 asks for: a refusal the author can answer by writing the type.
+// ---------------------------------------------------------------------------
+
+/**
+ * The three predicates, BY NAME -- the `RUNTIME_EXPORT_PREDICATES` discipline: the
+ * self-test pins the set and that the shipping function evaluates exactly it.
+ */
+export const RUNTIME_MEMBER_RETYPED_PREDICATES = [
+ 'present-at-both-type-differs',
+ 'no-metadata-surface',
+ 'from-operands-named',
+];
+
+/**
+ * How many `any` a member's own declarations WRITE: in an annotation, a parameter,
+ * a type argument, an initialiser. A function BODY is not read -- an `any` in there
+ * is not written on the member, and reaches its type only by inference.
+ */
+function writtenAnyIn(declarations, ts) {
+ let written = 0;
+ const visit = (node) => {
+ if (ts.isBlock(node)) return;
+ if (node.kind === ts.SyntaxKind.AnyKeyword) written++;
+ ts.forEachChild(node, visit);
+ };
+ for (const d of declarations ?? []) visit(d);
+ return written;
+}
+
+/**
+ * What the type printed for a member rests on that this reader cannot vouch for
+ * (reading (b) of predicate 1, see the header). Read off the node builder's own
+ * tree, which is the tree `typeToString` prints, so what is judged is what is
+ * compared. These are TRACES: a type can rest on something unresolved and leave
+ * neither, and is then compared (the header names the roads; #38379):
+ *
+ * - a type NAME with no declaration behind it. The checker prints an unresolved
+ * type as the name written, on a symbol it made up for the purpose. The
+ * LEFTMOST identifier is the one asked: a resolved `Color.Red` carries its
+ * symbol on `Color`, and an unresolved `Far.Thing` carries none anywhere.
+ * - more `any` than the member's own declarations write (`writtenAnyIn`).
+ *
+ * Reading the identifiers' symbols fails closed: a compiler that stopped setting
+ * them would refuse every named type, and RMR-G1 (`Promise`) would go red.
+ *
+ * @returns {string[]} one phrase per finding; empty when the type is vouched for
+ */
+function unvouchedParts(checker, prop, type, ts) {
+ const tree = checker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.NoTruncation | ts.NodeBuilderFlags.IgnoreErrors);
+ if (!tree) return ['is a type the compiler could not print as a tree'];
+ const names = new Set();
+ let printedAny = 0;
+ const spelled = (name) => (ts.isIdentifier(name) ? ts.idText(name) : `${spelled(name.left)}.${ts.idText(name.right)}`);
+ const visit = (node) => {
+ if (node.kind === ts.SyntaxKind.AnyKeyword) printedAny++;
+ const name = ts.isTypeReferenceNode(node) ? node.typeName : ts.isTypeQueryNode(node) ? node.exprName : null;
+ if (name) {
+ let leftmost = name;
+ while (!ts.isIdentifier(leftmost)) leftmost = leftmost.left;
+ if (!leftmost.symbol?.declarations?.length) names.add(spelled(name));
}
- const site = [...files, ...declarationFiles(at, member)].find((f) => metadataSurfaceKind(f) !== null);
- if (site) {
+ ts.forEachChild(node, visit);
+ };
+ visit(tree);
+ const written = writtenAnyIn(prop.declarations, ts);
+ const parts = [];
+ if (names.size > 0) parts.push(`names ${[...names].map((n) => `\`${n}\``).join(', ')}, which this reader does not resolve`);
+ if (printedAny > written) parts.push(`carries an \`any\` its own declaration does not write (${printedAny} printed, ${written} written)`);
+ return parts;
+}
+
+/**
+ * One member of an exported type at one rev, as predicate 1 compares it: its
+ * printed declared type and optionality, every type name its declaration names
+ * that the reader could not resolve (`unresolved`), and what the printed type
+ * itself rests on that the reader cannot vouch for (`unvouched`).
+ *
+ * @returns {{ state: 'not-exported'|'unreadable'|'absent', why?: string, members?: object }
+ * | { state: 'ok', members: object, prop: object, declared: string, printed: string,
+ * unresolved: string[], unvouched: string[] }}
+ */
+function memberTypeAt(surface, typeName, memberName, ts) {
+ const members = membersOf(surface, typeName, ts);
+ if (members.state !== 'ok') return members;
+ const prop = members.props.get(memberName);
+ if (!prop) return { state: 'absent', members };
+ const { checker } = surface;
+ const at = prop.valueDeclaration ?? prop.declarations?.[0] ?? surface.entryFile;
+ const type = checker.getTypeOfSymbolAtLocation(prop, at);
+ const printed = checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation);
+ const declared = `${prop.flags & ts.SymbolFlags.Optional ? '?' : ''}: ${printed}`;
+ const unresolved = [];
+ const visit = (node) => {
+ const name = ts.isTypeReferenceNode(node) ? node.typeName
+ : ts.isExpressionWithTypeArguments(node) ? node.expression
+ : ts.isTypeQueryNode(node) ? node.exprName : null;
+ if (name) {
+ const s = checker.getSymbolAtLocation(name);
+ const target = s && (s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s);
+ if (!target?.declarations?.length) unresolved.push(name.getText());
+ }
+ ts.forEachChild(node, visit);
+ };
+ for (const d of prop.declarations ?? []) ts.forEachChild(d, visit);
+ return { state: 'ok', members, prop, declared, printed, unresolved: [...new Set(unresolved)], unvouched: unvouchedParts(checker, prop, type, ts) };
+}
+
+/**
+ * Verify one `runtime-member-retyped` claim: the three predicates, all three, by
+ * name, every failure reported (the `verifyRuntimeExportRetired` discipline).
+ *
+ * @param {string[]} refs the `[/]#.` operands
+ * @param {{ base: string, head: string, cwd: string, body: string,
+ * packagesAt: (rev: string) => Map,
+ * kit?: object }} ctx `kit` defaults to the loaded `exportReaderKit`
+ * @returns {{ problems: string[], verified: {ref: string, kind: string, declared: string, from: string, to: string}[],
+ * checked: string[] }}
+ */
+export function verifyRuntimeMemberRetyped(refs, { base, head, cwd, body, packagesAt, kit = exportReaderKit }) {
+ const problems = [];
+ const verified = [];
+ const checked = [];
+ const P = (name) => { checked.push(name); return name; };
+ const HOW =
+ ' fix: name each retyped member by the package that published it and the exported type it sits on, e.g.\n' +
+ ' \n' +
+ ' and a type of a LITERAL `exports` key after the package: `@objectstack/cli/console#Options.port`.';
+ if (!kit) throw new Error('verifyRuntimeMemberRetyped: the export reader is not loaded -- await loadExportReader() first');
+ const { ts } = kit;
+
+ if (refs.length === 0) {
+ problems.push(
+ '`not-required (runtime-member-retyped)` names no operand.\n' +
+ ' The whole content of this exemption is WHICH members were retyped, and every predicate is a\n' +
+ ' statement about a named one. An unnamed claim asserts nothing checkable (#4690).\n' + HOW,
+ );
+ return { problems, verified, checked };
+ }
+ const operands = [];
+ for (const ref of refs) {
+ const parsed = parseExportOperand(ref);
+ if (parsed.refusal) { problems.push(`\`runtime-member-retyped\` operand "${ref}" ${parsed.refusal}.\n${HOW}`); continue; }
+ if (parsed.whole || parsed.member === null) {
problems.push(
- `${t} is false: \`${op.spelling}\` is declared in ${site} (${metadataSurfaceKind(site)}).\n` +
- ' A metadata surface is what `objectstack migrate meta` reaches, so the ledger IS a channel here.\n' +
- ' fix: register the migration.',
+ `\`runtime-member-retyped\` operand "${ref}" names ${parsed.whole ? 'a WHOLE package or subpath key' : `the export \`${parsed.exportName}\` itself`}, not a member.\n` +
+ ' This category is about a MEMBER that stays on an exported type while its declared type changes, and\n' +
+ ' it names one as `#.`. An export or a package that LEFT the published entry is\n' +
+ ' `runtime-export-retired`.\n' + HOW,
);
continue;
}
- const projection = (symbol.declarations ?? []).find((d) => ts.isTypeAliasDeclaration(d) && ZOD_PROJECTION_RE.test(d.type.getText()));
- if (projection) {
+ operands.push({ ref, ...parsed });
+ }
+ if (operands.length === 0) return { problems, verified, checked };
+
+ // ---- predicate 1: present at both revisions, declared type differs -----------
+ P('present-at-both-type-differs');
+ const read = new Map();
+ const surfaceAt = (rev, pkg, subpath) => {
+ const key = `${rev} ${pkg} ${subpath}`;
+ if (!read.has(key)) read.set(key, readExportSurface(rev, cwd, pkg, packagesAt(rev), kit, subpath, { strictNullChecks: true }, NO_ENTRY_TO.retype));
+ return read.get(key);
+ };
+ const tag = (op) => `\`runtime-member-retyped ${op.ref}\` [predicate 1: present-at-both-type-differs]`;
+ const where = { base: 'the merge base', head: 'HEAD' };
+ const retyped = [];
+ for (const op of operands) {
+ const sides = {};
+ let refused = false;
+ for (const side of ['base', 'head']) {
+ const surface = surfaceAt(side === 'base' ? base : head, op.pkg, op.subpath);
+ if (surface.refusal) { problems.push(`${tag(op)} cannot be read at ${where[side]}:\n ${surface.refusal}.`); refused = true; break; }
+ const m = memberTypeAt(surface, op.exportName, op.member, ts);
+ if (m.state === 'not-exported') {
+ problems.push(`${tag(op)} is false: the type \`${op.exportName}\` is not exported by ${surface.entry} at ${where[side]}.` +
+ (side === 'head' ? '\n A type that LEFT the published entry was retired, not retyped: `runtime-export-retired` names it.' : ''));
+ refused = true; break;
+ }
+ if (m.state === 'unreadable') { problems.push(`${tag(op)} cannot read the members of \`${op.exportName}\` at ${where[side]}: ${m.why}.`); refused = true; break; }
+ if (m.state === 'absent') {
+ const deps = m.members.unresolved.length
+ ? `\n Its shape there depends on ${m.members.unresolved.map((n) => `\`${n}\``).join(', ')}, which this reader does not resolve.` : '';
+ problems.push(side === 'base'
+ ? `${tag(op)} is false: \`${op.exportName}\` has no member \`${op.member}\` at the merge base, so there was\n` +
+ ` no published member to retype -- a member this diff ADDS is not a retyping.${deps}`
+ : `${tag(op)} is false: \`${op.exportName}\` has no member \`${op.member}\` at HEAD. A member that VANISHED was\n` +
+ ` retired, not retyped: \`not-required (runtime-export-retired ${op.ref})\` is the category that proves it.${deps}`);
+ refused = true; break;
+ }
+ sides[side] = { surface, ...m };
+ }
+ if (refused) continue;
+ const unprovable = ['base', 'head'].filter((side) => sides[side].unresolved.length > 0);
+ if (unprovable.length > 0) {
problems.push(
- `${t} is false: \`${op.exportName}\` is a projection of a Zod schema (${projection.type.getText().slice(0, 90)}).\n` +
- ' Under Prime Directive #1 that is the house spelling of "this type IS metadata".',
+ `${tag(op)} cannot be proven: the declaration of \`${op.spelling}\` names ` +
+ unprovable.map((side) => `${sides[side].unresolved.map((n) => `\`${n}\``).join(', ')} at ${where[side]}`).join(' and ') + ',\n' +
+ ' which this reader does not resolve. An unresolved name is only its spelling here -- one spelling can be\n' +
+ ' two types, and two spellings one -- so whether the declared type differs cannot be read: refused, never\n' +
+ ' guessed (#4690).',
);
continue;
}
- metadataTexts ??= showManyOrNull(base, surfacePaths, cwd);
- const hit = metadataSurfaceReference(op.exportName, files[0], metadataTexts, () => packagesAt(base));
- if (hit) {
+ // The declaration can name nothing unresolved and the type still rest on it: an
+ // inferred type, a local alias, a member with no declaration of its own.
+ const unvouched = ['base', 'head'].filter((side) => sides[side].unvouched.length > 0);
+ if (unvouched.length > 0) {
problems.push(
- `${t} is false: ${hit.hitPath} (${metadataSurfaceKind(hit.hitPath)}) ` +
- (hit.kind === 'import'
- ? `IMPORTS \`${op.exportName}\` from the module that declares it.`
- : `mentions \`${op.exportName}\` IN CODE while neither declaring nor importing it:\n ${hit.line.slice(0, 140)}`) +
- '\n An export a metadata surface reaches HAS a metadata surface (comment spans are already excluded).',
+ `${tag(op)} cannot be proven: the type this reader prints for \`${op.spelling}\` rests on what it cannot vouch for.\n` +
+ unvouched.map((side) => ` at ${where[side]}, \`${sides[side].printed.slice(0, 140)}\` ${sides[side].unvouched.join(' and ')}`).join(';\n') + '.\n' +
+ ' This reader resolves the package\'s own files and `lib.es2022`. An import from another package, a DOM\n' +
+ ' global and an `@types` global do not resolve: a bare reference to such a type prints as the name written,\n' +
+ ' and such a value as `any`. So SAME and DIFFERS would both be guesses -- refused, never guessed (#4690).\n' +
+ ' An `any` the member\'s own declaration writes is compared as written.\n' +
+ (unvouched.includes('base')
+ ? ' The merge base cannot be rewritten, so there is no remedy here: a member that is unprovable there cannot\n' +
+ ' be claimed under this category.'
+ : ' To claim this member here, declare its type in full at HEAD, in names this package declares.'),
);
continue;
}
- verified.push({ ref: op.ref, kind: op.member === null ? 'export' : 'member', declared: files[0] });
- }
-
- // ---- predicate 3: the FROM -> TO block names exactly the named operands ------
- P('from-operands-named');
- const t3 = '`not-required (runtime-export-retired)` [predicate 3: from-operands-named]';
- const named = new Set(operands.map((o) => o.spelling));
- const block = readFromBlock(body);
- for (const u of block.unread) {
- problems.push(`${t3}: the body carries ${u.shape}, which this category does not read:\n ${u.text.slice(0, 160)}\n${FROM_BLOCK_READS}`);
- }
- // A whole package's FROM side is the package name -- a whole subpath key's, the
- // specifier `/` (#30598) -- which is no identifier: read it as
- // that operand's spelling exactly when the marker names it with `#*`.
- const wholeNames = new Set(operands.filter((o) => o.whole).map((o) => o.spelling));
- const wholeNote = wholeNames.size === 0 ? '' :
- '\n A package retired whole (`#*`) is named on ONE FROM line, by the package name, and a\n' +
- ' subpath key retired whole (`/#*`) by its specifier; its exports take no line of their own.';
- const seen = new Set();
- const reported = new Set();
- for (const raw of block.sides) {
- const bare = stripTicks(raw.operand).trim();
- const side = raw.spelling === null && wholeNames.has(bare) ? { ...raw, spelling: bare } : raw;
- if (side.spelling === null) {
- if (reported.has(side.operand)) continue;
- reported.add(side.operand);
+ if (sides.base.declared === sides.head.declared) {
problems.push(
- `${t3}: the FROM operand ${side.operand} is not a canonical operand:\n ${side.text.slice(0, 160)}\n` +
- ' An export is spelled by its name -- a call `name(...)` or `new Name(...)` reads as that name --\n' +
- ' and a member as `.`. Nothing inside an argument list or an object literal is\n' +
- ' read (the ruling\'s ⛔ on parsing constructor arguments).',
+ `${tag(op)} is false: the declared type of \`${op.spelling}\` is the SAME at both revisions\n` +
+ ` (\`${op.member}${sides.base.declared.slice(0, 140)}\`), so nothing was retyped and the compiler has no break to deliver on it.\n` +
+ ' If a type it NAMES changed shape, that type\'s member is the operand to name.',
);
continue;
}
- seen.add(side.spelling);
- if (named.has(side.spelling) || reported.has(side.spelling)) continue;
- reported.add(side.spelling);
- problems.push(
- `${t3}: the FROM operand ${side.operand} names \`${side.spelling}\`, which the marker does not name -- out of range:\n` +
- ` ${side.text.slice(0, 160)}\n` +
- ' A prescription for anything but the named operands keeps the `no-migration-prescription` refusal.\n' +
- ' A retired MEMBER is named `.` in the marker and written the same way on the FROM side.' +
- wholeNote,
- );
+ retyped.push({ op, sides });
}
- for (const op of operands) {
- if (seen.has(op.spelling)) continue;
- problems.push(
- `${t3}: the named operand \`${op.ref}\` has no FROM side in the body. The block must name EXACTLY the\n` +
- ` named operands: write the one-line fix a consumer needs, a line such as\n` +
- ` - FROM \`${op.spelling}\` TO \n${FROM_BLOCK_READS}`,
- );
- }
- if (block.residual) {
- problems.push(
- `${t3}: once the named FROM sides are set aside, the body still carries a migration prescription\n` +
- ` (${block.residual.branch}):\n ${block.residual.line.slice(0, 160)}\n${FROM_BLOCK_READS}`,
- );
+
+ // ---- predicate 2: no metadata surface, read at BOTH revisions ----------------
+ P('no-metadata-surface');
+ const surfacePathsAt = new Map();
+ const textsAt = new Map();
+ for (const { op, sides } of retyped) {
+ let declared = null;
+ let refused = false;
+ for (const side of ['base', 'head']) {
+ const rev = side === 'base' ? base : head;
+ if (!surfacePathsAt.has(rev)) surfacePathsAt.set(rev, metadataSurfaceFilesAt(rev, cwd));
+ const paths = surfacePathsAt.get(rev);
+ if (paths.length === 0) {
+ problems.push(
+ `\`runtime-member-retyped ${op.ref}\` [predicate 2: no-metadata-surface] cannot be verified: NO metadata-surface\n` +
+ ` file (\`*.zod.ts\`, \`${SPEC_CONTRACTS_DIR}**\`, object definitions) exists at ${where[side]}, so the scan that\n` +
+ ' would refuse this claim has nothing to read (#4690).',
+ );
+ refused = true; break;
+ }
+ const { surface, members, prop } = sides[side];
+ const p2 = exportMetadataSurfaceRead({
+ t: `\`runtime-member-retyped ${op.ref}\` [predicate 2: no-metadata-surface, read at ${where[side]}]`,
+ op, surface, symbol: members.symbol, member: prop, ts, rev: where[side],
+ texts: () => { if (!textsAt.has(rev)) textsAt.set(rev, showManyOrNull(rev, paths, cwd)); return textsAt.get(rev); },
+ pkgs: () => packagesAt(rev),
+ });
+ if (p2.problem) { problems.push(p2.problem); refused = true; break; }
+ declared ??= p2.declared;
+ }
+ if (refused) continue;
+ verified.push({
+ ref: op.ref, kind: 'member', declared,
+ from: `${op.member}${sides.base.declared}`, to: `${op.member}${sides.head.declared}`,
+ });
}
+ // ---- predicate 3: the FROM -> TO block names exactly the named operands ------
+ P('from-operands-named');
+ problems.push(...fromOperandsNamedProblems(operands, body, 'runtime-member-retyped', 'eighth'));
+
return { problems, verified, checked };
}
@@ -5959,6 +6432,7 @@ const FIXIT = (ids) =>
' ',
' ',
' ',
+ ' ',
'',
' Each category is described in ADR-0087, addendum of 2026-08-13.',
].join('\n');
@@ -6145,7 +6619,8 @@ export function scan({ cwd, base, head = 'HEAD' }) {
' \n' +
' or, if one of them is TRUE, a category resting on a checked fact: `already-registered`\n' +
' (an entry at the merge base already covers this refusal), `unpublished`,\n' +
- ' `runtime-interface-only`, `type-surface-only`, `runtime-export-retired`.\n' +
+ ' `runtime-interface-only`, `type-surface-only`, `runtime-export-retired`,\n' +
+ ' `runtime-member-retyped`.\n' +
' If the change refuses nothing an author could write, the declaration is what is wrong:\n' +
' correct the `Metadata-protocol:` line, not the disposition.',
);
@@ -6245,7 +6720,11 @@ export function scan({ cwd, base, head = 'HEAD' }) {
// `verifyRuntimeExportRetired` runs this same detector over the body with ONLY
// the FROM sides it verified set aside, so what is refused here is refused
// there, minus exactly the lines naming operands predicates 1-2 proved retired.
- const prescription = d.category === 'type-surface-only' || d.category === 'runtime-export-retired'
+ //
+ // `runtime-member-retyped` (#37447) inherits it the same way and through the
+ // same function: its predicate 3 IS `fromOperandsNamedProblems`.
+ const prescription = d.category === 'type-surface-only' || d.category === 'runtime-export-retired' ||
+ d.category === 'runtime-member-retyped'
? null
: findMigrationPrescription(parsed.body);
if (prescription) {
@@ -6274,7 +6753,11 @@ export function scan({ cwd, base, head = 'HEAD' }) {
' published package RETIRED -- each one reachable from its entry at the merge base, gone at\n' +
' HEAD, no metadata surface -- the compiler delivers it too, and the operands are checked\n' +
' (#22918):\n' +
- ' ',
+ ' \n' +
+ ' And if it rewrites only MEMBERS a published package KEPT on an exported type while their\n' +
+ ' declared type changed -- present at both revisions, the type differing, no metadata\n' +
+ ' surface -- the operands are checked the same way (#37447):\n' +
+ ' ',
);
continue;
}
@@ -6316,6 +6799,30 @@ export function scan({ cwd, base, head = 'HEAD' }) {
continue;
}
+ if (d.category === 'runtime-member-retyped') {
+ if (!exportReaderKit) {
+ needsExportReader = true;
+ push(
+ '`not-required (runtime-member-retyped)` cannot be judged in this process: its member reader (the\n' +
+ ' TypeScript compiler) is loaded on demand and was not. The entry point loads it and scans\n' +
+ ' again; a caller of `scan()` must `await loadExportReader()` first. Never a pass (#4690).',
+ );
+ continue;
+ }
+ const { problems: bad, verified } = verifyRuntimeMemberRetyped(d.ids, {
+ base: from, head, cwd, body: parsed.body, packagesAt,
+ });
+ if (bad.length > 0) {
+ for (const message of bad) push(message);
+ continue;
+ }
+ judged.push({
+ file, verdict: 'not-required', category: d.category, ids: d.ids, why: d.why, signals: decl.signals,
+ detail: verified.map((v) => `${v.ref} (${v.from} -> ${v.to}, ${v.declared})`).join(', '),
+ });
+ continue;
+ }
+
if (d.category === 'type-surface-only') {
const { problems: bad, verified } = verifyTypeSurfaceOnly(d.ids, {
base: from, head, cwd, bumps: parsed.bumps, packages, changedPaths,
@@ -9064,6 +9571,327 @@ function selfTest() {
'REX-L5: a scan with the reader loaded, or with no such marker, never asks for it');
}
+ // ---- The #37447 category: `runtime-member-retyped` -------------------------
+ //
+ // The founding case in miniature: `@object-ui/auth` under `ui/packages/*`, whose
+ // `AuthClient.updateUser` result narrowed from `Promise` to
+ // `Promise` -- concrete to concrete, the shape no other category holds.
+ // The member stays; only its declared type moves. A `*.zod.ts` that names nothing
+ // here stands at both revisions, so predicate 2 has a surface to read (#4690).
+ battery('RMR (#37447): the eighth category `runtime-member-retyped`, D9\'s sibling');
+ const RMR_PKG = '@object-ui/auth';
+ const RMR_DIR = 'ui/packages/auth';
+ const rmrPath = (rel) => `${RMR_DIR}/${rel}`;
+ const RMR_PKGS = {
+ '@objectstack/spec': { dir: 'packages/spec', private: false },
+ [RMR_PKG]: { dir: RMR_DIR, private: false },
+ };
+ const RMR_MANIFEST = JSON.stringify({
+ name: RMR_PKG, version: '1.0.0', type: 'module', types: './dist/index.d.ts',
+ exports: { '.': { types: './dist/index.d.ts', import: './dist/index.js', default: './dist/index.js' } },
+ });
+ const RMR_TYPES = (updateUser = ' updateUser: (data: Partial) => Promise;\n') =>
+ 'export interface AuthUser {\n id: string;\n name: string;\n}\n' +
+ '/** The client contract a host may implement. */\n' +
+ 'export interface AuthClient {\n getSession: () => Promise;\n' + updateUser + '}\n' +
+ 'export type Hooks = {\n onSave(row: AuthUser): Promise;\n};\n';
+ const RMR_INDEX = "export type { AuthClient, AuthUser, Hooks } from './types.js';\nexport { createAuthClient } from './createAuthClient.js';\n";
+ const RMR_BASE_FILES = {
+ [rmrPath('package.json')]: RMR_MANIFEST,
+ [rmrPath('src/index.ts')]: RMR_INDEX,
+ [rmrPath('src/types.ts')]: RMR_TYPES(),
+ [rmrPath('src/createAuthClient.ts')]: "import type { AuthClient } from './types.js';\nexport function createAuthClient(): AuthClient { return {} as AuthClient; }\n",
+ 'packages/spec/src/ui/unrelated.zod.ts': 'export const UnrelatedSchema = { shape: {} };\n',
+ };
+ const RMR_NARROWED = RMR_TYPES(' updateUser: (data: Partial) => Promise;\n');
+ const RMR_LINE =
+ '- FROM `AuthClient.updateUser` resolving a user TO the same member resolving nothing: it was declared ' +
+ '`(data: Partial) => Promise` and now declares `(data: Partial) => Promise`.';
+ const RMR_VERTICAL =
+ '- **FROM:** `AuthClient.updateUser: (data: Partial) => Promise`.\n' +
+ '- **TO:** `AuthClient.updateUser: (data: Partial) => Promise`.';
+ const RMR_WHY =
+ 'a published member kept on an exported type while its declared type changed; the compiler reports it at ' +
+ 'the consumer\'s own call site, and no stored shape names it';
+ const RMR_CS = (operands, body = RMR_LINE, category = 'runtime-member-retyped') => CS({
+ bumps: [[RMR_PKG, 'patch']],
+ body:
+ 'fix(auth)!: `createAuthClient().updateUser` declares `Promise`\n\nClause-②: no (narrowing)\nMetadata-protocol: none\n\n' +
+ `**BREAKING** for a typed caller.\n\n${body}\n\n` +
+ `\n`,
+ });
+ const RMR_FIXTURE = (operands, { head = RMR_NARROWED, body, baseFiles = {}, files = {} } = {}) => ({
+ pkgs: RMR_PKGS,
+ baseFiles: { ...RMR_BASE_FILES, ...baseFiles },
+ files: { [rmrPath('src/types.ts')]: head, '.changeset/x.md': RMR_CS(operands, body), ...files },
+ });
+ const P1 = /\[predicate 1: present-at-both-type-differs\]/;
+
+ // RMR-G1: THE FOUNDING CASE -- concrete to concrete, admitted. The detail line is
+ // the compiler's reading at both revisions and the declaration it resolved.
+ const rmrG1 = run(mk(RMR_FIXTURE(['AuthClient.updateUser'])));
+ green('RMR-G1 THE FOUNDING CASE: `AuthClient.updateUser` narrowed `Promise` -> `Promise` is admitted', rmrG1);
+ assert(
+ rmrG1.judged[0]?.category === 'runtime-member-retyped' &&
+ rmrG1.judged[0]?.detail === `${RMR_PKG}#AuthClient.updateUser (updateUser: (data: Partial) => Promise -> ` +
+ `updateUser: (data: Partial) => Promise, ${rmrPath('src/types.ts')})`,
+ `RMR-G1b: the verdict names the declared type at both revisions and the declaration site. Got: ${JSON.stringify(rmrG1.judged[0])}`,
+ );
+ assert(rmrG1.needsExportReader === false, 'RMR-G1c: a process that HAS the reader judges the claim in one scan');
+
+ // RMR-G2: a METHOD signature on a type-literal alias -- the other member spelling.
+ green('RMR-G2 a method signature on a type-literal alias, its parameter retyped, is admitted', run(mk(RMR_FIXTURE(['Hooks.onSave'], {
+ head: RMR_TYPES().replace('onSave(row: AuthUser): Promise;', 'onSave(row: Partial): Promise;'),
+ body: '- FROM `Hooks.onSave` taking a whole user TO the same hook taking a partial one.',
+ }))));
+
+ // RMR-G3: `| null` is part of the declared type. With `strictNullChecks` OFF the
+ // checker prints `T | null` as `T`, and this narrowing would read as no change.
+ // (TypeScript 6 defaults it on, so this pins the behaviour, and the explicit
+ // option, not the default, is what keeps it.)
+ green('RMR-G3 a `| null` dropped from a member\'s type is a retyping (the reader compiles with strictNullChecks)', run(mk(RMR_FIXTURE(['AuthClient.getSession'], {
+ head: RMR_TYPES().replace('getSession: () => Promise;', 'getSession: () => Promise;'),
+ body: '- FROM `AuthClient.getSession` resolving null when signed out TO the same member rejecting instead.',
+ }))));
+
+ // RMR-R1: the member VANISHED. Predicate 1 refuses and names the category that holds it.
+ red('RMR-R1 a member that VANISHED at HEAD is refused by predicate 1 and pointed at `runtime-export-retired`', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ head: RMR_TYPES(''),
+ }))), [P1, /has no member `updateUser` at HEAD/, /retired, not retyped: `not-required \(runtime-export-retired @object-ui\/auth#AuthClient\.updateUser\)`/]);
+
+ // RMR-R2: the member is NEW at HEAD -- there was nothing published to retype.
+ red('RMR-R2 a member ADDED by the diff is refused by predicate 1', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { [rmrPath('src/types.ts')]: RMR_TYPES('') },
+ }))), [P1, /has no member `updateUser` at the merge base/, /a member this diff ADDS is not a retyping/]);
+
+ // RMR-R3: present at both, SAME declared type -- only its docblock moved.
+ red('RMR-R3 a member whose declared type is the SAME at both revisions is refused by predicate 1', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ head: RMR_TYPES(' /** reworded */\n updateUser: (data: Partial) => Promise;\n'),
+ }))), [P1, /is the SAME at both revisions/, /updateUser: \(data: Partial\) => Promise/]);
+
+ // RMR-R4..R6: predicate 2, the metadata-surface hit, at each revision and site.
+ red('RMR-R4 a metadata surface that IMPORTS the type at the merge base refuses it (predicate 2)', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { 'packages/spec/src/ui/auth-client.zod.ts': `import type { AuthClient } from '${RMR_PKG}';\nexport const AuthClientSchema = {} as unknown as AuthClient;\n` },
+ }))), [/\[predicate 2: no-metadata-surface, read at the merge base\] is false: packages\/spec\/src\/ui\/auth-client\.zod\.ts \(a Zod schema\) IMPORTS `AuthClient`/]);
+ red('RMR-R5 a metadata surface that reaches the type only at HEAD refuses it too: the operand exists at both', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ files: { 'packages/spec/src/ui/auth-client.zod.ts': `import type { AuthClient } from '${RMR_PKG}';\nexport const AuthClientSchema = {} as unknown as AuthClient;\n` },
+ }))), [/\[predicate 2: no-metadata-surface, read at HEAD\] is false: packages\/spec\/src\/ui\/auth-client\.zod\.ts \(a Zod schema\) IMPORTS `AuthClient`/]);
+ {
+ const ZOD_TYPES = 'ui/packages/auth/src/types.zod.ts';
+ red('RMR-R6 a type DECLARED in a `*.zod.ts` is refused by predicate 2 on its declaration site', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { [rmrPath('src/index.ts')]: RMR_INDEX.replace("'./types.js'", "'./types.zod.js'"), [ZOD_TYPES]: RMR_TYPES() },
+ files: { [ZOD_TYPES]: RMR_NARROWED, [rmrPath('src/types.ts')]: RMR_TYPES() },
+ }))), [/\[predicate 2: no-metadata-surface, read at the merge base\] is false: `AuthClient\.updateUser` is declared in ui\/packages\/auth\/src\/types\.zod\.ts \(a Zod schema\)/]);
+ }
+
+ // RMR-R7: the operand is a MEMBER, and nothing else.
+ red('RMR-R7a an EXPORT operand is refused by name: a member is `.`', run(mk(RMR_FIXTURE(['AuthClient']))),
+ [/operand "@object-ui\/auth#AuthClient" names the export `AuthClient` itself, not a member/]);
+ red('RMR-R7b a WHOLE-package operand is refused by name', run(mk(RMR_FIXTURE([`${RMR_PKG}#*`]))),
+ [/operand "@object-ui\/auth#\*" names a WHOLE package or subpath key, not a member/]);
+ red('RMR-R7c a marker naming no operand is refused', run(mk(RMR_FIXTURE([]))),
+ [/`not-required \(runtime-member-retyped\)` names no operand/]);
+
+ // RMR-R8..R9: predicate 3, D9's, unchanged.
+ red('RMR-R8 a vertical FROM / TO pair is reported, never skipped -- and the operand then has no FROM side', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ body: RMR_VERTICAL,
+ }))), [/predicate 3: from-operands-named\]: the body carries a vertical FROM \/ TO pair/, /`@object-ui\/auth#AuthClient\.updateUser` has no FROM side/]);
+ red('RMR-R9 a FROM operand the marker does not name is refused as out of range', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ body: `${RMR_LINE}\n- FROM \`AuthClient.getSession\` TO nothing.`,
+ }))), [/FROM operand `AuthClient\.getSession` names `AuthClient\.getSession`, which the marker does not name -- out of range/]);
+
+ // RMR-R10: a type the reader cannot resolve is only the name written, never a type
+ // to compare. Reading (a): the member's own declaration names it.
+ red('RMR-R10 a member whose type names an UNRESOLVED import is refused as unprovable, never compared', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ head: `import type { Receipt } from '@objectstack/spec/api';\n${RMR_TYPES(' updateUser: (data: Partial) => Promise;\n')}`,
+ }))), [P1, /cannot be proven: the declaration of `AuthClient\.updateUser` names `Receipt` at HEAD/]);
+
+ // RMR-R11: the TYPE left the entry -- a retirement, not a retyping.
+ red('RMR-R11 a type no longer exported at HEAD is refused by predicate 1', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ files: { [rmrPath('src/index.ts')]: RMR_INDEX.replace('AuthClient, ', '') },
+ }))), [P1, /the type `AuthClient` is not exported by .*src\/index\.ts at HEAD/, /retired, not retyped/]);
+
+ // RMR-R12..R15: reading (b). The declaration names nothing unresolved and the type
+ // still rests on it, so the PRINTED type is what is asked. Every bare import is
+ // unresolved here, and what does not resolve still prints: a value as `any`, a
+ // type as the name written. Without this reading R12 was refused as "the SAME at
+ // both revisions" and R13, R14 and R15 were admitted as retyped -- each one a guess.
+ const RMR_SESSION_INDEX = `${RMR_INDEX}export { AuthSession } from './session.js';\n`;
+ const RMR_SESSION = (signature, call = 'createClient()') =>
+ "import { createClient } from 'better-auth/client';\nimport type { AuthUser } from './types.js';\n" +
+ `export class AuthSession {\n owner: AuthUser | null = null;\n ${signature} { return ${call}; }\n}\n`;
+ const RMR_SESSION_FIXTURE = (baseSession, headSession) => RMR_FIXTURE(['AuthSession.connect'], {
+ head: RMR_TYPES(),
+ body: '- FROM `AuthSession.connect` resolving one client TO the same member resolving another.',
+ baseFiles: { [rmrPath('src/index.ts')]: RMR_SESSION_INDEX, [rmrPath('src/session.ts')]: baseSession },
+ files: { [rmrPath('src/session.ts')]: headSession },
+ });
+ {
+ // R12: `any` at BOTH revisions -- an unannotated member inferred through a value
+ // the reader could not resolve. Unprovable, and never "the SAME".
+ const res = run(mk(RMR_SESSION_FIXTURE(RMR_SESSION('async connect()'), RMR_SESSION('async connect()', 'createClient({ retry: true })'))));
+ red('RMR-R12 an INFERRED type that is the reader\'s own `any` at both revisions is refused as unprovable', res, [
+ P1, /cannot be proven: the type this reader prints for `AuthSession\.connect` rests on what it cannot vouch for/,
+ /at the merge base, `\(\) => Promise` carries an `any` its own declaration does not write \(1 printed, 0 written\)/,
+ /at HEAD, `\(\) => Promise` carries an `any` its own declaration does not write \(1 printed, 0 written\)/,
+ // Unprovable at the merge base: nothing the author can write at HEAD answers it.
+ /The merge base cannot be rewritten, so there is no remedy here/,
+ ]);
+ assert(
+ !/is the SAME at both revisions/.test(res.problems.map((p) => p.message).join('\n')),
+ 'RMR-R12b: two `any` the reader produced are not "the SAME declared type" -- that sentence is one the gate cannot know',
+ );
+ }
+ // R13: `any` at ONE revision -- the annotation was dropped. Refused, never admitted
+ // as a retyping: the difference is the reader's blindness, not the package's.
+ red('RMR-R13 an inferred `any` at ONE revision is refused as unprovable, never admitted as retyped',
+ run(mk(RMR_SESSION_FIXTURE(RMR_SESSION('async connect(): Promise'), RMR_SESSION('async connect()')))),
+ [P1, /cannot be proven: the type this reader prints for `AuthSession\.connect`/, /at HEAD, `\(\) => Promise` carries an `any` its own declaration does not write/,
+ /To claim this member here, declare its type in full at HEAD/]);
+ // R14: the annotation names a LOCAL alias, which resolves, and the alias rests on a
+ // name that does not. The printed type names it.
+ red('RMR-R14 an annotation naming a local alias that rests on an UNRESOLVED name is refused as unprovable', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ head: `import type { Receipt } from '@objectstack/spec/api';\ntype Outcome = Receipt;\n${RMR_TYPES(' updateUser: (data: Partial) => Promise;\n')}`,
+ }))), [P1, /at HEAD, `\(data: Partial\) => Promise` names `Receipt`, which this reader does not resolve/]);
+ // R15: a member with NO declaration node of its own -- a mapped type's. Reading (a)
+ // has nothing to walk; the printed type is all there is.
+ {
+ const FLAGS = (type, head = '') => `${head}export type SessionFlags = { [K in 'remember' | 'trusted']: ${type} };\n`;
+ red('RMR-R15 a member with no declaration of its own, typed by an UNRESOLVED name, is refused as unprovable', run(mk(RMR_FIXTURE(['SessionFlags.remember'], {
+ head: RMR_TYPES(),
+ body: '- FROM `SessionFlags.remember` as a boolean TO the same member as a receipt.',
+ baseFiles: { [rmrPath('src/index.ts')]: `${RMR_INDEX}export type { SessionFlags } from './flags.js';\n`, [rmrPath('src/flags.ts')]: FLAGS('boolean') },
+ files: { [rmrPath('src/flags.ts')]: FLAGS('Receipt', "import type { Receipt } from '@objectstack/spec/api';\n") },
+ }))), [P1, /at HEAD, `Receipt` names `Receipt`, which this reader does not resolve/]);
+ }
+ // RMR-G4: the accept set does not move for an `any` the declaration WRITES -- it is
+ // compared as written, at both revisions.
+ green('RMR-G4 a member whose own declaration WRITES `any` is compared as written, and its retyping admitted', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { [rmrPath('src/types.ts')]: RMR_TYPES(' updateUser: (data: Record) => Promise;\n') },
+ head: RMR_TYPES(' updateUser: (data: Record) => Promise;\n'),
+ }))));
+
+ // RMR-C1: STATED, NOT CLOSED -- road (b) of the header, carried by #38379. This
+ // pins what the gate DOES, not what it should. `keyof` consumes the unresolved type
+ // behind a local alias, so no name and no `any` prints: the member's key moved
+ // from one unresolved table to another and the reader says "the SAME". When #38379
+ // closes the road this case turns into an unprovable refusal -- change it then,
+ // deliberately, and the ADR's "without a trace" item with it.
+ {
+ const ROUTER = (routes) =>
+ "import type { ApiRoutes, AdminRoutes } from '@objectstack/spec/api';\n" +
+ `type RouteKey = keyof ${routes};\n` +
+ 'export class Router {\n getRoute(type: RouteKey): string { return String(type); }\n}\n';
+ red('RMR-C1 STATED, NOT CLOSED (#38379): `keyof` of an UNRESOLVED type behind a local alias leaves no trace and is COMPARED', run(mk(RMR_FIXTURE(['Router.getRoute'], {
+ head: RMR_TYPES(),
+ body: '- FROM `Router.getRoute` keyed by one route table TO the same member keyed by another.',
+ baseFiles: { [rmrPath('src/index.ts')]: `${RMR_INDEX}export { Router } from './router.js';\n`, [rmrPath('src/router.ts')]: ROUTER('ApiRoutes') },
+ files: { [rmrPath('src/router.ts')]: ROUTER('AdminRoutes') },
+ }))), [P1, /is the SAME at both revisions/, /getRoute: \(type: string \| number \| symbol\) => string/]);
+ }
+
+ // RMR-G5: the LITERAL-SUBPATH operand, which `HOW` advertises and this function
+ // wires itself (`op.subpath`): the member is read behind the `./client` key.
+ {
+ const manifest = JSON.parse(RMR_MANIFEST);
+ manifest.exports['./client'] = { types: './dist/client.d.ts', import: './dist/client.js', default: './dist/client.js' };
+ const CLIENT = (type) => `export interface ClientOptions {\n timeout: ${type};\n}\n`;
+ const res = run(mk(RMR_FIXTURE([`${RMR_PKG}/client#ClientOptions.timeout`], {
+ head: RMR_TYPES(),
+ body: '- FROM `ClientOptions.timeout` in milliseconds TO the same member as a duration string.',
+ baseFiles: { [rmrPath('package.json')]: JSON.stringify(manifest), [rmrPath('src/client.ts')]: CLIENT('number') },
+ files: { [rmrPath('src/client.ts')]: CLIENT('string') },
+ })));
+ green('RMR-G5 a member behind a LITERAL subpath key (`/#.`) is read and admitted', res);
+ assert(
+ res.judged[0]?.detail === `${RMR_PKG}/client#ClientOptions.timeout (timeout: number -> timeout: string, ${rmrPath('src/client.ts')})`,
+ `RMR-G5b: the verdict is read on the subpath key's own source entry. Got: ${JSON.stringify(res.judged[0])}`,
+ );
+ }
+ // RMR-R16: R10 on the OTHER side -- the unresolved name is at the merge base.
+ red('RMR-R16 a member whose type names an UNRESOLVED import at the MERGE BASE is refused as unprovable', run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { [rmrPath('src/types.ts')]: `import type { Receipt } from '@objectstack/spec/api';\n${RMR_TYPES(' updateUser: (data: Partial) => Promise;\n')}` },
+ }))), [P1, /cannot be proven: the declaration of `AuthClient\.updateUser` names `Receipt` at the merge base/]);
+ // RMR-G6: an OPTIONALITY-only change -- the `?` is part of the declared type.
+ {
+ const res = run(mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ head: RMR_TYPES(' updateUser?: (data: Partial) => Promise;\n'),
+ })));
+ green('RMR-G6 a member that only became OPTIONAL is a retyping: its `?` is part of the declared type', res);
+ assert(
+ (res.judged[0]?.detail ?? '').includes('(updateUser: (data: Partial) => Promise -> updateUser?: '),
+ `RMR-G6b: the verdict shows the \`?\` on the HEAD side only. Got: ${JSON.stringify(res.judged[0])}`,
+ );
+ }
+ // RMR-G7: a member of an exported VALUE (the second half of D10's operand sentence),
+ // read on the value's type. Its declaration is an initialiser, which is where the
+ // `any` count reads what is WRITTEN: one written, one printed, compared.
+ {
+ const DEFAULTS = (to) => `export const defaults = {\n port: 8080,\n parse: (raw: any) => ${to}(raw),\n};\n`;
+ const res = run(mk(RMR_FIXTURE(['defaults.parse'], {
+ head: RMR_TYPES(),
+ body: '- FROM `defaults.parse` returning a number TO the same member returning a string.',
+ baseFiles: { [rmrPath('src/index.ts')]: `${RMR_INDEX}export { defaults } from './defaults.js';\n`, [rmrPath('src/defaults.ts')]: DEFAULTS('Number') },
+ files: { [rmrPath('src/defaults.ts')]: DEFAULTS('String') },
+ })));
+ green('RMR-G7 a member of an exported VALUE is read on the value\'s type; the `any` its initialiser writes is compared as written', res);
+ assert(
+ res.judged[0]?.detail === `${RMR_PKG}#defaults.parse (parse: (raw: any) => number -> parse: (raw: any) => string, ${rmrPath('src/defaults.ts')})`,
+ `RMR-G7b: the verdict names the value's member at both revisions. Got: ${JSON.stringify(res.judged[0])}`,
+ );
+ }
+ // RMR-R17: a PRIVATE package has no published entry, so there is no published
+ // member on it to retype -- and the refusal says THAT, not D9's "to retire an
+ // export from" (`NO_ENTRY_TO`). D9's own sentence is unchanged (R17c; REX-R9).
+ {
+ const f = mk(RMR_FIXTURE(['AuthClient.updateUser'], {
+ baseFiles: { [rmrPath('package.json')]: JSON.stringify({ ...JSON.parse(RMR_MANIFEST), private: true }) },
+ }));
+ const res = run(f);
+ red('RMR-R17 a member of a PRIVATE package is refused: it has no published entry to retype a member on', res,
+ [P1, /cannot be read at the merge base/, /`@object-ui\/auth` is PRIVATE/, /it has no published entry to retype a\s+member on\. The disposition that says so is `not-required \(unpublished\)`/]);
+ assert(
+ !/retire an\s+export from/.test(res.problems.map((p) => p.message).join('\n')),
+ 'RMR-R17b: a retyping claim on a private package is not refused in the words of a retirement',
+ );
+ assert(
+ (sourceEntryAt(f.base, f.dir, RMR_PKG, workspacePackagesAt(f.base, f.dir), exportReaderKit).refusal ?? '')
+ .includes('it has no published entry to retire an\n export from. The disposition that says so is `not-required (unpublished)`'),
+ 'RMR-R17c: asked by D9 (no `noEntryTo`), the same refusal keeps D9\'s sentence byte for byte',
+ );
+ }
+
+ // RMR-L: the reader is paid for only by a run that needs it, and its absence is RED.
+ {
+ const kit = exportReaderKit;
+ exportReaderKit = null;
+ let unloaded;
+ try { unloaded = run(mk(RMR_FIXTURE(['AuthClient.updateUser']))); } finally { exportReaderKit = kit; }
+ red('RMR-L1 a scan without the reader is RED and asks for it', unloaded, [/member reader \(the\s+TypeScript compiler\) is loaded on demand and was not/]);
+ assert(unloaded.needsExportReader === true, 'RMR-L2: ...and sets `needsExportReader`, which is what makes the entry point load and re-scan');
+ }
+
+ // ---- RMR-N: the predicate set is pinned BY NAME, never by count ------------
+ battery('RMR-N: the eighth category\'s predicate set is pinned BY NAME, never by count');
+ assert(
+ JSON.stringify(RUNTIME_MEMBER_RETYPED_PREDICATES) ===
+ JSON.stringify(['present-at-both-type-differs', 'no-metadata-surface', 'from-operands-named']),
+ `RMR-N1: the three predicates are pinned BY NAME. Got: ${JSON.stringify(RUNTIME_MEMBER_RETYPED_PREDICATES)}. ` +
+ 'Changing one changes what the eighth category rests on (ADR-0087, the #37447 amendment) -- change this pin deliberately.',
+ );
+ {
+ const f = mk(RMR_FIXTURE(['AuthClient.updateUser']));
+ const seen = verifyRuntimeMemberRetyped([`${RMR_PKG}#AuthClient.updateUser`], {
+ base: f.base, head: 'HEAD', cwd: f.dir, body: RMR_LINE, packagesAt: (rev) => workspacePackagesAt(rev, f.dir),
+ });
+ assert(seen.problems.length === 0, `RMR-N2a: the all-true fixture must verify clean, got:\n${seen.problems.join('\n')}`);
+ assert(
+ JSON.stringify(seen.checked) === JSON.stringify(RUNTIME_MEMBER_RETYPED_PREDICATES),
+ 'RMR-N2b: the predicates verifyRuntimeMemberRetyped ACTUALLY evaluates must be exactly the exported ' +
+ `RUNTIME_MEMBER_RETYPED_PREDICATES, in order. Got: ${JSON.stringify(seen.checked)}.`,
+ );
+ }
+
// ---- WS (#26220): a ui workspace package, read through the workspace file --
//
// The gate's package globs are the rev's own `pnpm-workspace.yaml`, so an
@@ -11171,8 +11999,9 @@ if (isEntrypoint(import.meta.url)) {
let result;
try {
result = scan({ cwd: REPO_ROOT, base, head });
- // Only a PR whose changeset names `runtime-export-retired` pays for the
- // compiler (#22918): load it, then judge the same diff again with it.
+ // Only a PR whose changeset names `runtime-export-retired` or
+ // `runtime-member-retyped` pays for the compiler (#22918, #37447): load it,
+ // then judge the same diff again with it.
if (result.needsExportReader) {
await loadExportReader();
result = scan({ cwd: REPO_ROOT, base, head });
From 3511432500f9c03f6ed78ab634c0719953297b7c Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:04:01 +0000
Subject: [PATCH 002/162] chore(claude): ask before a glob spelling of the four
allowed commit and push forms (#38397)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Closes #38356
Clause-②: no
Metadata-protocol: none
Rule-change: ruled
Ruling-ref: the maintainer, verbatim in the security#2 session on
2026-11-28: 「按建议」 on the delta review 7238071861 of PR #38077, recorded
in comment 7241046206 on #38074; the option it chose cards the
glob-character guards separately, as this card. The ruling's recorded
words name the branch argument; the six commit-file rows (`-F` and
`--allow-empty -F`) come from this card's own scope (#38356) and the
delta reviewer's measured candidate set.
## 维护者速读
- 用户无感:云端值班席位提交和推送自己的卡分支、信箱分支时,写法里带通配符的变体改为先弹审批,四条原样写法照旧免审批。
- 为什么做:命令行会先把问号、方括号、星号展开成别的内容,免审批规则却按原样匹配,带通配符的写法可能推出不该推的分支。
- 出错会怎样:最坏是席位在这几种少见写法上多弹一次审批;撤回只需删掉这十行。
- 要你做什么:审阅后亲自合并这个草稿 PR。
## What changes
`.claude/settings.json`, `permissions.ask` gains ten rows, after the two
literal-`*` push guards from #38077:
```
"Bash(git push -u origin claude/issue-*?*)",
"Bash(git push -u origin claude/issue-*[*)",
"Bash(git push -u origin claude/mailbox-*?*)",
"Bash(git push -u origin claude/mailbox-*[*)",
"Bash(git commit -F *\\**)",
"Bash(git commit -F *?*)",
"Bash(git commit -F *[*)",
"Bash(git commit --allow-empty -F *\\**)",
"Bash(git commit --allow-empty -F *?*)",
"Bash(git commit --allow-empty -F *[*)"
```
Each of the four allowed forms now has an ask guard for `?`, `[` and a
literal `*` in its argument. The two push forms already had the
literal-`*` guard (#38077), so it is not repeated. Nothing else in the
file changes: the allow list, the deny roster (17 GitHub content-write
tools) and the hooks are as on `main`.
## Why
The shell expands `?`, `[...]` and `*` in the argument against files in
the working directory before the command runs. The permission matcher
reads the argument as typed, so a spelling that matches only the allow
rule could expand into a form the ask rules exist to stop. On `main` the
sandbox measurement below shows it: `git push -u origin
claude/mailbox-ui-4?pwned-glob`, the `[^a]` and `[!a]` spellings, and
the same on the card-branch family, ran without approval and created
`refs/heads/pwned-glob` on the sandbox origin. `git commit -F m*` and
`-F *` also ran without approval.
## Reach
Measured end to end: the CLI binary, driven against a mocked model
endpoint in throwaway sandbox repos, default mode unless stated.
Precedence is deny, then ask, then allow.
**Runs without approval** (unchanged from `main`):
- the four bare forms: `git commit -F FILE`, `git commit --allow-empty
-F FILE`, `git push -u origin claude/issue-N-SLUG`, `git push -u origin
claude/mailbox-SLUG`;
- the wrapper, redirect, chain and read-only pipe shapes listed in
#38077's Reach section, for example `timeout 30 ...`, `... 2>&1 | tail
-5`, two allowed commands joined by `&&` or `;`;
- a `*` that is not in the argument: a trailing `# *` comment, or `grep
'*'` after a pipe.
**An ask rule prompts for** (new rows, this PR):
- `?` anywhere in the branch argument of either push family, for example
`claude/mailbox-ui-4?pwned-glob`, `claude/issue-?-x`,
`claude/mailbox-?i-4`;
- `[` anywhere in the branch argument of either push family: `[x]`,
`[^a]`, `[!a]`, a range (`[:]` already asked on `main` through the `:**`
guard);
- `?`, `[` or a literal `*` in the message-file argument of `git commit
-F` and `git commit --allow-empty -F`: `m*`, `*`, `m?g`, `ms?`, `m[s]g`,
`m[^x]g`, `m[!x]g`, `m[a-z]g`.
**An ask rule prompts for** (already on `main`, held): anything after
the branch or the message file, a `src:dst` refspec, a literal `*` in
the branch argument, and arguments fed through `xargs`.
**Prompts for another reason, or matches no rule:** unchanged from
`main`, as #38077's Reach section lists. A quoted or backslash-escaped
`?`, `[` or `*` in the argument now asks by rule on all four forms,
although the shell would not expand it: on the commit forms it ran
before this PR; on the push forms a quoted `*` already asked. Glob
spellings behind a pipe prompt as a subcommand prompt rather than a
top-level rule ask.
**Not guarded here:** tilde expansion (`-F ~/x`), which is not a glob
and ran before and after.
## Readings
- `node scripts/pm/check-settings-deny-roster.mjs`: EXIT=0, `17
content-write tool(s) declared = enforced`.
- JSON parse of `.claude/settings.json`: EXIT=0.
- `node scripts/pm/mailbox-open.mjs --self-test`: EXIT=0, `93 cases in
10 batteries pass`.
- End to end, `main` (ff69bcabb2) against this head (6d072bbe87), 566
command shapes: 40 that ran without approval now ask by rule. Nothing
else changes, and nothing that prompted before runs now.
End to end, before (ff69bcabb2) and after
(6d072bbe87)
Each shape is one fresh CLI session in its own sandbox repo with a bare
`origin`, a mocked model endpoint that emits the one Bash call, and the
head's `permissions` block as project settings. Every prompt was
answered "deny". RAN = executed with no prompt. ASK(rule) = an ask rule
matched the line. PROMPT(...) = a prompt raised for another reason. Both
heads were run in this session, same binary. No session reached a real
model endpoint.
Sets: the 526 shapes of #38077's review (main 116, xargs/wrapper/chain
41, glob/continuation 29, acceptEdits 10, round-3 extras 9 + 158 + 163)
and 40 glob shapes added for this card (9 per commit form, 11 per push
family).
```
before after
RAN 116 76
ASK(rule) 167 207
PROMPT(subcommandResults) 186 186
PROMPT(other) 87 87
PROMPT(safetyCheck) 4 4
PROMPT(unclassified) 6 6
```
Every row that changed (all RAN before, ASK(rule) after):
```
set id command
e2e p58 git push -u origin claude/mailbox-?i-4
e2e c47 git commit --allow-empty -F *
e2e c48 git commit --allow-empty -F m*
e2e c49 git commit -F *
y y01 git push -u origin claude/mailbox-ui-4?pwned-glob (before: created refs/heads/pwned-glob)
y y06 git push -u origin claude/issue-1-x?pwned-glob (before: created refs/heads/pwned-glob)
y y18 git commit --allow-empty -F *
y y19 git commit --allow-empty -F m*
v v1 git push -u origin claude/mailbox-ui-4[^a]pwned-glob (before: created refs/heads/pwned-glob)
v v2 git push -u origin claude/issue-1-x[!a]pwned-glob (before: created refs/heads/pwned-glob)
glob cf01..cf08 git commit -F m* * m?g ms? m[s]g m[^x]g m[!x]g m[a-z]g
glob ca01..ca08 git commit --allow-empty -F (the same eight arguments)
glob pi01..pi03 git push -u origin claude/issue-1-x ?pwned-glob [^a]pwned-glob [!a]pwned-glob
glob pi06 pi07 git push -u origin claude/issue-1-x? claude/issue-1-x[x]
glob pi10 pi11 git push -u origin claude/issue-?-x claude/issue-[1]-x
glob pm01..pm03 git push -u origin claude/mailbox-ui-4 ?pwned-glob [^a]pwned-glob [!a]pwned-glob
glob pm06 pm07 git push -u origin claude/mailbox-ui-4? claude/mailbox-ui-4[x]
glob pm10 pm11 git push -u origin claude/mailbox-?i-4 claude/mailbox-[u]i-4
```
Held at both heads: the four bare forms RAN (glob cf00, ca00, pi00,
pm00; e2e c01, c18, i01, p01), each making its commit or creating its
own branch on the sandbox origin; the literal-`*` push shapes and `[:]`
asked by rule before and after (pi04, pi05, pi12, pm04, pm05, pm12).
Per-set totals, before / after: e2e RAN 29 / 25, y RAN 5 / 1, v RAN 2 /
0, glob RAN 34 / 4; x, z, z2 and acceptEdits identical.
Local gate readings at 6d072bbe87
`node scripts/pm/dispatch-gates.mjs --commands --repo
objectstack-ai/objectstack` derived 18 commands for this one path; all
18 ran and exited 0. `check:doc-formula-expressions` first exited 3
(prerequisite: `@objectstack/formula` and `@objectstack/lint` unbuilt,
nothing measured); after building those two it exited 0. The always-runs
tail and the type-check lanes are CI's.
Files to read first: `.claude/settings.json`, the ask block, the ten
rows after `claude/mailbox-*\\**`.
Two-minute check: `node scripts/pm/check-settings-deny-roster.mjs`
prints `17 content-write tool(s) declared = enforced`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov
Co-authored-by: Claude
---
.claude/settings.json | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/.claude/settings.json b/.claude/settings.json
index 06dc0d3b1d8..9e4b89e5c94 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -100,6 +100,16 @@
"Bash(git push -u origin claude/mailbox-*:**)",
"Bash(git push -u origin claude/issue-*\\**)",
"Bash(git push -u origin claude/mailbox-*\\**)",
+ "Bash(git push -u origin claude/issue-*?*)",
+ "Bash(git push -u origin claude/issue-*[*)",
+ "Bash(git push -u origin claude/mailbox-*?*)",
+ "Bash(git push -u origin claude/mailbox-*[*)",
+ "Bash(git commit -F *\\**)",
+ "Bash(git commit -F *?*)",
+ "Bash(git commit -F *[*)",
+ "Bash(git commit --allow-empty -F *\\**)",
+ "Bash(git commit --allow-empty -F *?*)",
+ "Bash(git commit --allow-empty -F *[*)",
"Bash(xargs git push -u origin claude/issue-*)",
"Bash(xargs git push -u origin claude/mailbox-*)",
"Bash(xargs git commit -F *)",
From 3579cf136ddea0bfacd684c857e099488736ec88 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:10:43 +0000
Subject: [PATCH 003/162] chore(pm): probe classifier carve-out, paste-safe
rerun line, runnable probe rule (#35237 slice 13) (#38393)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XHogQ9ogKPxHhiFfT2UQgJi)_
Fixes #35237
Claim on the card naming this branch: 7247494260 (slice 13; base claim
7245952141).
Clause-②: no
Metadata-protocol: none
Rule-change: none
## 维护者速读
- 用户无感:车队开发代理用的内部脚本和开发代理规则里的一行命令写法做了收尾修整,推送前后的行为对用户不可见。
- 属于「车队技能整理」里「把每次手敲的流程改成脚本」这一步,本次清掉这一步最后几项遗留小问题,做完后这一步可以关闭。
- 最坏情况是开发代理推送遇到超时、限流类错误时多重试几次(有固定上限)或照旧提前停下;一个提交即可整体撤回。
- 无
Slice 13 of the card: carrier item 24, the rule half of item 14 N7, and
items 26–29 (notes 7246458172 and 7246788470), plus the card's done-when
check below. 6 files, +54 / −16.
| Item | Where | What changed |
|:---|:---|:---|
| 24 | `scripts/pm/check-owed-reviews.mjs:140` | "The name is kept:
importers read it" was false (nothing imports `TRIAGE_ROUND_MINUTES`).
It now says the name is kept because this file reads it, in the trigger
(b) docblock and `owedReviewRow`, and that nothing imports it. Comment
only. |
| 14 N7 (rule half) | `.claude/agents/os-dev.md:31` | The probe command
now spells `--branch=BRANCH`, so it runs as written instead of ending in
a usage exit. Bytes are offset on the same line (see Acceptance notes).
|
| 14 N7 (ratchet) | `scripts/pm/check-skill-line-ratchet.mjs` | The
`os-dev.md` row is lowered 33500 → 33492, the landed size. No row
raised. |
| 26 | `scripts/pm/dev-worktree.sh` `classify_push_failure` | A new arm,
ahead of the 4xx arm and keyed exactly as it is, reads 408, 421, 429 and
every 5xx as `network`. "Received HTTP code 502 from proxy after
CONNECT" is now placed. The comment now says why. 5 classifier cases;
floor 14 → 19. |
| 27 | `scripts/pm/dev-worktree.sh` `rerun_with_probe` | A flag made
only of characters no shell reads specially is printed as typed
(`--backoff=2,4`). Any other flag is still quoted with `printf %q`. The
pinned line now carries `--backoff=2,4`. One round-trip case; floor 20 →
21. |
| 28 | `scripts/pm/git-history.mjs` self-test | The case titled "a
problem the CLI refuses as usage" now asserts through the CLI: `ancestor
--cwd=` pointed at a missing directory exits 1, prints nothing on stdout
and says "could not be checked" on stderr. |
| 29 | `scripts/pm/check-handover.mjs` `--inflight` clear line | The
line now names the unjudged case: "a claimed path fragment deeper inside
a dispatched directory, spelled DIR, DIR/** or DIR/**/GLOB alike". It is
pinned in the N12 case. |
### Why 408, 421 and 429 are network errors under rule 1
(`os-dev.md:33`, only a network error is retried)
The rule separates two kinds of failure. A refusal on the merits stops
the run (403, and every other judged 4xx). A failure of the path is
retried on a bounded schedule. Each of these three statuses says the
path failed and says nothing about the push itself:
- **408 Request Timeout.** The server closed the connection because the
request did not arrive whole in time. It is the same event as the
`Operation timed out` the classifier already retries; this time the
server noticed the timeout first.
- **421 Misdirected Request.** The request reached a connection that
cannot answer for this host, usually a reused HTTP/2 connection or a
proxy route. It describes the connection, not the request, and the
retry's new connection is the fix.
- **429 Too Many Requests.** The path is throttled for now. HTTP's own
remedy is to wait and retry, and the backoff schedule is that wait: four
retries, 30 s in all, never a loop.
All three read `network` before #38387 (through the words "RPC failed").
This PR restores that reading and keeps 401, 404, 407 and 409 as
`other`. Every 5xx already read `network` in the `error:` and `HTTP`
spellings. The new arm adds the key words the 4xx arm uses (`status`,
`code`, `response`, `HTTP/N`), so a proxy's "Received HTTP code 502"
reads the same way.
### Done-when check, item by item
The card's done-when: each listed procedure is a script with a
self-test, its prose is a one-line pointer, and the card-pick reader
works against the live board. The closing check also asks that no
carrier item stays open apart from item 7 option B, which landing ruled
out of scope (7222751511 ③).
| Part | State | Evidence |
|:---|:---|:---|
| Slice 1: card-pick, lock depth, prior-rulings `--paths` | landed | PR
#35482 |
| Slice 2: `landing-k`, `pr-state`, `sweep-closed-cards --pr` | landed |
PR #35576 |
| Slices 3, 5, 6: `fleet-roster --health`, the dispatch-runbook pointer,
`l1-face` | landed | PR #35671 |
| Slice 4: `check-handover --inflight`, `round-open` | landed | PR
#37878 |
| Slice 7: `git-history ancestor`, `dev-worktree.sh` | landed | PR
#38018 |
| Card-pick against the live board | works | `node
scripts/pm/card-pick.mjs --order area:fleet --seat repo:objectstack#5
--limit 3` at 23:04Z: read 231 open `pm:queue` issues over 3 pages, the
platform counts 231, `card-pick COMPLETE — 3 pick(s)`, exit 0 |
| Carrier items 1, 2 | done | slice 4 (landing note 7226135228) |
| 3, 5, 6, 11 (10's N6 too) | done | slice 8, PR #38146 |
| 16–19 | done | slice 9, PR #38212 |
| 4, 12, 13, 15 | done | slice 10, PR #38222 |
| 20–22 | done | slice 11, PR #38243 |
| 7 N11, 9, 14 N3/N5/N6 and N7's script half, 23, 25 | done | slice 12,
PR #38387 |
| 24, N7's rule half, 26–29 | done | this PR |
| 8, 10 | owe nothing | listed for completeness and accepted as
deviations (7222785044) |
| 7 option B | out of scope | landing kept option A (7222751511 ③) |
Each part holds as far as it can be measured, so the first line is
`Fixes #35237`. One limit: the review reports' section 4, the candidate
list the card names, cannot be read from this project, and slice 3's
claim (7022183772) recorded the same gap. "Each listed procedure" is
therefore checked against the slice plan in claim 7006559529, amendment
7013022048 and release 7017468070. If the seat holds a section-4
candidate outside that plan, the first line should become `Part of`.
## What changes
The four scripts and one comment above, one rule line and one ratchet
row. Nothing here ships in a package.
## Tests
All runs are at head `084b6dba7a`.
Self-tests of every script edited
- `bash scripts/pm/dev-worktree.sh --self-test`: `✓ dev-worktree
self-test: 95 cases pass across 7 batteries` (89 before: 5 classifier
cases and 1 probe case added).
- `node scripts/pm/git-history.mjs --self-test`: `git-history
--self-test: all cases passed.`
- `node scripts/pm/check-handover.mjs --self-test`: `✓ check-handover
self-test: 114 cases pass`.
- `node scripts/pm/check-owed-reviews.mjs --self-test`: `✓
check-owed-reviews self-test: 96 cases pass in 10 batteries`.
- `node scripts/pm/check-skill-line-ratchet.mjs --self-test`: `116 cases
pass`. The gate itself exits 0.
Ablations (scripts/ablation-replace.mjs; each mutation
was proven on disk and the restore proven blob == HEAD with an empty git
diff HEAD)
- A1 `(408|421|429|5[0-9][0-9])` → `(5[0-9][0-9])` in the new arm: 3 of
95 red, the 408, 429 and 421 cases.
- A2 `(408|421|429|5[0-9][0-9])` → `(408|421|429)`: 1 of 95 red, the
proxy CONNECT 502 case.
- A3 the as-typed branch of `rerun_with_probe` back to `printf %q`: 2 of
95 red, the pinned second-run line and the round-trip case.
- A4 the `--inflight` clear line back to its old text: 1 of 114 red, the
N12 case.
- A5 the CLI's usage refusal skipped for a "could not be checked"
problem: 1 red, the item 28 case, through its CLI half alone (the direct
calls stay green).
Classifier false-match probe (the shapes record
7246776227 tried against the 4xx arm, run against the new arm, at this
head and at the merge base)
A port (`port 429`, `github.com:502`), an errno (`errno 408`,
`errno=502`), an OpenSSL code (`error:0A000126`, `error:42900000`), a
byte count (`408 bytes`, `Total 429`, `(502/502)`) and an HTTP/2 stream
number (`HTTP/2 stream 421`, `stream 503`) read the same at head as at
base. Only two answers moved: `RPC failed; HTTP 429` and `Received HTTP
code 503 from proxy after CONNECT`, both from `other` to `network`.
## Acceptance notes
- **os-dev.md byte offset.** Adding `--branch=BRANCH ` costs 16 bytes
against 9 bytes of headroom. The same line drops 「建好分支后」 (15 bytes), so
the file lands at 33492 (+1 against main's 33491), within the 33500
ceiling. The row is then lowered to 33492. The rule is unchanged: the
timing it sets is still 「任何编辑前」, and the one command now builds the
branch and sends the probe in a single run. `BRANCH` is the placeholder
the file already uses three lines up (`Resume-from: BRANCH@SHA`). The
edit stays one line, adding one argument, with the offset on the same
line.
- **The old 5xx alternative is kept.** The case-insensitive
`(error:|HTTP)[ :]+5xx` alternative stays in the transport-words arm, so
no spelling that read `network` before reads anything else now.
- **`check-owed-reviews.mjs` keeps `export`.** Nothing imports the name,
and the sentence now says so. Removing the export would be a surface
change this item did not ask for.
## Verification
Read first, by risk: `scripts/pm/dev-worktree.sh` (the new arm in
`classify_push_failure`, then `rerun_with_probe`),
`.claude/agents/os-dev.md:31`, `scripts/pm/git-history.mjs` (the item 28
case).
Two-minute check: `bash scripts/pm/dev-worktree.sh --self-test` should
print `95 cases pass across 7 batteries`.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_
Co-authored-by: Claude
---
.claude/agents/os-dev.md | 2 +-
scripts/pm/check-handover.mjs | 4 +--
scripts/pm/check-owed-reviews.mjs | 2 +-
scripts/pm/check-skill-line-ratchet.mjs | 2 +-
scripts/pm/dev-worktree.sh | 48 ++++++++++++++++++++-----
scripts/pm/git-history.mjs | 12 +++++--
6 files changed, 54 insertions(+), 16 deletions(-)
diff --git a/.claude/agents/os-dev.md b/.claude/agents/os-dev.md
index 59148e5a309..4c1071ee066 100644
--- a/.claude/agents/os-dev.md
+++ b/.claude/agents/os-dev.md
@@ -28,7 +28,7 @@ model: opus
- 认领带 `Resume-from: BRANCH@SHA` ⇒ 从 `origin/BRANCH` 建同名分支续写,先合 `origin/main`。
- ⛔ 永不编辑共享检出;修复横跨姊妹仓时一仓一 worktree。
- 动笔前记下基点 `BASE=$(git rev-parse HEAD)`,它是标准条款节里家族规则的锚。
- - 建好分支后先推空分支(任何编辑前 `dev-worktree.sh --probe`):落地标记兼写路由探针。
+ - 先推空分支(任何编辑前 `dev-worktree.sh --branch=BRANCH --probe`):落地标记兼写路由探针。
- 卡线程分支由平台指定、harness 推送,⛔ 不推空分支;探针规则只对自建分支。
- 探针遇 403 ⇒ 停下报 `blocked`,⛔ 不进重试循环;只有网络错误才退避重试。
- Scratchpad 按 issue 隔离:在 scratchpad 目录下建 `issue-/` 子目录,临时文件全写进去。
diff --git a/scripts/pm/check-handover.mjs b/scripts/pm/check-handover.mjs
index 010e17f2052..5e24a5df90e 100644
--- a/scripts/pm/check-handover.mjs
+++ b/scripts/pm/check-handover.mjs
@@ -924,7 +924,7 @@ export function inflightText(verdict, { repo, paths, read, reconcile = null }) {
? `check-handover --inflight: OVERLAP — ${verdict.overlaps.length} in-flight claim(s) on ${repo} meet the surface about to be dispatched.`
: verdict.exit === EXIT_SURFACE_UNREAD
? `check-handover --inflight: NO OVERLAP READ, ${verdict.unread.length} SURFACE(S) UNREAD — no readable in-flight surface on ${repo} meets this one; the cards below name no path, so read their claims by hand.`
- : `check-handover --inflight: clear — no in-flight claim on ${repo} declares a surface that meets this one${verdict.notCompared?.length > 0 ? `; ${verdict.notCompared.length} claimed bare name(s) NOT COMPARED, listed below` : ''}. A claimed path fragment deeper inside a dispatched directory, and a claimed glob fragment, are never judged.`;
+ : `check-handover --inflight: clear — no in-flight claim on ${repo} declares a surface that meets this one${verdict.notCompared?.length > 0 ? `; ${verdict.notCompared.length} claimed bare name(s) NOT COMPARED, listed below` : ''}. A claimed path fragment deeper inside a dispatched directory, spelled DIR, DIR/** or DIR/**/GLOB alike, and a claimed glob fragment, are never judged.`;
const lines = [head, ` Dispatch surface: ${paths.map((p) => `\`${p}\``).join(', ')}.`];
verdict.overlaps.forEach((h, i) => {
const how = { path: '', name: ' (a bare file name on the claim, read anywhere)', suffix: ' (a path fragment on the claim, read as a suffix)' };
@@ -1609,7 +1609,7 @@ export function selfTest() {
t('inflight: N4 — a clear run NAMES the claimed bare names it could not judge against a directory or `DIR/**`; a `No changes outside …` clause is surface, not a fence', n4.exit === EXIT_OK && n4.notCompared.map((x) => x.claimed).join() === 'package.json' && inflightText(n4, { repo: 'o/r', paths: ['scripts/pm/**'], read: 'x' }).includes('1 claimed bare name(s) NOT COMPARED') && surfaceTokens('No changes outside `packages/lint/**`.').paths.join() === 'packages/lint/**');
t('inflight: ⭐ S5 — ONE directory, two spellings, one answer: a fragment that starts inside `DIR` meets `DIR` and `DIR/**` alike; a deeper fragment meets neither, and the clear line says so', meetKind('.claude/skills/pm-dispatch/references', 'references/contract-review.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**', 'references/contract-review.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**', 'lanes/director.md') === null && meetKind('.claude/skills/pm-dispatch/references', 'lanes/director.md') === null && inflightText(inflightVerdict({ paths: ['x/y.md'], held: [] }), { repo: 'o/r', paths: ['x/y.md'], read: 'x' }).includes('deeper inside a dispatched directory'));
- t('inflight: ⭐ N12 — a glob under the directory a fragment starts inside answers as the bare `DIR/**` does: `references/**/*.md` meets `references/contract-review.md`, a remainder that does not match (`**/*.ts`) and a fragment that would sit deeper (`pm-dispatch/**/*.md`) do not', meetKind('.claude/skills/pm-dispatch/references/**/*.md', 'references/contract-review.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**/*.md', 'references/lanes/director.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**/*.ts', 'references/contract-review.md') === null && meetKind('.claude/skills/pm-dispatch/**/*.md', 'references/contract-review.md') === null && meetKind('.claude/skills/pm-dispatch/xreferences/**/*.md', 'references/contract-review.md') === null);
+ t('inflight: ⭐ N12 — a glob under the directory a fragment starts inside answers as the bare `DIR/**` does: `references/**/*.md` meets `references/contract-review.md`, a remainder that does not match (`**/*.ts`) and a fragment that would sit deeper (`pm-dispatch/**/*.md`) do not, and the clear line names that deeper case', meetKind('.claude/skills/pm-dispatch/references/**/*.md', 'references/contract-review.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**/*.md', 'references/lanes/director.md') === 'suffix' && meetKind('.claude/skills/pm-dispatch/references/**/*.ts', 'references/contract-review.md') === null && meetKind('.claude/skills/pm-dispatch/**/*.md', 'references/contract-review.md') === null && meetKind('.claude/skills/pm-dispatch/xreferences/**/*.md', 'references/contract-review.md') === null && inflightText(inflightVerdict({ paths: ['x/y.md'], held: [] }), { repo: 'o/r', paths: ['x/y.md'], read: 'x' }).includes('deeper inside a dispatched directory, spelled DIR, DIR/** or DIR/**/GLOB alike'));
t('inflight: N8 — a single-segment dispatch directory (`scripts/`) lists a claimed bare name NOT COMPARED, like `scripts/pm/` and `scripts/**`', ['scripts/', 'scripts/pm/', 'scripts/**'].map((d) => inflightVerdict({ paths: [d], held: [{ issue: IF_CARD(), ...inflightSurface(IF_CARD(), [IF_CLAIM('File surface: `card-pick.mjs`.')]) }] }).notCompared.length).join() === '1,1,1');
// The claim-surface card, PR A: the qualified key, each claim's width, and the reconciliation against its pull.
diff --git a/scripts/pm/check-owed-reviews.mjs b/scripts/pm/check-owed-reviews.mjs
index 52a8976a2f7..3d61702e249 100644
--- a/scripts/pm/check-owed-reviews.mjs
+++ b/scripts/pm/check-owed-reviews.mjs
@@ -137,7 +137,7 @@ export const EXIT_USAGE = 2;
export const DEFAULT_REPO = 'objectstack-ai/objectstack';
/** The waiting label the dispatching seat hangs at ACCEPT (`references/contract-review.md` 〈等 L2 标记〉). */
export const WAITING_LABEL = 'needs:contract-review';
-/** One full round, trigger (b): `round-open.mjs`'s `ROUND_MINUTES`, the number on `seat-lifecycle.md`'s round line — one source, never a second copy. The name is kept: importers read it. */
+/** One full round, trigger (b): `round-open.mjs`'s `ROUND_MINUTES`, the number on `seat-lifecycle.md`'s round line — one source, never a second copy. The name is kept because this file reads it (the trigger (b) docblock above, `owedReviewRow`); nothing imports it. */
export const TRIAGE_ROUND_MINUTES = ROUND_MINUTES;
/** The seat posts' label (`seat-post-protocol.md`); `parseSeat` reads each one. */
export const SEAT_LABEL = 'pm:seat';
diff --git a/scripts/pm/check-skill-line-ratchet.mjs b/scripts/pm/check-skill-line-ratchet.mjs
index 8edc49bab6f..503f487f638 100644
--- a/scripts/pm/check-skill-line-ratchet.mjs
+++ b/scripts/pm/check-skill-line-ratchet.mjs
@@ -136,7 +136,7 @@ export const CEILINGS = new Map([
['.claude/skills/pm-dispatch/references/lanes/queue.md', 2003],
['.claude/skills/pm-dispatch/references/lanes/cloud.md', 1232],
['.claude/skills/pm-dispatch/references/lanes/objectstack.md', 2540], // raised 2270 → 2540 by the ruled text (one seat per lane by default; a new `area:*` is a partition of that seat), ruling record 7030459053
- ['.claude/agents/os-dev.md', 33500], // lowered 33504 → 33500 by the #35237 slice-10 entry-pointers PR (the file's landed size, headroom 0); before that: lowered 38986 → 33504 by the entry-file slimming PR (four one-path blocks moved verbatim to references/dev-traps.md and references/dev-ablation.md, one pointer line left for each); before that: lowered 39008 → 38848 by the re-basing PR's own edit; raised 38848 → 38986 (+138) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」): a card thread's first step reads the tier it is served and compares it with the order
+ ['.claude/agents/os-dev.md', 33492], // lowered 33500 → 33492 by the #35237 slice-13 PR (rule 1's probe line spells its --branch; the file's landed size, headroom 0); before that: lowered 33504 → 33500 by the #35237 slice-10 entry-pointers PR (the file's landed size, headroom 0); before that: lowered 38986 → 33504 by the entry-file slimming PR (four one-path blocks moved verbatim to references/dev-traps.md and references/dev-ablation.md, one pointer line left for each); before that: lowered 39008 → 38848 by the re-basing PR's own edit; raised 38848 → 38986 (+138) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」): a card thread's first step reads the tier it is served and compares it with the order
['.claude/skills/checklist-test/SKILL.md', 14209], // lowered 19558 → 14209 by the entry-file slimming PR (the bodies of §5 and §6 moved verbatim to the two reference files below, one pointer line left in each section)
['.claude/skills/checklist-test/references/closure.md', 4553], // new row, landed size, headroom 0
['.claude/skills/checklist-test/references/standing-regression.md', 1261], // new row, landed size, headroom 0
diff --git a/scripts/pm/dev-worktree.sh b/scripts/pm/dev-worktree.sh
index f38cec4a4b5..dd5158ea034 100644
--- a/scripts/pm/dev-worktree.sh
+++ b/scripts/pm/dev-worktree.sh
@@ -139,9 +139,15 @@ refuse() {
# The two misreadings are not equal: a failure wrongly read as 403 stops one
# run early, and one wrongly read as network costs a bounded handful of pushes
# — neither is a loop, and anything this cannot place is `other`: stop.
-# Every other 4xx status is `other` in each spelling git prints it — the bare
-# line and `RPC failed; HTTP 401` alike, although the second carries the words
-# of a transport failure: a client error does not change on a retry.
+# Three 4xx statuses, and every 5xx, are the path failing rather than the push
+# being judged, so they read `network`: 408 (the connection timed out before
+# the request arrived whole), 421 (the request reached a connection that cannot
+# answer for this host; a new connection can) and 429 (the path is throttled
+# for now, and its remedy is the wait the backoff schedule already is). They
+# are keyed exactly as the next arm is, ahead of it. Every other 4xx status is
+# `other` in each spelling git prints it — the bare line and `RPC failed; HTTP
+# 401` alike, although the second carries the words of a transport failure: a
+# client error the server judged on the request does not change on a retry.
# ---------------------------------------------------------------------------
classify_push_failure() {
local out="$1"
@@ -149,6 +155,10 @@ classify_push_failure() {
printf '403\n'
return 0
fi
+ if printf '%s\n' "$out" | grep -Eq '(error:|HTTP(/[0-9.]+)?|status|code|response)[ :]+(408|421|429|5[0-9][0-9])([^0-9]|$)'; then
+ printf 'network\n'
+ return 0
+ fi
if printf '%s\n' "$out" | grep -Eq '(error:|HTTP(/[0-9.]+)?|status|code|response)[ :]+4[0-9][0-9]([^0-9]|$)'; then
printf 'other\n'
return 0
@@ -263,11 +273,17 @@ probe_push() {
# The second run that completes a tree built without --probe: this run's own
# flags, verbatim, plus `--probe --no-install` — the tree is already installed,
-# or was left to you, so the second run repeats no install.
+# or was left to you, so the second run repeats no install. A flag made only of
+# characters no shell reads specially is printed as typed; any other is quoted
+# with `printf %q`, which alone would print `--backoff=2,4` as `--backoff=2\,4`.
rerun_with_probe() {
local a line='bash scripts/pm/dev-worktree.sh'
for a in "${ORIG_ARGS[@]}"; do
- [ "$a" = '--no-install' ] || line="$line $(printf '%q' "$a")"
+ [ "$a" = '--no-install' ] && continue
+ case "$a" in
+ '' | *[!A-Za-z0-9_./=:,@%+-]*) line="$line $(printf '%q' "$a")" ;;
+ *) line="$line $a" ;;
+ esac
done
printf '%s --probe --no-install' "$line"
}
@@ -450,11 +466,11 @@ mode_build() {
# name=minimum, one per line. A battery below its minimum means cases stopped
# running; the roster's own length is pinned too, so a deleted row cannot take
# its floor with it.
-ST_BATTERIES='the probe failure classifier=14
+ST_BATTERIES='the probe failure classifier=19
a fresh worktree=13
refusals before anything is created=13
resume from a claimed sha=11
-the probe=20
+the probe=21
re-run, scratchpad and install=14
what the script never spells=4'
ST_BATTERY_FLOOR=7
@@ -626,6 +642,16 @@ SHIM
"$(classify_push_failure 'error: RPC failed; HTTP 401 curl 22 The requested URL returned error: 401')|$(classify_push_failure 'error: RPC failed; HTTP/2 404')" 'other|other'
st_case 'OpenSSL'\''s "Connection was reset" and an HTTP/2 stream or framing error are network errors, retried like a reset by peer' \
"$(classify_push_failure 'fatal: unable to access: OpenSSL SSL_read: Connection was reset, errno 10054')|$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': HTTP/2 stream 1 was not closed cleanly: PROTOCOL_ERROR (err 1)")|$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': Error in the HTTP2 framing layer")" 'network|network|network'
+ st_case '408 is the path failing, not the push judged: a request timeout is a network error in either spelling, retried on the schedule' \
+ "$(classify_push_failure 'error: RPC failed; HTTP 408 curl 22 The requested URL returned error: 408')|$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 408")" 'network|network'
+ st_case '429 is the path throttled for now: a network error, whose remedy is the wait the schedule already is' \
+ "$(classify_push_failure 'error: RPC failed; HTTP 429 curl 22 The requested URL returned error: 429')|$(classify_push_failure 'error: RPC failed; HTTP/2 429')" 'network|network'
+ st_case '421 is a connection that cannot answer for this host: a network error, which a new connection on the retry can clear' \
+ "$(classify_push_failure 'error: RPC failed; HTTP/2 421')|$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': The requested URL returned error: 421")" 'network|network'
+ st_case 'a proxy that answers the CONNECT with a 5xx is a network error: the 5xx statuses are keyed as the 4xx arm keys its own' \
+ "$(classify_push_failure "fatal: unable to access 'https://github.com/o/r/': Received HTTP code 502 from proxy after CONNECT")" network
+ st_case 'a number no status word keys, or one digit too long, is not a status: a 502-byte count, `code 4290`, an OpenSSL code' \
+ "$(classify_push_failure 'Writing objects: 100% (3/3), 502 bytes | 502.00 KiB/s, done.')|$(classify_push_failure 'remote: fatal: pack rejected (code 4290)')|$(classify_push_failure 'error:0A000126:SSL routines::unexpected eof while reading')" 'other|other|other'
# ── a fresh worktree ──────────────────────────────────────────────────────
st_battery 'a fresh worktree'
@@ -741,14 +767,18 @@ SHIM
# ── the probe ─────────────────────────────────────────────────────────────
st_battery 'the probe'
reset_shim
- out="$(run "$dir/objectstack" --branch=claude/issue-30-noflag --no-install)"
+ out="$(run "$dir/objectstack" --branch=claude/issue-30-noflag --no-install --backoff=2,4)"
rc=$?
st_case '⛔ NO FLAG, the very spelling rule 1 prints (claude/issue--): the tree is built and NOTHING is pushed — zero pushes, origin has no such branch' \
"$rc|$(pushes)|$(field "$out" PROBE)|$(on_origin claude/issue-30-noflag)|$([ -d "$dir/objectstack-issue-30" ] && echo dir)" '0|0|skipped|absent|dir'
st_case '…the base is pinned all the same, and the line printed says what a self-built branch still owes' \
"$(field "$out" BASE)|$(grep -c 'run this command again with --probe' "$err")" "$main_sha|1"
st_case '…and that line spells the whole second run: this run'\''s flags, plus --probe --no-install, never a bare --probe' \
- "$(grep -c -- 'run this command again with --probe: bash scripts/pm/dev-worktree.sh --branch=claude/issue-30-noflag --probe --no-install\.' "$err")" 1
+ "$(grep -c -- 'run this command again with --probe: bash scripts/pm/dev-worktree.sh --branch=claude/issue-30-noflag --backoff=2,4 --probe --no-install\.' "$err")" 1
+ out="$(ORIG_ARGS=(--branch=claude/issue-31-quoted '--scratchpad=/tmp/a b' --backoff=2,4 --no-install) && rerun_with_probe)"
+ st_case '…a flag is printed as typed when no character of it needs quoting (`--backoff=2,4`, never `2\,4`), quoted when one does, and the line pastes back to the very words typed' \
+ "$(printf '%s\n' "$out" | grep -c -- ' --backoff=2,4 ')|$(eval "set -- ${out#bash scripts/pm/dev-worktree.sh }" && printf '%s|' "$@")" \
+ '1|--branch=claude/issue-31-quoted|--scratchpad=/tmp/a b|--backoff=2,4|--probe|--no-install|'
reset_shim
out="$(run "$dir/objectstack" --branch=claude/issue-30-noflag --probe --no-install)"
st_case '…and the same command WITH --probe completes it: one push, the empty branch on origin, nothing re-created' \
diff --git a/scripts/pm/git-history.mjs b/scripts/pm/git-history.mjs
index 0e4d3cd5536..7ce0e2672fa 100644
--- a/scripts/pm/git-history.mjs
+++ b/scripts/pm/git-history.mjs
@@ -2231,10 +2231,18 @@ function selfTest() {
/ambiguous/.test(hexPrefixProblem(full, '0148abc', () => [c2, c38]) ?? '')
&& /not a commit/.test(hexPrefixProblem(full, '0148abc', () => [c2]) ?? '')
&& hexPrefixProblem(full, 'deadbeefdeadbeef') === null);
+ // Through the CLI: spawned from a directory that exists, asking about one that does not, so git's listing fails.
+ const unlistable = spawnSync(process.execPath, [self, 'ancestor', '--commit=deadbeefdeadbeef', `--cwd=${join(full, 'no-such-dir')}`], {
+ cwd: full,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
t('⛔ a listing git could not give is NOT an empty one: a failed `rev-parse --disambiguate` (injected, and real — '
- + 'a cwd that does not exist) is a problem the CLI refuses as usage, never "absent"',
+ + 'a cwd that does not exist) is a problem the CLI refuses as usage, exit 1 with empty stdout, never "absent"',
/could not be checked/.test(hexPrefixProblem(full, '0148abc', () => null) ?? '')
- && /could not be checked/.test(hexPrefixProblem(join(full, 'no-such-dir'), 'deadbeefdeadbeef') ?? ''));
+ && /could not be checked/.test(hexPrefixProblem(join(full, 'no-such-dir'), 'deadbeefdeadbeef') ?? '')
+ && unlistable.status === 1 && unlistable.stdout === '' && /could not be checked/.test(unlistable.stderr),
+ JSON.stringify({ status: unlistable.status, stdout: unlistable.stdout, stderr: unlistable.stderr }));
const usageText = spawnSync(process.execPath, [self, 'ancestor'], { encoding: 'utf8' });
t('the usage line says a proven no is proven against the ref AS LAST FETCHED, so "PROVEN" is not read as "fresh"',
usageText.status === 1 && /a no is proven against [ as last fetched/.test(usageText.stderr), JSON.stringify(usageText.stderr));
From d751790ced3d1c8d998cc6dbc3f9e014317778ec Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:31:50 +0000
Subject: [PATCH 004/162] refactor(example-starter): rename the Starter
namespace from starter to biz (#38405)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_
Fixes #38371
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:新工作区装上的基础模板应用里,公司、联系人、应用、仪表盘和两个数据集的接口名前缀从 starter 换成
biz,界面上的显示名称不变。
- 为什么做:维护者裁定模板应用的前缀改为 biz,替看接口名的搭建者和 AI 去掉像临时代号的前缀,赶在下一次版本发布把模板推上预发市场之前。
- 出错会怎样:只影响新装的模板应用;已经装过旧版的环境保留原有对象不受影响,本改动可以直接撤回。
- 要你做什么:无。
## What changes
The Starter app (`examples/app-starter`) now declares `namespace:
'biz'`, and every API name that carried `starter_` carries `biz_`:
| Was | Now |
|:---|:---|
| `starter_company` | `biz_company` |
| `starter_contact` | `biz_contact` |
| `starter_app` | `biz_app` |
| `starter_overview_dashboard` | `biz_overview_dashboard` |
| `starter_company_metrics` | `biz_company_metrics` |
| `starter_contact_metrics` | `biz_contact_metrics` |
Every reference follows: the contact's company lookup, the company's
related list, the views' `data.object`, the menu, the dashboard widgets'
datasets, the translation keys in both locales, the README listing text
and the boot test. Unchanged, per the ruling: `manifest.id`
(`com.example.starter`), the package name, file names and the display
name. No alias and no retirement window (the Starter installs unmanaged,
ADR-0131 D6).
The blank-template parity test
(`packages/create-objectstack/src/blank-template-starter-parity.test.ts`)
now guards the Starter's namespace as `'biz'`; the blank template itself
keeps `blank_*` and `namespace: 'blank'`. The publish script's self-test
fixture spells the same namespace. One patch changeset for
`@objectstack/example-starter`.
The cloud half is carried by #38373; the knowledge-article card #38372
starts from this branch.
First read (by risk):
1. `examples/app-starter/src/translations/starter.translation.ts`: the
nested object, app, dataset and dashboard keys in both locales; a missed
key would surface as an untranslated label.
2.
`packages/create-objectstack/src/blank-template-starter-parity.test.ts`:
the namespace guard is the one assertion that changed value.
3. `examples/app-starter/test/boot.test.ts`: the install, menu and
uninstall paths now read `biz_*`.
## Tests
- `pnpm --filter @objectstack/example-starter validate`: Validation
passed.
- `pnpm --filter @objectstack/example-starter test`: Test Files 1 passed
(1), Tests 5 passed (5) (installs unmanaged, reads the menu,
uninstalls).
- `pnpm --filter @objectstack/example-starter typecheck`: exit 0.
- `pnpm --filter create-objectstack exec vitest run --maxWorkers=2
src/blank-template-starter-parity.test.ts`: Tests 9 passed (9); `pnpm
--filter create-objectstack typecheck`: exit 0.
- `node scripts/ci/publish-starter-marketplace.mjs --self-test`: 20
cases pass.
- After building the Starter, `--dry-run` prints `"namespace": "biz"`
and `"manifest_id": "com.example.starter"`; the built
`dist/objectstack.json` holds 0 `starter_` names.
All readings at head d11655ca.
## Acceptance notes
- `git grep -n "starter_" -- examples/app-starter
':!examples/app-starter/CHANGELOG.md'` prints nothing at d11655ca.
- Outside `examples/app-starter`, the only remaining `starter_company`
spellings are the two standalone fixtures the card puts out of scope
(`packages/spec/src/stack-nav-platform-object-requires-object.test.ts`,
`packages/lint/src/validate-object-references.test.ts`); neither reads
the Starter.
## Verification
Two-minute check: `pnpm --filter @objectstack/example-starter test`
shows 5 passed, and the menu assertion lists `biz_company`,
`biz_contact`, `sys_task`, `sys_note`.
]Derived local gate subset (dispatch-gates --commands
at d11655ca)
81 derived; 78 run with exit 0 (`check-plugin-teardown-shape
--self-test` first exited 3 on the shallow clone, then 0 after fetching
its pinned fixture commit; `check:i18n-coverage` first refused on
missing builds, then OK after building its prerequisite closure: 15
configs, none new). NOT MEASURED, left to CI:
`check:dual-build-cjs-loads` (needs a whole-workspace build),
`check:type-check-debt` (whole-workspace sweep) and
`check:pm-dispatch-gates` (beyond the foreground cap). Dogfood: not owed
(no `!` title, no narrowing arm).
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb)_
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude
---
.changeset/38371-starter-namespace-biz.md | 10 ++++++++++
examples/app-starter/README.md | 6 +++---
examples/app-starter/objectstack.config.ts | 4 ++--
examples/app-starter/src/apps/starter.app.ts | 8 ++++----
.../src/dashboards/overview.dashboard.ts | 14 +++++++-------
.../src/datasets/company.dataset.ts | 4 ++--
.../src/datasets/contact.dataset.ts | 4 ++--
.../app-starter/src/objects/company.object.ts | 6 +++---
.../app-starter/src/objects/contact.object.ts | 4 ++--
.../src/translations/starter.translation.ts | 18 +++++++++---------
examples/app-starter/src/views/company.view.ts | 6 +++---
examples/app-starter/src/views/contact.view.ts | 6 +++---
examples/app-starter/test/boot.test.ts | 16 ++++++++--------
.../src/blank-template-starter-parity.test.ts | 8 ++++----
scripts/ci/publish-starter-marketplace.mjs | 4 ++--
15 files changed, 64 insertions(+), 54 deletions(-)
create mode 100644 .changeset/38371-starter-namespace-biz.md
diff --git a/.changeset/38371-starter-namespace-biz.md b/.changeset/38371-starter-namespace-biz.md
new file mode 100644
index 00000000000..a62808494dd
--- /dev/null
+++ b/.changeset/38371-starter-namespace-biz.md
@@ -0,0 +1,10 @@
+---
+'@objectstack/example-starter': patch
+---
+
+refactor(example-starter): the Starter app's namespace is now `biz` (was `starter`)
+
+Clause-②: no
+Metadata-protocol: none
+
+Every API name that carried the `starter_` prefix now carries `biz_`: the objects `starter_company` → `biz_company` and `starter_contact` → `biz_contact`, the app `starter_app` → `biz_app`, the dashboard `starter_overview_dashboard` → `biz_overview_dashboard`, and the datasets `starter_company_metrics` → `biz_company_metrics` and `starter_contact_metrics` → `biz_contact_metrics`, with their translation keys in both locales. The manifest id stays `com.example.starter`, and the package name and display name are unchanged. No alias is kept: the Starter installs unmanaged, as a copy the organization owns, so an environment that already installed it keeps its `starter_*` objects as they are.
diff --git a/examples/app-starter/README.md b/examples/app-starter/README.md
index ad36a91eb97..9f97e37a57b 100644
--- a/examples/app-starter/README.md
+++ b/examples/app-starter/README.md
@@ -3,8 +3,8 @@
A small, complete app an organization installs and then makes its own:
companies, the people at them, and the platform's tasks and notes in one menu.
-- `src/objects/` — `starter_company` (name, type, industry, website, phone,
- address) and `starter_contact` (name, company, job title, influence, email,
+- `src/objects/` — `biz_company` (name, type, industry, website, phone,
+ address) and `biz_contact` (name, company, job title, influence, email,
phone). A contact is a person outside the organization, never a user.
- `src/views/` — a grid and a board for each object. The create and edit form
is each object's `fieldGroups`; the company's record page lists its contacts.
@@ -15,7 +15,7 @@ companies, the people at them, and the platform's tasks and notes in one menu.
- `src/data/` — five sample companies and six sample contacts.
- `src/translations/` — English and Simplified Chinese.
-The API names carry the `starter_` namespace, so a tenant can install this
+The API names carry the `biz_` namespace, so a tenant can install this
starter beside a CRM package without a name clash. Uninstalling the package
removes companies and contacts; tasks and notes stay.
diff --git a/examples/app-starter/objectstack.config.ts b/examples/app-starter/objectstack.config.ts
index a9f53fd9b0e..a5b0560fd30 100644
--- a/examples/app-starter/objectstack.config.ts
+++ b/examples/app-starter/objectstack.config.ts
@@ -15,7 +15,7 @@ import { StarterSeedData } from './src/data/index.js';
* and notes in the same menu.
*
* A small, complete app an organization installs and then makes its own: two
- * objects (`starter_company`, `starter_contact`), a grid and a board for each,
+ * objects (`biz_company`, `biz_contact`), a grid and a board for each,
* the company's contacts on its record page, sample rows, and one dashboard.
* Tasks and notes are not part of the package: the menu points at the
* platform's `sys_task` and `sys_note`, so they stay when the package goes.
@@ -23,7 +23,7 @@ import { StarterSeedData } from './src/data/index.js';
export default defineStack({
manifest: {
id: 'com.example.starter',
- namespace: 'starter',
+ namespace: 'biz',
version: '0.1.0',
type: 'app',
name: 'Starter',
diff --git a/examples/app-starter/src/apps/starter.app.ts b/examples/app-starter/src/apps/starter.app.ts
index 767c9f15e9b..ce8f4ad19aa 100644
--- a/examples/app-starter/src/apps/starter.app.ts
+++ b/examples/app-starter/src/apps/starter.app.ts
@@ -12,7 +12,7 @@ import { App } from '@objectstack/spec/ui';
* label: each shows the current, localized label of what it opens.
*/
export const StarterApp = App.create({
- name: 'starter_app',
+ name: 'biz_app',
label: 'Starter',
icon: 'rocket',
branding: {
@@ -20,13 +20,13 @@ export const StarterApp = App.create({
},
navigation: [
- { id: 'nav_companies', type: 'object', objectName: 'starter_company', icon: 'building-2' },
- { id: 'nav_contacts', type: 'object', objectName: 'starter_contact', icon: 'contact' },
+ { id: 'nav_companies', type: 'object', objectName: 'biz_company', icon: 'building-2' },
+ { id: 'nav_contacts', type: 'object', objectName: 'biz_contact', icon: 'contact' },
// `requiresObject` names the object again because `defineStack` refuses a
// menu entry for an object the stack does not declare unless the entry
// says the object comes from elsewhere — here, the platform.
{ id: 'nav_tasks', type: 'object', objectName: 'sys_task', requiresObject: 'sys_task', icon: 'square-check' },
{ id: 'nav_notes', type: 'object', objectName: 'sys_note', requiresObject: 'sys_note', icon: 'notebook-pen' },
- { id: 'nav_overview', type: 'dashboard', dashboardName: 'starter_overview_dashboard', icon: 'layout-dashboard' },
+ { id: 'nav_overview', type: 'dashboard', dashboardName: 'biz_overview_dashboard', icon: 'layout-dashboard' },
],
});
diff --git a/examples/app-starter/src/dashboards/overview.dashboard.ts b/examples/app-starter/src/dashboards/overview.dashboard.ts
index 504fa4aa1d8..7bba4d03bdf 100644
--- a/examples/app-starter/src/dashboards/overview.dashboard.ts
+++ b/examples/app-starter/src/dashboards/overview.dashboard.ts
@@ -7,7 +7,7 @@ import { Dashboard } from '@objectstack/spec/ui';
* Every widget binds to one of the two datasets (ADR-0021).
*/
export const OverviewDashboard = Dashboard.create({
- name: 'starter_overview_dashboard',
+ name: 'biz_overview_dashboard',
label: 'Overview',
description: 'Companies and contacts at a glance.',
columns: 12,
@@ -17,7 +17,7 @@ export const OverviewDashboard = Dashboard.create({
type: 'metric',
title: 'Companies',
description: 'Every company, whatever its type.',
- dataset: 'starter_company_metrics',
+ dataset: 'biz_company_metrics',
values: ['company_count'],
layout: { x: 0, y: 0, w: 4, h: 2 },
},
@@ -27,7 +27,7 @@ export const OverviewDashboard = Dashboard.create({
title: 'Customers',
description: 'Companies whose type is Customer.',
filter: { type: 'customer' },
- dataset: 'starter_company_metrics',
+ dataset: 'biz_company_metrics',
values: ['company_count'],
layout: { x: 4, y: 0, w: 4, h: 2 },
},
@@ -36,7 +36,7 @@ export const OverviewDashboard = Dashboard.create({
type: 'metric',
title: 'Contacts',
description: 'Every contact.',
- dataset: 'starter_contact_metrics',
+ dataset: 'biz_contact_metrics',
values: ['contact_count'],
layout: { x: 8, y: 0, w: 4, h: 2 },
},
@@ -45,7 +45,7 @@ export const OverviewDashboard = Dashboard.create({
type: 'bar',
title: 'Companies by Type',
description: 'How many companies there are of each type.',
- dataset: 'starter_company_metrics',
+ dataset: 'biz_company_metrics',
dimensions: ['type'],
values: ['company_count'],
layout: { x: 0, y: 2, w: 6, h: 4 },
@@ -55,7 +55,7 @@ export const OverviewDashboard = Dashboard.create({
type: 'pie',
title: 'Companies by Industry',
description: 'How the companies split across industries.',
- dataset: 'starter_company_metrics',
+ dataset: 'biz_company_metrics',
dimensions: ['industry'],
values: ['company_count'],
layout: { x: 6, y: 2, w: 6, h: 4 },
@@ -65,7 +65,7 @@ export const OverviewDashboard = Dashboard.create({
type: 'bar',
title: 'Contacts by Company',
description: 'How many contacts each company has.',
- dataset: 'starter_contact_metrics',
+ dataset: 'biz_contact_metrics',
dimensions: ['company'],
values: ['contact_count'],
layout: { x: 0, y: 6, w: 12, h: 4 },
diff --git a/examples/app-starter/src/datasets/company.dataset.ts b/examples/app-starter/src/datasets/company.dataset.ts
index 57e490ea8c1..cbe63a27e1e 100644
--- a/examples/app-starter/src/datasets/company.dataset.ts
+++ b/examples/app-starter/src/datasets/company.dataset.ts
@@ -7,10 +7,10 @@ import { defineDataset } from '@objectstack/spec/ui';
* select the dimension and measure by name.
*/
export const CompanyDataset = defineDataset({
- name: 'starter_company_metrics',
+ name: 'biz_company_metrics',
label: 'Company Metrics',
description: 'How many companies there are, by type and by industry',
- object: 'starter_company',
+ object: 'biz_company',
dimensions: [
{
diff --git a/examples/app-starter/src/datasets/contact.dataset.ts b/examples/app-starter/src/datasets/contact.dataset.ts
index bc149ba406d..d443afccf33 100644
--- a/examples/app-starter/src/datasets/contact.dataset.ts
+++ b/examples/app-starter/src/datasets/contact.dataset.ts
@@ -6,10 +6,10 @@ import { defineDataset } from '@objectstack/spec/ui';
* Contact counts (ADR-0021): the dashboard's contact tiles bind here.
*/
export const ContactDataset = defineDataset({
- name: 'starter_contact_metrics',
+ name: 'biz_contact_metrics',
label: 'Contact Metrics',
description: 'How many contacts there are, by company and by influence',
- object: 'starter_contact',
+ object: 'biz_contact',
dimensions: [
{
diff --git a/examples/app-starter/src/objects/company.object.ts b/examples/app-starter/src/objects/company.object.ts
index 2796c0c3d45..f3cdf217d35 100644
--- a/examples/app-starter/src/objects/company.object.ts
+++ b/examples/app-starter/src/objects/company.object.ts
@@ -6,7 +6,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
* A company the organization works with — a customer, a prospect, a supplier
* or a partner.
*
- * The API names carry the package namespace (`starter_`), so a tenant that
+ * The API names carry the package namespace (`biz_`), so a tenant that
* installs this starter beside a CRM package keeps both: the CRM's own account
* and contact objects use other names.
*
@@ -14,7 +14,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
* `owner_id` column, set to the creator on insert.
*/
export const Company = ObjectSchema.create({
- name: 'starter_company',
+ name: 'biz_company',
// Shared inside the organization: a starter workspace where everyone sees
// every company. An organization that wants owner-only records changes this
// after it installs the starter.
@@ -78,6 +78,6 @@ export const Company = ObjectSchema.create({
// The company's record page lists its contacts.
relatedLists: [
- { list: 'starter_contact', columns: ['name', 'title', 'email', 'phone'] },
+ { list: 'biz_contact', columns: ['name', 'title', 'email', 'phone'] },
],
});
diff --git a/examples/app-starter/src/objects/contact.object.ts b/examples/app-starter/src/objects/contact.object.ts
index a4ddb36a1fb..eb675fd266d 100644
--- a/examples/app-starter/src/objects/contact.object.ts
+++ b/examples/app-starter/src/objects/contact.object.ts
@@ -10,7 +10,7 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
* company (`company`), and the company's record page lists its contacts.
*/
export const Contact = ObjectSchema.create({
- name: 'starter_contact',
+ name: 'biz_contact',
// Shared inside the organization, as the companies are.
sharingModel: 'public_read_write',
label: 'Contact',
@@ -28,7 +28,7 @@ export const Contact = ObjectSchema.create({
searchable: true,
maxLength: 120,
}),
- company: Field.lookup('starter_company', {
+ company: Field.lookup('biz_company', {
label: 'Company',
}),
title: Field.text({
diff --git a/examples/app-starter/src/translations/starter.translation.ts b/examples/app-starter/src/translations/starter.translation.ts
index 562da8ca235..72af5a4d728 100644
--- a/examples/app-starter/src/translations/starter.translation.ts
+++ b/examples/app-starter/src/translations/starter.translation.ts
@@ -11,7 +11,7 @@ import { defineTranslationBundle } from '@objectstack/spec/system';
export const StarterTranslationBundle = defineTranslationBundle({
en: {
objects: {
- starter_company: {
+ biz_company: {
label: 'Company',
pluralLabel: 'Companies',
fields: {
@@ -25,7 +25,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
owner_id: { label: 'Owner' },
},
},
- starter_contact: {
+ biz_contact: {
label: 'Contact',
pluralLabel: 'Contacts',
fields: {
@@ -41,7 +41,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
},
},
apps: {
- starter_app: {
+ biz_app: {
label: 'Starter',
description: 'Companies and contacts, with tasks and notes',
},
@@ -54,7 +54,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
'com.example.starter': { name: '入门示例', description: '公司与联系人,菜单中附带平台的任务和备注。' },
},
objects: {
- starter_company: {
+ biz_company: {
label: '公司',
pluralLabel: '公司',
description: '与本组织往来的公司。',
@@ -98,7 +98,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
more: { label: '更多' },
},
},
- starter_contact: {
+ biz_contact: {
label: '联系人',
pluralLabel: '联系人',
description: '往来公司里的人,不是本组织的员工。',
@@ -132,13 +132,13 @@ export const StarterTranslationBundle = defineTranslationBundle({
},
},
apps: {
- starter_app: {
+ biz_app: {
label: '起步应用',
description: '公司和联系人,以及任务和备忘',
},
},
datasets: {
- starter_company_metrics: {
+ biz_company_metrics: {
label: '公司统计',
description: '公司有多少家,按类型和行业分',
dimensions: {
@@ -152,7 +152,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
company_count: { label: '公司数', description: '公司有多少家,不论类型。' },
},
},
- starter_contact_metrics: {
+ biz_contact_metrics: {
label: '联系人统计',
description: '联系人有多少位,按公司和影响力分',
dimensions: {
@@ -165,7 +165,7 @@ export const StarterTranslationBundle = defineTranslationBundle({
},
},
dashboards: {
- starter_overview_dashboard: {
+ biz_overview_dashboard: {
label: '概览',
description: '公司和联系人一览。',
widgets: {
diff --git a/examples/app-starter/src/views/company.view.ts b/examples/app-starter/src/views/company.view.ts
index 99c232f978c..529538825e3 100644
--- a/examples/app-starter/src/views/company.view.ts
+++ b/examples/app-starter/src/views/company.view.ts
@@ -13,7 +13,7 @@ export const CompanyViews = defineView({
list: {
label: 'All Companies',
type: 'grid',
- data: { provider: 'object', object: 'starter_company' },
+ data: { provider: 'object', object: 'biz_company' },
columns: [
{ field: 'name' },
{ field: 'type' },
@@ -27,7 +27,7 @@ export const CompanyViews = defineView({
all: {
label: 'All Companies',
type: 'grid',
- data: { provider: 'object', object: 'starter_company' },
+ data: { provider: 'object', object: 'biz_company' },
columns: [
{ field: 'name' },
{ field: 'type' },
@@ -40,7 +40,7 @@ export const CompanyViews = defineView({
by_type: {
label: 'Companies by Type',
type: 'kanban',
- data: { provider: 'object', object: 'starter_company' },
+ data: { provider: 'object', object: 'biz_company' },
columns: ['name', 'industry', 'phone'],
kanban: {
groupByField: 'type',
diff --git a/examples/app-starter/src/views/contact.view.ts b/examples/app-starter/src/views/contact.view.ts
index 41bf1f839ed..71b06d8e5ae 100644
--- a/examples/app-starter/src/views/contact.view.ts
+++ b/examples/app-starter/src/views/contact.view.ts
@@ -12,7 +12,7 @@ export const ContactViews = defineView({
list: {
label: 'All Contacts',
type: 'grid',
- data: { provider: 'object', object: 'starter_contact' },
+ data: { provider: 'object', object: 'biz_contact' },
columns: [
{ field: 'name' },
{ field: 'company' },
@@ -26,7 +26,7 @@ export const ContactViews = defineView({
all: {
label: 'All Contacts',
type: 'grid',
- data: { provider: 'object', object: 'starter_contact' },
+ data: { provider: 'object', object: 'biz_contact' },
columns: [
{ field: 'name' },
{ field: 'company' },
@@ -39,7 +39,7 @@ export const ContactViews = defineView({
by_influence: {
label: 'Contacts by Influence',
type: 'kanban',
- data: { provider: 'object', object: 'starter_contact' },
+ data: { provider: 'object', object: 'biz_contact' },
columns: ['name', 'company', 'title'],
kanban: {
groupByField: 'influence',
diff --git a/examples/app-starter/test/boot.test.ts b/examples/app-starter/test/boot.test.ts
index c9c41ef6971..57c5872541f 100644
--- a/examples/app-starter/test/boot.test.ts
+++ b/examples/app-starter/test/boot.test.ts
@@ -95,18 +95,18 @@ describe('app-starter — installed as a starter, menu, uninstall', () => {
// The copy is a writable package of its own, beside the package id.
base = install.body?.data?.targetPackageId;
- app = await call('GET', '/meta/app/starter_app');
- companies = await call('GET', '/data/starter_company');
- contacts = await call('GET', '/data/starter_contact');
+ app = await call('GET', '/meta/app/biz_app');
+ companies = await call('GET', '/data/biz_company');
+ contacts = await call('GET', '/data/biz_contact');
task = await call('POST', '/data/sys_task', { title: 'Call Northwind about the renewal' });
note = await call('POST', '/data/sys_note', { title: 'Northwind visit', body: 'Met the purchasing team.' });
uninstall = await call('DELETE', `/packages/${base}`);
- after.company = await call('GET', '/meta/object/starter_company');
- after.contact = await call('GET', '/meta/object/starter_contact');
- after.app = await call('GET', '/meta/app/starter_app');
+ after.company = await call('GET', '/meta/object/biz_company');
+ after.contact = await call('GET', '/meta/object/biz_contact');
+ after.app = await call('GET', '/meta/app/biz_app');
after.task = await call('GET', `/data/sys_task/${unwrap(task)?.id}`);
after.note = await call('GET', `/data/sys_note/${unwrap(note)?.id}`);
}, 180_000);
@@ -132,8 +132,8 @@ describe('app-starter — installed as a starter, menu, uninstall', () => {
const objectEntries = (unwrap(app)?.navigation ?? [])
.filter((n: any) => n.type === 'object')
.map((n: any) => n.objectName);
- expect(objectEntries).toEqual(['starter_company', 'starter_contact', 'sys_task', 'sys_note']);
- expect((stack.objects ?? []).map((o) => o.name).sort()).toEqual(['starter_company', 'starter_contact']);
+ expect(objectEntries).toEqual(['biz_company', 'biz_contact', 'sys_task', 'sys_note']);
+ expect((stack.objects ?? []).map((o) => o.name).sort()).toEqual(['biz_company', 'biz_contact']);
});
it('precondition: a task and a note were written before the uninstall', () => {
diff --git a/packages/create-objectstack/src/blank-template-starter-parity.test.ts b/packages/create-objectstack/src/blank-template-starter-parity.test.ts
index 730729c832c..c029449c6b3 100644
--- a/packages/create-objectstack/src/blank-template-starter-parity.test.ts
+++ b/packages/create-objectstack/src/blank-template-starter-parity.test.ts
@@ -16,12 +16,12 @@
//
// ## What "equal" means: the code, modulo the namespace, blind to comments
//
-// The Starter names its objects under its own namespace (`starter_company`);
+// The Starter names its objects under its own namespace (`biz_company`);
// the template names them under the template's (`blank_company`), and the
// scaffolder moves every such literal onto the project's namespace
// (`rewriteObjectNamePrefix`, which rewrites every quoted `blank_…` literal,
// references included — see `rewrite-identity.test.ts`). So the Starter's
-// source is compared with `starter_` literals spelled `blank_`, and nothing
+// source is compared with `biz_` literals spelled `blank_`, and nothing
// else changed.
//
// Comments are NOT compared. The template's comments are written for a
@@ -50,7 +50,7 @@ const BLANK_SRC = path.join(BLANK, 'src');
const STARTER_SRC = path.resolve(HERE, '../../../examples/app-starter/src');
const STARTER_CONFIG = path.resolve(HERE, '../../../examples/app-starter/objectstack.config.ts');
-/** The template's namespace, from its config: what every `starter_` literal is spelled as here. */
+/** The template's namespace, from its config: what every `biz_` literal is spelled as here. */
const BLANK_NAMESPACE = /\bnamespace:\s*'([a-z0-9_]+)'/.exec(
fs.readFileSync(path.join(BLANK, 'objectstack.config.ts'), 'utf8'),
)?.[1];
@@ -117,7 +117,7 @@ const PAIRS = [
describe('blank template — the Starter app\'s companies and contacts, as source', () => {
it('reads two real namespaces (vacuity guard)', () => {
expect(BLANK_NAMESPACE).toBe('blank');
- expect(STARTER_NAMESPACE).toBe('starter');
+ expect(STARTER_NAMESPACE).toBe('biz');
});
it.each(PAIRS)('the $what is the Starter\'s definition, modulo the namespace', ({ file, callee }) => {
diff --git a/scripts/ci/publish-starter-marketplace.mjs b/scripts/ci/publish-starter-marketplace.mjs
index 996f10d31c8..7e07829c208 100644
--- a/scripts/ci/publish-starter-marketplace.mjs
+++ b/scripts/ci/publish-starter-marketplace.mjs
@@ -389,8 +389,8 @@ function fixtureDir({ objects = 1, id = STARTER_MANIFEST_ID, manifestVersion = '
if (dist) {
fs.mkdirSync(path.join(dir, 'dist'));
const artifact = {
- manifest: { id, namespace: 'starter', version: manifestVersion, type: 'app', name: 'Starter', description: 'Companies and contacts.' },
- objects: Array.from({ length: objects }, (_, i) => ({ name: `starter_o${i}` })),
+ manifest: { id, namespace: 'biz', version: manifestVersion, type: 'app', name: 'Starter', description: 'Companies and contacts.' },
+ objects: Array.from({ length: objects }, (_, i) => ({ name: `biz_o${i}` })),
apps: [{ name: 'starter' }],
};
fs.writeFileSync(path.join(dir, 'dist', 'objectstack.json'), JSON.stringify(artifact));
From dee75315c38d85b77d96543672d691cbaa995864 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:38:28 +0000
Subject: [PATCH 005/162] fix(react): an action gated on a deployment feature
shows when that feature is on (#38408)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Sales** · [project
thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu1qwDPHjy2whY6EPpDtLVUY)_
Fixes #38385
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:部署开了两步验证后,用户打开自己的记录页,能看到「Enable Two-Factor
Auth」按钮了;其他按部署功能开关显示的按钮(比如团队、OAuth 应用、邀请相关的按钮)也按开关正确显示或隐藏。
- 为什么做:控制台判断这类按钮该不该显示时,没有拿到部署的功能开关,判断直接报错,按钮就一律被藏起来,功能开着也没人能自己开启两步验证。
- 出错会怎样:最坏是某个按功能开关的按钮在开关关着时也显示出来,点了会被服务端拒绝;只改控制台一处取值,可以直接撤回。
- 要你做什么:无。
## What changes
The console's action runner now binds the predicate scope's `features`
root (the deployment's `/auth/config` flags), beside the `current_user`
it already bound.
- **Cause, measured.** `requiresFeature: 'twoFactor'` is lowered at
parse time into a `visible` conjunct `… && features.twoFactor == true`
(`featureGatePredicate`, `@objectstack/spec/kernel`).
`ActionEngine.getActionsForLocation` evaluates `visible` against the
runner's bag with `throwOnError: true`. That bag is the host's context
plus `current_user` from the predicate scope; `features` was never on
it, so the predicate faulted and the action hid fail-closed. A probe on
main `c610020e` with the exact `sys_user.enable_two_factor` predicate
under `ActionProvider` above `PredicateScopeProvider` (the console's
arrangement) printed the card's warning verbatim and returned no action;
the same predicate without the `features` conjunct showed the action. So
the identifier that throws is `features`, not `ctx` or `ctx.user`.
- **Fix.** New `useRunnerScopeBindings`
(`ui/packages/react/src/hooks/useRunnerScopeBindings.ts`, not exported
from the package entry) returns the scope roots a runner binds,
`current_user` and `features`, with one content key for memo
dependencies. `useActionEngine` (shared and standalone runners) and
`ActionProvider` (its own runner) both use it, so the two writes cannot
drift apart. A root the scope does not carry is not bound, as before.
- **Reach.** The fix is where the context is built, so every
`features.*` action gate on this path evaluates: the three
`requiresFeature: 'twoFactor'` actions on `sys_user`, the `organization`
and `oidcProvider` gates on `sys_team`, `sys_team_member` and
`sys_oauth_application`, and the hand-written `features.cloudManaged !=
true` gates on `sys_user`, `sys_member` and `sys_invitation`.
- `.changeset/38385-action-runner-features-root.md`: `@object-ui/react`
patch.
## Tests
New top-level describe in
`ui/packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx`
(the existing `useActionEngine` × `ActionProvider` harness), 8 cases.
The two actions are lowered by the spec's own `ActionSchema` from the
shapes `sys_user.enable_two_factor` and `sys_team.create_team` declare,
so a change to the lowering is read here too.
- the spec lowers both gates onto `features` (`== true` for opt-in
`twoFactor`, `!= false` for default-on `organization`);
- for each of three arrangements (provider above the scope, provider
inside it, standalone): flags on, both actions show and both gates
evaluate `true`; flags off, both hide and both gates evaluate `false`
without throwing (the engine warns once per predicate per module, so the
hide is also checked by evaluating each gate fail-closed on the bag the
engine read);
- `ActionProvider`'s own runner carries `features` and `current_user`
from a scope above it.
Reverse verification: with `useActionEngine.ts` and `ActionContext.tsx`
restored to main (tree only, fix committed first), 7 of the 8 new cases
fail; with the fix, all 11 in the file pass. `@object-ui/react` package
test: 141 files, 1609 tests passed. `tsc --noEmit` on
`ui/packages/react` `tsconfig.json` and `tsconfig.test.json`: exit 0.
## Acceptance notes
- The claim's file surface names `ui/packages/core`. The action engine
there is unchanged: the runner's bag is built in `@object-ui/react`
(`useActionEngine` and `ActionProvider`), which is where `current_user`
is already bound from the predicate scope, and `core` has no access to
that scope. `sys-user.object.ts` is unchanged: the predicate is right.
- Only the top-level `features` root is bound, the root the spec lowers
onto. `ctx.features` is not added: no action predicate in
`packages/platform-objects` reads it.
- A flag the server does not serve (absent from `features`) still faults
and hides, as it did; the flags the auth plugin serves are booleans, so
an on and an off deployment both answer by verdict.
- Platform checklist: two-factor enrolment is already covered
(`identity-auth.two-factor-enrollment-reveal` and its siblings name
`enable_two_factor`), so no item is added.
- Not measured in a browser: the reproduction from the card (production
`objectstack start` with `OS_AUTH_TWO_FACTOR=true`) was not re-run; the
pins drive the same hooks the record page mounts.
- Branch `claude/project-thread-9ndw7c` is assigned by the harness, not
the repo's `claude/issue-N-…` convention.
## Verification
Two-minute check: `pnpm --dir ui exec vitest run
packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx`,
expect 11 passed.
Read first, by risk: `ui/packages/react/src/hooks/useActionEngine.ts`
(the engine memo now reads `scopeBound`),
`ui/packages/react/src/context/ActionContext.tsx` (the binding memo),
`ui/packages/react/src/hooks/useRunnerScopeBindings.ts`.
Gates at 646c3313
- `dispatch-gates.mjs --commands` derived 38 families from this tree
(objectstack-ai/objectstack at 646c3313); all 38 ran locally, each exit
0. `dispatch-gates.mjs --ran` on the record with exit codes: 38 derived,
38 run, 0 NOT-MEASURED, 0 UNRUN.
- `overlap-check.mjs` against origin/main c610020e: VERDICT clean (0 PR
heads read; the claim records that no open PR of the seat edits these
files).
- `@object-ui/react` test: 141 files, 1609 tests passed. `tsc --noEmit`
on its `tsconfig.json` and `tsconfig.test.json`: exit 0.
- CI at 646c3313 when written: 36 success, 13 skipped, 0 failed, 8 in
progress.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01L6bhgWZUEXV9XJ6bqbPqzh)_
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L6bhgWZUEXV9XJ6bqbPqzh
---------
Co-authored-by: Claude
---
.../38385-action-runner-features-root.md | 10 ++
.../react/src/context/ActionContext.tsx | 56 ++++----
.../useActionEngine.sharedRunner.test.tsx | 122 +++++++++++++++++-
.../react/src/hooks/useActionEngine.ts | 52 +++-----
.../react/src/hooks/useRunnerScopeBindings.ts | 68 ++++++++++
5 files changed, 242 insertions(+), 66 deletions(-)
create mode 100644 .changeset/38385-action-runner-features-root.md
create mode 100644 ui/packages/react/src/hooks/useRunnerScopeBindings.ts
diff --git a/.changeset/38385-action-runner-features-root.md b/.changeset/38385-action-runner-features-root.md
new file mode 100644
index 00000000000..f3a9a3f3173
--- /dev/null
+++ b/.changeset/38385-action-runner-features-root.md
@@ -0,0 +1,10 @@
+---
+'@object-ui/react': patch
+---
+
+fix(react): an action gated on a deployment feature shows when that feature is on
+
+Clause-②: no
+Metadata-protocol: none
+
+An action declared with `requiresFeature` (its `visible` gets a `features.` conjunct at parse time), or with a hand-written `features.*` gate, was hidden in the Console even when the feature was on: the action runner evaluated it without the deployment's `features` flags, so the predicate faulted and the action hid fail-closed, with an `[ActionEngine] … predicate threw` warning in the browser console. On a deployment with two-factor sign-in on, "Enable Two-Factor Auth" never appeared on a user's own record. `useActionEngine` and `ActionProvider` now bind the predicate scope's `features` onto the runner beside `current_user`, so these gates answer from the served flags: the action shows while its feature is on and stays hidden while it is off. Nothing changes for an action with no feature gate.
diff --git a/ui/packages/react/src/context/ActionContext.tsx b/ui/packages/react/src/context/ActionContext.tsx
index dad41d73895..41a2766741c 100644
--- a/ui/packages/react/src/context/ActionContext.tsx
+++ b/ui/packages/react/src/context/ActionContext.tsx
@@ -16,7 +16,6 @@
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
import {
ActionRunner,
- subjectPermissionsOf,
type ActionContext as ActionCtx,
type ActionDef,
type ActionResult,
@@ -28,7 +27,7 @@ import {
type ResultDialogHandler,
} from '@object-ui/core';
import { useActionRunnerDisplayLocale, useActionRunnerTenantCurrency, useActionRunnerTranslator } from './actionRunnerTranslator.js';
-import { usePredicateScope } from '../hooks/useExpression.js';
+import { useRunnerScopeBindings } from '../hooks/useRunnerScopeBindings.js';
export interface ActionProviderProps {
children: React.ReactNode;
@@ -138,39 +137,34 @@ export const ActionProvider: React.FC = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(context)]);
- // The acting subject the surrounding predicate scope binds as `current_user`
- // (objectui#11242): the ONE object `ExpressionProvider` publishes under
- // `current_user` / `user` / `ctx.user` / `os.user`, carrying the caller's
- // effective object permissions once they have loaded. The runner evaluates
- // its own gates — `execute`'s `disabled` re-check, `params[].visible`, the
- // engine's `visible` filter — against ITS bag, which a host seeds with its
- // own `user` and never with `current_user`. Bound here, every `execute` gate
- // under this provider answers `current_user.can(…)` and every other
- // `current_user.*` predicate, whatever else the page mounts. Before, only
- // `useActionEngine` wrote it onto a shared runner, so the answer depended on
- // whether the page happened to mount `record:quick_actions`, `record:alert`
- // or a dashboard (the objectui#6493 "one bag" rule, broken per page).
- //
- // The same object, not a copy: the engine answers `can` only for a receiver
- // IDENTICAL to the bound `current_user`. Only `current_user` is added — the
- // runner's `user` / `ctx.user` / `os.user` stay the host's object, which
- // carries the `systemPermissions` the capability gate reads — so on this bag
- // `user.can(…)` still faults while `current_user.can(…)` answers. With no
- // scope above this provider (`{}`) nothing is bound, and a host's own
- // `context.current_user`, if it passed one, is left as it is.
+ // The roots of the surrounding predicate scope this runner's bag binds —
+ // `current_user` (objectui#11242) and `features`, the deployment's public auth
+ // flags a `requiresFeature` gate is lowered onto (`useRunnerScopeBindings`
+ // says what each answers and why). The runner evaluates its own gates —
+ // `execute`'s `disabled` re-check, `params[].visible`, the engine's `visible`
+ // filter — against ITS bag, which a host seeds with its own `user` and never
+ // with either root. Bound here, every gate under this provider answers
+ // `current_user.can(…)`, every other `current_user.*` predicate and every
+ // `features.*` flag, whatever else the page mounts. Before, only
+ // `useActionEngine` wrote `current_user` onto a shared runner, so the answer
+ // depended on whether the page happened to mount `record:quick_actions`,
+ // `record:alert` or a dashboard (the objectui#6493 "one bag" rule, broken per
+ // page). Only these two roots are added — the runner's `user` / `ctx.user` /
+ // `os.user` stay the host's object, which carries the `systemPermissions` the
+ // capability gate reads — so on this bag `user.can(…)` still faults while
+ // `current_user.can(…)` answers. With no scope above this provider (`{}`)
+ // nothing is bound, and a host's own context value for either root, if it
+ // passed one, is left as it is.
//
// Bound during render, before any child renders or executes, and keyed on
- // what the binding READS, never on the subject's identity (a memoised value
- // upstream — AGENTS.md #10): its serialisable fields, and the permissions map
- // it carries, which the upstream adapter caches per payload outside React. A
- // new runner (the host `context` changed) is bound again.
- const subject = usePredicateScope().current_user as Record | undefined;
- const subjectKey = subject === undefined ? '' : JSON.stringify(subject);
- const subjectPermissions = subjectPermissionsOf(subject);
+ // what the binding READS, never on the objects' identities (memoised values
+ // upstream — AGENTS.md #10). A new runner (the host `context` changed) is
+ // bound again.
+ const { bound: scopeBound, key: scopeKey, subjectPermissions } = useRunnerScopeBindings();
useMemo(() => {
- if (subject !== undefined) runner.updateContext({ current_user: subject } as Partial);
+ if (Object.keys(scopeBound).length > 0) runner.updateContext(scopeBound as Partial);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [runner, subjectKey, subjectPermissions]);
+ }, [runner, scopeKey, subjectPermissions]);
const execute = useCallback(
async (action: ActionDef): Promise => {
diff --git a/ui/packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx b/ui/packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx
index c4f9a2c344b..8e2bd430a60 100644
--- a/ui/packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx
+++ b/ui/packages/react/src/hooks/__tests__/useActionEngine.sharedRunner.test.tsx
@@ -28,9 +28,12 @@
*/
import React from 'react';
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import { renderHook } from '@testing-library/react';
+import { toPredicateInput } from '@object-ui/core';
+import { ActionSchema } from '@objectstack/spec/ui';
import { useActionEngine } from '../useActionEngine';
+import { PredicateScopeProvider } from '../useExpression';
import { ActionProvider, useAction } from '../../context/ActionContext';
const SELF_ID = 'user-self';
@@ -137,3 +140,120 @@ describe('useActionEngine — shared ActionProvider runner', () => {
expect(visible.sort()).toEqual(['self_only_ctx', 'self_only_flat']);
});
});
+
+/**
+ * A `requiresFeature` gate evaluates on the runner's bag.
+ *
+ * The spec lowers `requiresFeature: ''` at parse time into a `visible`
+ * conjunct on the `features` root (`… && features.twoFactor == true`), and the
+ * console publishes `features` (the deployment's `/auth/config` flags) on the
+ * predicate scope. The engine filters `visible` against the RUNNER's bag, which
+ * bound `current_user` from that scope and not `features`, so every such gate
+ * faulted and the action hid fail-closed: with two-factor on, "Enable
+ * Two-Factor Auth" never showed on the user's own record.
+ *
+ * The actions are lowered by the spec's own `ActionSchema` (the shapes
+ * `sys_user.enable_two_factor` and `sys_team.create_team` declare), not
+ * hand-spelled, so a change to the lowering is read here too. Each state is
+ * pinned in the console's arrangement (the shared provider ABOVE the scope),
+ * with the provider INSIDE the scope, and standalone.
+ */
+describe('useActionEngine — features.* gates bind from the predicate scope', () => {
+ const SELF = { id: SELF_ID };
+ const enableTwoFactor = ActionSchema.parse({
+ name: 'enable_two_factor',
+ label: 'Enable Two-Factor Auth',
+ locations: ['record_section'],
+ type: 'api',
+ target: '/api/v1/auth/two-factor/enable',
+ visible: 'has(record.id) && record.id == ctx.user.id && has(record.two_factor_enabled) && record.two_factor_enabled != true',
+ requiresFeature: 'twoFactor',
+ }) as any;
+ const createTeam = ActionSchema.parse({
+ name: 'create_team',
+ label: 'Create Team',
+ locations: ['record_section'],
+ type: 'api',
+ target: '/api/v1/auth/organization/create-team',
+ requiresFeature: 'organization',
+ }) as any;
+ const ACTIONS = [enableTwoFactor, createTeam];
+ const RECORD = { id: SELF_ID, two_factor_enabled: false };
+
+ afterEach(() => vi.restoreAllMocks());
+
+ function scopeOf(features: Record) {
+ return { current_user: SELF, user: SELF, ctx: { user: SELF }, os: { user: SELF }, features };
+ }
+
+ type Arrangement = 'provider-above-scope' | 'provider-inside-scope' | 'standalone';
+ function visibleUnder(arrangement: Arrangement, features: Record) {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const scope = scopeOf(features);
+ const hostContext = { record: { id: SELF_ID }, user: SELF, objectName: 'sys_user' };
+ const wrapper = ({ children }: { children: React.ReactNode }) => {
+ const scoped = (inner: React.ReactNode) =>
+ React.createElement(PredicateScopeProvider, { scope, children: inner });
+ const provided = (inner: React.ReactNode) =>
+ React.createElement(ActionProvider, { context: hostContext, children: inner });
+ if (arrangement === 'provider-above-scope') return provided(scoped(children));
+ if (arrangement === 'provider-inside-scope') return scoped(provided(children));
+ return scoped(children);
+ };
+ const { result } = renderHook(
+ () =>
+ useActionEngine({
+ actions: ACTIONS,
+ context: arrangement === 'standalone'
+ ? { record: RECORD, recordId: SELF_ID, user: SELF, objectName: 'sys_user' }
+ : { record: RECORD, recordId: SELF_ID, objectName: 'sys_user' },
+ }),
+ { wrapper },
+ );
+ const names = result.current.getActionsForLocation('record_section').map(a => a.name).sort();
+ // The engine warns once per predicate per module, so the warning alone
+ // cannot tell a later hide-by-fault from a hide-by-verdict. Each gate is
+ // therefore also evaluated on the same bag the engine filtered against,
+ // fail-closed: a fault throws here instead of reading as `false`.
+ const evaluator = result.current.engine.getRunner().getEvaluator();
+ const verdicts = Object.fromEntries(
+ ACTIONS.map(a => [a.name, evaluator.evaluateCondition(toPredicateInput(a.visible), { throwOnError: true })]),
+ );
+ const faults = warn.mock.calls.map(c => String(c[0])).filter(m => m.includes('[ActionEngine]'));
+ return { names, faults, verdicts };
+ }
+
+ it('the spec lowers both gates onto the features root', () => {
+ expect(enableTwoFactor.visible.source).toContain('features.twoFactor == true');
+ expect(createTeam.visible.source).toContain('features.organization != false');
+ });
+
+ for (const arrangement of ['provider-above-scope', 'provider-inside-scope', 'standalone'] as const) {
+ it(`${arrangement}: both feature-gated actions show while their flags are on, with no fault`, () => {
+ const { names, faults, verdicts } = visibleUnder(arrangement, { twoFactor: true, organization: true });
+ expect(names).toEqual(['create_team', 'enable_two_factor']);
+ expect(verdicts).toEqual({ enable_two_factor: true, create_team: true });
+ expect(faults).toEqual([]);
+ });
+
+ it(`${arrangement}: both stay hidden while their flags are off, by verdict and not by fault`, () => {
+ const { names, faults, verdicts } = visibleUnder(arrangement, { twoFactor: false, organization: false });
+ expect(names).toEqual([]);
+ expect(verdicts).toEqual({ enable_two_factor: false, create_team: false });
+ expect(faults).toEqual([]);
+ });
+ }
+
+ it("the provider's own runner binds features from a scope above it", () => {
+ const features = { twoFactor: true };
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(PredicateScopeProvider, {
+ scope: scopeOf(features),
+ children: React.createElement(ActionProvider, { context: { user: SELF }, children }),
+ });
+ const { result } = renderHook(() => useAction(), { wrapper });
+ const bag = result.current.runner.getEvaluator().getContext().toObject() as Record;
+ expect(bag.features).toEqual(features);
+ expect(bag.current_user).toEqual(SELF);
+ });
+});
diff --git a/ui/packages/react/src/hooks/useActionEngine.ts b/ui/packages/react/src/hooks/useActionEngine.ts
index 03e8e604342..95f27a07810 100644
--- a/ui/packages/react/src/hooks/useActionEngine.ts
+++ b/ui/packages/react/src/hooks/useActionEngine.ts
@@ -26,14 +26,13 @@
import { useCallback, useContext, useMemo } from 'react';
import {
ActionEngine,
- subjectPermissionsOf,
type ActionLocation,
type ActionDef,
type ActionContext,
type ActionResult,
} from '@object-ui/core';
import { ActionCtxReact } from '../context/ActionContext.js';
-import { usePredicateScope } from './useExpression.js';
+import { useRunnerScopeBindings } from './useRunnerScopeBindings.js';
export interface UseActionEngineOptions {
/** Action definitions to register */
@@ -71,43 +70,28 @@ export function useActionEngine(options: UseActionEngineOptions = {}): UseAction
const providerCtx = useContext(ActionCtxReact);
const sharedRunner = providerCtx?.runner ?? null;
- // The acting subject the host's predicate scope binds as `current_user`
- // (objectui#11212): the ONE object `ExpressionProvider` publishes under
- // `current_user` / `user` / `ctx.user` / `os.user`, carrying the caller's
- // effective object permissions once they have loaded. The engine filters
- // `visible` against the RUNNER's bag, which a host seeds with its own `user`
- // and never with `current_user` — so `current_user.can(…)`, and any other
- // `current_user.*` predicate, faulted on this path in every state and the
- // action was hidden even for a grant holder, while the same predicate
- // answered on every predicate-scope surface. Binding the scope's subject
- // itself — the same object, not a copy, because the engine answers `can`
- // only for a receiver IDENTICAL to the bound `current_user` — is what makes
- // the two paths one bag (objectui#6493). With no host scope (`{}`) nothing
- // is bound and the path behaves as it always did.
+ // The roots of the host's predicate scope the runner's bag binds —
+ // `current_user` and `features` (`useRunnerScopeBindings`, which says what
+ // each one answers and why). The engine filters `visible` against the
+ // RUNNER's bag, which a host seeds with its own `record` / `user` / `ctx` and
+ // never with either root, so `current_user.can(…)` (objectui#11212) and
+ // every `requiresFeature`-lowered `… && features. …` gate faulted on
+ // this path in every state and the action was hidden fail-closed, while the
+ // same predicate answered on every predicate-scope surface. With no host
+ // scope (`{}`) nothing is bound and the path behaves as it always did.
//
- // Only `current_user` is added. The runner's `user` / `ctx.user` / `os.user`
- // stay the host's own object: it carries what the runner itself reads (the
- // `systemPermissions` capability set), which the scope's subject does not.
- //
- // Since objectui#11242 `` binds the same subject on its own
+ // Since objectui#11242 `` binds the same roots on its own
// runner, so under a provider mounted INSIDE the predicate scope this write
- // re-binds the object that is already there. It stays for the two runners
+ // re-binds the objects that are already there. It stays for the two runners
// no provider binds: this hook's own standalone runner (no provider at
// all), and a shared runner whose provider sits ABOVE the scope — the
// console's global provider does (`GlobalActionRuntimeProvider` wraps the
// routes, and `ExpressionProvider` is mounted inside them) — where the
// provider has no scope to read.
- const subject = usePredicateScope().current_user as Record | undefined;
- // Keyed on what the binding READS, never on the subject's identity (a
- // memoised value upstream — AGENTS.md #10): its serialisable fields, and the
- // permissions map it carries, which the upstream adapter caches per payload
- // outside React. A discarded-and-recomputed subject with the same content
- // keeps the engine; the permissions arriving (or leaving) rebuilds it.
- const subjectKey = subject === undefined ? '' : JSON.stringify(subject);
- const subjectPermissions = subjectPermissionsOf(subject);
+ const { bound: scopeBound, key: scopeKey, subjectPermissions } = useRunnerScopeBindings();
const engine = useMemo(() => {
- const bound: Partial = subject !== undefined ? { current_user: subject } : {};
+ const bound = scopeBound;
// When standalone (no surrounding ``), normalize the
// context so predicates can use both `record`/`user` and `ctx.*`.
const normalizedStandalone = (context && Object.keys(context).length > 0)
@@ -139,15 +123,15 @@ export function useActionEngine(options: UseActionEngineOptions = {}): UseAction
...bound,
};
runner.updateContext(merged as any);
- } else if (sharedRunner && subject !== undefined) {
- // A caller that passes no per-render keys: the subject is still bound,
- // onto the same shared runner the location filter reads.
+ } else if (sharedRunner && Object.keys(bound).length > 0) {
+ // A caller that passes no per-render keys: the scope's roots are still
+ // bound, onto the same shared runner the location filter reads.
e.getRunner().updateContext(bound);
}
e.registerActions(actions);
return e;
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [sharedRunner, JSON.stringify(actions), JSON.stringify(context), subjectKey, subjectPermissions]);
+ }, [sharedRunner, JSON.stringify(actions), JSON.stringify(context), scopeKey, subjectPermissions]);
const getActionsForLocation = useCallback(
(location: ActionLocation) => engine.getActionsForLocation(location),
diff --git a/ui/packages/react/src/hooks/useRunnerScopeBindings.ts b/ui/packages/react/src/hooks/useRunnerScopeBindings.ts
new file mode 100644
index 00000000000..40ea3f1b678
--- /dev/null
+++ b/ui/packages/react/src/hooks/useRunnerScopeBindings.ts
@@ -0,0 +1,68 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/**
+ * The roots of the surrounding predicate scope an `ActionRunner`'s bag binds,
+ * so an action gate the runner evaluates answers the way the same predicate
+ * answers on every predicate-scope surface (the objectui#6493 "one bag" rule).
+ *
+ * The runner evaluates its own gates — the engine's `visible` filter,
+ * `execute`'s `disabled` re-check, `params[].visible` — against ITS bag, which
+ * a host seeds with its own `record` / `user` / `ctx` and never with the
+ * scope's roots. Two of those roots are bound onto it here:
+ *
+ * - `current_user` (objectui#11212, objectui#11242): the ONE subject object
+ * `ExpressionProvider` publishes under `current_user` / `user` /
+ * `ctx.user` / `os.user`, carrying the caller's effective object
+ * permissions once they have loaded. The same object, not a copy: the
+ * engine answers `can` only for a receiver IDENTICAL to the bound
+ * `current_user`. The runner's `user` / `ctx.user` / `os.user` stay the
+ * host's own object, which carries the `systemPermissions` the capability
+ * gate reads.
+ * - `features`: the deployment's public auth flags (`/auth/config`'s
+ * `features`), the root a `requiresFeature` gate is lowered onto at parse
+ * time (`featureGatePredicate` in `@objectstack/spec/kernel`, e.g.
+ * `… && features.twoFactor == true`), and the root a hand-written
+ * `features.cloudManaged != true` gate reads. Unbound, every such gate
+ * faulted on the runner's bag and the action was hidden fail-closed — on a
+ * deployment with two-factor on, nobody could see "Enable Two-Factor Auth"
+ * on their own record, while the same predicate answered on the record
+ * header and the related-list toolbar, which read the scope directly.
+ *
+ * A root the scope does not carry (no `ExpressionProvider` above, `{}`) is not
+ * bound, so a host's own context value for it, if it passed one, stays.
+ *
+ * `key` is what a caller memoises the binding on: what the binding READS,
+ * never the objects' identities (memoised values upstream — AGENTS.md #10).
+ * The subject's serialisable fields and the deployment flags, plus the
+ * permissions map the subject carries, which the upstream adapter caches per
+ * payload outside React, so its identity changes only when the payload does.
+ */
+
+import { subjectPermissionsOf, type ActionContext } from '@object-ui/core';
+import { usePredicateScope } from './useExpression.js';
+
+export interface RunnerScopeBindings {
+ /** The roots to write onto the runner's bag (empty when the scope has none). */
+ bound: Partial;
+ /** A content key over what `bound` carries, for memo dependencies. */
+ key: string;
+ /** The permissions map the subject carries (a memo dependency by identity). */
+ subjectPermissions: ReturnType;
+}
+
+export function useRunnerScopeBindings(): RunnerScopeBindings {
+ const scope = usePredicateScope();
+ const subject = scope.current_user as Record | undefined;
+ const features = scope.features as Record | undefined;
+ const bound: Partial = {};
+ if (subject !== undefined) (bound as Record).current_user = subject;
+ if (features !== undefined) (bound as Record).features = features;
+ const key = JSON.stringify([subject ?? null, features ?? null]);
+ return { bound, key, subjectPermissions: subjectPermissionsOf(subject) };
+}
From f5f77c84e7782eab964f38560f8bb5c086fa61e8 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:42:17 +0000
Subject: [PATCH 006/162] docs: shipped READMEs and the os test error point at
the moved reference tables; the redirect table fails loudly without its
folder (#38409)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Tesla** · [project
thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoE5JajoFCMekD8cvstGDmPY)_
Fixes #38337
repo:objectstack#3 · os-tesla · session_01L9qibvFXC2YadYHU4FMbqf
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:core、runtime、rest 三个包的 README 里「API
Reference」直接打开仓库里的参数表;`os test`
遇到格式不对的测试文件,报错里给的参考链接能打开了(原来指向一个已删的文件);「Locked items」页补准了两种情况。
- 为什么做:九类平台和接口参数表撤下网站后的收尾(你 11-28 14:00Z 的决定「只撤平台和接口类,留编写类」的第三张卡)。
-
出错会怎样:只改文字和一处构建自检;最坏是某条链接不对,旧网址仍有永久跳转兜底,可直接撤回。参数表目录缺失时文档站构建会直接报错,不会再悄悄丢掉全部跳转。
- 要你做什么:无。
## What changes
- **Shipped READMEs.** The "API Reference" link in
`packages/core/README.md` and `packages/runtime/README.md` (was
`objectstack.ai/docs/references/kernel`) and in
`packages/rest/README.md` (was `.../references/api`) now opens the
category folder on GitHub, `packages/spec/docs/references/{kernel,api}`,
in the spelling #38381 used for the hand-written pages. The old URLs
keep redirecting; this removes the hop.
- **`os test` error text** (`packages/cli/src/commands/test.ts`). A file
that is not a valid Quality Protocol suite printed `Reference:
content/docs/references/qa/testing.mdx`, a file #38381 removed and no
redirect covers (it is a repo path, not a URL). It now prints the GitHub
URL of `packages/spec/docs/references/qa/testing.md`. No test pins the
text.
- **N1 from #38381** (`apps/docs/reference-redirects.mjs`).
`repoReferencePages` answered an empty map when
`packages/spec/docs/references` was missing, so the docs site would
build and serve none of the 292 reference redirects without a word. It
now throws when the folder is missing or holds no category folder, and
the error names the generator command. `check:docs-redirects` gains a
self-test battery (4 assertions) that drives the real function at
fixture roots: a missing folder, an empty folder, and a populated
control. The battery floor rises from 8 to 9.
- **Locked items page** (`content/docs/permissions/locked-items.mdx`),
the two nits from the L2 record on #38343 (7241541435):
- N4: the object-delete clause now holds only where the deployment runs
an environment kernel. The removal door sits inside `environmentId !==
undefined` (`protocol-diff-delete-load.ts:515`, `:571`); a host-config
kernel does not ask it (`:604-613`).
- N6: a save that names the read-only package answers `403 ITEM_LOCKED`
with a message that the package is read-only
(`protocol-packaged-base-refusal.ts:151-156`,
`SysMetadataRepository.readOnlyBaseOverrideError`), as
`concepts/metadata-lifecycle.mdx:230` already states.
- **Changeset** `.changeset/38337-moved-reference-links.md`: patch for
`@objectstack/core`, `@objectstack/runtime`, `@objectstack/rest` (README
ships in the tarball) and `@objectstack/cli` (the message ships in
`dist`).
## Acceptance notes
- Premise corrected at claim (7247472854): #38381 already rewrote every
hand-written `content/docs` link into the nine namespaces. On
`origin/main` ff69bcab, `git grep` for
`/docs/references/{api,identity,integration,kernel,marketplace,qa,shared,studio,system}`
outside the generated trees finds none in `content/docs`, none under
`/en/docs`, and no relative `../references/...` links.
- Moved to #38394 by the claim (Q1 = A): the skills example `docsUrl` in
`skills/objectstack-data/references/examples-objects.md` and the
AGENTS.md Documentation Guardrails row for
`packages/spec/docs/references/`. Both are governed and the skills path
mandates a higher tier.
- Not changed, per the claim: the hotcrm skills copy (synced from
`@objectstack/skills` and pinned in `skills-lock.json`), and history
mentions of the old paths (ADRs, audits, migration descriptions,
comments, `variant-docs.json` reasons).
- The other package READMEs that link `objectstack.ai/docs/references`,
`/references/security` or `/references/automation` point at the index or
at categories that stay on the site. They are unchanged.
- The live deploy reading the card asks for is posted on the card on its
own, from the 11-29 00:43Z scheduled deploy. It is not tied to this PR.
## Verification
All readings at head `710368a2`.
- **Two-minute check.** Move `packages/spec/docs/references` aside and
import the table: `node -e
"import('./apps/docs/reference-redirects.mjs')"` exits 1 with `Error:
reference-redirects: packages/spec/docs/references does not exist, so
the redirect table for the moved reference pages would be empty.
Generate it with \`pnpm --filter @objectstack/spec gen:docs\`.` Put the
folder back and it loads.
- **Read first:** `apps/docs/reference-redirects.mjs` (the two throws),
then the new battery at the end of `scripts/check-docs-redirects.mjs`'s
self-test, then the N4/N6 sentence in `locked-items.mdx`.
Redirect gate
- `node scripts/check-docs-redirects.mjs --self-test`: exit 0, 69
assertions (was 65), 9 batteries.
- `node scripts/check-docs-redirects.mjs`: exit 0. The reference table
still has 292 entries, with 290 repository destinations resolved against
the checkout and 2 on-site.
Derived gates
- `node scripts/pm/dispatch-gates.mjs --commands` derived 113 families.
All 113 ran and exited 0, and `--ran` reports 113 run, 0 NOT-MEASURED.
- 12 of them first exited 3 (prerequisite). They passed after `turbo run
build --filter='./packages/**' --filter='@objectstack/dogfood^...'`
under the verify lock (exit 0, 86 tasks). `check-plugin-teardown-shape
--self-test` passed after fetching its fixture commit.
- `dispatch-gates.mjs --tier` on this diff: no path-derived mandate. 79
changed lines, under the 3000 threshold.
- `overlap-check`: clean against `origin/main`, and no open PR shares a
file.
Package checks
- `pnpm --filter @objectstack/cli typecheck`: exit 0.
- `vitest run test/qa-suite-schema-load.test.ts test/commands.test.ts`
in `@objectstack/cli`: 2 files, 58 tests passed. No test pins the
`Reference:` line.
- `eslint --no-inline-config` on the three changed scripts and modules:
exit 0.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01L9qibvFXC2YadYHU4FMbqf)_
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L9qibvFXC2YadYHU4FMbqf
Co-authored-by: Claude
---
.changeset/38337-moved-reference-links.md | 13 ++++++++
apps/docs/reference-redirects.mjs | 12 ++++++-
content/docs/permissions/locked-items.mdx | 7 ++--
packages/cli/src/commands/test.ts | 2 +-
packages/core/README.md | 2 +-
packages/rest/README.md | 2 +-
packages/runtime/README.md | 2 +-
scripts/check-docs-redirects.mjs | 39 ++++++++++++++++++++++-
8 files changed, 71 insertions(+), 8 deletions(-)
create mode 100644 .changeset/38337-moved-reference-links.md
diff --git a/.changeset/38337-moved-reference-links.md b/.changeset/38337-moved-reference-links.md
new file mode 100644
index 00000000000..0b9b4be7788
--- /dev/null
+++ b/.changeset/38337-moved-reference-links.md
@@ -0,0 +1,13 @@
+---
+'@objectstack/core': patch
+'@objectstack/runtime': patch
+'@objectstack/rest': patch
+'@objectstack/cli': patch
+---
+
+docs: README links and the `os test` error point at the platform reference tables' new home
+
+Clause-②: no
+Metadata-protocol: none
+
+The platform and wire-contract reference tables (kernel, api, qa and six others) are no longer pages on objectstack.ai. They are published as markdown in the repository, under `packages/spec/docs/references/`. The "API Reference" links in the `@objectstack/core`, `@objectstack/runtime` and `@objectstack/rest` READMEs now open those folders directly, without the redirect hop. When `os test` refuses a file that is not a valid Quality Protocol suite, its `Reference:` line now names the suite table's URL, `packages/spec/docs/references/qa/testing.md` on GitHub. Before, it named a docs file that no longer exists. Nothing an author can write changed.
diff --git a/apps/docs/reference-redirects.mjs b/apps/docs/reference-redirects.mjs
index 8c3df5f40f7..7b3a6c5cec0 100644
--- a/apps/docs/reference-redirects.mjs
+++ b/apps/docs/reference-redirects.mjs
@@ -72,10 +72,19 @@ const EARLIER_MOVES = [
/**
* `category` -> its page slugs, read from the generator's output folder.
* Sorted, so the table is a pure function of the folder's contents.
+ *
+ * A missing folder, or one with no category in it, throws. The alternative is
+ * an empty table: the site would build, serve none of these redirects and say
+ * nothing, and every old reference URL would answer 404.
*/
export function repoReferencePages(root = REPO_ROOT) {
const dir = join(root, REPO_REFERENCES_REL);
- if (!existsSync(dir)) return new Map();
+ const missing = (what) =>
+ new Error(
+ `reference-redirects: ${what}, so the redirect table for the moved reference pages would be empty. ` +
+ 'Generate it with `pnpm --filter @objectstack/spec gen:docs`.',
+ );
+ if (!existsSync(dir)) throw missing(`${REPO_REFERENCES_REL} does not exist`);
const out = new Map();
for (const entry of readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory())) {
const slugs = readdirSync(join(dir, entry.name))
@@ -87,6 +96,7 @@ export function repoReferencePages(root = REPO_ROOT) {
.sort();
out.set(entry.name, slugs);
}
+ if (out.size === 0) throw missing(`${REPO_REFERENCES_REL} holds no category folder`);
return new Map([...out].sort(([a], [b]) => a.localeCompare(b)));
}
diff --git a/content/docs/permissions/locked-items.mdx b/content/docs/permissions/locked-items.mdx
index 391e2442a12..f5273683df1 100644
--- a/content/docs/permissions/locked-items.mdx
+++ b/content/docs/permissions/locked-items.mdx
@@ -78,8 +78,11 @@ There is no switch that lets an administrator lift a lock in place.
- **`403 NOT_OVERRIDABLE`** refuses an in-place edit of an item a package
ships because the package, not the environment, owns it. It is asked before
the lock, so it is the answer you get first for the platform's own objects and
- apps: a save that names no package, and the delete of an object, answer
- `NOT_OVERRIDABLE` even though those items are also locked. A package you
+ apps: a save that names no package answers `NOT_OVERRIDABLE` even though
+ those items are also locked, and so does the delete of an object where the
+ deployment runs an environment kernel. A save that names the read-only
+ package instead answers `403 ITEM_LOCKED`, and its message says the package
+ is read-only rather than giving the item's reason. A package you
installed is customized through its paired customization package instead:
see [What a managed install keeps](/docs/deployment/install-modes#what-a-managed-install-keeps).
Flows, actions and permission sets name their own routes, such as a clone or
diff --git a/packages/cli/src/commands/test.ts b/packages/cli/src/commands/test.ts
index d1733563922..8781d34046e 100644
--- a/packages/cli/src/commands/test.ts
+++ b/packages/cli/src/commands/test.ts
@@ -224,7 +224,7 @@ export function loadTestSuite(file: string): QA.TestSuite {
throw new Error(
`${file} is not a valid Quality Protocol suite (TestSuiteSchema):\n${issues}\n` +
` Expected shape: ${SUITE_SHAPE}\n` +
- ` Reference: content/docs/references/qa/testing.mdx`,
+ ` Reference: https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/qa/testing.md`,
);
}
diff --git a/packages/core/README.md b/packages/core/README.md
index f677f6bfbef..7713533d1ba 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -113,7 +113,7 @@ use() → init() → start() → [running] → stop() → unload()
## Links
- 📖 Docs:
-- 📚 API Reference:
+- 📚 API Reference:
- 🤖 Skill: [`skills/objectstack-platform/SKILL.md`](../../skills/objectstack-platform/SKILL.md)
## License
diff --git a/packages/rest/README.md b/packages/rest/README.md
index 067ddb798c7..48f43422c05 100644
--- a/packages/rest/README.md
+++ b/packages/rest/README.md
@@ -153,7 +153,7 @@ have no second copy anywhere.
## Links
- 📖 Docs:
-- 📚 API Reference:
+- 📚 API Reference:
- 🤖 Skill: [`skills/objectstack-api/SKILL.md`](../../skills/objectstack-api/SKILL.md)
## License
diff --git a/packages/runtime/README.md b/packages/runtime/README.md
index 94b960644bb..ae81b2db077 100644
--- a/packages/runtime/README.md
+++ b/packages/runtime/README.md
@@ -689,7 +689,7 @@ Defaults are noop — zero overhead until you plug an adapter.
## Documentation
- 📖 Docs:
-- 📚 API Reference:
+- 📚 API Reference:
- 🛡️ Hardening: [`docs/HARDENING.md`](../../docs/HARDENING.md)
- 📈 Observability: [`docs/OBSERVABILITY.md`](../../docs/OBSERVABILITY.md)
diff --git a/scripts/check-docs-redirects.mjs b/scripts/check-docs-redirects.mjs
index 56c68b3c6ae..8ef836fa6b9 100644
--- a/scripts/check-docs-redirects.mjs
+++ b/scripts/check-docs-redirects.mjs
@@ -551,11 +551,12 @@ const SELF_TEST_BATTERIES = Object.freeze({
'A host-scoped table chains against the table its destinations are served by': 5,
'A repository destination resolves against the checkout, and only this repository\'s': 8,
'The generator and the docs app spell the repo reference folder alike': 4,
+ 'The reference table refuses a missing or empty folder instead of serving nothing': 4,
});
// DELETING an entry silences that battery's floor exactly as effectively as
// zeroing it, so the roster's own size is pinned too.
-const SELF_TEST_BATTERY_FLOOR = 8;
+const SELF_TEST_BATTERY_FLOOR = 9;
// 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
@@ -917,6 +918,42 @@ async function selfTest() {
plant(placementAt('packages/x/docs', 'https://site.example'), false);
const partDrift = await placementSpellingDrift(spelling);
assert(partDrift.length === 1 && partDrift[0].includes('continuation-file pattern'), `a table that skips other files is named -- got ${JSON.stringify(partDrift)}`);
+
+ battery('The reference table refuses a missing or empty folder instead of serving nothing');
+ // The real module, its folder-reading half pointed at fixture roots. An
+ // empty table builds a site that serves none of the moved pages' redirects
+ // and says nothing, so the read throws and names the generator.
+ const { repoReferencePages, REPO_REFERENCES_REL: referencesRel } = await import(
+ pathToFileURL(join(scriptRepoRoot(), 'apps/docs/reference-redirects.mjs')).href
+ );
+ const throwsOn = (root) => {
+ try {
+ repoReferencePages(root);
+ return null;
+ } catch (error) {
+ return String(error?.message ?? error);
+ }
+ };
+ const absent = throwsOn(join(dir, 'pages-absent'));
+ assert(
+ absent !== null && absent.includes('does not exist') && absent.includes('gen:docs'),
+ `a missing folder throws and names the generator -- got ${JSON.stringify(absent)}`,
+ );
+ mkdirSync(join(dir, 'pages-empty', referencesRel), { recursive: true });
+ const empty = throwsOn(join(dir, 'pages-empty'));
+ assert(
+ empty !== null && empty.includes('no category folder') && empty.includes('gen:docs'),
+ `a folder with no category throws and names the generator -- got ${JSON.stringify(empty)}`,
+ );
+ write(`pages-one/${referencesRel}/api/batch.md`, '# Batch\n');
+ write(`pages-one/${referencesRel}/api/protocol.part-2.md`, '# Part 2\n');
+ write(`pages-one/${referencesRel}/api/README.md`, '# Api\n');
+ const one = repoReferencePages(join(dir, 'pages-one'));
+ assert(
+ JSON.stringify([...one]) === JSON.stringify([['api', ['batch']]]),
+ `control: one category reads as its pages, without README or continuation parts -- got ${JSON.stringify([...one])}`,
+ );
+ assert(throwsOn(join(dir, 'pages-one')) === null, 'control: a populated folder does not throw');
} finally {
rmSync(dir, { recursive: true, force: true });
}
From a3c71d785c6f339d37dff53528cf66ac96a2322c Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:42:25 +0000
Subject: [PATCH 007/162] fix(plugin-chatbot): a restored chat approval card
shows a row approved, executed, failed or held elsewhere as that outcome
(#38410)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XAqkG8y9atnquyRXBY4zVGV)_
Fixes #38344
Clause-②: no
Metadata-protocol: none
## 维护者速读
-
控制台用户重新打开一段对话时,聊天里那张早已在别处(审批收件箱、另一个标签页)被批准、执行、失败或转人工审批的审批卡片,现在直接显示结果,不再显示「批准
/ 拒绝」按钮。
- 属于聊天内审批卡片的收尾:上一轮已让过期和被拒的卡片显示结果,这一轮补齐其余四种结果,并把每段对话的读取次数压到固定的两次。
- 出错时最坏情况是卡片仍显示按钮(与改动前一样),点下去会收到服务端拒绝;不涉及数据写入,撤回本改动即可回到原样。
- 无。
## What changes
`ui/packages/plugin-chatbot/src/useHitlInChat.ts` only (plus tests and a
changeset). No route, query parameter, status value, server change or
public export change.
**End states.** `settledDecisionOf` now maps every settled row status
from `PendingActionStatus` (`@objectstack/spec/contracts`: `pending |
approved | held | executed | failed | rejected`) to the decision state
the card already draws after its own press. The press path and the
restored path now share the same wording constants, so they cannot
drift:
| Row | Decision state | What the card says |
|:---|:---|:---|
| `executed` | `success`, `decision: approved`, `result` = the row's
stored `result` decoded | "Approved — action executed." (the press
wording) |
| `held` | `held`, `decision: approved` | "Waiting for approval"
(`aiApprovals.statusHeld`, the press wording) |
| `failed` | `error`, `decision: approved` | the row's `error`, or
"Action approved but execution failed." (the press fallback) |
| `approved` (approval taken, no outcome recorded yet) | `pending`,
`decision: approved` | "Approving…" — the state the card holds between
an Approve press and its answer |
| lapsed (`rejected` + `lapsed` + no `decided_by`) | `expired` |
unchanged |
| `rejected` by a person | `success`, `decision: rejected` | unchanged |
| `pending`, unknown status, no answer | none | buttons stay, unchanged
|
`approved` is the one status the press path never receives (the approve
answer is `executed | held | failed`), so it has no press wording of its
own. It maps to the in-flight state rather than to `success`, because a
`success` with `decision: approved` makes the record-write card say the
record was written, which an `approved` row does not record. No new
string was added.
The press-wins rule is unchanged: a read that lands after a decision
made on this card never overwrites it.
**The read bound.** The rows of one conversation are now read with at
most two requests in the common case, not one per card:
1. the first awaiting card's row by id (`GET …/pending-actions/:id`, as
before);
2. if more cards await and that row names its `conversation_id`, ONE
list read for the rest: `GET …/pending-actions?conversationId=ID`.
A card the list does not answer (past the list's row cap, a row with no
conversation, a failed list read) falls back to its own item read, so no
card is left unread. A single awaiting card, or a first row with no
`conversation_id`, behaves exactly as before.
Why this read and not "one list read filtered to the conversation's
pending ids", as the card suggested: the list route takes no id filter.
What it does take, read from this tree (the route handler itself is not
in this repository):
- `ListAiPendingActionsRequestSchema` in
`packages/spec/src/api/protocol.zod.ts`: `status`, `conversationId`,
`limit`, documented there as "Only the three the ROUTE reads";
- `@objectstack/client` `pendingActions.list`: sends exactly those
three;
- the AI Approvals inbox (`usePendingActions`): sends `status`,
`conversationId`, `limit`.
An id filter would be a new query parameter, which the card rules out.
The conversation filter is the narrowest read that exists, and the hook
gets the conversation id from the first row
(`PendingActionRow.conversation_id`) rather than from a new hook option,
so `UseHitlInChatOptions` and the console's call site are unchanged. No
`status` filter is sent, since every status is needed, and no `limit`,
so the server default applies; the fallback covers any card past it.
## Tests
New pins in
ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx (the restored-card
harness), all green at HEAD 8bb62c20
Two new top-level `describe` blocks in the existing harness file:
- end states: executed, held, failed (with the row error and with the
fallback), approved, and the decoded stored `result` handed to the
decision;
- the bound: four cards read with exactly `GET …/pending-actions/pa_1`
then `GET …/pending-actions?conversationId=conv_1`; a card the list
leaves out gets its own item read; a first row with no conversation
sends no list read.
```
pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx packages/plugin-chatbot/src/__tests__/useHitlInChat.test.tsx
Test Files 2 passed (2)
Tests 22 passed (22)
```
The four pins this file already held (lapse, person rejected, press
wins, pending or no answer) are unchanged and green: the lapse and
person-rejected paths and `pendingActionLapse.ts` are not touched.
Ablation, one mutation per behaviour, each restored to
the HEAD blob
All via `node scripts/ablation-replace.mjs` (anchor hit 1 to 0, restore
blob == HEAD blob `73b205115eb7`, `git diff HEAD` empty):
- the list read disabled (`listed` forced to `null`): 2 failed, 10
passed: the two bound pins went red, every end-state pin stayed green;
- the end-state mapping disabled (only `rejected` reaches the switch): 8
failed, 4 passed: every new pin red, the four existing pins green;
- the stored-result decode disabled (`JSON.parse` removed): 1 failed, 11
passed: the decoded-result pin alone.
Package, ratchet and console sweeps
```
pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-chatbot/ [16 ui ratchet test files] packages/app-shell/src/console/
Test Files 383 passed (383)
Tests 3363 passed (3363)
pnpm --filter @object-ui/plugin-chatbot run type-check (after building its dependency closure)
exit 0, 0 TS errors; tsconfig.test.json's program lists both changed files
```
`packages/app-shell/src/console/` was run as a whole directory (a
superset of the `console/*.test.tsx` the card's seat asked for). It
includes `AiChatPage.approvalRehydration.test.tsx`, which pins a single
card's read URL.
## Acceptance notes
- **`approved` → in-flight.** A judgment call. The other honest reading
would be a new "Approved" line, which is a new string. Flagged in the
report as an open question, with a recommendation to keep this.
- **Routing (seat repo:objectstack#5):** the card's wording "the same
wording the card uses after its own press" covers `approved` → A
("Approving…", the state after an Approve press until its answer); not a
maintainer decision. B (`Status: approved`, which draws `written` early)
and C (new copy) are out.
- **Not filed, read only:** `countWritesAwaitingApproval` (app-shell)
counts a decision in state `error` as a write still awaiting approval. A
press whose approve answers `failed` (a terminal row) draws `error`, so
it is counted. A restored `failed` row now draws `error` too, which
leaves its count where it was before this PR (an undecided card was
counted already). Executed, held and approved rows stop being counted,
which is correct. Not measured on a host.
- The list route's handler is not in this repository, so its honouring
of `conversationId` was read from the spec schema and the two existing
callers, not measured. If a host ignored the filter, cards are still
matched by id and any card it misses falls back to its own read.
## Verification
Read first, by risk:
1. `useHitlInChat.ts`, the read effect (`settleCards`): the two-step
read and the per-card fallback.
2. `useHitlInChat.ts`, `settledDecisionOf`: the status mapping,
especially `approved`.
3. The new `describe` blocks in
`ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx`.
Two-minute check: `pnpm --dir ui exec vitest run
packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx`.
Expect 12 passed, including "reads the first row by id, then every other
row through one list read of its conversation".
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5nvFivDeQyYgTFkZhi)_
---------
Co-authored-by: Claude
---
.changeset/38344-restored-card-end-states.md | 12 +
...nced.restoredLapsedApproval-38250.test.tsx | 230 +++++++++++++++++-
.../plugin-chatbot/src/useHitlInChat.ts | 217 +++++++++++++----
3 files changed, 403 insertions(+), 56 deletions(-)
create mode 100644 .changeset/38344-restored-card-end-states.md
diff --git a/.changeset/38344-restored-card-end-states.md b/.changeset/38344-restored-card-end-states.md
new file mode 100644
index 00000000000..81598470986
--- /dev/null
+++ b/.changeset/38344-restored-card-end-states.md
@@ -0,0 +1,12 @@
+---
+'@object-ui/plugin-chatbot': patch
+---
+
+fix(plugin-chatbot): a restored chat approval card whose action was approved, executed, failed or held elsewhere shows that outcome instead of Approve and Reject
+
+Clause-②: no
+Metadata-protocol: none
+
+A chat approval card restored from a saved conversation now reads every settled row the way the card reads the same outcome after its own press, with no buttons: an `executed` row reads "Approved — action executed.", a `held` row reads "Waiting for approval", a `failed` row reads the row's `error` (or "Action approved but execution failed."), and an `approved` row with no outcome recorded yet reads "Approving…", never as a write that happened. A lapsed row still reads "Expired" and a row a person rejected still reads as that rejection; a row still `pending`, or a read that gets no answer, keeps the buttons; a decision made on the card meanwhile is never overwritten.
+
+The row reads are bounded per conversation: `useHitlInChat` reads the first awaiting card's row by id (`GET …/pending-actions/:id`), then the other cards' rows through one list read filtered to that row's `conversation_id` (`GET …/pending-actions?conversationId=…`, the filter the AI Approvals inbox sends). A card the list does not answer falls back to its own item read. A host whose tests script `fetch` in call order sees, for a conversation with two or more awaiting cards, the item read of the first card followed by one list read.
diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx
index 7ca0561300e..6ea0f17383a 100644
--- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx
+++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.restoredLapsedApproval-38250.test.tsx
@@ -17,9 +17,12 @@
* met the lapse `409`. Now `useHitlInChat` reads each awaiting card's row once
* (`GET …/pending-actions/:id`, the item read `@objectstack/client`'s
* `pendingActions.get` uses): a lapsed row
- * reads Expired, a row a person rejected reads as that rejection, and anything
- * else, or no answer, leaves the buttons. A press made while the read is still
- * out stands when the read lands.
+ * reads Expired, a row a person rejected reads as that rejection, a row
+ * approved, executed, failed or held elsewhere reads as the card reads that
+ * outcome after its own press (objectstack#38344), and a row still pending, or
+ * no answer, leaves the buttons. A press made while the read is still out
+ * stands when the read lands. With several restored cards, the rows after the
+ * first come from one list read filtered to the first row's conversation.
*
* The hook and the card run together and the assertions are on what a person
* sees. Rendered in zh: 已过期 comes only from the pack.
@@ -28,7 +31,7 @@
import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, afterEach, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, renderHook, screen, waitFor, within } from '@testing-library/react';
import { I18nProvider } from '@object-ui/i18n';
import { ChatbotEnhanced } from '../ChatbotEnhanced';
import { uiMessagesToChatMessages } from '../mapMessages';
@@ -195,3 +198,222 @@ describe('a restored chat approval card reads where its pending action settled (
expect(screen.queryByTestId('tool-decision')).not.toBeInTheDocument();
});
});
+
+const ZH_HELD = '审批中';
+
+/** Several restored approvals in one saved conversation, `c` → `pa_`. */
+const restoredMany = (n: number) =>
+ uiMessagesToChatMessages(
+ Array.from({ length: n }, (_, i) => ({
+ id: `a${i + 1}`,
+ role: 'assistant' as const,
+ parts: [
+ {
+ type: 'tool-action_delete_task',
+ toolCallId: `c${i + 1}`,
+ state: 'output-available' as const,
+ input: { id: `t${i + 1}` },
+ output: {
+ type: 'text' as const,
+ value: JSON.stringify({
+ status: 'pending_approval',
+ pendingActionId: `pa_${i + 1}`,
+ message: 'Needs approval',
+ }),
+ },
+ },
+ ],
+ })),
+ );
+
+function ManyHarness({ n }: { n: number }) {
+ const messages = React.useMemo(() => restoredMany(n), [n]);
+ const hitl = useHitlInChat({ messages, apiBase: '/api/v1/ai' });
+ return (
+
+ );
+}
+
+function renderManyZh(n: number) {
+ return render(
+
+
+ ,
+ );
+}
+
+/**
+ * Answer GETs by URL: `items` answers the item read of `/pending-actions/`,
+ * `list` answers `/pending-actions?conversationId=…`. A URL with no answer gets
+ * a 404; any other method fails the test.
+ */
+function stubReads(answers: { items?: Record; list?: Record }) {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (init?.method !== 'GET') throw new Error(`unexpected ${init?.method} ${url}`);
+ const listMatch = /\/pending-actions\?conversationId=(.+)$/.exec(url);
+ const itemMatch = /\/pending-actions\/([^/?]+)$/.exec(url);
+ const body = listMatch
+ ? answers.list?.[decodeURIComponent(listMatch[1])]
+ : itemMatch
+ ? answers.items?.[decodeURIComponent(itemMatch[1])]
+ : undefined;
+ if (body === undefined) return { ok: false, status: 404, text: async () => '' } as Response;
+ return { ok: true, status: 200, text: async () => JSON.stringify(body) } as Response;
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+/** The decision strip of the card whose tool input names `t`. */
+async function stripOf(n: number) {
+ await waitFor(() => expect(screen.getAllByTestId('tool-decision').length).toBeGreaterThanOrEqual(n));
+ return screen.getAllByTestId('tool-decision')[n - 1];
+}
+
+describe('a restored chat approval card shows a row approved, executed, failed or held elsewhere as that outcome (objectstack#38344)', () => {
+ it('reads an executed row as the press reads an executed approval, with no buttons', async () => {
+ stubRowRead(200, { success: true, data: row({ status: 'executed', decided_by: 'user_1', result: '{"deleted":1}' }) });
+ renderZh();
+
+ const strip = await screen.findByTestId('tool-decision');
+ expect(strip).toHaveAttribute('data-state', 'success');
+ expect(strip).toHaveTextContent('Approved — action executed.');
+ expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
+ expect(screen.queryByText('DENY')).not.toBeInTheDocument();
+ });
+
+ it('reads a held row as waiting for approval, never as executed', async () => {
+ stubRowRead(200, row({ status: 'held', decided_by: 'user_1' }));
+ renderZh();
+
+ const strip = await screen.findByTestId('tool-decision');
+ expect(strip).toHaveAttribute('data-state', 'held');
+ expect(strip).toHaveTextContent(ZH_HELD);
+ expect(strip).not.toHaveTextContent('Approved — action executed.');
+ expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
+ });
+
+ it('reads a failed row as the failure, with the row error or the press fallback', async () => {
+ stubRowRead(200, row({ status: 'failed', decided_by: 'user_1', error: 'task t1 is locked' }));
+ renderZh();
+ const strip = await screen.findByTestId('tool-decision');
+ expect(strip).toHaveAttribute('data-state', 'error');
+ expect(strip).toHaveTextContent('task t1 is locked');
+ expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
+ cleanup();
+
+ stubRowRead(200, row({ status: 'failed', decided_by: 'user_1' }));
+ renderZh();
+ const bare = await screen.findByTestId('tool-decision');
+ expect(bare).toHaveAttribute('data-state', 'error');
+ expect(bare).toHaveTextContent('Action approved but execution failed.');
+ });
+
+ it('reads an approved row with no outcome yet as an approval under way, never as executed', async () => {
+ stubRowRead(200, row({ status: 'approved', decided_by: 'user_1' }));
+ renderZh();
+
+ const strip = await screen.findByTestId('tool-decision');
+ expect(strip).toHaveAttribute('data-state', 'pending');
+ expect(strip).toHaveTextContent('Approving…');
+ expect(strip).not.toHaveTextContent('Approved — action executed.');
+ expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
+ });
+
+ it('hands an executed row its stored result decoded, as the approve answer carries it', async () => {
+ stubRowRead(200, row({ status: 'executed', decided_by: 'user_1', result: '{"deleted":1}' }));
+ const messages = restored();
+ const { result } = renderHook(() => useHitlInChat({ messages, apiBase: '/api/v1/ai' }));
+ await waitFor(() => expect(result.current.decisions.c1).toBeDefined());
+ expect(result.current.decisions.c1).toEqual({
+ state: 'success',
+ message: 'Approved — action executed.',
+ decision: 'approved',
+ result: { deleted: 1 },
+ });
+ });
+});
+
+describe('the restored rows of one conversation are read with one item read and one list read (objectstack#38344)', () => {
+ it('reads the first row by id, then every other row through one list read of its conversation', async () => {
+ const fetchMock = stubReads({
+ items: { pa_1: row({ id: 'pa_1', status: 'executed', decided_by: 'u', conversation_id: 'conv_1' }) },
+ list: {
+ conv_1: {
+ success: true,
+ data: {
+ items: [
+ row({ id: 'pa_4', status: 'approved', decided_by: 'u', conversation_id: 'conv_1' }),
+ row({ id: 'pa_3', status: 'failed', decided_by: 'u', error: 'locked', conversation_id: 'conv_1' }),
+ row({ id: 'pa_2', status: 'held', decided_by: 'u', conversation_id: 'conv_1' }),
+ row({ id: 'pa_1', status: 'executed', decided_by: 'u', conversation_id: 'conv_1' }),
+ ],
+ total: 4,
+ },
+ },
+ },
+ });
+ renderManyZh(4);
+
+ expect(await stripOf(4)).toBeInTheDocument();
+ const strips = screen.getAllByTestId('tool-decision');
+ expect(strips.map((s) => s.getAttribute('data-state'))).toEqual(['success', 'held', 'error', 'pending']);
+ expect(within(strips[2]).getByText('locked')).toBeInTheDocument();
+ expect(screen.queryByText('APPROVE')).not.toBeInTheDocument();
+ // Two reads for four cards, whatever the count: never one per card.
+ expect(fetchMock.mock.calls.map(([u]) => u)).toEqual([
+ '/api/v1/ai/pending-actions/pa_1',
+ '/api/v1/ai/pending-actions?conversationId=conv_1',
+ ]);
+ });
+
+ it('falls back to its own item read for a card the list does not answer', async () => {
+ const fetchMock = stubReads({
+ items: {
+ pa_1: row({ id: 'pa_1', status: 'executed', decided_by: 'u', conversation_id: 'conv_1' }),
+ pa_3: row({ id: 'pa_3', status: 'held', decided_by: 'u', conversation_id: 'conv_1' }),
+ },
+ list: { conv_1: { items: [row({ id: 'pa_2', status: 'executed', decided_by: 'u', conversation_id: 'conv_1' })], total: 1 } },
+ });
+ renderManyZh(3);
+
+ expect(await stripOf(3)).toBeInTheDocument();
+ expect(screen.getAllByTestId('tool-decision').map((s) => s.getAttribute('data-state'))).toEqual([
+ 'success',
+ 'success',
+ 'held',
+ ]);
+ expect(fetchMock.mock.calls.map(([u]) => u)).toEqual([
+ '/api/v1/ai/pending-actions/pa_1',
+ '/api/v1/ai/pending-actions?conversationId=conv_1',
+ '/api/v1/ai/pending-actions/pa_3',
+ ]);
+ });
+
+ it('reads every card by id when the first row names no conversation, and sends no list read', async () => {
+ const fetchMock = stubReads({
+ items: {
+ pa_1: row({ id: 'pa_1', status: 'executed', decided_by: 'u' }),
+ pa_2: row({ id: 'pa_2', status: 'pending' }),
+ },
+ });
+ renderManyZh(2);
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.getAllByTestId('tool-decision')).toHaveLength(1);
+ // The pending card keeps its buttons.
+ expect(screen.getByText('APPROVE')).toBeInTheDocument();
+ expect(fetchMock.mock.calls.map(([u]) => u)).toEqual([
+ '/api/v1/ai/pending-actions/pa_1',
+ '/api/v1/ai/pending-actions/pa_2',
+ ]);
+ });
+});
diff --git a/ui/packages/plugin-chatbot/src/useHitlInChat.ts b/ui/packages/plugin-chatbot/src/useHitlInChat.ts
index 724460e0986..73b205115eb 100644
--- a/ui/packages/plugin-chatbot/src/useHitlInChat.ts
+++ b/ui/packages/plugin-chatbot/src/useHitlInChat.ts
@@ -215,10 +215,18 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
// objectstack#38250 — a card restored from a saved conversation still says
// `approval-requested`, whatever became of its pending action since: the
- // transcript is the proposal, not its outcome. So each awaiting card reads
- // its row once, through the pending-actions item read (`GET
- // …/pending-actions/:id`, what `@objectstack/client`'s `pendingActions.get`
- // reads), and settles where the row says it settled.
+ // transcript is the proposal, not its outcome. So each awaiting card's row
+ // is read once, and the card settles where the row says it settled.
+ //
+ // The reads are bounded per conversation, not per card (objectstack#38344):
+ // the first card's row comes from the item read (`GET …/pending-actions/:id`,
+ // what `@objectstack/client`'s `pendingActions.get` reads), and the row names
+ // its `conversation_id`; the other cards' rows then come from ONE list read
+ // filtered to that conversation (`GET …/pending-actions?conversationId=`, the
+ // filter the AI Approvals inbox and `pendingActions.list` send). The list
+ // route takes no id filter, so this is the narrowest existing read. A card
+ // the list does not answer (past its row cap, or a row with no conversation)
+ // falls back to its own item read, so no card is left unread.
const awaiting = React.useMemo(() => {
const list: Array<{ toolCallId: string; pendingActionId: string }> = [];
for (const msg of messages) {
@@ -230,7 +238,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
}
return list;
}, [messages]);
- /** Rows already asked for, by pending-action id: one read per card per mount. */
+ /** Rows already asked for, by pending-action id: each row is read once per mount. */
const rowReadRef = React.useRef(new Set());
// Unmount guard. Not a per-run flag: the effect below re-runs whenever a new
// message arrives, and a read already in flight must still land then.
@@ -245,33 +253,65 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
// Re-running is cheap and safe: a card whose row was already asked for is
// skipped, so a new `headers` object or a streamed message re-reads nothing.
React.useEffect(() => {
- for (const { toolCallId, pendingActionId } of awaiting) {
- if (rowReadRef.current.has(pendingActionId)) continue;
- rowReadRef.current.add(pendingActionId);
- void readRow(pendingActionId).then((row) => {
- if (!mountedRef.current || !row) return;
- const settled = settledDecisionOf(row);
- if (!settled) return;
- // Never over a decision made on this card meanwhile: the press wins.
- setDecisions((prev) => (toolCallId in prev ? prev : { ...prev, [toolCallId]: settled }));
- });
+ const unread: Array<{ toolCallId: string; pendingActionId: string }> = [];
+ for (const card of awaiting) {
+ if (rowReadRef.current.has(card.pendingActionId)) continue;
+ rowReadRef.current.add(card.pendingActionId);
+ unread.push(card);
}
+ if (unread.length === 0) return;
+ void settleCards(unread);
- async function readRow(pendingActionId: string) {
+ function settle(toolCallId: string, row: RestoredRow | null) {
+ if (!mountedRef.current || !row) return;
+ const settled = settledDecisionOf(row);
+ if (!settled) return;
+ // Never over a decision made on this card meanwhile: the press wins.
+ setDecisions((prev) => (toolCallId in prev ? prev : { ...prev, [toolCallId]: settled }));
+ }
+
+ async function settleCards(cards: Array<{ toolCallId: string; pendingActionId: string }>) {
+ const [first, ...rest] = cards;
+ const firstRow = await readRow(first.pendingActionId);
+ settle(first.toolCallId, firstRow);
+ if (rest.length === 0) return;
+ const conversationId = firstRow?.conversation_id;
+ const listed = conversationId ? await readConversationRows(conversationId) : null;
+ await Promise.all(
+ rest.map(async ({ toolCallId, pendingActionId }) => {
+ settle(toolCallId, listed?.get(pendingActionId) ?? (await readRow(pendingActionId)));
+ }),
+ );
+ }
+
+ async function getJson(url: string): Promise | null> {
try {
const doFetch = apiFetch ?? fetch;
- const response = await doFetch(
- `${base}/pending-actions/${encodeURIComponent(pendingActionId)}`,
- { method: 'GET', credentials: 'include', headers: buildHeaders(headers, false) },
- );
+ const response = await doFetch(url, {
+ method: 'GET',
+ credentials: 'include',
+ headers: buildHeaders(headers, false),
+ });
if (!response.ok) return null;
- return readPendingActionRow(await parseJson(response));
+ return await parseJson(response);
} catch {
// No answer (offline, no AI service): the card keeps its buttons, as
// before; a press still meets the lapse `409` and draws Expired.
return null;
}
}
+
+ async function readRow(pendingActionId: string) {
+ return readPendingActionRow(
+ await getJson(`${base}/pending-actions/${encodeURIComponent(pendingActionId)}`),
+ );
+ }
+
+ async function readConversationRows(conversationId: string) {
+ return readPendingActionRows(
+ await getJson(`${base}/pending-actions?conversationId=${encodeURIComponent(conversationId)}`),
+ );
+ }
}, [awaiting, base, headers, apiFetch]);
const decide = React.useCallback(
@@ -291,7 +331,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
const decision = approved ? 'approved' : 'rejected';
setDecision(toolCallId, {
state: 'pending',
- message: approved ? 'Approving…' : 'Rejecting…',
+ message: approved ? APPROVING_MESSAGE : 'Rejecting…',
decision,
});
inflightRef.current += 1;
@@ -348,7 +388,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
if (status === 'executed') {
setDecision(toolCallId, {
state: 'success',
- message: 'Approved — action executed.',
+ message: EXECUTED_MESSAGE,
decision,
result: payload.result,
});
@@ -356,7 +396,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
} else if (status === 'rejected') {
setDecision(toolCallId, {
state: 'success',
- message: reason ? `Rejected: ${reason}` : 'Rejected.',
+ message: rejectedMessage(reason),
decision,
});
succeeded = true;
@@ -368,7 +408,7 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
// the action ran.
setDecision(toolCallId, { state: 'held', decision: 'approved', result: payload.result });
} else if (status === 'failed') {
- const errMsg = (payload.error as string) ?? 'Action approved but execution failed.';
+ const errMsg = (payload.error as string) ?? EXECUTION_FAILED_MESSAGE;
setDecision(toolCallId, { state: 'error', message: errMsg, decision });
} else {
setDecision(toolCallId, { state: 'success', message: `Status: ${status}`, decision });
@@ -417,47 +457,120 @@ export function useHitlInChat(options: UseHitlInChatOptions): UseHitlInChatRetur
}
/**
- * The row out of a `GET …/pending-actions/:id` answer: the bare row, or the
- * `{ success, data }` envelope around it (`@objectstack/client`'s
- * `pendingActions.get` reads both). Anything without a string `status` is not
- * a row, and the card is left as it is.
+ * The wording a decision draws, shared by the press path above and by a
+ * restored card, so a card that settled elsewhere reads exactly as it would
+ * after its own press.
+ */
+const EXECUTED_MESSAGE = 'Approved — action executed.';
+const EXECUTION_FAILED_MESSAGE = 'Action approved but execution failed.';
+const APPROVING_MESSAGE = 'Approving…';
+function rejectedMessage(reason: string | undefined): string {
+ return reason ? `Rejected: ${reason}` : 'Rejected.';
+}
+
+/** The fields of a pending-action row a restored card reads. */
+type RestoredRow = Pick<
+ PendingActionRow,
+ 'status' | 'rejection_reason' | 'decided_by' | 'result' | 'error' | 'conversation_id'
+> &
+ Partial>;
+
+/**
+ * The inner value of an answer: the bare value, or the `{ success, data }`
+ * envelope around it (`@objectstack/client` reads both).
*/
-function readPendingActionRow(
+function unwrapEnvelope(body: Record): Record {
+ return typeof body.success === 'boolean' && body.data && typeof body.data === 'object'
+ ? (body.data as Record)
+ : body;
+}
+
+/** A row is an object with a string `status`; anything else is not one. */
+function asRow(value: unknown): RestoredRow | null {
+ if (!value || typeof value !== 'object') return null;
+ if (typeof (value as { status?: unknown }).status !== 'string') return null;
+ return value as RestoredRow;
+}
+
+/**
+ * The row out of a `GET …/pending-actions/:id` answer, bare or enveloped.
+ * Anything without a string `status` is not a row, and the card is left as it
+ * is.
+ */
+function readPendingActionRow(body: Record | null): RestoredRow | null {
+ if (!body) return null;
+ return asRow(unwrapEnvelope(body));
+}
+
+/**
+ * The rows of a `GET …/pending-actions?conversationId=` answer
+ * (`{ items, total }`, bare or enveloped), by id. `null` when the answer holds
+ * no item list, so every card falls back to its own read.
+ */
+function readPendingActionRows(
body: Record | null,
-): Pick | null {
+): Map | null {
if (!body) return null;
- const inner =
- typeof body.success === 'boolean' && body.data && typeof body.data === 'object'
- ? (body.data as Record)
- : body;
- if (typeof inner.status !== 'string') return null;
- return inner as unknown as Pick;
+ const items = unwrapEnvelope(body).items;
+ if (!Array.isArray(items)) return null;
+ const rows = new Map();
+ for (const item of items) {
+ const row = asRow(item);
+ if (row && typeof row.id === 'string') rows.set(row.id, row);
+ }
+ return rows;
+}
+
+/**
+ * A row's `result` is stored serialised (`PendingActionRow.result`); the card
+ * reads the value the approve answer carries, so decode it back. A stored
+ * string that is not JSON is that string.
+ */
+function storedResultOf(result: string | undefined): unknown {
+ if (result === undefined) return undefined;
+ try {
+ return JSON.parse(result);
+ } catch {
+ return result;
+ }
}
/**
* What a restored card shows for a row that has already settled, or
- * `undefined` to leave its buttons (still pending, or settled some other way).
+ * `undefined` to leave its buttons (the row is still `pending`, or its status
+ * is not one this card knows).
*
* - lapsed (nobody decided in time, or the proposer lost access) → `expired`,
* the state a press on it would reach through the lapse `409`;
* - rejected by a person (a decider is recorded) → the rejection, drawn as
- * the card draws one made in this session.
- *
- * Other settled rows (approved, executed, failed, held) keep their buttons:
- * this card's ask is the lapse, and a press on one of them still answers.
+ * the card draws one made in this session;
+ * - `executed`, `held`, `failed` → the state and wording the press path draws
+ * for the same approve outcome;
+ * - `approved` (the approval was taken and no outcome is recorded yet) → the
+ * state the card holds between an Approve press and its answer, so the
+ * card never claims a write that is not recorded.
*/
-function settledDecisionOf(
- row: Pick,
-): ToolDecisionState | undefined {
+function settledDecisionOf(row: RestoredRow): ToolDecisionState | undefined {
if (isLapsedPendingAction(row)) return { state: 'expired' };
- if (row.status === 'rejected') {
- return {
- state: 'success',
- message: row.rejection_reason ? `Rejected: ${row.rejection_reason}` : 'Rejected.',
- decision: 'rejected',
- };
+ switch (row.status) {
+ case 'rejected':
+ return { state: 'success', message: rejectedMessage(row.rejection_reason), decision: 'rejected' };
+ case 'executed':
+ return {
+ state: 'success',
+ message: EXECUTED_MESSAGE,
+ decision: 'approved',
+ result: storedResultOf(row.result),
+ };
+ case 'held':
+ return { state: 'held', decision: 'approved', result: storedResultOf(row.result) };
+ case 'failed':
+ return { state: 'error', message: row.error ?? EXECUTION_FAILED_MESSAGE, decision: 'approved' };
+ case 'approved':
+ return { state: 'pending', message: APPROVING_MESSAGE, decision: 'approved' };
+ default:
+ return undefined;
}
- return undefined;
}
/**
From 28c2fe88b708b76742faf792310b17efdcc45963 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:45:46 +0000
Subject: [PATCH 008/162] fix(data-objectstack): a byte upload the storage
refuses for good fails at once instead of being re-sent whole three more
times (#38407)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Tesla** · [project
thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoY84428Lgy3xhZTWvnZmD5t)_
Fixes #38270
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 在控制台上传文件时,存储服务明确拒收(签名过期 403、令牌过期 401、文件太大 413)现在立刻报错,不再把整个文件再传 3 次、多等约
3.5 秒。
- 只有"暂时失败"才自动重传:断网、408/425/429/502/503/504,沿用仓里唯一一份 `TRANSIENT_STATUS`
定义。取消上传照旧不重传。
- 代价:直传 S3 偶尔遇到 500 时会直接报错,不再自动重传(500 不在那份定义里,是它有意的决定)。
- 无
## What changes
- `ui/packages/data-objectstack/src/upload-adapter.ts`,
`uploadWithProgress` (step 2 of the presigned flow, the byte upload): a
failure that carries an HTTP status is retried only when the status is
in `TRANSIENT_STATUS` from `@object-ui/types` (408, 425, 429, 502, 503,
504), the one definition of "not now" `http-retry.ts` keeps for the
whole tree. Any other refusal throws at once. A failure with no HTTP
answer (a network error, the XHR `onerror`) is retried as before, and an
abort is never retried, as before. No second definition is written.
- 500 is not retried. `http-retry.ts` already decides that (a genuine
server fault). Cost, accepted in the claim: an S3 `500 InternalError` on
a direct presigned upload, which AWS documents as retryable, now fails
at once instead of being re-sent.
- Rider (accepted in the claim): the byte refusal now goes through the
same file's `refusalOf` on both the fetch path (reads `res.text()`) and
the XHR path (reads `xhr.responseText`), so it carries the server's
error `code` beside its `status` when the answer was the declared
envelope, as the presign and completion refusals already did.
`uploadFile` / `uploadFiles` map that code to `serverCode`. The local
raw PUT answers the envelope (401 `INVALID_TOKEN` for an expired upload
token); S3 answers XML, which `refusalOf` leaves as status only.
- `ui/packages/types/src/upload.ts`: the `maxRetries` JSDoc says which
failures it counts. No type change.
- `patch` changeset for `@object-ui/data-objectstack` and
`@object-ui/types`.
## Tests
- New `ui/packages/data-objectstack/src/upload-retry-38270.test.ts`: a
fake storage service answers the byte PUT, and each case runs on both
the fetch path (no `onProgress`) and the XHR path (an `onProgress` and a
stand-in `XMLHttpRequest`, unstubbed after each test). 8 cases × 2
paths:
- 413 `FILE_TOO_LARGE`, 403 and 401 `INVALID_TOKEN`: one byte request,
the error carries the status (and the code where the envelope has one).
- 500: one byte request.
- 503 then 200: two byte requests, upload succeeds. 503 forever with
`maxRetries: 3`: four byte requests, then the 503 is thrown.
- Network error then 200: two byte requests.
- Abort during the retry wait after a 503: `AbortError`, one byte
request.
Readings at 8ac61177 (base origin/main
f42bcc18)
- Premise at f42bcc18: `uploadWithProgress` (upload-adapter.ts 213-247)
rethrew only `AbortError` and retried every other failure up to
`maxRetries` (default 3), 500 × 2^n ms apart: 0.5 + 1 + 2 = 3.5 s for a
refusal that cannot change. `UploadOptions.maxRetries` was already
documented as retries "on network failure".
- New pins: `Test Files 1 passed (1)`, `Tests 16 passed (16)`.
- Request counts, read from the pins: 403 → 1 byte request with the fix,
**4** with the gate ablated (`expected 4 to be 1`); 503 then 200 → 2;
503 forever → 4 (1 + `maxRetries`).
- Ablation 1, the `TRANSIENT_STATUS` gate line replaced by a no-op:
`Tests 8 failed | 8 passed (16)` — 413, 403, 401 and 500 on both paths.
Restored after.
- Ablation 2, the two `refusalOf` calls put back to the status-only
error: `Tests 4 failed | 12 passed (16)` — the 413 and 401 code
assertions on both paths. Restored after.
- Ablation 3, the loop's `signal.aborted` check removed: `Tests 2 failed
| 14 passed (16)` — the abort pin on both paths (`expected 'Error' to be
'AbortError'`, `expected 2 to be 1`). Restored after.
- `pnpm --filter @object-ui/data-objectstack test` (under the verify
lock): `Test Files 129 passed (129)`, `Tests 1466 passed (1466)`,
`VERDICT command-exit 0`.
- `pnpm --filter @object-ui/data-objectstack --filter @object-ui/types
run type-check`: exit 0 (the package `tsconfig.json` includes
`src/**/*`, the new test with it).
- `dispatch-gates.mjs --tier`: no path-derived mandate, default tier;
273 changed lines, under 3000.
- `overlap-check.mjs` at 8ac61177: `VERDICT clean exit 0`, 0 open PR
heads touch the changed files.
- Derived gates (`dispatch-gates --commands`, 38): 38 run at 8ac61177,
every one exit 0 (each command, its exit code and its verdict line:
`/mnt/project-files/card-38270/gates-results-8ac61177.txt`).
`dispatch-gates --ran`: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN.
`pnpm --dir ui exec vitest run scripts/` (under the verify lock) and
`check:type-check-debt` included.
- PR check-runs at 8ac61177: 45 success, 13 expected skip, 0 unexpected
skip, 0 failed, 0 pending; `mergeable_state` clean (`pr-state.mjs`).
## Acceptance notes
- None.
## Verification
Read first (by risk):
1. `upload-adapter.ts`, the `catch` in `uploadWithProgress`: the
`TRANSIENT_STATUS` gate sits after the abort rethrow and before the
attempt budget.
2. The two `refusalOf` calls (fetch `!res.ok`, XHR `onload` non-2xx).
Two-minute check: `pnpm --dir ui exec vitest run
packages/data-objectstack/src/upload-retry-38270.test.ts` passes 16/16;
replace the `TRANSIENT_STATUS` gate line with a no-op and 8 go red (a
403 then makes 4 byte requests instead of 1).
---
_Generated by [Claude
Code](https://claude.ai/code/session_01L9qibxgdN9nHqqceW6yq9Q)_
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L9qibxgdN9nHqqceW6yq9Q
Co-authored-by: Claude
---
.../38270-upload-retry-transient-only.md | 15 ++
.../data-objectstack/src/upload-adapter.ts | 19 +-
.../src/upload-retry-38270.test.ts | 232 ++++++++++++++++++
ui/packages/types/src/upload.ts | 7 +-
4 files changed, 269 insertions(+), 4 deletions(-)
create mode 100644 .changeset/38270-upload-retry-transient-only.md
create mode 100644 ui/packages/data-objectstack/src/upload-retry-38270.test.ts
diff --git a/.changeset/38270-upload-retry-transient-only.md b/.changeset/38270-upload-retry-transient-only.md
new file mode 100644
index 00000000000..b44f5e686f1
--- /dev/null
+++ b/.changeset/38270-upload-retry-transient-only.md
@@ -0,0 +1,15 @@
+---
+'@object-ui/data-objectstack': patch
+'@object-ui/types': patch
+---
+
+fix(data-objectstack): a byte upload the storage refuses for good fails at once instead of being re-sent whole three more times
+
+Clause-②: no
+Metadata-protocol: none
+
+`createObjectStackUploadAdapter` retried every failure of the byte upload but an abort, so a refusal that cannot change on a resend (403 for an expired signature, 413 for a file too large, 401 `INVALID_TOKEN` for an expired local upload token) sent the whole file three more times and waited about 3.5 s before the same error reached the user. The byte upload is now retried only on a transient failure: no HTTP answer (a network error), or a status in `TRANSIENT_STATUS` from `@object-ui/types` (408, 425, 429, 502, 503, 504). Any other refusal throws at once, on both the fetch and the XHR path, and an abort is still never retried. A 500 is not retried either, as `TRANSIENT_STATUS` already decides, so an occasional S3 `500 InternalError` on a direct upload now fails at once rather than being re-sent.
+
+The refusal now carries the server's error `code` beside its `status` when the answer was the declared error envelope, as the presign and completion refusals already did, so `uploadFile` / `uploadFiles` report it as `serverCode`.
+
+`UploadOptions.maxRetries` in `@object-ui/types` now documents which failures it counts. No type changes.
diff --git a/ui/packages/data-objectstack/src/upload-adapter.ts b/ui/packages/data-objectstack/src/upload-adapter.ts
index 16ba775cad0..ca8d3cb0507 100644
--- a/ui/packages/data-objectstack/src/upload-adapter.ts
+++ b/ui/packages/data-objectstack/src/upload-adapter.ts
@@ -16,6 +16,7 @@
* data adapter.
*/
import type { API, UploadAdapter, UploadOptions } from '@object-ui/types';
+import { TRANSIENT_STATUS } from '@object-ui/types';
export interface ObjectStackUploadAdapterOptions {
/**
@@ -207,7 +208,9 @@ interface UploadFetchOptions extends UploadOptions {
/**
* Internal helper — performs a single PUT/POST with progress reporting,
- * exponential-backoff retry, and abort propagation.
+ * exponential-backoff retry of a transient failure, and abort propagation.
+ * A refusal throws `refusalOf`'s error on both paths, so it carries the
+ * status and, when the answer was the declared envelope, the server's code.
*/
async function uploadWithProgress(
fetchFn: typeof fetch,
@@ -233,12 +236,22 @@ async function uploadWithProgress(
headers: options.headers,
signal: options.signal,
});
- if (!res.ok) throw Object.assign(new Error(`Upload failed with status ${res.status}`), { status: res.status });
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw refusalOf(`Upload failed with status ${res.status}`, res.status, text);
+ }
options.onProgress?.(1);
}
return;
} catch (err) {
if ((err as DOMException)?.name === 'AbortError') throw err;
+ // A refusal with an HTTP answer is retried only when the answer means
+ // "not now" (`TRANSIENT_STATUS`, the one definition `@object-ui/types`
+ // keeps); a definitive refusal (403 expired signature, 413 too large)
+ // cannot succeed on a resend of the same bytes. A failure with no HTTP
+ // answer (network error) is retried.
+ const status = (err as { status?: unknown })?.status;
+ if (typeof status === 'number' && !TRANSIENT_STATUS.has(status)) throw err;
if (attempt >= maxRetries) throw err;
const delay = baseDelay * Math.pow(2, attempt);
attempt++;
@@ -262,7 +275,7 @@ function xhrUpload(url: string, body: Blob, options: UploadFetchOptions): Promis
options.onProgress?.(1);
resolve();
} else {
- reject(Object.assign(new Error(`Upload failed with status ${xhr.status}`), { status: xhr.status }));
+ reject(refusalOf(`Upload failed with status ${xhr.status}`, xhr.status, xhr.responseText ?? ''));
}
};
xhr.onerror = () => reject(new Error('Network error during upload'));
diff --git a/ui/packages/data-objectstack/src/upload-retry-38270.test.ts b/ui/packages/data-objectstack/src/upload-retry-38270.test.ts
new file mode 100644
index 00000000000..46b5c09f2d7
--- /dev/null
+++ b/ui/packages/data-objectstack/src/upload-retry-38270.test.ts
@@ -0,0 +1,232 @@
+/**
+ * ObjectUI
+ * Copyright (c) 2024-present ObjectStack Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/**
+ * objectstack#38270 — the byte upload is retried only on a transient failure.
+ *
+ * `createObjectStackUploadAdapter` sends the file's bytes in step 2 of the
+ * presigned flow, on the fetch path (no `onProgress`) or the XHR path (an
+ * `onProgress` and an `XMLHttpRequest`). Both used to retry every failure but
+ * an abort, so a storage refusal that cannot change on a resend — 403 (an
+ * expired signature), 413 (too large), 401 `INVALID_TOKEN` (an expired local
+ * upload token) — sent the whole file three more times before the same error
+ * reached the user.
+ *
+ * Now a refusal is retried only when its status is in `TRANSIENT_STATUS`
+ * (`@object-ui/types`, the one definition of "not now"); a failure with no HTTP
+ * answer is retried as before, and an abort never is. The refusal carries its
+ * status and, when the answer was the declared envelope, the server's code.
+ */
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { createObjectStackUploadAdapter } from './upload-adapter';
+
+const BASE = 'http://fake-38270.test';
+const STORAGE = `${BASE}/api/v1/storage`;
+const PUT_URL = `${STORAGE}/_local/raw/tok-1`;
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+/** One byte-PUT answer: a status (with an optional envelope code), or a thrown network error. */
+type PutAnswer = { status: number; code?: string } | 'network-error';
+
+function envelope(answer: { status: number; code?: string }): string {
+ return JSON.stringify({ success: false, error: { code: answer.code ?? 'REFUSED', message: 'refused' } });
+}
+
+/**
+ * A fake storage service: presign and complete always succeed; each byte PUT
+ * takes the next answer from `puts` (the last one repeats). `putCount` is how
+ * many byte requests reached it.
+ */
+function fakeStorage(puts: PutAnswer[]) {
+ let putCount = 0;
+ const nextPut = (): PutAnswer => puts[Math.min(putCount++, puts.length - 1)];
+ const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit): Promise => {
+ const url = String(input);
+ const method = init?.method ?? 'GET';
+ if (url === `${STORAGE}/upload/presigned` && method === 'POST') {
+ return json({ success: true, data: { uploadUrl: PUT_URL, fileId: 'file_1' } });
+ }
+ if (url === PUT_URL && method === 'PUT') {
+ const answer = nextPut();
+ if (answer === 'network-error') throw new TypeError('Failed to fetch');
+ if (answer.status >= 200 && answer.status < 300) return new Response(null, { status: answer.status });
+ return new Response(envelope(answer), { status: answer.status, headers: { 'Content-Type': 'application/json' } });
+ }
+ if (url === `${STORAGE}/upload/complete` && method === 'POST') {
+ return json({ success: true, data: {} });
+ }
+ return json({ success: false, error: { code: 'ENDPOINT_NOT_FOUND' } }, 404);
+ }) as typeof fetch;
+ return { fetchImpl, nextPut, putCount: () => putCount };
+}
+
+/**
+ * A stand-in `XMLHttpRequest` that answers each `send` from the same fake
+ * storage's byte-PUT answers, so the XHR path is driven the way the fetch path
+ * is. A network error fires `onerror`, as a browser does.
+ */
+function fakeXhrClass(storage: ReturnType) {
+ return class FakeXhr {
+ status = 0;
+ responseText = '';
+ upload: { onprogress: ((e: { lengthComputable: boolean; loaded: number; total: number }) => void) | null } = {
+ onprogress: null,
+ };
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onabort: (() => void) | null = null;
+ private url = '';
+ open(_method: string, url: string) {
+ this.url = url;
+ }
+ setRequestHeader() {}
+ abort() {
+ queueMicrotask(() => this.onabort?.());
+ }
+ send() {
+ if (this.url !== PUT_URL) throw new Error(`unexpected XHR to ${this.url}`);
+ const answer = storage.nextPut();
+ queueMicrotask(() => {
+ if (answer === 'network-error') {
+ this.onerror?.();
+ return;
+ }
+ this.status = answer.status;
+ if (answer.status < 200 || answer.status >= 300) this.responseText = envelope(answer);
+ this.onload?.();
+ });
+ }
+ };
+}
+
+const file = () => new File(['hello'], 'hello.txt', { type: 'text/plain' });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+/** Both byte-upload paths, driven through the same fake storage. */
+const paths = [
+ {
+ name: 'fetch path',
+ setup(_storage: ReturnType) {
+ // No `onProgress`: the adapter sends the bytes through the injected fetch.
+ return {};
+ },
+ },
+ {
+ name: 'XHR path',
+ setup(storage: ReturnType) {
+ vi.stubGlobal('XMLHttpRequest', fakeXhrClass(storage));
+ return { onProgress: () => {} };
+ },
+ },
+] as const;
+
+describe.each(paths)('byte upload retry — $name', (path) => {
+ it('a 413 refusal makes one byte request and throws its status and code at once', async () => {
+ const storage = fakeStorage([{ status: 413, code: 'FILE_TOO_LARGE' }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e);
+
+ expect(storage.putCount()).toBe(1);
+ expect(err).toMatchObject({ status: 413, code: 'FILE_TOO_LARGE' });
+ });
+
+ it('a 403 refusal (expired signature) makes one byte request', async () => {
+ const storage = fakeStorage([{ status: 403 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e);
+
+ expect(storage.putCount()).toBe(1);
+ expect(err).toMatchObject({ status: 403 });
+ });
+
+ it('a 401 INVALID_TOKEN (expired local upload token) makes one byte request', async () => {
+ const storage = fakeStorage([{ status: 401, code: 'INVALID_TOKEN' }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e);
+
+ expect(storage.putCount()).toBe(1);
+ expect(err).toMatchObject({ status: 401, code: 'INVALID_TOKEN' });
+ });
+
+ it('a 500 is not retried (TRANSIENT_STATUS leaves it out)', async () => {
+ const storage = fakeStorage([{ status: 500 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const err = await adapter.upload(file(), { ...opts, retryDelayMs: 1 }).catch((e: unknown) => e);
+
+ expect(storage.putCount()).toBe(1);
+ expect(err).toMatchObject({ status: 500 });
+ });
+
+ it('a 503 is retried, and the upload succeeds on the next attempt', async () => {
+ const storage = fakeStorage([{ status: 503 }, { status: 200 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const result = await adapter.upload(file(), { ...opts, retryDelayMs: 1 });
+
+ expect(storage.putCount()).toBe(2);
+ expect(result.meta).toMatchObject({ fileId: 'file_1' });
+ });
+
+ it('a 503 that never clears is sent 1 + maxRetries times, then throws its status', async () => {
+ const storage = fakeStorage([{ status: 503 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ const err = await adapter.upload(file(), { ...opts, maxRetries: 3, retryDelayMs: 1 }).catch((e: unknown) => e);
+
+ expect(storage.putCount()).toBe(4);
+ expect(err).toMatchObject({ status: 503 });
+ });
+
+ it('a network error (no HTTP answer) is still retried', async () => {
+ const storage = fakeStorage(['network-error', { status: 200 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+
+ await adapter.upload(file(), { ...opts, retryDelayMs: 1 });
+
+ expect(storage.putCount()).toBe(2);
+ });
+
+ it('an abort during a retry wait is not retried', async () => {
+ const storage = fakeStorage([{ status: 503 }]);
+ const opts = path.setup(storage);
+ const adapter = createObjectStackUploadAdapter({ baseUrl: BASE, fetchImpl: storage.fetchImpl });
+ const controller = new AbortController();
+
+ const pending = adapter
+ .upload(file(), { ...opts, signal: controller.signal, retryDelayMs: 50 })
+ .catch((e: unknown) => e);
+ // The first byte request answers 503; abort while the adapter waits to retry.
+ await vi.waitFor(() => expect(storage.putCount()).toBe(1));
+ controller.abort();
+ const err = await pending;
+
+ expect((err as DOMException).name).toBe('AbortError');
+ expect(storage.putCount()).toBe(1);
+ });
+});
diff --git a/ui/packages/types/src/upload.ts b/ui/packages/types/src/upload.ts
index 7e34de8b522..14c5a0c40f8 100644
--- a/ui/packages/types/src/upload.ts
+++ b/ui/packages/types/src/upload.ts
@@ -45,7 +45,12 @@ export interface UploadOptions {
onProgress?: (ratio: number) => void;
/** External abort signal — cancels the upload (and any retry attempts). */
signal?: AbortSignal;
- /** Number of retry attempts on network failure. @default 3 */
+ /**
+ * Number of retry attempts on a transient failure: no HTTP answer (a
+ * network error) or a status in `TRANSIENT_STATUS`. A definitive refusal
+ * (an expired signature, a file too large) and an abort are never retried.
+ * @default 3
+ */
maxRetries?: number;
/** Initial backoff in ms; exponential. @default 500 */
retryDelayMs?: number;
From 5df10eccaa32e64ea677b39033f382f0cf9c267b Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 00:51:11 +0000
Subject: [PATCH 009/162] fix(spec)!: retire the build-progress stream frame
now that no code reads it (#38398)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Sales** · [project
thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu7HuZkRt8dQwHpB1ErcP8fX)_
Fixes #37753
Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: none — no `skills/**` file names any of the six exports or
`data-build-progress` (`git grep -n -i
"build-progress\|BuildProgress\|BUILD_PROGRESS" -- skills/` returns
nothing)
## 维护者速读
- 是什么:spec 里给 build 对话进度面板用的流式帧定义(`ai/build-progress.zod.ts`,6
个导出)整个删掉。它唯一的读方(控制台的 build 进度面板)已随 build 对话前端删除,云端产生它的 build
循环也已删除(cloud#5046 已合并),现在没有任何代码读它。
- 为什么:没人读的导出 schema 会被下一个读者当成平台还有这个能力(ADR-0049 留或删)。
- 出错会怎样:用户无感,元数据作者无感(它从来不是可编写的元数据)。若有宿主代码还 import 这 6
个名字,升级后编译报错,changeset 里写了改法:删掉 import。可整体撤回。
- 要你做什么:批准这个拉取请求——它收窄了 `@objectstack/spec` 的公开导出,属 Tier H。
## What changes
`packages/spec/src/ai/build-progress.zod.ts` and its test are deleted,
with the `ai/index.ts` re-export. The six exports leave
`@objectstack/spec/ai`: `BuildProgressFrameSchema`,
`BuildProgressFrame`, `BuildProgressPhaseSchema`, `BuildProgressPhase`,
`BUILD_PROGRESS_PHASES`, `BUILD_PROGRESS_FRAME_TYPE`.
Route: the playbook's "nobody parses it" row (`spec-property-retirement`
§2). The frame was a stream payload, never a metadata type, so there is
no tombstone, no D2 conversion and no liveness-ledger row. What the
build asks for a whole-def removal is there:
- `RETIRED_DEFS_BY_MAJOR[19]`:
`retired-defs/19.ai__BuildProgressFrame.ts`,
`retired-defs/19.ai__BuildProgressPhase.ts` (the manifest deletion gate
names both).
- D3 semantic `ai-build-progress-frame-retired`
(`semantic/19.ai-build-progress-frame-retired.ts`), so the upgrade guide
tells a host what to delete. The changeset's ADR-0087 marker is
`registered ai-build-progress-frame-retired`. `runtime-export-retired`
does not fit: its predicate 2 refuses an operand declared in a
`*.zod.ts`.
- Deliberate baseline deletions: `json-schema.manifest/ai.json` (2 defs)
and `authorable-surface/ai.json` (3 keys). The build's check (c) accepts
the second because the whole def leaves. `authorable-surface.base.json`
is the pinned anchor and is not touched.
- Regenerated: `api-surface/ai.json` (−6), `export-origins/ai.json`
(−6), `declaration-map/ai.json` (−4), the reference docs
(`content/docs/references/ai/build-progress.mdx` removed, both indexes),
and the strictness-ledger counts.
- `type-alias-convention.pin.test.ts`: the M188 import leaves (slot
stays vacant, as for M166), the two `Iso_ai_buildProgress__*` pins
leave, and the count goes 881 → 879 in the assertion and both prose
counts.
- Three comments that cited the module as a precedent are reworded:
`contracts/ai-service.ts` (`onProgress`), `ai/record-citation.zod.ts`,
`ui/component.zod.ts` (which now says its remaining precedent,
`DashboardWidgetConfigSchema`, is declared in `ui/packages/types`).
- `packages/spec/llms.txt` (hand-kept, ships in the tarball): the schema
inventory count 233 → 232, the `ai` row 18 → 17 and its "Build Progress"
entry removed (contract review 7247625401 M2; `check:llms-txt`).
Changeset `.changeset/37753-build-progress-frame-retired.md`:
`@objectstack/spec` **minor** (kind `narrowed`), BREAKING banner, one
FROM → TO line per export group. The claim said `Metadata-protocol:
none`; `Check Changeset` reads the three removed
`authorable-surface/ai.json` rows as a narrowing and refuses `none` (run
46202350592 on 5036e03f), so the line and the level follow the gate
(7b40319d).
## Premise
- This repo, exact-name `git grep` of all six exports at `main` 600197a6
and again after merging `main` ff69bcab: zero code readers. Hits were
only the module, its test, the type-alias pin, the generated baselines,
the reference page, CHANGELOGs and three prose citations. Control, same
instrument: `KnowledgeBuildProgress` has live readers in
`service-knowledge` and `cli`. Under `ui/`, only three comments
(`plugin-chatbot/src/chat/liveness.tsx` twice,
`plugin-chatbot/src/toolResultParsers.ts:138`) and one test fixture
literal `'data-build-progress'` in
`useObjectChat.setMessagesHonest-8342.test.tsx` remain; none imports the
spec.
- Cloud: `objectstack-ai/cloud` is outside what this thread can read.
The premise that cloud no longer produces or imports the frame rests on
the maintainer's word, relayed by seat 2 on 2026-11-28 23:24Z: 「5046
已合并」 (cloud#5046, the cloud producer's removal, has merged). Card step 3
("order after cloud#5046") is therefore met.
## Verification
runs
Head 5036e03f (after `git merge origin/main`, no rebase); 7b40319d
changes only the changeset's level and kind line, and
`check:adr-0087-registration` was re-run on it (exit 0,
`metadata-protocol-narrowed`). Rework for contract review 7247625401:
1d77b3ab (M2, `llms.txt`) and 45c0e273 (S1, the changeset's fix line
names `ToolExecutionContext.onProgress`; N1, the `component.zod.ts`
comment). At 45c0e273, after a fresh spec build: `check:generated`
14/14, `check:llms-txt` 98 claims re-derived (232 schemas),
`check:adr-0087-registration` exit 0.
- `pnpm --filter @objectstack/spec build`: exit 0. The first two runs
went red on purpose, first on the manifest rows and then on the
authorable-surface rows, and each remedy above was applied.
- `pnpm --filter @objectstack/spec check:generated`: exit 0, 14/14
current.
- `pnpm check:adr-0087-registration`: exit 0 (self-test 871 assertions;
`registered ai-build-progress-frame-retired (new here)`).
- `pnpm --filter @objectstack/spec typecheck` (tsc, scripts typecheck,
test-typecheck): exit 0.
- `vitest run` on `src/type-alias-convention.pin.test.ts src/migrations
scripts/build-schemas-check-mode.deletion-proofs.test.ts src/ai`: 31
files, 791 tests passed.
- `node scripts/pm/overlap-check.mjs`: VERDICT clean.
**Dogfood battery** at 45c0e273: `pnpm --filter @objectstack/dogfood
test` under the verify lock after building its closure, VERDICT
command-exit 0, 495 test files passed (3 skipped), 4183 tests passed (68
skipped). Browser pass on `app-showcase` (own port, `--seed-admin`,
console built from this head): the boot log has no build-progress line,
the showcase app renders with zero console errors, and discovery reports
`services.ai` `enabled: false` (no AI service ships in the open
framework), so no assistant entry renders. A real tool-calling assistant
turn is NOT MEASURED: this container has no model provider key.
## Out of scope
- `docs/adr/0037-live-canvas-draft-preview.md` still lists
`data-build-progress` parts as shipped, and the three
`ui/packages/plugin-chatbot` comments cite the part name. Not touched
here (an ADR edit is its own tier); carrier: #38402.
## Human Minimum
- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
(a module removed, nothing added)
- [x] 2. Every name I added uses the casing for its kind. (entry ids
only)
- [x] 3. No formatter ran.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` touched: its generated artifacts are
regenerated and committed.
- [x] 7. No hand edits to `content/docs/releases/`.
- [x] 8. Title, body and comments are in English. (the 维护者速读 summary is
the seat's Chinese summary for the maintainer)
The branch is `claude/project-thread-akskmv`, assigned by the platform
rather than the repo's `claude/issue--…` convention.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L6bhgVih5qknszNdfFQwYb
---------
Co-authored-by: Claude
---
.../37753-build-progress-frame-retired.md | 22 ++
content/docs/references/ai/build-progress.mdx | 131 ----------
content/docs/references/ai/index.mdx | 3 +-
content/docs/references/ai/meta.json | 1 -
content/docs/references/index.mdx | 9 +-
.../ai.md | 2 +-
packages/spec/api-surface/ai.json | 6 -
packages/spec/authorable-surface/ai.json | 3 -
packages/spec/declaration-map/ai.json | 4 -
packages/spec/export-origins/ai.json | 6 -
packages/spec/json-schema.manifest/ai.json | 2 -
packages/spec/llms.txt | 4 +-
packages/spec/src/ai/build-progress.test.ts | 239 ------------------
packages/spec/src/ai/build-progress.zod.ts | 202 ---------------
packages/spec/src/ai/index.ts | 2 -
packages/spec/src/ai/record-citation.zod.ts | 5 +-
packages/spec/src/contracts/ai-service.ts | 9 +-
.../retired-defs/19.ai__BuildProgressFrame.ts | 12 +
.../retired-defs/19.ai__BuildProgressPhase.ts | 8 +
.../19.ai-build-progress-frame-retired.ts | 30 +++
.../src/type-alias-convention.pin.test.ts | 26 +-
packages/spec/src/ui/component.zod.ts | 7 +-
22 files changed, 97 insertions(+), 636 deletions(-)
create mode 100644 .changeset/37753-build-progress-frame-retired.md
delete mode 100644 content/docs/references/ai/build-progress.mdx
delete mode 100644 packages/spec/src/ai/build-progress.test.ts
delete mode 100644 packages/spec/src/ai/build-progress.zod.ts
create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressFrame.ts
create mode 100644 packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressPhase.ts
create mode 100644 packages/spec/src/migrations/entries/semantic/19.ai-build-progress-frame-retired.ts
diff --git a/.changeset/37753-build-progress-frame-retired.md b/.changeset/37753-build-progress-frame-retired.md
new file mode 100644
index 00000000000..66e78b95621
--- /dev/null
+++ b/.changeset/37753-build-progress-frame-retired.md
@@ -0,0 +1,22 @@
+---
+'@objectstack/spec': minor
+---
+
+fix(spec)!: retire the build-progress stream frame (`ai/build-progress.zod.ts`) — its reader and its producer are gone
+
+Clause-②: no (narrowing) — six published exports of `@objectstack/spec/ai` are removed
+Metadata-protocol: narrowed
+
+
+
+**BREAKING** for TypeScript code that imports the build-progress frame from `@objectstack/spec/ai`. The module declared the payload of the `data-build-progress` stream part the build chat drew as its progress panel. That panel was removed with the build chat front end, and the cloud build loop that emitted the frame was removed with it, so nothing parsed the frame any more and the exported schemas read as a capability that no longer exists (ADR-0049 enforce-or-remove). It was never authored metadata: no metadata type, source file or stored row carries it, so there is nothing for `os migrate meta` to rewrite. A lingering import stops compiling, which is where an upgrader meets the change.
+
+What moves (each line FROM → TO):
+
+- `BuildProgressFrameSchema`, `BuildProgressFrame` (`@objectstack/spec/ai`): FROM the frame's `data` floor (`phase`, `hop`, `tool`) TO removed — delete the import and the code that emits or reads a `data-build-progress` part.
+- `BuildProgressPhaseSchema`, `BuildProgressPhase`, `BUILD_PROGRESS_PHASES` (`@objectstack/spec/ai`): FROM the closed phase vocabulary (`structure`, `data`, `verify`, `done`) TO removed — delete the import.
+- `BUILD_PROGRESS_FRAME_TYPE` (`@objectstack/spec/ai`): FROM the literal `'data-build-progress'` TO removed — delete the import.
+
+The fix: delete the imports. A host that still streams a progress part of its own passes any `data-` part name to `ctx.onProgress` (`ToolExecutionContext.onProgress`, unchanged) and owns the payload shape it sends.
+
+The retirement kit: `ai/build-progress.zod.ts` and its test deleted, `RETIRED_DEFS_BY_MAJOR[19]` rows `ai/BuildProgressFrame` and `ai/BuildProgressPhase`, D3 `ai-build-progress-frame-retired`, the `json-schema.manifest/ai.json` and `authorable-surface/ai.json` rows deleted deliberately (the def is no longer emitted), the regenerated `api-surface`, `export-origins` and `declaration-map` shards, the removed `build-progress` reference page, and the `type-alias-convention` pin count 881 → 879.
diff --git a/content/docs/references/ai/build-progress.mdx b/content/docs/references/ai/build-progress.mdx
deleted file mode 100644
index 059fe43db7a..00000000000
--- a/content/docs/references/ai/build-progress.mdx
+++ /dev/null
@@ -1,131 +0,0 @@
----
-title: Build Progress schema — AI Protocol reference
-navTitle: Build Progress
-description: "Build-progress PHASE vocabulary for the data-build-progress stream frame (the cloud build-progress card, ruling A)."
----
-
-{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
-
-Build-progress PHASE vocabulary for the `data-build-progress` stream frame
-(the cloud build-progress card, ruling A).
-
-## How to read the claims in this module
-
-This vocabulary is CLOSED, so whoever next asks whether a fifth member is
-warranted has to re-measure before moving the array — and can only do that
-if they can tell a reading from a ruling. Every producer claim below
-therefore carries exactly one of three labels, and none is left bare:
-
-- **measured on a named reachable source** — a repository and path the
- reader can open and re-measure, cited with the tree it was read against.
-- **declared by ruling** — a maintainer decision. The authority is the
- ruling; ⛔ it is not evidence the behaviour exists yet.
-- **inferred** — deduced from something reachable, or carried from a record
- this repository cannot open. ⛔ Never re-cite it as a measurement.
-
-## Producer
-
-The cloud AI-studio **agent loop** — deliberately not the tool it just ran.
-**Declared by ruling**: the cloud build-progress card's ruling A owns WHERE in the loop a frame is
-emitted; this module declares only what such a frame may SAY.
-
-A build turn applies its change through `apply_blueprint` / `apply_edit` and
-then keeps working: the loop spends a further POST-APPLY VERIFICATION window
-re-reading and re-seeding what it wrote. **Inferred.** The only record of
-that window is the cloud#1838 turn, reported there as 111 seconds and 9 tool
-calls *after* `apply_blueprint` returned — and `objectstack-ai/cloud` is
-outside the set of repositories a reader of this file can open, so the
-figure is carried here, not measured, and cannot be re-measured from this
-repo. WHICH tools those 9 calls were is recorded nowhere reachable either:
-neither objectstack#18451 nor objectui#7388 names them, so "one of them ran
-the registered `verify_build` tool" is **inferred** as well. What is
-**measured on a named reachable source** is narrower than that — only that
-`verify_build` is a registered platform tool, listed in
-`PLATFORM_TOOLS_BY_PACKAGE` in `../system/constants/platform-tool-names`.
-
-A tool's own `ctx.onProgress` handle dies when the tool returns, so a frame
-emitted in that window can only come from the loop. **Inferred** from a
-reachable contract: `AIToolContext.onProgress` in `../contracts/ai-service`
-declares the emit as happening WHILE the tool executes, before it returns;
-that the handle is gone afterwards is the deduction, not the declaration.
-
-## Consumer
-
-The objectui chat panel — `extractBuildProgress` in
-`packages/plugin-chatbot/src/mapMessages.ts`, which lifts the reconciled part
-onto `ChatBuildProgress` for the build panel in `ChatbotEnhanced.tsx`. That
-reader recognises a fixed set and coerces everything else to `'structure'`,
-which renders a "still building" spinner. So an UNDECLARED phase is not
-merely unlabelled — it reads as the wrong phase, and the user watches a
-build that finished two minutes ago still claim to be building
-(objectui#7388). The panel's per-phase COPY is objectui's to choose; this
-module fixes only the set of values it must be able to tell apart.
-
-## Channel
-
-Unchanged: the `data-`-prefixed custom part described on
-`AIToolContext.onProgress` in `../contracts/ai-service`, reconciled in place
-under a stable part id. This module adds the vocabulary that prose has always
-assumed and never declared; it moves no transport and renames nothing.
-
-## Liveness watch — declared ahead, and ⛔ nothing gates it
-
-Three surfaces here are declared ahead of any code that uses them: the
-`verify` phase, and the frame's `hop` and `tool` fields. Across every
-repository reachable from here they have zero emitters and zero readers
-(**measured on named reachable sources** — each reading is recorded in the
-source beside its surface: on `BUILD_PROGRESS_PHASES` for the phase, and on
-the `hop` / `tool` field declarations). They stand on a ruling instead
-(**declared by ruling**): the cloud build-progress card ruled the vocabulary in, and
-objectui#7388 asked the panel to be able to name the phase. That is a good
-reason, and it is not a measurement.
-
-⛔ No gate watches this. The ADR-0049 liveness ledger is rooted in the
-metadata-type registry, and `BuildProgressFrame` is not a registered
-metadata type, so the liveness job stays green however long these three go
-unused. Two named carriers are meant to close it — the cloud build-progress card for the
-emitter, block 2 of the objectui build-panel card for the consumer's strict parse. If neither
-lands, the three become enforce-or-remove candidates with nothing watching
-them, and the only thing that notices is a person reading this paragraph.
-
-
-**Source:** `packages/spec/src/ai/build-progress.zod.ts`
-
-
-## TypeScript Usage
-
-```typescript
-import { BuildProgressFrameSchema, BuildProgressPhaseSchema } from '@objectstack/spec/ai';
-import type { BuildProgressFrame, BuildProgressPhase } from '@objectstack/spec/ai';
-
-// Validate data
-const result = BuildProgressFrameSchema.parse(data);
-```
-
----
-
-## BuildProgressFrame
-
-### Properties
-
-| Property | Type | Required | Description |
-| :--- | :--- | :--- | :--- |
-| **phase** | `Enum<'structure' \| 'data' \| 'verify' \| 'done'>` | ✅ | Build-turn phase this frame reports |
-| **hop** | `integer` | optional | Post-apply verification hop this frame reports |
-| **tool** | `string` | optional | Name of the tool the current hop is running |
-
-
----
-
-## BuildProgressPhase
-
-### Allowed Values
-
-* `structure`
-* `data`
-* `verify`
-* `done`
-
-
----
-
diff --git a/content/docs/references/ai/index.mdx b/content/docs/references/ai/index.mdx
index dd0bf3925c6..cd644fb5866 100644
--- a/content/docs/references/ai/index.mdx
+++ b/content/docs/references/ai/index.mdx
@@ -1,7 +1,7 @@
---
title: AI Protocol — complete schema reference
navTitle: AI Protocol
-description: "The ObjectStack AI Protocol in 18 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
+description: "The ObjectStack AI Protocol in 17 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
---
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
@@ -12,7 +12,6 @@ This section contains all protocol schemas for the ai layer of ObjectStack.
-
diff --git a/content/docs/references/ai/meta.json b/content/docs/references/ai/meta.json
index d77e258852b..8803b3e8f34 100644
--- a/content/docs/references/ai/meta.json
+++ b/content/docs/references/ai/meta.json
@@ -17,7 +17,6 @@
"---More---",
"ai-context",
"ask-question",
- "build-progress",
"dataset-tools",
"draft-review",
"object-query-source",
diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx
index 04a0cd9dd38..42379619350 100644
--- a/content/docs/references/index.mdx
+++ b/content/docs/references/index.mdx
@@ -1,7 +1,7 @@
---
title: Protocol reference — every schema by module
navTitle: Protocol Reference
-description: Every schema published by @objectstack/spec — 1744 schemas across 14 protocol modules
+description: Every schema published by @objectstack/spec — 1742 schemas across 14 protocol modules
---
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
@@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with
| Module | Pages | Schemas | Description |
| :--- | ---: | ---: | :--- |
-| [AI Protocol](/docs/references/ai) | 18 | 104 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. |
+| [AI Protocol](/docs/references/ai) | 17 | 102 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. |
| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 529 | REST contracts, endpoints, routing, realtime, batch, discovery. |
| [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. |
| [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. |
@@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with
| [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. |
| [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. |
| [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. |
-| **Total** | **224** | **1744** | 14 protocol modules |
+| **Total** | **223** | **1742** | 14 protocol modules |
---
## AI Protocol
-**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 104 schemas**
+**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 102 schemas**
Agents, tools, skills, RAG and knowledge sources, model registry, conversations.
@@ -51,7 +51,6 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations.
| [`agent.zod.ts`](/docs/references/ai/agent) | `AIModelConfig`, `Agent`, `StructuredOutputConfig`, `StructuredOutputFormat`, `TransformPipelineStep` |
| [`ai-context.zod.ts`](/docs/references/ai/ai-context) | `AiContext`, `AiContextBody`, `AiContextRelated`, `AiContextRelatedWhere` |
| [`ask-question.zod.ts`](/docs/references/ai/ask-question) | `AskQuestion`, `AskQuestionEnvelope`, `AskQuestionOption` |
-| [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` |
| [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` |
| [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` |
| [`draft-review.zod.ts`](/docs/references/ai/draft-review) | `DraftReviewItem`, `DraftReviewLinks`, `DraftReviewList`, `DraftReviewVerdict`, `DraftReviewVerdictRefusal` |
diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md
index 5f25e0c458c..3bf684e33e2 100644
--- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md
+++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md
@@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate.
| Dir | Sites |
|---|---|
-| `ai/` | 121 |
+| `ai/` | 120 |
diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json
index fdd2e061505..fbc00deb6cc 100644
--- a/packages/spec/api-surface/ai.json
+++ b/packages/spec/api-surface/ai.json
@@ -45,8 +45,6 @@
"AskQuestionOptionSchema (const)",
"AskQuestionParsed (type)",
"AskQuestionSchema (const)",
- "BUILD_PROGRESS_FRAME_TYPE (const)",
- "BUILD_PROGRESS_PHASES (const)",
"BlueprintApp (type)",
"BlueprintAppParsed (type)",
"BlueprintAppSchema (const)",
@@ -71,10 +69,6 @@
"BlueprintWidgetCondition (type)",
"BlueprintWidgetConditionSchema (const)",
"BodyHeading (interface)",
- "BuildProgressFrame (type)",
- "BuildProgressFrameSchema (const)",
- "BuildProgressPhase (type)",
- "BuildProgressPhaseSchema (const)",
"CodeContentSchema (const)",
"ConversationAnalytics (type)",
"ConversationAnalyticsParsed (type)",
diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json
index f5d1964962c..b844b115a60 100644
--- a/packages/spec/authorable-surface/ai.json
+++ b/packages/spec/authorable-surface/ai.json
@@ -123,9 +123,6 @@
"ai/BlueprintWidgetCondition:field",
"ai/BlueprintWidgetCondition:op",
"ai/BlueprintWidgetCondition:value",
- "ai/BuildProgressFrame:hop",
- "ai/BuildProgressFrame:phase",
- "ai/BuildProgressFrame:tool",
"ai/CodeContent:language",
"ai/CodeContent:metadata",
"ai/CodeContent:text",
diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json
index 745aae943a1..5c53d6cc8af 100644
--- a/packages/spec/declaration-map/ai.json
+++ b/packages/spec/declaration-map/ai.json
@@ -41,10 +41,6 @@
"BlueprintViewSchema": "ai/BlueprintView",
"BlueprintWidgetCondition": "ai/BlueprintWidgetCondition",
"BlueprintWidgetConditionSchema": "ai/BlueprintWidgetCondition",
- "BuildProgressFrame": "ai/BuildProgressFrame",
- "BuildProgressFrameSchema": "ai/BuildProgressFrame",
- "BuildProgressPhase": "ai/BuildProgressPhase",
- "BuildProgressPhaseSchema": "ai/BuildProgressPhase",
"CodeContentSchema": "ai/CodeContent",
"ConversationAnalytics": "ai/ConversationAnalytics",
"ConversationAnalyticsSchema": "ai/ConversationAnalytics",
diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json
index ad9e5772fec..d5129c141cd 100644
--- a/packages/spec/export-origins/ai.json
+++ b/packages/spec/export-origins/ai.json
@@ -45,8 +45,6 @@
"AskQuestionOptionSchema": "src/ai/ask-question.zod.ts#AskQuestionOptionSchema (const)",
"AskQuestionParsed": "src/ai/ask-question.zod.ts#AskQuestionParsed (type)",
"AskQuestionSchema": "src/ai/ask-question.zod.ts#AskQuestionSchema (const)",
- "BUILD_PROGRESS_FRAME_TYPE": "src/ai/build-progress.zod.ts#BUILD_PROGRESS_FRAME_TYPE (const)",
- "BUILD_PROGRESS_PHASES": "src/ai/build-progress.zod.ts#BUILD_PROGRESS_PHASES (const)",
"BlueprintApp": "src/ai/solution-blueprint.zod.ts#BlueprintApp (type)",
"BlueprintAppParsed": "src/ai/solution-blueprint.zod.ts#BlueprintAppParsed (type)",
"BlueprintAppSchema": "src/ai/solution-blueprint.zod.ts#BlueprintAppSchema (const)",
@@ -71,10 +69,6 @@
"BlueprintWidgetCondition": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetCondition (type)",
"BlueprintWidgetConditionSchema": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetConditionSchema (const)",
"BodyHeading": "src/ai/record-body-anchor.ts#BodyHeading (interface)",
- "BuildProgressFrame": "src/ai/build-progress.zod.ts#BuildProgressFrame (type)",
- "BuildProgressFrameSchema": "src/ai/build-progress.zod.ts#BuildProgressFrameSchema (const)",
- "BuildProgressPhase": "src/ai/build-progress.zod.ts#BuildProgressPhase (type)",
- "BuildProgressPhaseSchema": "src/ai/build-progress.zod.ts#BuildProgressPhaseSchema (const)",
"CodeContentSchema": "src/ai/conversation.zod.ts#CodeContentSchema (const)",
"ConversationAnalytics": "src/ai/conversation.zod.ts#ConversationAnalytics (type)",
"ConversationAnalyticsParsed": "src/ai/conversation.zod.ts#ConversationAnalyticsParsed (type)",
diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json
index 75ae2fdc37d..4045da724c8 100644
--- a/packages/spec/json-schema.manifest/ai.json
+++ b/packages/spec/json-schema.manifest/ai.json
@@ -22,8 +22,6 @@
"ai/BlueprintSummaryOperations",
"ai/BlueprintView",
"ai/BlueprintWidgetCondition",
- "ai/BuildProgressFrame",
- "ai/BuildProgressPhase",
"ai/CodeContent",
"ai/ConversationAnalytics",
"ai/ConversationContext",
diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt
index 2118475e129..421abf76260 100644
--- a/packages/spec/llms.txt
+++ b/packages/spec/llms.txt
@@ -77,7 +77,7 @@ const query = {
---
-## 3. Schema Inventory by Domain (233 schemas)
+## 3. Schema Inventory by Domain (232 schemas)
Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources
that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number
@@ -92,7 +92,7 @@ here is verifiable from the installed package.
| ui | 19 | View, App (incl. AI Chat Nav Params), Action, Dashboard, Page, Chart, Component, Animation |
| automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization |
| shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) |
-| ai | 18 | Agent, AI Context (context pack), Ask Question (question-card envelope), Build Progress, Conversation, Dataset Tools, Draft Review (`data-draft-review` part), Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Citation, Record Context Tools (`get_record_context`), Skill, Tool |
+| ai | 17 | Agent, AI Context (context pack), Ask Question (question-card envelope), Conversation, Dataset Tools, Draft Review (`data-draft-review` part), Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Citation, Record Context Tools (`get_record_context`), Skill, Tool |
| identity | 5 | Identity, Organization, Position, SCIM, Eval User |
| marketplace | 5 | Marketplace, Package, Package Version, Template Manifest, Taxonomy |
| security | 5 | Permission, RLS, Sharing, Queue, Explain |
diff --git a/packages/spec/src/ai/build-progress.test.ts b/packages/spec/src/ai/build-progress.test.ts
deleted file mode 100644
index ba4b916177c..00000000000
--- a/packages/spec/src/ai/build-progress.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
-
-/**
- * Pin for the build-progress PHASE vocabulary (cloud#2172 ruling A).
- *
- * What is actually at stake here is not "does zod reject a bad string" — it is
- * that this vocabulary is CLOSED and that its refusal is LOUD. objectui#7388
- * measured the cost of the alternative: the consumer's reader coerces any
- * value it does not recognise to `'structure'`, so a phase nobody declared
- * renders as a "still building" spinner for the 111 seconds the build spends
- * being verified after it finished. A refusal that merely throws leaves the
- * next author guessing; a refusal that names the accepted set tells them.
- *
- * So the refusal leg asserts the ENVELOPE, not the throw: zod 4 answers an
- * out-of-vocabulary enum value with `invalid_value` and carries the full
- * accepted set on the issue. ⛔ A bare `expect(...).toThrow()` here would stay
- * green against a schema that had degraded to a bare `z.string()` with a
- * refinement, which is exactly the degradation worth catching.
- *
- * The membership leg is the closed-enum pin. Each member was measured against
- * a real end of the channel (provenance is recorded per member on
- * `BUILD_PROGRESS_PHASES` in the source), so this array moving is a claim that
- * someone re-measured — not an edit to wave through.
- */
-
-import { readFileSync } from 'node:fs';
-import { dirname, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-import { describe, it, expect } from 'vitest';
-
-import {
- BUILD_PROGRESS_PHASES,
- BUILD_PROGRESS_FRAME_TYPE,
- BuildProgressPhaseSchema,
- BuildProgressFrameSchema,
- type BuildProgressPhase,
-} from './build-progress.zod';
-
-/**
- * The phases objectui's reader discriminates TODAY
- * (`packages/plugin-chatbot/src/mapMessages.ts` `extractBuildProgress`, and the
- * `ChatBuildProgress['phase']` union in `ChatbotEnhanced.tsx`). Declaring
- * `verify` must not disturb the inherited three — this is the control that has
- * to keep moving, not a restatement of the vocabulary under test.
- */
-const PHASES_THE_CONSUMER_ALREADY_RENDERS = ['structure', 'data', 'done'] as const;
-
-describe('BUILD_PROGRESS_PHASES (closed membership)', () => {
- it('is exactly the measured vocabulary, in lifecycle order', () => {
- expect(BUILD_PROGRESS_PHASES).toEqual(['structure', 'data', 'verify', 'done']);
- });
-
- it('still contains every phase the objectui reader already discriminates', () => {
- for (const phase of PHASES_THE_CONSUMER_ALREADY_RENDERS) {
- expect(BUILD_PROGRESS_PHASES).toContain(phase);
- }
- });
-
- it('names the post-apply verification phase the card exists to declare', () => {
- expect(BUILD_PROGRESS_PHASES).toContain('verify');
- });
-});
-
-describe('BuildProgressPhaseSchema', () => {
- it('parses every declared phase', () => {
- for (const phase of BUILD_PROGRESS_PHASES) {
- const result = BuildProgressPhaseSchema.safeParse(phase);
- expect(result.success).toBe(true);
- expect(result.success && result.data).toBe(phase);
- }
- });
-
- it('REFUSES an undeclared phase, and the refusal names the accepted set', () => {
- const result = BuildProgressPhaseSchema.safeParse('rebuilding');
-
- expect(result.success).toBe(false);
- if (result.success) throw new Error('unreachable: an undeclared phase parsed');
-
- const [issue] = result.error.issues;
- expect(result.error.issues).toHaveLength(1);
- expect(issue.code).toBe('invalid_value');
- // The loud half: the author is told what WAS allowed, not merely that they
- // were wrong. Compared against the exported vocabulary so the two cannot
- // drift apart silently.
- expect((issue as { values?: readonly unknown[] }).values).toEqual([...BUILD_PROGRESS_PHASES]);
- });
-
- it('REFUSES the neighbouring vocabulary of the sibling blueprint-progress frame', () => {
- // `data-blueprint-progress` is a DIFFERENT channel with its own phases
- // (`designing` / `done`). Folding its vocabulary in here would be the
- // "one enum for two frames" mistake; `designing` must not parse.
- expect(BuildProgressPhaseSchema.safeParse('designing').success).toBe(false);
- });
-
- it('REFUSES a non-string', () => {
- expect(BuildProgressPhaseSchema.safeParse(3).success).toBe(false);
- expect(BuildProgressPhaseSchema.safeParse(undefined).success).toBe(false);
- });
-});
-
-describe('BUILD_PROGRESS_FRAME_TYPE', () => {
- it('is the literal both ends select on', () => {
- // objectui selects parts with `p.type === 'data-build-progress'`; the
- // `data-` prefix is what makes it a custom data part at all.
- expect(BUILD_PROGRESS_FRAME_TYPE).toBe('data-build-progress');
- expect(BUILD_PROGRESS_FRAME_TYPE.startsWith('data-')).toBe(true);
- });
-});
-
-describe('BuildProgressFrameSchema', () => {
- it('parses a frame carrying only the required phase', () => {
- const result = BuildProgressFrameSchema.safeParse({ phase: 'verify' });
- expect(result.success).toBe(true);
- expect(result.success && result.data.phase).toBe('verify');
- expect(result.success && result.data.hop).toBeUndefined();
- expect(result.success && result.data.tool).toBeUndefined();
- });
-
- it('parses a frame carrying both optional fields', () => {
- const result = BuildProgressFrameSchema.safeParse({
- phase: 'verify',
- hop: 4,
- tool: 'verify_build',
- });
- expect(result.success).toBe(true);
- expect(result.success && result.data).toMatchObject({
- phase: 'verify',
- hop: 4,
- tool: 'verify_build',
- });
- });
-
- it('parses a frame carrying each optional field on its own', () => {
- expect(BuildProgressFrameSchema.safeParse({ phase: 'data', hop: 0 }).success).toBe(true);
- expect(BuildProgressFrameSchema.safeParse({ phase: 'data', tool: 'create_seed' }).success).toBe(true);
- });
-
- it('is a FLOOR: the panel fields objectui already reads survive the parse', () => {
- // Regression guard for "tighten it to .strict()". Every key below is read
- // by `extractBuildProgress` off this same frame today; refusing or
- // stripping them would break the shipping consumer.
- const shipping = {
- phase: 'structure' as const,
- appLabel: 'CRM',
- items: [{ type: 'object', name: 'contacts' }],
- done: 1,
- total: 4,
- seq: 12,
- };
-
- const result = BuildProgressFrameSchema.safeParse(shipping);
- expect(result.success).toBe(true);
- expect(result.success && result.data).toMatchObject(shipping);
- });
-
- it('REFUSES an undeclared phase, locating it at `phase`', () => {
- const result = BuildProgressFrameSchema.safeParse({ phase: 'rebuilding', hop: 1 });
-
- expect(result.success).toBe(false);
- if (result.success) throw new Error('unreachable: a frame with an undeclared phase parsed');
-
- const [issue] = result.error.issues;
- expect(issue.code).toBe('invalid_value');
- expect(issue.path).toEqual(['phase']);
- });
-
- it('REFUSES a frame with no phase at all', () => {
- const result = BuildProgressFrameSchema.safeParse({ hop: 2, tool: 'verify_build' });
- expect(result.success).toBe(false);
- expect(result.success === false && result.error.issues[0].path).toEqual(['phase']);
- });
-
- it('REFUSES a malformed hop and an empty tool name', () => {
- expect(BuildProgressFrameSchema.safeParse({ phase: 'verify', hop: -1 }).success).toBe(false);
- expect(BuildProgressFrameSchema.safeParse({ phase: 'verify', hop: 1.5 }).success).toBe(false);
- expect(BuildProgressFrameSchema.safeParse({ phase: 'verify', tool: '' }).success).toBe(false);
- });
-});
-
-describe('BuildProgressPhase (type)', () => {
- it('admits every declared member and is assignable from the array', () => {
- const everyPhase: BuildProgressPhase[] = [...BUILD_PROGRESS_PHASES];
- expect(everyPhase).toHaveLength(BUILD_PROGRESS_PHASES.length);
- });
-});
-
-/**
- * The provenance leg — and the one leg whose subject is TEXT on purpose.
- *
- * This module's docblock is not incidental prose. The published
- * `@objectstack/spec` tarball ships the `.zod.ts` sources themselves, and the
- * same text is rendered verbatim into
- * `content/docs/references/ai/build-progress.mdx`. For a CLOSED vocabulary it
- * is the audit trail the "re-measure before you move the array" discipline
- * reads: a reader who cannot tell a MEASUREMENT from a RULING re-cites the
- * ruling as evidence, and the next member goes in on a claim nobody ever made.
- *
- * So what is pinned here is narrow and load-bearing: that the three labels are
- * defined, that `verify` is labelled as the ruling it is rather than as a
- * measurement, and that the liveness watch is still present — ⛔ not the
- * wording around any of them. Nothing else in this file asserts on text.
- */
-describe('module docblock provenance', () => {
- const SOURCE = readFileSync(
- resolve(dirname(fileURLToPath(import.meta.url)), 'build-progress.zod.ts'),
- 'utf-8',
- );
-
- it('defines all three provenance labels', () => {
- for (const label of ['measured on a named reachable source', 'declared by ruling', 'inferred']) {
- expect(SOURCE).toContain(label);
- }
- });
-
- it('labels `verify` as declared by ruling, and ⛔ never as measured membership', () => {
- // The bullet itself, not the surrounding paragraph: `verify` is in the
- // enum because cloud#2172 ruled it in, which is a good reason and is not
- // an observation of any producer or consumer.
- const bullet = SOURCE.slice(SOURCE.indexOf(' * - `verify`'));
- expect(bullet.slice(0, 200)).toContain('**declared by ruling**');
-
- // The retired headline claimed every member was measured against a real
- // end of the channel. It was false for `verify` on the day it was written.
- expect(SOURCE).not.toContain('Membership was MEASURED');
- expect(SOURCE).not.toContain('every member below is one a real producer emits');
- });
-
- it('keeps the liveness watch for the three declared-ahead surfaces', () => {
- expect(SOURCE).toContain('## Liveness watch');
- for (const surface of ['`verify` phase', '`hop`', '`tool`']) {
- expect(SOURCE).toContain(surface);
- }
- // The point of the watch: no gate notices, so the paragraph is the notice.
- expect(SOURCE).toContain('ADR-0049');
- expect(SOURCE).toContain('the cloud build-progress card');
- expect(SOURCE).toContain('block 2 of the objectui build-panel card');
- });
-});
diff --git a/packages/spec/src/ai/build-progress.zod.ts b/packages/spec/src/ai/build-progress.zod.ts
deleted file mode 100644
index 974f47dea2b..00000000000
--- a/packages/spec/src/ai/build-progress.zod.ts
+++ /dev/null
@@ -1,202 +0,0 @@
-// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
-
-import { z } from 'zod';
-import { lazySchema } from '../shared/lazy-schema';
-
-/**
- * Build-progress PHASE vocabulary for the `data-build-progress` stream frame
- * (the cloud build-progress card, ruling A).
- *
- * ## How to read the claims in this module
- *
- * This vocabulary is CLOSED, so whoever next asks whether a fifth member is
- * warranted has to re-measure before moving the array — and can only do that
- * if they can tell a reading from a ruling. Every producer claim below
- * therefore carries exactly one of three labels, and none is left bare:
- *
- * - **measured on a named reachable source** — a repository and path the
- * reader can open and re-measure, cited with the tree it was read against.
- * - **declared by ruling** — a maintainer decision. The authority is the
- * ruling; ⛔ it is not evidence the behaviour exists yet.
- * - **inferred** — deduced from something reachable, or carried from a record
- * this repository cannot open. ⛔ Never re-cite it as a measurement.
- *
- * ## Producer
- *
- * The cloud AI-studio **agent loop** — deliberately not the tool it just ran.
- * **Declared by ruling**: the cloud build-progress card's ruling A owns WHERE in the loop a frame is
- * emitted; this module declares only what such a frame may SAY.
- *
- * A build turn applies its change through `apply_blueprint` / `apply_edit` and
- * then keeps working: the loop spends a further POST-APPLY VERIFICATION window
- * re-reading and re-seeding what it wrote. **Inferred.** The only record of
- * that window is the cloud#1838 turn, reported there as 111 seconds and 9 tool
- * calls *after* `apply_blueprint` returned — and `objectstack-ai/cloud` is
- * outside the set of repositories a reader of this file can open, so the
- * figure is carried here, not measured, and cannot be re-measured from this
- * repo. WHICH tools those 9 calls were is recorded nowhere reachable either:
- * neither objectstack#18451 nor objectui#7388 names them, so "one of them ran
- * the registered `verify_build` tool" is **inferred** as well. What is
- * **measured on a named reachable source** is narrower than that — only that
- * `verify_build` is a registered platform tool, listed in
- * `PLATFORM_TOOLS_BY_PACKAGE` in `../system/constants/platform-tool-names`.
- *
- * A tool's own `ctx.onProgress` handle dies when the tool returns, so a frame
- * emitted in that window can only come from the loop. **Inferred** from a
- * reachable contract: `AIToolContext.onProgress` in `../contracts/ai-service`
- * declares the emit as happening WHILE the tool executes, before it returns;
- * that the handle is gone afterwards is the deduction, not the declaration.
- *
- * ## Consumer
- *
- * The objectui chat panel — `extractBuildProgress` in
- * `packages/plugin-chatbot/src/mapMessages.ts`, which lifts the reconciled part
- * onto `ChatBuildProgress` for the build panel in `ChatbotEnhanced.tsx`. That
- * reader recognises a fixed set and coerces everything else to `'structure'`,
- * which renders a "still building" spinner. So an UNDECLARED phase is not
- * merely unlabelled — it reads as the wrong phase, and the user watches a
- * build that finished two minutes ago still claim to be building
- * (objectui#7388). The panel's per-phase COPY is objectui's to choose; this
- * module fixes only the set of values it must be able to tell apart.
- *
- * ## Channel
- *
- * Unchanged: the `data-`-prefixed custom part described on
- * `AIToolContext.onProgress` in `../contracts/ai-service`, reconciled in place
- * under a stable part id. This module adds the vocabulary that prose has always
- * assumed and never declared; it moves no transport and renames nothing.
- *
- * ## Liveness watch — declared ahead, and ⛔ nothing gates it
- *
- * Three surfaces here are declared ahead of any code that uses them: the
- * `verify` phase, and the frame's `hop` and `tool` fields. Across every
- * repository reachable from here they have zero emitters and zero readers
- * (**measured on named reachable sources** — each reading is recorded in the
- * source beside its surface: on `BUILD_PROGRESS_PHASES` for the phase, and on
- * the `hop` / `tool` field declarations). They stand on a ruling instead
- * (**declared by ruling**): the cloud build-progress card ruled the vocabulary in, and
- * objectui#7388 asked the panel to be able to name the phase. That is a good
- * reason, and it is not a measurement.
- *
- * ⛔ No gate watches this. The ADR-0049 liveness ledger is rooted in the
- * metadata-type registry, and `BuildProgressFrame` is not a registered
- * metadata type, so the liveness job stays green however long these three go
- * unused. Two named carriers are meant to close it — the cloud build-progress card for the
- * emitter, block 2 of the objectui build-panel card for the consumer's strict parse. If neither
- * lands, the three become enforce-or-remove candidates with nothing watching
- * them, and the only thing that notices is a person reading this paragraph.
- */
-
-/**
- * The closed phase vocabulary, in emission-lifecycle order.
- *
- * Membership is MIXED-PROVENANCE, not uniformly measured. Each member carries
- * its own label (the three are defined at the top of this module), because the
- * question a re-measure has to answer is which members a real end of the
- * channel already uses and which are standing on a ruling alone:
- *
- * - `structure`, `data`, `done` — **measured on a named reachable source**:
- * the consumer's own declared union,
- * `ChatBuildProgress['phase']` at `packages/plugin-chatbot/src/ChatbotEnhanced.tsx:163`
- * in objectui, and the set its reader discriminates at
- * `packages/plugin-chatbot/src/mapMessages.ts:743`
- * (`d.phase === 'data' || d.phase === 'done' ? d.phase : 'structure'`).
- * `structure` doubles as that reader's coercion default. Read at objectui
- * `dda8f3815`; line numbers drift, the two symbols are the anchor.
- * - `verify` — **declared by ruling**, ⛔ not measured: the post-apply
- * verification window objectui#7388 asks the panel to be able to name, and
- * the reason the cloud build-progress card ruled this vocabulary into the spec. At objectui
- * `dda8f3815` `packages/plugin-chatbot` has ZERO occurrences of `'verify'`
- * (bright control, same instrument: `'structure'` hits 4 files there), and
- * this repository emits no frame at all, so `verify` has no reachable
- * emitter and no reachable reader today. **Measured on a named reachable
- * source** alongside it, and narrower than a corroboration of the phase:
- * `service-ai-studio` registers a `verify_build` tool
- * (`../system/constants/platform-tool-names`). See the liveness watch at the
- * top of this module.
- *
- * Order is the order a build turn passes through these states; it is NOT a
- * scale. ⛔ Consumers compare phases by VALUE — never by index, and never by
- * assuming every phase occurs. The two illustrations of a phase being skipped
- * — a turn that applies no seed data never reporting `data`, and `apply_edit`
- * turns not reporting `structure` — are **inferred**: no reachable repository
- * records either, and the cloud build-progress card's emitter has not landed. ⛔ The guidance
- * does not rest on them; treat every phase as optional whatever a producer
- * turns out to do.
- *
- * Exported as an array as well as a schema so a consumer can build an
- * exhaustive per-phase label map without forcing the lazy schema to
- * construct just to read `.options`.
- */
-export const BUILD_PROGRESS_PHASES = ['structure', 'data', 'verify', 'done'] as const;
-
-/**
- * The phase a `data-build-progress` frame is reporting.
- *
- * Closed on purpose: an unrecognised value is REFUSED here, loudly, at the
- * seam that can still say which value was wrong. The alternative is what
- * objectui#7388 measured — a silent coercion to a neighbouring phase, which
- * costs the user a correct-looking label describing something that already
- * finished.
- */
-export const BuildProgressPhaseSchema = lazySchema(() => z.enum(BUILD_PROGRESS_PHASES));
-
-/**
- * The stream part name this vocabulary rides, as a Vercel UI-message-stream
- * custom data-part name. Emitters pass it as `ctx.onProgress({ type, id, data })`
- * and the objectui reader selects parts by exactly this string, so it is the
- * one literal both ends must agree on.
- */
-export const BUILD_PROGRESS_FRAME_TYPE = 'data-build-progress';
-
-/**
- * The `data` payload of a `data-build-progress` frame — a FLOOR, not a
- * ceiling.
- *
- * Declared minimal on purpose, and deliberately **not** strict. The same frame
- * already carries the objectui build panel's own presentation fields
- * (`appLabel`, `items`, `done`, `total`, `seq` — read in `extractBuildProgress`),
- * which are the consumer's to shape; a strict schema here would refuse every
- * frame shipping today and would claim ownership of fields this package does
- * not define. What this schema asserts is the part any consumer may rely on:
- * a frame says which phase it is in, and may say which verification hop it is
- * on and which tool that hop is running.
- */
-export const BuildProgressFrameSchema = lazySchema(() => z.looseObject({
- /** Which phase of the build turn this frame reports. */
- phase: BuildProgressPhaseSchema.describe('Build-turn phase this frame reports'),
- /**
- * Which hop of the post-apply verification loop this frame is on — the
- * counter behind the "9 tool calls" the cloud#1838 turn record reports, so
- * the panel can show motion through a window that is otherwise a single flat
- * phase. **Inferred** that a producer counts hops at all: that record is not
- * reachable from this repository (see the Producer section).
- *
- * Typed as a non-negative integer rather than pinned to a base: whether the
- * loop counts its first hop as 0 or 1 is part of the emitter's placement,
- * which the cloud build-progress card owns and this card does not decide. ⛔ Consumers render it
- * as progress, never as an index into anything here.
- *
- * ⛔ Zero emitters and zero readers in every reachable repository at this
- * tree — see the liveness watch at the top of this module.
- */
- hop: z.number().int().nonnegative().optional().describe('Post-apply verification hop this frame reports'),
- /**
- * Name of the tool the current hop is running, e.g. `verify_build`.
- *
- * A free string, not a closed set: the runtime's executable tool set is
- * registered at boot and legitimately includes plugin-contributed names that
- * `PLATFORM_PROVIDED_TOOL_NAMES` cannot know about
- * (`../system/constants/platform-tool-names`). Consumers treat it as a label.
- *
- * ⛔ Zero emitters and zero readers in every reachable repository at this
- * tree — see the liveness watch at the top of this module.
- */
- tool: z.string().min(1).optional().describe('Name of the tool the current hop is running'),
-}));
-
-/** A phase from the closed {@link BUILD_PROGRESS_PHASES} vocabulary. */
-export type BuildProgressPhase = z.input;
-
-/** The `data` payload of a `data-build-progress` frame. */
-export type BuildProgressFrame = z.input;
diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts
index 4c371be2f7b..838213617eb 100644
--- a/packages/spec/src/ai/index.ts
+++ b/packages/spec/src/ai/index.ts
@@ -24,7 +24,6 @@
* - Context pack — the `ai_context` kind and the `get_record_context` tool's input and output (ADR-0160)
* - Record citation — the citation shape an answer carries, and the body anchor it names (ADR-0160 D9)
* - Object-query source — the `source` block the Ask data tools answer beside their result
- * - Build Progress — phase vocabulary for the agent loop's `data-build-progress` frames
* - Ask question — the envelope a question tool's result carries, from which the console draws a question card
* - Draft review — the `data-draft-review` part listing the drafts an ask turn saved, drawn as a review card
*/
@@ -51,7 +50,6 @@ export * from './object-query-source.zod';
export * from './knowledge-source.zod';
export * from './knowledge-document.zod';
export * from './solution-blueprint.zod';
-export * from './build-progress.zod';
export * from './ask-question.zod';
export * from './draft-review.zod';
diff --git a/packages/spec/src/ai/record-citation.zod.ts b/packages/spec/src/ai/record-citation.zod.ts
index 76ded7ac9d7..07d0a9604cd 100644
--- a/packages/spec/src/ai/record-citation.zod.ts
+++ b/packages/spec/src/ai/record-citation.zod.ts
@@ -41,9 +41,8 @@ import { strictObject } from '../shared/strict-object';
/**
* The stream part name a verified citation list rides, as a UI-message-stream
- * custom data-part name (the precedent is `BUILD_PROGRESS_FRAME_TYPE`). The
- * producer and every surface that draws the list select the part by exactly
- * this string.
+ * custom data-part name. The producer and every surface that draws the list
+ * select the part by exactly this string.
*/
export const RECORD_CITATIONS_PART_TYPE = 'data-record-citations';
diff --git a/packages/spec/src/contracts/ai-service.ts b/packages/spec/src/contracts/ai-service.ts
index 75ebf89f893..8ae4e70d3f6 100644
--- a/packages/spec/src/contracts/ai-service.ts
+++ b/packages/spec/src/contracts/ai-service.ts
@@ -1405,12 +1405,9 @@ export interface ToolExecutionContext {
* so handlers must call it optionally (`ctx.onProgress?.(…)`).
*
* `type` is a Vercel UI-message-stream custom data-part name (must start
- * with `data-`, e.g. `data-build-progress`). Pass a stable `id` to RECONCILE
- * (replace) the part across emits — ideal for a single progress object that
- * updates in place; omit `id` for append-only events. `data` is the payload.
- *
- * Example (apply_blueprint streaming its build tree):
- * ctx.onProgress?.({ type: 'data-build-progress', id: 'build', data: { phase, items } });
+ * with `data-`). Pass a stable `id` to RECONCILE (replace) the part across
+ * emits — ideal for a single progress object that updates in place; omit
+ * `id` for append-only events. `data` is the payload.
*/
onProgress?: (part: { type: string; id?: string; data?: unknown }) => void;
}
diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressFrame.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressFrame.ts
new file mode 100644
index 00000000000..d842d9a72b9
--- /dev/null
+++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressFrame.ts
@@ -0,0 +1,12 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+// #37753 — `ai/BuildProgressFrame` (`phase`, `hop`, `tool`), the payload floor
+// of the `data-build-progress` stream frame, leaves with the whole
+// `ai/build-progress.zod.ts` module (ADR-0049 enforce-or-remove; the #3950
+// rule: an exported schema with no consumer reads as a capability). Its one
+// reader, the plugin-chatbot build panel, was deleted by the build retirement
+// (#37720), and its producer, the cloud AI-studio build loop, by cloud#5046.
+// It was a stream payload, never authored metadata, so no source or stored
+// row carries it and there is nothing for `migrate meta` to rewrite. D3:
+// `ai-build-progress-frame-retired`.
+export const entry = 'ai/BuildProgressFrame';
diff --git a/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressPhase.ts b/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressPhase.ts
new file mode 100644
index 00000000000..2d1048b8c90
--- /dev/null
+++ b/packages/spec/src/migrations/entries/retired-defs/19.ai__BuildProgressPhase.ts
@@ -0,0 +1,8 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+// #37753 — `ai/BuildProgressPhase` (`structure`, `data`, `verify`, `done`),
+// the closed phase vocabulary of the `data-build-progress` stream frame,
+// leaves with `ai/BuildProgressFrame` and the whole `ai/build-progress.zod.ts`
+// module: its only composer was that frame. D3:
+// `ai-build-progress-frame-retired`.
+export const entry = 'ai/BuildProgressPhase';
diff --git a/packages/spec/src/migrations/entries/semantic/19.ai-build-progress-frame-retired.ts b/packages/spec/src/migrations/entries/semantic/19.ai-build-progress-frame-retired.ts
new file mode 100644
index 00000000000..f5214e9fab8
--- /dev/null
+++ b/packages/spec/src/migrations/entries/semantic/19.ai-build-progress-frame-retired.ts
@@ -0,0 +1,30 @@
+// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
+
+import type { SemanticMigration } from '../../types.js';
+
+// #37753 — the D3 entry of the build-progress frame's retirement (ADR-0049
+// enforce-or-remove). No D2 conversion: the frame was a stream payload a
+// host's agent loop emitted and a chat panel read, never authored metadata,
+// so no source or stored row carries it. The family is the two defs
+// (`ai/BuildProgressFrame`, `ai/BuildProgressPhase`), both in
+// RETIRED_DEFS_BY_MAJOR[19], and the module's two constants,
+// `BUILD_PROGRESS_PHASES` and `BUILD_PROGRESS_FRAME_TYPE`.
+export const entry: SemanticMigration = {
+ id: 'ai-build-progress-frame-retired',
+ surface:
+ 'Host code that imports `BuildProgressFrameSchema`, `BuildProgressPhaseSchema`, `BuildProgressFrame`, '
+ + '`BuildProgressPhase`, `BUILD_PROGRESS_PHASES` or `BUILD_PROGRESS_FRAME_TYPE` from `@objectstack/spec/ai`',
+ replacement:
+ 'none: delete the import and the code that emits or reads a `data-build-progress` stream part. A host that '
+ + 'still wants to stream its own progress part passes any `data-` part name to `ctx.onProgress` and owns '
+ + 'the payload shape it sends.',
+ reason:
+ 'The module declared the payload of the `data-build-progress` frame for the build chat. Its only reader, '
+ + 'the console build panel, was removed with the build chat front end, and its producer, the cloud build '
+ + 'loop, was removed with it. Nothing parsed the frame any more, so the exported schemas read as a '
+ + 'capability that no longer exists. They are removed whole; a lingering import no longer compiles, which '
+ + 'is where the upgrader meets the change.',
+ acceptanceCriteria:
+ 'No code imports any of the six names from `@objectstack/spec`, no code emits or reads a '
+ + '`data-build-progress` part it expects the platform to draw, and the project type-checks.',
+};
diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts
index 34125ab59bb..2d56e6314f8 100644
--- a/packages/spec/src/type-alias-convention.pin.test.ts
+++ b/packages/spec/src/type-alias-convention.pin.test.ts
@@ -268,8 +268,8 @@ import type * as M185 from './shared/epoch.zod.js';
// [#18122] The closed duration vocabulary beside that instant — new module,
// next free index (M186 is `automation/schedule-organization.zod.ts`).
import type * as M187 from './shared/duration.zod.js';
-// [#18451] The build-progress PHASE vocabulary -- new module, next free index.
-import type * as M188 from './ai/build-progress.zod.js';
+// M188 was './ai/build-progress.zod.js' (#18451) — retired whole by #37753 (ADR-0049
+// enforce-or-remove); the M-indices are positional, so the slot stays vacant.
// The host fate supplement (ADR-0131 D10's C10 stage) -- new module, next free index.
import type * as M189 from './system/fate-supplement.zod.js';
// [#23287] The ADR-0069 posture vocabulary and its scope -- next free index.
@@ -305,7 +305,7 @@ import type * as M205 from './ai/object-query-source.zod.js';
import type * as M207 from './api/ai-answer.zod.js';
// ---------------------------------------------------------------------------
-// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared.
+// 879 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared.
//
// That number is machine-checked, not hand-kept. The runtime companion at the
// bottom of this file recomputes the pin count from the source and asserts that
@@ -359,18 +359,6 @@ import type * as M207 from './api/ai-answer.zod.js';
export type Iso_ai_agent__StructuredOutputFormatSchema = Assert, z.infer< typeof M0.StructuredOutputFormatSchema > >>;
export type Iso_ai_agent__TransformPipelineStepSchema = Assert, z.infer< typeof M0.TransformPipelineStepSchema > >>;
-// ai/build-progress.zod.ts -- the closed build-progress PHASE vocabulary
-// (#18451, cloud#2172 ruling A) and the frame that carries it. The enum has
-// no default and no transform; the frame is a `z.looseObject` whose three
-// members are a bare enum and two plain optionals, so both are the (RISE)
-// case. The frame pin is the load-bearing one: it is deliberately a FLOOR
-// that passes the consumer's own panel fields through untouched, and the day
-// someone gives `phase` or `hop` a `.default()` to 'help' a producer that
-// omits it, author state and parsed state part company -- this is the line
-// that says so by name.
-export type Iso_ai_buildProgress__BuildProgressFrameSchema = Assert, z.infer< typeof M188.BuildProgressFrameSchema > >>;
-export type Iso_ai_buildProgress__BuildProgressPhaseSchema = Assert, z.infer< typeof M188.BuildProgressPhaseSchema > >>;
-
// ai/conversation.zod.ts
export type Iso_ai_conversation__ConversationContextSchema = Assert, z.infer< typeof M1.ConversationContextSchema > >>;
export type Iso_ai_conversation__ConversationSummarySchema = Assert, z.infer< typeof M1.ConversationSummarySchema > >>;
@@ -1858,7 +1846,7 @@ describe('ADR-0122 type-alias convention', () => {
// this title and the section header above the pin list — are now asserted
// against the recomputed count below, so neither can go stale without a red
// test naming it.
- it('still declares all 881 isomorphic pins', () => {
+ it('still declares all 879 isomorphic pins', () => {
// The truth of each pin is proved by tsc, not here — an `Assert>`
// that stops holding is a compile error with the alias named. What tsc
// cannot notice is a pin that was DELETED: removing the assertion removes
@@ -2990,7 +2978,11 @@ describe('ADR-0122 type-alias convention', () => {
// `ai/embedding.zod.ts` leaves whole, its only composer having been the
// removed `embedding` and `vectorStore` keys (Iso_ai_embedding__*, three
// pins; RETIRED_DEFS_BY_MAJOR[19]). -6.
- expect(pins).toHaveLength(881);
+ // 881 -> 879 is #37753: `ai/build-progress.zod.ts` leaves whole, its one
+ // reader (the build panel in plugin-chatbot) and its producer having been
+ // deleted by the build retirement (Iso_ai_buildProgress__BuildProgressFrameSchema,
+ // __BuildProgressPhaseSchema; RETIRED_DEFS_BY_MAJOR[19]). -2.
+ expect(pins).toHaveLength(879);
// The count is stated in PROSE twice as well — this case's title and the
// section header above the pin list — and until commit c6b05c76a nothing read either
diff --git a/packages/spec/src/ui/component.zod.ts b/packages/spec/src/ui/component.zod.ts
index 1338a32c184..9691cdfc75b 100644
--- a/packages/spec/src/ui/component.zod.ts
+++ b/packages/spec/src/ui/component.zod.ts
@@ -5326,10 +5326,9 @@ export const ObjectGridPropsSchema = lazySchema(() => strictObject({
* `…` in its own describe says authors pass them — which is a wider
* narrowing than the defect measured above and a different decision. So what
* narrows is the accept set of a page size; what does NOT narrow is which
- * keys the bag may carry. `BuildProgressFrameSchema`
- * (`ai/build-progress.zod.ts`) is the house precedent for a floor-not-ceiling
- * shape, and `DashboardWidgetConfigSchema` for an open bag with declared
- * members.
+ * keys the bag may carry. `DashboardWidgetConfigSchema` (declared in
+ * `ui/packages/types`, `src/zod/complex.zod.ts`) is the house precedent for
+ * an open bag with declared members.
*
* Read points recorded in `liveness/page.json`, row `regions`: the grid
* reads `(schema.pagination as any)?.pageSize ?? schema.pageSize`,
From 0c1b2ffe30af21e84b2a5ca1fd962cde61a5d173 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 01:13:19 +0000
Subject: [PATCH 010/162] docs(adr): ADR-0161 dated note on item 12, a mounted
knowledge service is enabled by configuration (#38401)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_
Fixes #38368
Clause-②: no
Metadata-protocol: none
## 维护者速读
-
用户能看到什么变化:用户无感;只在知识平台的架构决策记录里加一条带日期的注记,写明知识服务挂上不等于启用:私有部署配齐嵌入参数和存储才启用,没配齐时所有知识源都留着、管理员列得出,但不建索引、不同步、不能搜,也不能保存或移入应用包。
-
为什么做:属于知识平台专题;您定的规则(同一套元数据,私有部署看参数配没配,云端不管)和您随后裁定的四处细节,现有条文都没写,随后的实现要有据可依。
- 出错会怎样:只改一份文档,运行行为不变;条文若写错,碰到的是随后照它做实现的人,可以直接撤回。
- 要你做什么:审阅并合并这份注记(受管面,由您批准合并)。
## What changes
One file,
`docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md`,
22 lines added and none removed against `main`, in three places:
- **Header.** A third `**Amended**` line, dated 2026-11-28, beside the
two that are there. It names both sources of the note: the maintainer's
words of 2026-11-28 and the four points he ruled on 2026-11-29. The
status line is left as it is.
- **K4.** A cross-reference appended to the existing cross-reference
block, in the shape of the one dated 2026-11-26. It says which two texts
of K4 are read with the new note (clause 3, "A real consumer", and
"Source admission at save") and closes with "No sentence of this record
is changed."
- **K8.** A third dated note after the two notes under the table, read
with item 12:
- item 12 is unchanged, and mounted is not enabled; the maintainer's six
sentences of 2026-11-28 are quoted verbatim, untranslated and in order;
- **Enabled**: at `kernel:bootstrapped` an embedder is available and the
deployment's store is mounted, which means its adapter is registered;
read once per boot;
- **Not enabled: held, not served**: sources are loaded and listed to
administrators, and not built, synced, reconciled or searched; no tool
definition is handed out; a direct search is refused with a coded
refusal and never answered empty; the state is said once in the boot's
log;
- **Enabling is an egress decision** (K5); the boot that first finds
both halves runs K7's boot pass;
- **The switch** is the existing setting `ai.embedder_provider`, default
`none`;
- the three ◆ choices ruled on 2026-11-28 by 「以上都同意」, each quoted in the
card's words: an author's save, the log line, a service the host mounts;
- the four ◆ points ruled on 2026-11-29 by the maintainer's choice of
the decision card's option 「全按推荐(1A 2A 3A 4A)」, each under the number
the ruling record gives it (comment 7248214179 on the card):
- point 1: the package move-in of a package-less source is an author's
save, refused while the service is not enabled, and no door value is
added;
- point 2: the state is the whole service's, so every source of a
runtime-mounted service is held, whichever store it names; an
application whose store embeds on its own mounts the knowledge service
itself;
- point 3: the service registers no lifecycle reap guard and calls no
store, so a retention sweep deletes its rows on time; an entry left in a
store that holds an earlier index joins the known gap, and K3 item 3 is
read with the note as the promise of an enabled service;
- point 4: the refusal of an author's save names the half that is
missing;
- **A known gap**, **Alternatives not taken**, and **Cloud is out of
scope**;
- the closing paragraph: no contract member, no settings key, no
capability token; `main` has no such state until the implementation card
#38369 lands; "The table is left as written; read item 12 with this
note."
The K8 table and every earlier sentence of the record are untouched. No
file outside `docs/adr/` changes.
**Read first, by risk** (one file, three bullets of the K8 note):
1. **Point 2, the state is the whole service's.** It is the one bullet
that declares a narrowing: on `main` a source on an application's store
that reads no embedder is built and searched under a runtime-mounted
service, and under this note it is held. The bullet says so and says it
is a named part of the narrowing #38369 declares.
2. **Point 3, no reap guard and no store call.** It is read against K3
item 3 ("an index entry never outlives its row") and the header's
"Leaves unchanged" list. The bullet states the reading and changes
neither sentence.
3. **Point 4, the refusal names the half that is missing.** The store
sentence, "mount the deployment's knowledge store, restart, then save",
is this area's English. The ruling record says it was not put to the
maintainer word for word and is the delta review's to read.
## Tests
No package is touched, so there is no build closure to build and no
package test to run. A record is prose: nothing here is ablated. The
checks that read the changed file are listed under Verification.
## Acceptance notes
**The card's acceptance.**
- The note sits under K8 and ends with the line "The table is left as
written; read item 12 with this note".
- K4 carries a cross-reference.
- The three ◆ choices of 2026-11-28 are recorded as ruled, each in the
card's words inside quotation marks, and are unchanged by the second
commit.
- `git diff origin/main...HEAD --stat` reads one file, 22 insertions.
**The contract review's findings on the first head (comment 7247818861
on this pull request), and the ruling that answers them.**
- The open choice of the first report, move-in: ruled, point 1. The two
sentences that said the note did not decide it are replaced.
- S1, a source on a store the application registered: ruled, point 2.
- S2, the lifecycle reap guard: ruled, point 3, and one sentence added
to **A known gap**.
- S3, the save remedy when the store is the missing half: ruled, point
4, and "the boot that first finds an embedder" now reads "the boot that
first finds both, an embedder and the deployment's store".
- N1, applied: the K4 cross-reference says "listed to administrators".
- N2, applied: the log-line bullet says the rule is about this state
alone, and that a declared capability whose provider cannot be built
still fails the boot, as before.
- N3, not applied in the record: the Consequences sentence on index
state, "The service keeps none of its own", is an earlier sentence and
is left as written. It reads against the per-source sync state row that
landed with pull request #38307. It stays a follow-up for a later
revision of the record.
- N4, applied: **Enabled** says the store is mounted when its adapter is
registered, and that whether a registered store can open its database is
outside the note, which declares no boot probe of it.
**What the note says about code, read on `main`.** The files the note
cites are byte-identical at `ff69bcabb2`, where they were first read,
and at `3579cf136d`, which this branch has merged. Every anchor is a
`path#symbol` or a file, as the record's anchor check requires.
- The knowledge plugin provides its embedder from a
`kernel:bootstrapped` hook: it keeps one another plugin registered, else
builds one from the saved settings, else registers a stand-in whose
every use is refused
(`packages/services/service-knowledge/src/knowledge-service-plugin.ts#provideEmbedder`).
`embedder_provider` defaults to `none`, and a saved default counts as
not configured.
- The settings description of that key reads "Read when the server
starts: a saved change to any embedder setting takes effect after the
next restart."
(`packages/services/service-settings/src/manifests/ai.manifest.ts#aiEmbedderSettingsSpecifiers`).
- Ruling D's three save doors ask `authoredKnowledgeSourceRefusal`: the
REST `PUT /meta/:type/:name`, the dispatcher's same route, and the MCP
draft save. The package duplicate door is `POST
/packages/:id/duplicate`, through `refuseDuplicatedKnowledgeSources`,
with the predicate's `duplicate` door. `POST /packages/:id/move-in` asks
the same predicate with the default door, `save`.
- A scheduled reconcile exists: `scheduleReconcile` registers a daily
job on the job service by default, and an option turns it off. A
reconcile walk removes the documents of rows that were deleted, for a
store that lists its documents.
- Composition is decided from the stack and the process environment
before the kernel starts; the settings service reads saved values only
once its data engine is bound at `kernel:ready`; the embedder settings
section is contributed by the knowledge service itself
(`contributeKnowledgeSettings`). Both halves of the first alternative
hold.
- For point 2: the service core never reads the embedder service, and
the in-memory store plugin reads none, so on `main` a source on such a
store builds and is searched with no embedder saved.
- For point 3: the reap guard's work is a store call
(`packages/services/service-knowledge/src/knowledge-reap-guard.ts`), and
a failed call keeps the row.
- For N2: under `os serve` a declared capability whose provider cannot
be provided is a hard boot error, and a capability the stack's items
mount is read as declared
(`packages/core/src/capability-composition.ts`).
- K9 rule 1, K7 rule 5, K8 rule 2, K5, K1, K3 item 3 and ADR-0078 §4
each say what the note cites them for.
**Places where the note's wording departs from the card's, each on a
reading of `main` or of the ruling record.**
1. Card point 9 gives the reason "(the service keeps no state of its
own)". That no longer holds: a per-source sync state row landed on
`main` after the card's evidence commit (pull request #38307;
`packages/services/service-knowledge/src/knowledge-sync-state.ts`). The
gap itself stands, for a different reason, and the note states that one:
the row holds a source's last build and its failed syncs, and a change
that was never attempted is neither.
2. Card point 4 says the enabling boot "builds every held source and
names each". Read literally that contradicts point 9, since a store that
already holds a current index is not rebuilt. The note says the boot
runs K7's boot pass over every held source and names each one it builds,
and that a source held since it was first loaded is built whole.
3. Ruling D's item 5 cites the capability file by line number. The
record's anchor check refuses line anchors, so the note cites the same
place as
`packages/spec/src/kernel/platform-capabilities.ts#PLATFORM_CAPABILITY_TOKENS`
and quotes the comment's words, "Requested, never always-on".
4. The note keeps its date, 2026-11-28, the day of the maintainer's
words and of the first three choices. The four later points carry their
own date, 2026-11-29, in the header line, in the note's first paragraph
and in each bullet's title.
**Noted, not filed, and not changed here.**
- The stdio MCP bridge reads the knowledge service in its `start()`,
before `kernel:bootstrapped`, the event at which the note says the state
is read. The implementation card #38369 has to make `search_knowledge`
absent on that transport too; the note states the outcome and leaves the
mechanism to that card.
- The Consequences sentence named under N3 above.
## Verification
**Two-minute check.** Open the Files changed tab: one file, 22 lines
added, none removed. The K8 note carries four bullets whose titles begin
"◆ Ruled 2026-11-29 (point", and its last line ends with "The table is
left as written; read item 12 with this note."
Local checks on head 83e9252e (the 21 commands derived for this
diff)
Derived with `node scripts/pm/dispatch-gates.mjs --commands` and
reconciled with `--ran`:
`✓ dispatch-gates --ran: 21 derived famil(ies) accounted for — 21 run, 0
NOT-MEASURED`
Each exit code was captured before any pipe.
| Command | Exit |
| --- | --- |
| `node scripts/check-adr-links.mjs` | 0 |
| `node scripts/check-adr-links.mjs --self-test` | 0 |
| `node scripts/check-closing-keyword-parity.mjs` | 0 |
| `node scripts/check-closing-keyword-parity.mjs --self-test` | 0 |
| `node scripts/check-comment-mask-corpus.mjs` | 0 |
| `node scripts/ci/plan-test-core-shards.mjs --self-test` | 0 |
| `pnpm --filter @objectstack/lint run check:doc-formula-expressions` |
0 |
| `pnpm check:adr-anchors` | 0 |
| `pnpm check:adr-index` | 0 |
| `pnpm check:adr-symbol-anchors` | 0 |
| `pnpm check:ci-filter-parity` | 0 |
| `pnpm check:closed-ceremony-text` | 0 |
| `pnpm check:cross-package-test-inputs` | 0 |
| `pnpm check:doc-authoring` | 0 |
| `pnpm check:driver-memory-census` | 0 |
| `pnpm check:gitlink-declared` | 0 |
| `pnpm check:nul-bytes` | 0 |
| `pnpm check:pm-governed-merges` | 0 |
| `pnpm check:pm-prior-rulings` | 0 |
| `pnpm check:refd-timer-probe` | 0 |
| `pnpm check:watch-hint-literal` | 0 |
Verdict lines the checks print:
- `check-adr-links: 1268 relative link destination(s) under docs/adr/
resolve`
- `check-adr-symbol-anchors: 4538 anchors across 164 records resolve`,
with 0 line anchors surviving
- `adr-index --report: OK — docs/adr/README.md is current, every record
parsed`
- `check-nul-bytes: OK`, no raw ASCII control bytes
The repo-wide scans and the full check farm are left to CI.
---------
Co-authored-by: Claude
---
...urn-knowledge-source-is-a-governed-type.md | 22 +++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md
index 4af7eecfbe5..a4b140313ec 100644
--- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md
+++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md
@@ -18,6 +18,7 @@
- **Inputs**: every code and docs text quoted below was read on `objectstack-ai/objectstack` `main` at `254e396a29`, the commit this record's branch starts from. Positions are in [Readings](#readings-taken-at-254e396a29). PR #36823 and PR #36850 are merged and are in that tree; PR #37075 is open and edits §6 of `content/docs/protocol/knowledge.mdx`, so the §6 quotations may move when it lands.
- **Amended** (2026-11-25, [#37097](https://github.com/objectstack-ai/objectstack/issues/37097)): a dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) records that the document hash of item 2 covers `organizationId` when the document has one (item 9), with no version bump. The status line above is left as it is.
- **Amended** (2026-11-25, [#37324](https://github.com/objectstack-ai/objectstack/issues/37324)): a second dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) gives item 17 its final shape, `AdapterSearchOptions.scope?`: the typed scope the service builds from `scope: [{ object, ids }]`, on the maintainer's ruling of that day, 「也能指定上级对象(制度)」 (record `7168192820` on #37308). The status line above is left as it is.
+- **Amended** (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)): a third dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item), read with item 12, records that a knowledge service the runtime mounts is enabled by configuration: a boot enables it when it finds an embedder and the deployment's store, and until then its sources are held and not served. It is written on the maintainer's words of that day, 「平台没有知识服务时,知识源不应该启用啊。」 and 「私有部署判断的是相关参数有没有配置」, as the filing gate of #38368 records them, and on four points he ruled on 2026-11-29 by choosing the decision card's option 「全按推荐(1A 2A 3A 4A)」 (record [`7248214179`](https://github.com/objectstack-ai/objectstack/issues/38368#issuecomment-7248214179) on #38368). It adds no contract member and no settings key. A cross-reference stands under [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type). The status line above is left as it is.
---
@@ -220,6 +221,8 @@ The package whose README and tests carry the `http` shape, `knowledge-ragflow`,
> **Cross-reference (2026-11-25, [#37325](https://github.com/objectstack-ai/objectstack/issues/37325)).** Which package's source a name means is ADR-0150's question, and this record does not ask it. Its [addendum of 2026-11-25](./0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md#addendum-2026-11-25-knowledge_source-joins-bucket-3) puts `knowledge_source` in bucket 3 beside `skill` and `ai_context`, on the maintainer's ruling 「按应用+名字区分,都保留」 (record [`7168239918`](https://github.com/objectstack-ai/objectstack/issues/37304#issuecomment-7168239918) on #37304): a source is identified by `(package, name)`, two packages that ship one source name each keep their source, and the keys of a source's index carry the package. Point 3 above is read with it: "A name is one source" holds between two packages by keeping both, and which holder a registration in code is stays open there, for row 3. So is [K6](#k6--adr-0087-dispositions): item 4 stays true of the rename, and the re-keying is what moves a document id and rebuilds an index; item 5 keeps its spellings, and the value each carries for a package's source is that addendum's and row 3's to state. Row 3 ([#37304](https://github.com/objectstack-ai/objectstack/issues/37304)) follows the addendum. No sentence of this record is changed.
>
> **Cross-reference (2026-11-26, [#37545](https://github.com/objectstack-ai/objectstack/issues/37545)).** Which holder a registration in code is was ruled on 2026-11-26: **A**, by the maintainer's word 「两处都选 A」 (record [`7192063608`](https://github.com/objectstack-ai/objectstack/issues/37304#issuecomment-7192063608) on #37304). ADR-0150's addendum carries the ruling as the dated note under [point 6 of "Past the ruling's words"](./0150-behavioural-metadata-addressed-by-package-objects-keep-the-literal-prefix.md#addendum-2026-11-25-knowledge_source-joins-bucket-3). The record states it as: "A knowledge source registered in code belongs to no package. It is read as the environment's own source and takes the one package-less slot of its name, keeping its bare key, bare face and existing index. The duplicate refusal compares `(package, name)`. A code registration and an environment-authored source of one name are the same slot, so the second arrival is refused, naming both doors. A code registration and a package's source of one name are two sources, and both are kept." Point 3 above is read with it. No sentence of this record is changed.
+>
+> **Cross-reference (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)).** Whether a mounted knowledge service is enabled is the question of the dated note of 2026-11-28 under the table of [K8](#k8--the-contract-additions-decided-item-by-item), read with item 12. Two texts above are read with it. Clause 3 ("A real consumer"): where the runtime mounted the service and it is not enabled, a source is loaded and listed to administrators, whichever store it names, and it is not built, synced or searched until a boot finds an embedder and the deployment's store. "Source admission at save": an author's save is also refused while the service is not enabled, at the save doors that note names, the package move-in among them, and the package duplicate door is not refused for that reason. No sentence of this record is changed.
### K5 — A source lists its content fields; embedding is egress
@@ -347,6 +350,25 @@ The epic holds the contract shut until this record merges ("No new adapter-contr
>
> This note adds exactly one member, `AdapterSearchOptions.scope` with its term type, and no other: the list stays closed beyond it (rules 3 and 5). #37308 builds it after this note merges, in one PR: the member, its first reader in `knowledge-memory`, and the suite cases. The code this note cites was read on `main` at `829a45e96c`. The table is left as written; read item 17 with this note.
+> **Note (2026-11-28, [#38368](https://github.com/objectstack-ai/objectstack/issues/38368)) — item 12: a knowledge service the runtime mounts is enabled by configuration; until it is, its sources are held and not served.** Item 12 is unchanged: the `knowledge` token, or a `knowledge_source` the stack ships, mounts the knowledge service and the deployment's store. Mounted is not enabled. The maintainer's words of 2026-11-28, verbatim and untranslated, in the order the filing gate of #38368 records them: 「如果我还是想把知识库放到 统一的 app-starter,但是根据平台的实际运行情况,决定是否有知识搜索的能力呢?」「也就是同一套元数据,企业版和社区版运行结果不一样」「平台没有知识服务时,知识源不应该启用啊。」「知识服务本身应该也可以有一个开关」「云端不需要管,企业版其实看的也是有没有配置相关的参数」「私有部署判断的是相关参数有没有配置」. So one set of metadata ships to every deployment, and what a self-hosted deployment has configured decides whether it searches. A ◆ marks a choice past those words. Three were put to the maintainer with their recommendations and ruled that day by 「以上都同意」; each is recorded below in the card's words. Four more were put to him on 2026-11-29 and ruled by his choice of the decision card's option 「全按推荐(1A 2A 3A 4A)」 (record [`7248214179`](https://github.com/objectstack-ai/objectstack/issues/38368#issuecomment-7248214179) on #38368); each is recorded below with that date, under the number the record gives it.
+>
+> - **Enabled.** A knowledge service the runtime composes for item 12 (`packages/core/src/capability-composition.ts#resolveServedCapabilities`, read by `os serve` and by `@objectstack/verify`) is enabled when, at `kernel:bootstrapped`, an embedder is available and the deployment's store is mounted. An embedder is available when another plugin registered one, or when the saved `ai.embedder_*` settings build one (`packages/services/service-knowledge/src/knowledge-service-plugin.ts#provideEmbedder`). The store is mounted when its adapter is registered; whether a registered store can open its database is outside this note, which declares no boot probe of it. That event follows every plugin's `start()` and every `kernel:ready` handler, so an embedder or a store that is absent then is absent for that boot. The state is read once per boot: a changed setting takes effect at the next restart, which the settings page already says (the description of `embedder_provider` in `packages/services/service-settings/src/manifests/ai.manifest.ts#aiEmbedderSettingsSpecifiers`).
+> - **◆ Ruled 2026-11-29 (point 2): the state is the whole service's.** Every source of a service the runtime mounted is held while the service is not enabled, whichever store it names, a store the application registered included. An application whose store embeds on its own mounts the knowledge service itself in `plugins[]`, which the third ◆ below leaves outside this note. On `main` a source on an application's store that reads no embedder is built and searched under a runtime-mounted service with none saved, so holding it is a narrowing, and a named part of the one #38369 declares.
+> - **Not enabled: held, not served.** The sources are loaded and listed to administrators. They are not built, synced, reconciled or searched. The service hands out no tool definition, so no transport registers `search_knowledge`: every transport registers the one definition the service hands out (K9 rule 1), so the tool is absent on all of them alike. A direct `search` is refused with a coded refusal (ADR-0112) that names the remedy, and it is never answered empty, which is K7 rule 5's rule for a source that cannot be searched. The state is said once, in the boot's log (K8 rule 2: nothing is skipped silently).
+> - **◆ Ruled 2026-11-29 (point 3): no reap guard and no store call.** While it is not enabled the service registers no lifecycle reap guard and calls no store, so a retention sweep deletes its rows on time. A row deleted or reaped then can leave an entry in a store that holds an earlier index. Nothing searches that entry while the service is not enabled, and the reconcile after enabling, or an operator's rebuild, removes it: this joins the known gap below. K3 item 3 ("an index entry never outlives its row") is read with this note as the promise of an enabled service. No earlier sentence of the record is changed.
+> - **Enabling is an egress decision.** Embedding is egress (K5), so configuring an embedder is the deployment's decision to send the listed fields of its sources to that provider. The boot that first finds both, an embedder and the deployment's store, runs K7's boot pass ("What starts a rebuild") over every held source and names each one it builds. A source held since it was first loaded has nothing in the store, so it is built whole.
+> - **The switch.** The switch the maintainer asked for is a setting that exists: `ai.embedder_provider`, whose default is `none`. No settings key is added.
+> - **◆ Ruled: an author's save.** "An author's save is refused while the service is not enabled, at the three save doors of #37983's ruling D, with the remedy "save an embedder provider, restart, then save". The package duplicate door is not refused then." Ruling D is the maintainer's 「D 拒绝保存并说明」 (record [`7220511579`](https://github.com/objectstack-ai/objectstack/issues/37983#issuecomment-7220511579) on #37983): where no knowledge service is registered, an author's save of a `knowledge_source` is refused at each door that saves one, and the engine's own write (a package install, a seed, a migration) is not. It stands. This refusal stands beside it and draws the same line, between an author's save and the engine's write, so a shipped source still installs and is held. The three doors are `PUT /meta/:type/:name` on both transports and the MCP draft save, and they ask one predicate (`packages/metadata-core/src/knowledge-source-save-admission.ts#authoredKnowledgeSourceRefusal`). The package duplicate door is `POST /packages/:id/duplicate`, which asks that predicate for each source it copies (`packages/runtime/src/domains/packages.ts#refuseDuplicatedKnowledgeSources`). What it answers where no knowledge service is registered, and to a caller who may not search what a source indexes, is unchanged; a service that is not enabled is no reason for it to refuse.
+> - **◆ Ruled 2026-11-29 (point 1): the package move-in is an author's save.** One more door asks that predicate on `main`, as a save: `POST /packages/:id/move-in`, for a package-less source it moves into a package. It is an author's save: it is refused while the service is not enabled, with the save's remedy. No door value is added for it: the predicate's doors stay `save` and `duplicate`.
+> - **◆ Ruled 2026-11-29 (point 4): the refusal names the half that is missing.** This is the refusal of an author's save, at each door above that refuses one. With no embedder it is the ruled sentence, unchanged: "save an embedder provider, restart, then save". Where the deployment's store is not mounted, the refusal says so and says that the boot's log names the reason, and its remedy is "mount the deployment's knowledge store, restart, then save". With both missing it says both.
+> - **◆ Ruled: the log line.** "Log level: `info` when only a shipped item mounted the service and nothing was configured; `warn` when the stack lists `requires: ['knowledge']`, the saved settings are incomplete, or the store could not be mounted. Never a boot refusal (ADR-0078 §4)." ADR-0078 §4 is the rule that the runtime seam warns and never throws. It is about this state alone: a declared capability whose provider cannot be built still fails the boot, as before.
+> - **◆ Ruled: a service the host mounts.** "A knowledge service a host mounts itself in `plugins[]` is outside this note: its adapters may embed on their own (K1)." K1 leaves to the adapter whether an embedding call is made at all, so the absence of the kernel's embedder says nothing about such a composition. This note changes nothing for it.
+> - **A known gap.** A deployment that was enabled, built its indexes and then boots not enabled syncs nothing while it stays so. The boot that finds it enabled again builds by what each store holds (K7), and a store that holds a current index for a source is left as it is. The record changes made in between are repaired by the next reconcile, which runs daily by default on the job service for a store that lists its documents (`packages/services/service-knowledge/src/knowledge-service-plugin.ts#scheduleReconcile`), or by an operator's rebuild (`os knowledge rebuild`). They are not repaired by the enabling boot, because nothing records which changes went unsynced: the sync state the service keeps for a source (`packages/services/service-knowledge/src/knowledge-sync-state.ts`) holds its last build and its failed syncs, and a change that was never attempted is neither. A row deleted or reaped in between is such a change (point 3 above): its entry stays in a store that holds an earlier index until that reconcile or rebuild.
+> - **Alternatives not taken.** Mounting by configuration, so that an unconfigured deployment has no knowledge service. The runtime decides what it mounts from the stack and the process environment before the kernel starts, and the settings service, which it mounts, reads a saved value only once its data engine is bound at `kernel:ready`. The `ai.embedder_*` keys are also contributed by the knowledge service itself (`packages/services/service-knowledge/src/knowledge-settings-contribution.ts#contributeKnowledgeSettings`), so the setting that would mount the service could be saved only where it is already mounted. An always-on knowledge service: ruling D's item 5 keeps it out (the same record), and `packages/spec/src/kernel/platform-capabilities.ts#PLATFORM_CAPABILITY_TOKENS` states the token as "Requested, never always-on".
+> - **Cloud is out of scope**, by the maintainer's word above: 「云端不需要管」.
+>
+> This note adds no contract member, no settings key and no capability token: the list stays closed (rules 3 and 5). It declares, and [#38369](https://github.com/objectstack-ai/objectstack/issues/38369) builds it after this note merges. Until then `main` has no such state: a mounted service with no embedder registers a stand-in whose every use is refused with the reason, and still starts its boot build, its record sync and its reconcile job and hands out its tool. The code this note cites was read on `main` at `ff69bcabb2`. The table is left as written; read item 12 with this note.
+
**What "capabilities" became.** #36990's rule named "capabilities" among the members that waited for this record. Two things answer it. A method that is absent is the capability signal for listing, dropping, status, and the start and end of a build: the service asks whether the method is there. One flag covers what a method cannot say, `capabilities.chunks` (item 5). No wider descriptor is added.
**What counts as a member** (for rule 5 below, and for the epic's "no new adapter-contract member"). A member is anything an adapter author must read to be correct:
From 4437c5080bbc5f13c891b7d7a1e3edf5287e183d Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 01:32:31 +0000
Subject: [PATCH 011/162] docs(skills): the objectstack-ui kanban section names
the rule that judges a board's group field (#38430)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XAqkG8y9atnquyRXBY4zVGV)_
Fixes #38153
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 用户无感:只改对外发布的技能包里教 AI 做看板的一处文字,把“分组字段要用选项字段”的口头提示换成指向已上线的那条检查和它给的首选改法。
- 属于「发布时拦下保存成功却用不了的元数据」这组检查的技能包收尾:检查上线后,技能包里口头教的同一个坑让位给检查本身。
- 只是一句教 AI 的话,写错最多让 AI 学到一句不准的说法,可以直接撤回这次修改。
- 无
## What changes
One published skill page, `skills/objectstack-ui/rules/list-views.md`,
in its kanban section. `skills/objectstack-ui/SKILL.md` is not changed
(measured below: it teaches none of the six traps).
- The kanban example no longer carries the comment "a select field"
beside `groupByField`.
- A two-line note under the example takes its place: "Group by a
single-valued `select`, boolean or lookup: a text, number or date field
or a multi-valued one warns
`list-view-kanban-group-field-uncategorical`." The first half follows
the rule's own hint in
`packages/lint/src/validate-list-view-field-refs.ts`
(`checkKanbanGroupField`); the fields that warn are named in the rule
explanation's terms. The hint's second remedy, a grid grouping, is not
taught: the engine refuses that grouping for a multi-value,
structured-JSON or formula field (contract review S1, record 7248601916;
follow-up #38433).
**Each of the six rule ids of PR #38107, measured against both files at
`f42bcc18`:**
| Rule id | `rules/list-views.md` | `SKILL.md` |
|:--|:--|:--|
| `list-view-filter-field-virtual` (error) | not taught, no change.
Filtering (lines 94-119) and the quick-filter rules (lines 140-154) name
no formula field. The two `formula` mentions (lines 184 and 202) are the
search axis, already named by `searchable-field-unsearchable`. | not
taught, no change |
| `list-view-kanban-group-field-uncategorical` | taught as prose at line
267 (the example comment "a select field"): changed | not taught as this
trap, no change. Line 89 describes the kind ("a board by status"); lines
99-100 are another trap (a board over a field added in the same change
opens empty), which none of the six rules judges. |
| `dashboard-without-widgets` | not taught, no change | not taught, no
change |
| `app-navigation-empty` | not taught, no change | not taught, no
change. App Navigation (lines 103-108) says one app per package and that
hiding is not gating. |
| `object-unreachable-from-navigation` | not taught, no change | not
taught, no change |
| `object-without-view` | not taught, no change | not taught, no change
|
None of the six ids appeared anywhere under `skills/` before this change
(`grep -rn` over the tree, zero hits; control:
`searchable-field-unsearchable` hits).
**Paid for in the same file (token ratchet; no ceiling row moves).**
| Cut | Bytes | Where it still lives |
|:--|--:|:--|
| the comment "a select field" and its padding | 33 | replaced by the
note |
| alignment padding before the two "optional, default true" comments of
the kanban example | 28 | the comments stay |
| the sentence "`summary`, `showFieldLabels` and `hideEmptyFields` are
optional." and the line break it left | 67 | the example marks the two
card keys "optional, default true"; the note still says "Omit `summary`
to keep the older `summarizeField`'s sum" |
| alignment padding before the comment "open, OR urgent" in the
Filtering example | 33 | the comment stays |
161 bytes cut, 162 added.
Skill size readings, base `f42bcc18`, head `6395a44f`:
| | lines before | lines after | bytes before | bytes after | tokens
before | tokens after |
|:--|--:|--:|--:|--:|--:|--:|
| `skills/objectstack-ui/rules/list-views.md` | 412 | 414 | 18038 |
18039 | 4510 | 4510 (ceiling 4510) |
| `skills/objectstack-ui/SKILL.md` (untouched) | 164 | 164 | 8937 | 8937
| 2228 | 2228 (ceiling 2228) |
| every published `SKILL.md`, summed | 4386 | 4386 | | | | |
| whole shipped bundle | | | | | 304822 | 304822 |
Net over `skills/**`: 8 lines added, 6 removed.
## Why
PR #38107 made `os validate`, `os lint`, `os build` and the publish door
warn on a board grouped by a field with no fixed lanes. Card #35143's
Scope says: "When a family lands, the matching trap leaves the published
skills where it is taught as prose." The kanban example taught it as a
three-word comment, and incompletely: a boolean or a lookup draws fixed
lanes too. The page now names the rule, its first fix and the fields
that warn.
## Tests
Prose and comments only: no unit test changes, no ablation, no eval case
edited and no eval round run.
Local gates, run on head `6395a44f` (the final commit, clean tree) after
`turbo run build` over the workspace (verify lock: `VERDICT command-exit
0`):
```text
✓ dispatch-gates --ran: 48 derived famil(ies) accounted for — 48 run, 0 NOT-MEASURED (a DERIVED zero — all 48 recorded an exit code and none of them is 3).
```
verdict lines of the gates that read the
page
```text
✓ check-skills-token-ratchet: skills/objectstack-ui/rules/list-views.md is 4510 tokens (ceiling 4510; headroom 0).
✓ check-skills-token-ratchet: 61 authored bundle file(s) within their ceilings; 11 generator-owned file(s) and 42 eval fixture(s) measured, not ratcheted.
✓ check-skill-served-sections: 24 served section(s), each heading exactly once in its file (6 json, 2 json+ts, 16 neutral); 10 JSON fence(s) parse and pass their spec validators.
✓ check-skill-links: 281 relative link(s) in 76 published skill file(s) resolve; 149 fragment(s) name a real heading under GitHub's slug rule.
check-nul-bytes: OK (scanned 28762 text file(s) -- 28762 tracked, 0 untracked-not-ignored; skipped 101 binary; no raw ASCII control bytes).
```
Outside the derived list, run on `85c42af4` because the kanban block is
a checked example (the block is unchanged since): `pnpm --filter
@objectstack/spec run check:skill-examples` under the verify lock,
`VERDICT command-exit 0`, "352 prose examples type-check across 3
surface(s)".
`node scripts/pm/overlap-check.mjs` before each push: `VERDICT clean
exit 0`.
Everything else is CI's run: the check-runs on this pull request are the
record.
## Acceptance notes
- **Premise, re-read on `main` at `f42bcc18`:** it holds for one id of
the six. The six ids are live in `packages/lint/src` and none was named
in `skills/`. Only the board's group field was taught as prose, and only
in `list-views.md`.
- **No other file of this skill teaches one of the six traps as prose.**
`rules/navigation.md` was read in full; `rules/dashboards.md`,
`rules/pages.md`, `rules/record-page.md` and `rules/actions.md` were
searched by keyword (empty dashboard, navigation reach, list view,
board, formula filter). `rules/dashboards.md` lines 106-108 say a
`formula` is refused as a dataset dimension or `groupBy`: that is the
dataset contract, not a list view filter.
- **Noted, not filed:** `skills/objectstack-formula/SKILL.md` lines
430-435 say a `where` on a `formula` field answers `400 INVALID_FIELD`.
That is the engine's refusal for every query; the new list-view rule
covers one producer of such a query, so the sentence stays true and is
left alone.
- **`radio`:** the rule also passes a `radio` field
(`KANBAN_CATEGORICAL_TYPES`), though its hint names `select` only. The
note follows the hint for what to group by and names only the fields
that do warn, so it does not claim a `radio` field warns.
- **Budget:** two lines net on one file; `SKILL.md` unchanged at 8,937
bytes.
- `skills/**` is a governed path: this pull request stays a draft, and
its contract review is the seat's to arrange.
## Verification
Read first: the note under the kanban example in
`skills/objectstack-ui/rules/list-views.md`. The risk hunk is the
removed "optional" sentence in the note below it.
Two-minute check: `node scripts/check-skills-token-ratchet.mjs` prints
`skills/objectstack-ui/rules/list-views.md` at 4510 / 4510.
## Human Minimum
- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
- [x] 2. Every name I added uses the casing for its kind.
- [ ] 3. No formatter ran; `pnpm lint` is the CI-owned repo scan, not
run locally.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` not touched.
- [x] 7. No hand edits to `content/docs/references/`,
`packages/*/CHANGELOG.md` or `content/docs/releases/`.
- [x] 8. Title, body and comments are in English.
- [x] The *Before Submitting* list in CONTRIBUTING.md is done.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5nvFivDeQyYgTFkZhi)_
---------
Co-authored-by: Claude
---
.../38153-ui-skill-kanban-group-field-rule.md | 10 ++++++++++
skills/objectstack-ui/rules/list-views.md | 14 ++++++++------
2 files changed, 18 insertions(+), 6 deletions(-)
create mode 100644 .changeset/38153-ui-skill-kanban-group-field-rule.md
diff --git a/.changeset/38153-ui-skill-kanban-group-field-rule.md b/.changeset/38153-ui-skill-kanban-group-field-rule.md
new file mode 100644
index 00000000000..16e96bb90d7
--- /dev/null
+++ b/.changeset/38153-ui-skill-kanban-group-field-rule.md
@@ -0,0 +1,10 @@
+---
+'@objectstack/skills': patch
+---
+
+docs(skills): the objectstack-ui kanban section names the rule that judges a board's group field
+
+Clause-②: no
+Metadata-protocol: none
+
+`skills/objectstack-ui/rules/list-views.md`: the kanban example no longer carries the comment "a select field" beside `groupByField`. The note under the example now says to group by a single-valued `select`, boolean or lookup, and names the warning a text, number or date field or a multi-valued one gets, `list-view-kanban-group-field-uncategorical`. The sentence that listed `summary`, `showFieldLabels` and `hideEmptyFields` as optional is gone: the example's comments and the `summary` note already say so. No token ceiling moves.
diff --git a/skills/objectstack-ui/rules/list-views.md b/skills/objectstack-ui/rules/list-views.md
index 0fffa9ef1b2..4d360aaee1e 100644
--- a/skills/objectstack-ui/rules/list-views.md
+++ b/skills/objectstack-ui/rules/list-views.md
@@ -99,7 +99,7 @@ matches when **any** of its rules does — still ANDed with the elements beside
```typescript
filter: [
- { or: [ // open, OR urgent …
+ { or: [ // open, OR urgent …
{ field: 'status', operator: 'equals', value: 'open' },
{ field: 'priority', operator: 'equals', value: 'urgent' },
] },
@@ -264,11 +264,11 @@ const board: ListView = {
data: { provider: 'object', object: 'project_task' },
columns: ['title', 'owner_id', 'priority'],
kanban: {
- groupByField: 'status', // a select field
+ groupByField: 'status',
lanes: ['todo', 'in_progress', 'review'],
summary: { type: 'sum', field: 'estimate_hours' }, // each lane's foot statistic
- showFieldLabels: false, // optional, default true: cards name each field
- hideEmptyFields: false, // optional, default true: cards drop an empty field
+ showFieldLabels: false, // optional, default true: cards name each field
+ hideEmptyFields: false, // optional, default true: cards drop an empty field
columns: ['title', 'owner_id', 'priority'], // fields shown on each card
cardFooter: { comments: true, attachments: true }, // optional foot counts
},
@@ -276,13 +276,15 @@ const board: ListView = {
};
```
+> Group by a single-valued `select`, boolean or lookup: a text, number or date
+> field or a multi-valued one warns `list-view-kanban-group-field-uncategorical`.
+
> `lanes` chooses the lanes and their order, not the records: a record whose
> value is unlisted lands in `Uncategorized`, so filter the view to keep records
> off the board. Omit it to draw every option in its own order; a value that is
> not one of the field's inline options, or listed twice, fails `os validate`.
-> `summary`, `showFieldLabels` and `hideEmptyFields` are optional. `summary.type`:
-> `none`, `count`, or `sum` / `avg` / `min` / `max` of a `field`, computed by the
+> `summary.type`: `none`, `count`, or `sum` / `avg` / `min` / `max` of a `field`, computed by the
> query over every record of the lane, lanes over a lookup field included. Omit
> `summary` to keep the older `summarizeField`'s sum, or no statistic without it.
> `cardFooter` takes those two members only: `comments` counts the record's open
From 038ccf5d8436f68dc84358d6404a0b82bd3fcc33 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 01:37:43 +0000
Subject: [PATCH 012/162] docs(adr,skills): ADR-0163 records the two-tier field
write lock; objectstack-data teaches the four locks (#38428)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Sales** · [project
thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu8dhiDUf1jDKZiZnYduzapm)_
Fixes #37405
Clause-②: no (no accept set or export changes; governed rules text, so
one contract-review-tier review before the queue; Tier H)
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:给应用建数据模型的人和
AI,现在能从技能里学到「锁定一个字段」的四种写法各在什么时候用(比如销售订单的状态只让「确认」按钮改、不让人手改);把两种锁同时配在一个字段上时,校验报错会指出该看哪份设计说明。平台行为不变。
- 为什么做:你对「字段只读分两级」那张决策卡已经定了长远模型,功能也已上线,但设计说明和技能里一直没有记下来,这一步是补上记录。
- 出错会怎样:最坏是说明里某句话和平台实际做法对不上,作者照着配错了锁;只改文字和一句报错提示,可以直接撤回。
- 要你做什么:设计说明和技能文件的改动需要你批准合并。
## What changes
No key, schema, accepted value, default or runtime behaviour changes.
This records the ruling of record on #36806 (ruling record 7180466652,
「按长远模型」) and the two object-level rulings on #37402 (ruling records
7235326611 and 7237772411), whose code landed in #37436, #37888 and
#38169.
-
`docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md`
(new, `Accepted (2026-11-26)` on the ruling record; it reaches `main`
only by the Tier H approval). D1 two tiers (server lock `readonly` /
`readonlyWhen`, hand lock `uiReadonly` / `uiReadonlyWhen`), D2 two forms
(`readonlyWhen: P\`true\`` is the set-once spelling), D3 two levels (the
object's `uiReadonlyWhen`; a field's own declaration wins; `uiReadonly:
false` is not a declaration), D4 what "by hand" is, D5 the admission
rule of the `ui` prefix (`uiVisibleWhen` / `uiRequiredWhen` are not
admitted), D6 contradictions, D7 the server lock stays a strip. The
record keeps two kinds of statement apart: Decision carries only what
the rulings say, quoted; "As built" says what `main` does at `c610020e`,
by symbol anchor. A third section, "Ruled and not yet held", lists the
three places the ruling covers and the code does not reach yet, each
with its open carrier card.
- `docs/adr/README.md`: regenerated by `node scripts/adr-index.mjs` (164
records).
- `skills/objectstack-data/rules/validation.md`: new section `## Locking
a Field`: a two-by-two table of the four keys (who is kept out, and
when), one checked sales-order example (the hotcrm#2716 case: a `status`
only the Confirm action moves), and five bullets on what each column
does at run time.
- `skills/objectstack-data/SKILL.md` § Conditional Field Rules: the
first bullet keeps its trap (the value is dropped, the write is not
refused, a declarative action's included) and routes to the new section.
- `skills/objectstack-data/evals/objects-fields-relationships.json`:
case 30, a `uiReadonly` status field (`must_contain`: `uiReadonly:
true`, `state_machine`). `evals/README.md` names it.
- `packages/spec/src/data/field.zod.ts`: the parse refusal for
`uiReadonly: true` beside `readonly: true` keeps its wording and now
ends `The two locks and which one to choose: ADR-0163 (D1, D6).` This is
the text `objectstack validate` prints for the pair. Pinned in
`field-ui-readonly.test.ts`.
- `.changeset/37405-field-write-lock-adr-skill.md`: `@objectstack/spec`
and `@objectstack/skills`, patch.
**One sentence of the skill is corrected, not only moved.**
`rules/validation.md` said "Imports and migrations are system-context
writes too." An import is not a system-context write. The `readonly`
describe in `FieldSchema` says so ("A normal (non-system) import is NOT
system-context and still strips"), `importControlOptOutRefusal` in
`packages/rest/src/import-prepare.ts` refuses the historical-import
opt-out to every HTTP caller, and the #36806 measurement found the same.
The new section lists an import among the writes `readonly: true` drops,
and a migration among the system writers it lets through.
**Token ratchet** (`scripts/check-skills-token-ratchet.mjs`), two rows:
- `skills/objectstack-data/SKILL.md` 2239 → 2224: lowered to the
measurement.
- `skills/objectstack-data/rules/validation.md` 3466 → 3862 (+396). The
section is ordered into this skill by the ruling of record on #36806
(ruling record 7180466652: the four spellings, which one to use, the
sales-order status example), and the raise follows the standing ruling,
verbatim: 「A:先削重复,余额按实测提高」 (ruling record 6513306068). Paid down first
in the same file, 1035 bytes cut against 2622 added:
- the two `readonly` / `readonlyWhen` bullets of § Conditional Field
Rules are now one pointer at the new section, which says the same once;
- § Conditional Validation loses its first example
(`enterprise_requires_manager`) and the lead-in of the second, whose
`when` / `then` / `otherwise` rule shows everything the first did.
### Skills readings (lines / bytes / tokens)
| | before | after |
|:-|:-|:-|
| `skills/objectstack-data/rules/validation.md` | 392 / 13861 / 3466 |
421 / 15448 / 3862 |
| `skills/objectstack-data/SKILL.md` | 167 / 8983 / 2239 | 167 / 8923 /
2224 |
| `skills/objectstack-data/evals/objects-fields-relationships.json` (not
ratcheted) | 520 / 37381 | 533 / 38751 |
| `skills/objectstack-data/evals/README.md` (not ratcheted) | 17 / 969 |
18 / 1016 |
| all of `skills/objectstack-data/**` | 4643 / 252853 | 4686 / 255797 |
| all `skills/*/SKILL.md` | 4386 / 228159 | 4386 / 228099 |
| all of `skills/**` | 23333 / 1230467 | 23376 / 1233411 |
| ratcheted (authored) total, tokens | 200510 | 200891 |
### Round 2 (head 6e397de7): the contract review of 0922ab3a
The review (comment 7248470779, PASS) left one should-fix and one nit.
Both are done in one commit.
- S1, `SKILL.md`: "a button's action included" was true of a declarative
action only. A script action's body runs in a system context, so its
write to a `readonly: true` field lands (ADR-0163, Alternatives, row 3).
The clause now reads "a declarative action's included". The ratchet row
follows the file to its measurement, 2224 (2223 at the previous head).
- N1, `rules/validation.md`: the table's left column was headed "Every
non-system write" over `readonlyWhen` too, which binds system writes as
well. The header is now "Every write" and the `readonly: true` cell
carries "(system writes pass)". The right header lost one word to pay
for it ("Only a person at the console"), and the Confirm sentence names
"a declarative Confirm". The file is 15448 bytes and its row stays 3862.
- The changeset's sentence on the Confirm action says "a declarative
action's own write" to match.
## Tests
- `packages/spec/src/data/field-ui-readonly.test.ts`: the existing
refusal case also asserts the message ends with `ADR-0163 (D1, D6).`
`vitest run src/data/field-ui-readonly.test.ts` in `packages/spec`: 5 of
5 pass.
- The new skill example carries the `os:check` marker, so
`check:skill-examples` type-checks it against the built
`@objectstack/spec` declarations. Exit 0: 353 marked examples
type-check, this one among them. The example was also parsed by
`ObjectSchema` and read by `validateStackExpressions` in two scratch
vitest files (not committed): it parses, and the expression lint reports
no issue for `readonlyWhen: P`true`` or `uiReadonlyWhen: P`false``.
- `check:skill-eval-tokens`: exit 0; both `must_contain` tokens of case
30 are taught by the bundle.
- Not run: a model-driven round of the skill evals. Case 30 has a new
hash and no recorded answer yet.
## Acceptance notes
- Done-when, line by line. "ADR accepted on `main`": the record's status
is `Accepted` on the ruling record and it lands by the Tier H approval
of this PR. "Skill section in place and its eval exercises a
`uiReadonly` status field": the section and case 30. "`objectstack
validate`'s refusal text for `uiReadonly` + `readonly` points at the
ADR": the message above.
- The card's Asked lists what the ruling says. Three points of it are
not held by code on `main` yet. The ADR says so in "Ruled and not yet
held" and names the open carrier of each: #37898 (the assistant is among
the hands the ruling names; cloud AI service), #38202 (console Duplicate
carries a hand-locked value), #38249 (inline child lines of a
hand-locked parent). The skill section teaches only what `main` does
today.
- "`uiVisibleWhen` / `uiRequiredWhen` refused" (card wording): the
ruling's rule is that a key earns a `ui` twin only when an action must
write what a person may not, and only read-only meets it. Neither key
exists in the schema, so a strict parse answers each as an unknown key.
No dedicated refusal is added here; the ADR records the rule (D5) and
the skill says there is no `uiVisibleWhen`.
- D3 records that an object-level server lock (`readonlyWhen` on the
object) is not filed anywhere; it is named so a later reader does not
infer it from the hand lock's object level.
- The refusal message names the ADR by number, the form the spec's other
messages use (`ADR-0158 U2`, `ADR-0049`).
- Branch `claude/project-thread-bqsxpg` is assigned by the harness, not
the repo's `claude/issue-N-…` convention.
## Verification
Two-minute check: `node scripts/check-skills-token-ratchet.mjs`, expect
exit 0 with `skills/objectstack-data/rules/validation.md` 3862 / 3862
and `skills/objectstack-data/SKILL.md` 2224 / 2224.
Read first, by risk:
1. `skills/objectstack-data/rules/validation.md` § Locking a Field (it
ships to third parties verbatim): the left-column bullet, where the
writers `readonly: true` drops and lets through are listed, and the
import correction.
2. `docs/adr/0163-…md` D3 and D4 against the ruling records, then "Ruled
and not yet held".
3. `scripts/check-skills-token-ratchet.mjs`: the two rows and their
arithmetic.
Local gates at 6e397de7 (only what reads the two
changed skill files)
Not the whole list again: the second commit changes two skill files, the
ratchet rows and one changeset sentence. Re-run, each exit 0:
`check-skills-token-ratchet.mjs` (and `--self-test`), `ui`
`check:skill-eval-tokens`, `check:skill-links`,
`check:skill-frame-sync`, `check:skill-identifier-liveness`, spec
`check:skill-examples` (353 examples), `check:skill-docs`,
`check:skill-refs`, `check:skill-served-sections`,
`check-nul-bytes.mjs`.
Local gates at 0922ab3a
`node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack
--ran FILE`, each command recorded as `CMD :: exit N`: **124 derived,
120 run, 4 NOT-MEASURED, 0 UNRUN**. Every run family exit 0, among them
`check-skills-token-ratchet.mjs` (and `--self-test`), `check:adr-index`,
`check:adr-anchors`, `check:adr-symbol-anchors`, `check-adr-links.mjs`,
`check:skill-links`, `check:skill-frame-sync`,
`check:skill-identifier-liveness`, spec `check:docs` /
`check:api-surface` / `check:authorable-surface` / `check:skill-docs` /
`check:skill-refs` / `check:liveness`, `check-empty-changeset.mjs`,
`check-adr-0087-registration.mjs --base origin/main`,
`check:ratchet-remedy-authority`, `check:type-check-debt`.
- The four recorded exit 3 (prerequisite not met), as the tool reads the
record:
- `check-plugin-teardown-shape.mjs --self-test`: NOT MEASURED. Its
positive control is pinned to a commit this shallow clone cannot reach.
The gate itself (without `--self-test`) ran, exit 0.
- `check:doc-formula-expressions`, `check:dual-build-cjs-loads`,
`check:lean-entry-closure`: exit 3 on the first pass (their build
closures were missing). After the closures were built each was run again
alone, exit 0. The record keeps both lines, and the tool reads a command
with two codes as the worse one, so its count stays 4.
- Outside the derived list, run by hand: spec `check:skill-examples`
(exit 3 before the `@objectstack/client-react` closure was built, exit 0
after: 353 examples), `ui` `check:skill-eval-tokens` (exit 0), `ui`
`check:skills-paths` (exit 0).
- `scripts/pm/overlap-check.mjs`: clean against `origin/main` (3579cf13)
and the one open PR that shares a file (#38192,
`skills/objectstack-data/SKILL.md`).
- Built at `c610020e` plus this diff; `main` moved three commits since
(none under this diff's paths), not merged in.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01L6bhgTpyo8gQyqf9Tj9mfz
---------
Co-authored-by: Claude
---
.../37405-field-write-lock-adr-skill.md | 15 ++
...wo-forms-two-levels-ui-prefix-admission.md | 141 ++++++++++++++++++
docs/adr/README.md | 7 +-
.../spec/src/data/field-ui-readonly.test.ts | 3 +
packages/spec/src/data/field.zod.ts | 6 +-
scripts/check-skills-token-ratchet.mjs | 22 ++-
skills/objectstack-data/SKILL.md | 6 +-
skills/objectstack-data/evals/README.md | 3 +-
.../evals/objects-fields-relationships.json | 13 ++
skills/objectstack-data/rules/validation.md | 81 ++++++----
10 files changed, 260 insertions(+), 37 deletions(-)
create mode 100644 .changeset/37405-field-write-lock-adr-skill.md
create mode 100644 docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md
diff --git a/.changeset/37405-field-write-lock-adr-skill.md b/.changeset/37405-field-write-lock-adr-skill.md
new file mode 100644
index 00000000000..38872b90a95
--- /dev/null
+++ b/.changeset/37405-field-write-lock-adr-skill.md
@@ -0,0 +1,15 @@
+---
+'@objectstack/spec': patch
+'@objectstack/skills': patch
+---
+
+docs(skills,spec): the `objectstack-data` skill teaches which of the four field locks to use, and the `uiReadonly` + `readonly` refusal names ADR-0163
+
+Clause-②: no
+Metadata-protocol: none
+
+`skills/objectstack-data/rules/validation.md` gains `## Locking a Field`: a two-by-two table of `readonly`, `readonlyWhen`, `uiReadonly` and `uiReadonlyWhen` (who is kept out, and when), one checked sales-order example, and what each column does at run time. The server lock (`readonly`, `readonlyWhen`) drops the value from every non-system write and answers success; the hand lock (`uiReadonly`, `uiReadonlyWhen`) stops the console offering the field while an action, an import and the API still write it, each write judged by the object's validations. A status field that only a Confirm action moves is `uiReadonly: true`; under `readonly: true` a declarative action's own write is dropped. The section also covers the object-level `uiReadonlyWhen` and how a field replaces it, what a console create does with a `uiReadonly` field, and the refused pair.
+
+One sentence the skill carried is corrected on the way: an import is not a system-context write, so `readonly: true` drops an imported value like any other client write. The two bullets that said otherwise are now one pointer at the new section, and `SKILL.md` § Conditional Field Rules routes there. `evals/objects-fields-relationships.json` gains case 30, a `uiReadonly` status field.
+
+`@objectstack/spec`: the parse refusal for `uiReadonly: true` beside `readonly: true` keeps its wording and now ends with where the model is recorded: `The two locks and which one to choose: ADR-0163 (D1, D6).` No schema, accepted value or default changes.
diff --git a/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md b/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md
new file mode 100644
index 00000000000..4530857cb94
--- /dev/null
+++ b/docs/adr/0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md
@@ -0,0 +1,141 @@
+# ADR-0163: A field's write lock has two tiers, two forms and two levels — `readonly` / `readonlyWhen` keep every client write out, `uiReadonly` / `uiReadonlyWhen` keep a person's hand out at the console, a field's own declaration wins over its object's default, and a `ui`-prefixed key is admitted only where the console's answer and the server's legitimately differ
+
+**Status**: Accepted (2026-11-26) — maintainer ruling on [#36806](https://github.com/objectstack-ai/objectstack/issues/36806), ruling record [`7180466652`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7180466652), verbatim 「按长远模型」, and the maintainer's ruling of 2026-11-28 on the object level, ruling record [`7235326611`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7235326611), verbatim 「B 不算放开 (Recommended)」. `docs/adr/**` is Tier H (Prime Directive #14): this record lands by the maintainer's merge or enqueue, or by an authorised approval. **This record declares.** The keys it describes are on `main` already, landed by [#37436](https://github.com/objectstack-ai/objectstack/pull/37436), [#37888](https://github.com/objectstack-ai/objectstack/pull/37888) and [#38169](https://github.com/objectstack-ai/objectstack/pull/38169); the PR that carries this record changes one refusal message so that it names this record ([D6](#d6--contradictions)). Three things the rulings decide are held by no code yet, each with its card: [Ruled and not yet held](#ruled-and-not-yet-held).
+
+- **Date**: 2026-11-28
+- **Card**: [#37405](https://github.com/objectstack-ai/objectstack/issues/37405) (p2, `area:data`), a sub-issue of #36806, filed by the ruling record so that the model and the naming rule have a record to cite and do not live only in the keys' describe texts.
+- **Decided by**: the maintainer, 2026-11-26, in the decision thread 「裁决 #36806 只读字段命名」: option A 「新增 uiReadonly 布尔键」 on the decision card, then 「按长远模型」, after 「我说的合理的方案是从元数据应用实际可能发生的业务需求角度出发,不等卡」 and 「考虑长远合理的方案」. Ruling record `7180466652` states the model, its phases and the naming rule. The ruling's own text is the authority this record writes down; where the two differ in words, the ruling wins and this record is corrected.
+- **Ruled since**: the maintainer, 2026-11-28, on two questions the object level raised, both on [#37402](https://github.com/objectstack-ai/objectstack/issues/37402). Ruling record `7235326611`: 「B 不算放开 (Recommended)」, a field's explicit `uiReadonly: false` does not open it inside a locked record ([D3](#d3--two-levels-the-field-and-the-object-and-the-fields-own-declaration-wins)). Ruling record [`7237772411`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7237772411): 「本 PR 按字面落地+立跟进卡 (Recommended)」, the inline line rows of a hand-locked parent are a follow-up card ([Ruled and not yet held](#ruled-and-not-yet-held)).
+- **Builds on**: [ADR-0049](./0049-no-unenforced-security-properties.md) (a declared key is enforced on every surface it names). [ADR-0085](./0085-object-semantic-roles-over-surface-hint-blocks.md) §2 (the admission test for future keys: a key binds the object across surfaces, and fails if its honest name contains a page name). [ADR-0092](./0092-sys-user-profile-field-delegation.md) (history: it recorded field-level `readonly` as a UI hint and not a server boundary; the write-path strip has since made it one, which is why the hand lock needs a name of its own). [ADR-0124](./0124-server-enforces-client-is-courtesy.md) (the server is the enforcement point; a client gate stricter than the server is a presentation choice, D4). [ADR-0137](./0137-predicate-fault-semantics-are-contract.md) D2 (what a field-rule predicate that faults does). [ADR-0020](./0020-state-machine-converge-and-enforce.md) (the `state_machine` rule that judges the writes the hand lock lets through).
+- **Leaves unchanged**: `readonly` and `readonlyWhen`, in every respect; every permission grant; the closed-state lock of [ADR-0162](./0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md), which is a record lock that refuses and not a field lock.
+- **Inputs**: code and docs text read on `objectstack-ai/objectstack` `main` at `c610020e`. Positions are in [As built](#as-built-read-at-c610020e).
+
+---
+
+## Provenance
+
+Two kinds of statement appear below, and they are kept apart.
+
+1. **Ruled.** [Decision](#decision) carries only what the rulings say: ruling record `7180466652` (the model, the naming rule, what counts as by hand, the contradiction handling), and ruling records `7235326611` and `7237772411` (the object level). Where a D-item quotes, the words are the ruling record's.
+2. **Readings.** [As built](#as-built-read-at-c610020e) says what the code on `main` does at `c610020e`, cited by symbol anchor (`path#symbol`). A behaviour that appears only there was settled by the PR that landed it and its contract review. It is not a decision of this record.
+
+## TL;DR
+
+| | Server lock: no client may write | Hand lock: no person edits by hand; API, import, actions and flows write, judged by validations |
+|:--|:--|:--|
+| Always | `readonly` | `uiReadonly` |
+| Conditional (CEL over `record`) | `readonlyWhen` | `uiReadonlyWhen` |
+
+- Two **tiers**. The engine reads the server lock and never the hand lock. The console reads both.
+- Two **forms**. A boolean, and a predicate over the record's own columns. `readonlyWhen: P\`true\`` is "set once on create"; there is no key for it.
+- Two **levels**. An object's `uiReadonlyWhen` hand-locks the whole record, and a field's own hand-lock declaration replaces it for that field.
+- **One naming rule.** A `ui`-prefixed twin of a key exists only where the console and the server legitimately answer the same question differently. Read-only is the only such concept today: `uiVisibleWhen` and `uiRequiredWhen` are refused.
+- The hand lock is **not a security boundary**. Who may write a field is a permission.
+
+## Context
+
+A document's status usually moves only through its actions: an order is confirmed by Confirm, not by picking "Confirmed" in a form. Until this ruling the platform had one word for a field nobody edits, `readonly`, and that word is a server boundary: a non-system write that carries a `readonly` field has the field dropped and the rest lands. Measured on the hotcrm sales order (the body of #36806, for objectstack-ai/hotcrm#2716): with `status` declared `readonly`, a declarative update action answered success while the status stayed `draft`, a `PATCH` answered 200 with `X-ObjectStack-Dropped-Fields: status;reason=readonly`, and an import update reported the field dropped. The state machine saw none of them. So an author could keep people out of the field only by keeping the action, the import and the API out with them.
+
+The ruling adds the second fact a field can carry, under its own name, and settles the whole model at once so that later cards do not each invent a spelling: which keys exist, at which levels, what "by hand" means, and when a `ui`-prefixed key may be added at all.
+
+## Decision
+
+### D1 — Two tiers: the server lock and the hand lock
+
+A field carries two independent write facts.
+
+- **The server lock** (`readonly`, `readonlyWhen`): no client may write the field. It is enforced on the write path, for every door.
+- **The hand lock** (`uiReadonly`, `uiReadonlyWhen`): no person edits the field by hand. Writes through the API, import, actions and flows keep the field, and the object's validations judge each of them exactly as they judge an ordinary field, a `state_machine` rule included.
+
+The engine never reads the hand-lock keys. A write to a hand-locked field is not dropped and is not reported as dropped. The console reads both tiers through one verdict: a field is read-only by hand now when `readonly` is true, or `readonlyWhen` is TRUE, or `uiReadonly` is true, or `uiReadonlyWhen` is TRUE.
+
+The hand lock answers a different question from a permission, and it is not one. It says by which route a person changes the field, not who may change it: a caller who may edit the record can write a hand-locked field through the API. Deleting the console's check would let no caller land a write the server refuses, so under ADR-0124 the check is a presentation rule and not an enforcement point in the wrong place. Who may write a field is the permission set's `editable` grant. An object whose fields carry only hand locks is no more protected than one with none, which is the boundary ADR-0092 refused to draw in the interface and this record does not draw there either.
+
+### D2 — Two forms: always and conditional
+
+Each tier has a boolean and a predicate. The predicate is CEL over `record`, the bound record's own columns, and both tiers' predicates have the same scope.
+
+"Set on create, fixed afterwards" is `readonlyWhen: P\`true\``, in the ruling record's words "the RAP `readonly:update` / OData `Core.Immutable` shape; no new key".
+
+A create from the console leaves a `uiReadonly` field out, and the server applies the field's `defaultValue`. An insert through the API, an import or an action may set the field, judged by the validations (a state machine's initial states).
+
+### D3 — Two levels: the field and the object, and the field's own declaration wins
+
+The object level of the hand lock is `uiReadonlyWhen` on the object: while TRUE the whole record is locked by hand. It is a default for each field. A field that declares a hand lock of its own, `uiReadonly: true` or a `uiReadonlyWhen`, is judged by that declaration instead, in both directions: a field whose own `uiReadonlyWhen` is `P\`false\`` stays editable inside a locked record, and a field's own predicate can lock it where the object does not.
+
+An explicit `uiReadonly: false` is not such a declaration (ruling record `7235326611`). It is that key's default, and a Studio switch turned on and then off stores it; read as an opt-out, it would silently open the field on every locked record. The one opt-out spelling is `uiReadonlyWhen: P\`false\``.
+
+A field's server lock is not a hand-lock declaration. It keeps locking on its own, whatever the object declares.
+
+The ruling record names an object-level `readonlyWhen` as "the symmetric completion the model allows later; not filed". This record files nothing for it either. The object level has one key today.
+
+### D4 — What "by hand" is
+
+Quoted from the ruling record:
+
+> "By hand" = create/edit dialogs (and the submitted payload), record-page inline edit, highlight-strip chip, grid inline edit and multi-row save, kanban drag, calendar drag, duplicating a record from the console, and an in-app assistant acting for a person. Not by hand = REST create/update, import (including the console import wizard's mapping), declarative and script actions, flows.
+
+ADR-0049 holds the key to every surface it names. A console surface through which a person changes a field's stored value reads the one verdict of D1, and a surface added later joins that read in the PR that adds it.
+
+### D5 — The `ui` prefix has an admission rule
+
+Quoted from the ruling record, which asks to be cited for it:
+
+> a `ui`-prefixed twin of a key is admitted only where the console's and the server's answers to the same question legitimately differ. Read-only is the only such concept today: visibility has one tier (the server side is permission masking, `requiredPermissions` / FLS `readable`, a different key) and required-ness has one tier (the server; the console mirrors `requiredWhen` for feedback). `uiVisibleWhen` and `uiRequiredWhen` are refused by this rule.
+
+`ui` names the console as a channel and not a page, which is how the two keys pass ADR-0085 §2. A later card that wants a `ui`-prefixed key cites this rule and shows the two answers that legitimately differ. One that cannot show them does not add the key.
+
+### D6 — Contradictions
+
+- `uiReadonly: true` beside `readonly: true` is refused at validate, at `['uiReadonly']`, at every door that parses a field. The server lock already keeps every client out, so the pair says two things at once. The refusal's text names this record.
+- `uiReadonlyWhen` beside `readonlyWhen` is allowed. The two predicates can differ, and where `readonlyWhen` is TRUE the server lock is the stricter one.
+
+### D7 — The server lock stays a strip
+
+This record changes nothing on the write path. A client write that carries a server-locked field has the field dropped and the rest lands, and the answer names the dropped field (`X-ObjectStack-Dropped-Fields`, `droppedFields`). A mode in which the server lock refuses the write instead is out of this record's scope. The option a caller can already pass to have such a write refused whole is unchanged.
+
+## Ruled and not yet held
+
+Three things the rulings decide have no code holding them at `c610020e`. Each is a card, and none is re-opened here.
+
+| Ruled | Today | Card |
+|:--|:--|:--|
+| An in-app assistant acting for a person is a hand surface (D4). | Its writes run in the AI service, outside this repository, which does not read the hand lock. The keys' describe texts say so. | [#37898](https://github.com/objectstack-ai/objectstack/issues/37898) |
+| Duplicating a record from the console is by hand (D4): the copy takes each hand-locked field's `defaultValue`. | The console has no person-triggered duplicate. The REST clone door is an API write, which the ruling keeps. | [#38202](https://github.com/objectstack-ai/objectstack/issues/38202) |
+| The inline line rows of a hand-locked parent come under its lock (ruling record `7237772411`). | A line-item column follows the child object's own lock. | [#38249](https://github.com/objectstack-ai/objectstack/issues/38249) |
+
+## As built, read at `c610020e`
+
+- **The four field keys and the object key**: `packages/spec/src/data/field.zod.ts#FieldSchema` (`readonly`, `readonlyWhen`, `uiReadonly`, `uiReadonlyWhen`, and the refusal of D6 in its refinement); `packages/spec/src/data/object.zod.ts#ObjectSchemaBase` (`uiReadonlyWhen`). `uiReadonly` is optional with no default materialised: absent reads as false.
+- **The server lock**: `packages/objectql/src/validation/rule-validator.ts#stripReadonlyFields` and `#stripReadonlyWhenFields`. Neither reads a hand-lock key. A conditional lock is not judged on a create, which is what makes `readonlyWhen: P\`true\`` set-once. The dropped fields reach the caller through `packages/rest/src/error-response.ts#applyDroppedFieldsHeader`; the refusal a caller can opt into is `packages/objectql/src/readonly-strict-errors.ts#ReadonlyFieldRejectedError`.
+- **The one hand-lock verdict**: `ui/packages/core/src/evaluator/handLock.ts#fieldReadOnlyByHand`, with the object level folded in by `#effectiveUiReadonlyWhen`. Beyond the surfaces the ruling lists, the same verdict is read by the stage path, the line-item grid, the calendar quick-create, the Gantt (drag, resize, progress handle, dependency link, in-place edit), the timesheet cell and the command palette's create-as prefill. The import wizard's target mapping and the Studio authoring reads stay on the raw `readonly`.
+- **A conditional hand lock is judged on an existing record only.** The create dialog does not read `uiReadonlyWhen`.
+- **A hand-lock predicate that cannot be evaluated locks the field**, since no server judges it, and the edit dialog refuses to submit until it is fixed. `os validate` checks a field's and an object's `uiReadonlyWhen` as it checks `readonlyWhen` (`packages/lint/src/validate-expressions.ts`).
+- **A caller denied a field the predicate reads** is served the lock closed instead of the predicate: `uiReadonly: true` on the field, a constant TRUE for the object's (`packages/metadata-core/src/object-schema-fls-references.ts`).
+- **MCP `describe_object`** reports the hand-lock keys as their own keys, never folded into `readonly`, which tells an agent to leave a field out of a write (`packages/runtime/src/domains/mcp.ts#describeServedObject`).
+- **Proof that every write keeps a hand-locked field**: `packages/qa/dogfood/test/ui-readonly-hand-lock-36806.dogfood.test.ts`. Over HTTP, a `PATCH`, an import and a declarative action write a `uiReadonly` field with no dropped-fields header, the `state_machine` rule refuses an illegal move with its own message on each door, and a `readonly` sibling is stripped as the control. The verdict's pins are `ui/packages/core/src/evaluator/__tests__/handLock-36806.test.ts`; the refusal's is `packages/spec/src/data/field-ui-readonly.test.ts`.
+
+## Consequences
+
+- An author has an honest declaration for "people do not type this; the buttons, the imports and the API set it": `uiReadonly`. `readonly` keeps its strong meaning, and nothing about it moves.
+- The console can be stricter than the server by declaration. A person who may edit the record can still write a hand-locked field through the API. Where that must not happen, the answer is a permission, or the server lock.
+- The hand lock has no server judge. It holds only as far as every console surface reads the one verdict, and a surface that forgets it opens the field with no refusal anywhere. The three rows of [Ruled and not yet held](#ruled-and-not-yet-held) are that cost today.
+- A card that wants another `ui`-prefixed key has a rule to meet (D5) before it has a name to pick.
+
+## Alternatives considered
+
+The decision analysis the maintainer read is comment [`7179210173`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7179210173) on #36806. In short:
+
+| Alternative | Why not |
+|:--|:--|
+| `editable: 'actions'` on the field | `editable` is the permission set's write grant. The word would mean "may write" on a grant and "the console may not write" on a field, and the value misdescribes API, import and flow writes. |
+| Widen `readonly` to `boolean \| 'ui'` | The engine strips on a truthy `readonly`, so `'ui'` would be stripped on every write, the opposite of the ask, on a shipped server-enforced key. |
+| No key: `readonly` plus a script action, which runs in a system context | The button works, and API and import writes to the field are still dropped silently. |
+| A key for "editable on create, locked afterwards" | `readonlyWhen: P\`true\`` already says it (D2). |
+| `uiVisibleWhen`, `uiRequiredWhen` | Refused by D5: each of those questions has one tier. |
+
+## Refs
+
+- Card [#37405](https://github.com/objectstack-ai/objectstack/issues/37405); parent [#36806](https://github.com/objectstack-ai/objectstack/issues/36806), ruling record [`7180466652`](https://github.com/objectstack-ai/objectstack/issues/36806#issuecomment-7180466652); object level [#37402](https://github.com/objectstack-ai/objectstack/issues/37402), ruling records [`7235326611`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7235326611) and [`7237772411`](https://github.com/objectstack-ai/objectstack/issues/37402#issuecomment-7237772411).
+- Landed by [#37436](https://github.com/objectstack-ai/objectstack/pull/37436) (the field keys and the console surfaces), [#37888](https://github.com/objectstack-ai/objectstack/pull/37888) (the Gantt, the timesheet, the calendar quick-create and the palette prefill) and [#38169](https://github.com/objectstack-ai/objectstack/pull/38169) (the object level).
+- Open: [#37898](https://github.com/objectstack-ai/objectstack/issues/37898), [#38202](https://github.com/objectstack-ai/objectstack/issues/38202), [#38249](https://github.com/objectstack-ai/objectstack/issues/38249).
diff --git a/docs/adr/README.md b/docs/adr/README.md
index ef063606780..30d5db78151 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -13,11 +13,11 @@
## Summary
-163 records under `docs/adr/` (158 numbers), 11 under `ui/docs/adr/` (listed separately below).
+164 records under `docs/adr/` (159 numbers), 11 under `ui/docs/adr/` (listed separately below).
| Status | Records |
|---|---|
-| Accepted | 139 |
+| Accepted | 140 |
| Proposed | 10 |
| Superseded | 4 |
| Draft | 3 |
@@ -26,7 +26,7 @@
| Amended | 1 |
| Partially implemented | 1 |
| Revised | 1 |
-| **Total** | **163** |
+| **Total** | **164** |
## Shared numbers
@@ -230,6 +230,7 @@ A bare `ADR-0006` names the decision; its current text is [0006-project-environm
| [ADR-0160](./0160-record-scoped-ai-inquiry.md) | Record-scoped AI inquiry — a context pack is its own metadata type, read as the caller and served by one tool… | Accepted — merged 2026-11-24 (PR objectstack#37115); amended 2026-11-25, 2… | 2026-11-24 | — | — |
| [ADR-0161](./0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md) | The knowledge platform boundary — the platform owns document assembly, sync and reconcile, structural split a… | Proposed — 2026-11-24, written for objectstack#37001 on the maintainer's r… | 2026-11-24 | — | — |
| [ADR-0162](./0162-an-object-declares-its-closed-states-the-record-and-its-lines-are-closed-to-change.md) | An object declares its closed states — in them the record and its master-detail lines are closed to change fo… | Proposed — 2026-11-26, written for objectstack#36253 on the maintainer's r… | 2026-11-26 | — | — |
+| [ADR-0163](./0163-field-write-locks-two-tiers-two-forms-two-levels-ui-prefix-admission.md) | A field's write lock has two tiers, two forms and two levels — `readonly` / `readonlyWhen` keep every client… | Accepted — 2026-11-26 — maintainer ruling on #36806, ruling record `718046… | 2026-11-28 | — | — |
## ObjectUI registry — `ui/docs/adr/` (`ui-` prefix)
diff --git a/packages/spec/src/data/field-ui-readonly.test.ts b/packages/spec/src/data/field-ui-readonly.test.ts
index 15ef6161bd4..60e5f2d99c4 100644
--- a/packages/spec/src/data/field-ui-readonly.test.ts
+++ b/packages/spec/src/data/field-ui-readonly.test.ts
@@ -48,6 +48,9 @@ describe('Field.uiReadonly / Field.uiReadonlyWhen', () => {
expect(issues).toHaveLength(1);
expect(issues[0].code).toBe('custom');
expect(issues[0].message).toMatch(/^`uiReadonly: true` locks the field against editing by hand at the console/);
+ // [#37405] The refusal names the record of the model, so the author who
+ // meets it can read why there are two locks and which one to keep.
+ expect(issues[0].message).toMatch(/ADR-0163 \(D1, D6\)\.$/);
});
it('refuses the pair through the object door too', () => {
diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts
index 0d3ab0d986d..f9a7d525065 100644
--- a/packages/spec/src/data/field.zod.ts
+++ b/packages/spec/src/data/field.zod.ts
@@ -3430,7 +3430,8 @@ export const FieldSchema = lazySchema(() => {
});
}
}
- // The hand lock beside the server lock (ruling record 7180466652): a
+ // The hand lock beside the server lock (ruling record 7180466652, recorded
+ // as ADR-0163 D6, which the message names so the reader can find the model): a
// `readonly: true` field already keeps every client out, so `uiReadonly`
// beside it says two things at once — refused at every door that parses a
// field (`defineStack`, `os validate`, the metadata save). The conditional
@@ -3444,7 +3445,8 @@ export const FieldSchema = lazySchema(() => {
'`uiReadonly: true` locks the field against editing by hand at the console while API, import, action and '
+ 'flow writes keep it, and this field is also `readonly: true`, which keeps every client write out. Keep '
+ 'one: `readonly` when no client may write the field, `uiReadonly` when people at the console may not but '
- + 'actions, imports and the API may (each write judged by the object\'s validations).',
+ + 'actions, imports and the API may (each write judged by the object\'s validations). The two locks and '
+ + 'which one to choose: ADR-0163 (D1, D6).',
});
}
diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs
index 5f9bb5b3cda..20083a325da 100644
--- a/scripts/check-skills-token-ratchet.mjs
+++ b/scripts/check-skills-token-ratchet.mjs
@@ -914,7 +914,14 @@ export const CEILINGS = new Map([
// `references/examples-objects.md` § Object Extension Model; the rule list `main` trimmed is
// the routing table here). 8983 bytes on this tree, whose stamp line is 27 bytes: 8956 priced.
// ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 27) / 4) == ceil(8956 / 4)
- ['skills/objectstack-data/SKILL.md', 2239],
+ // 2239 -> 2224 (#37405, ADR-0163): LOWERED to the measurement. The first bullet of
+ // `## Conditional Field Rules` keeps its trap (the value is dropped, the write is not
+ // refused, a declarative action's included) and routes the choice of lock to
+ // `rules/validation.md` § Locking a Field in place of the clause on which writers
+ // `readonly: true` binds, which that section now carries. 8983 -> 8923 bytes (8956 ->
+ // 8896 priced), -60, -> 2224 tokens, pinned AT the measurement.
+ // ceil(($(wc -c < skills/objectstack-data/SKILL.md) - 27) / 4) == ceil(8896 / 4)
+ ['skills/objectstack-data/SKILL.md', 2224],
// 5997 -> 6008 (the formula skills follow-ups of PRs #34443 and #34447): the
// `label(record.f)` row teaches a multi-select (`multiple: true`) reading each
// selected label in stored order, joined with `, `, and the built-ins line
@@ -1731,7 +1738,18 @@ export const CEILINGS = new Map([
// headroom absorbed, ceiling +705, pinned AT the measurement. Authority as the
// `references/examples-objects.md` row.
// ceil($(wc -c < skills/objectstack-data/rules/validation.md) / 4) == ceil(13861 / 4)
- ['skills/objectstack-data/rules/validation.md', 3466],
+ // 3466 -> 3862 (#37405, ADR-0163): GAINS `## Locking a Field`, the section the ruling of
+ // record on #36806 orders into this skill (ruling record 7180466652: the four spellings,
+ // which one to use, the sales-order status example), with one checked example. PAID DOWN
+ // FIRST inside the file: the two `readonly` / `readonlyWhen` bullets of § Conditional Field
+ // Rules become one pointer at the new section, which says the same once (and corrects their
+ // claim that an import is a system-context write); § Conditional Validation loses its first
+ // example and the lead-in of the second, whose `when` / `then` / `otherwise` rule shows
+ // everything the first did. -1035 bytes cut, +2622 added: 13861 -> 15448 bytes (+1587) ->
+ // 3862 tokens, no headroom to absorb any of it, ceiling +396, the measured remainder, pinned
+ // AT the measurement. Raise path 「A:先削重复,余额按实测提高」 (ruling record 6513306068).
+ // ceil($(wc -c < skills/objectstack-data/rules/validation.md) / 4) == ceil(15448 / 4)
+ ['skills/objectstack-data/rules/validation.md', 3862],
// objectstack-platform
['skills/objectstack-platform/references/plugin-hooks.md', 2413], // -215 to the measurement (was 2628)
diff --git a/skills/objectstack-data/SKILL.md b/skills/objectstack-data/SKILL.md
index e1e6f822b25..12fa061fe6a 100644
--- a/skills/objectstack-data/SKILL.md
+++ b/skills/objectstack-data/SKILL.md
@@ -82,9 +82,9 @@ over `record.*` (`P\`record.status == 'paid'\``), so every form and
API write honours them.
- **`readonlyWhen` and `readonly: true` drop the value; they do not refuse the
- write.** `readonly: true` binds non-system writes only; a `runAs:'system'`
- flow, system hook or seed does write it
- ([objectstack-automation → Failure routing & `runAs`](../objectstack-automation/SKILL.md#failure-routing--runas)).
+ write**, a declarative action's included. A field that only actions, imports
+ and the API change is `uiReadonly`
+ ([Locking a Field](./rules/validation.md#locking-a-field)).
- **`requiredWhen` is a transition gate, not an invariant**: it judges the
write, not the stored row. A fact true of every stored record is a
`validations[]` `script` rule.
diff --git a/skills/objectstack-data/evals/README.md b/skills/objectstack-data/evals/README.md
index 41ef4dd78b2..26cfeba52df 100644
--- a/skills/objectstack-data/evals/README.md
+++ b/skills/objectstack-data/evals/README.md
@@ -6,7 +6,8 @@ JSON fixtures in the objectui shape (`skill_name`, `evals[]`: `prompt`,
- `objects-fields-relationships.json` — naming, field types (`secret` vs
`password`), relationships (junction vs multi-value lookup,
`deleteBehavior`, on a `user` field too), validation (`state_machine`, unique **index**),
- conditional field rules, the record owner (负责人 is `owner_id`), an
+ conditional field rules, the hand lock (a `uiReadonly` status field), the
+ record owner (负责人 is `owner_id`), an
object extension placing what it brings (`place`), the `.custom` pair's
whole arrangement (`relatedLists`, `{ list, hidden: true }`).
- `hooks-security-seeds-datasources.json` — search mirrors via hooks,
diff --git a/skills/objectstack-data/evals/objects-fields-relationships.json b/skills/objectstack-data/evals/objects-fields-relationships.json
index 4e27cd38d68..d658205ce7e 100644
--- a/skills/objectstack-data/evals/objects-fields-relationships.json
+++ b/skills/objectstack-data/evals/objects-fields-relationships.json
@@ -515,6 +515,19 @@
],
"must_not_contain": []
}
+ },
+ {
+ "id": 30,
+ "prompt": "On `sales_order`, `status` (`draft`, then `confirmed`) should change only through the Confirm button: nobody may pick another status in the form, in a grid cell or by dragging a card on the board. A colleague set `readonly: true` on `status`; now Confirm answers success and the order stays `draft`. Why, and how should the field be declared so that Confirm works and can only take a draft order to confirmed?",
+ "expected_output": "`readonly: true` is the server lock: every non-system write to the field is dropped, not refused, and the Confirm action's own update is such a write, so it answers success without the change (`X-ObjectStack-Dropped-Fields` names the field). Declare the hand lock instead: `status: Field.select({ options: [...], defaultValue: 'draft', uiReadonly: true })`. Forms, inline edit, grid cells and board drags stop offering the field, while the action, an import and the API still write it, each write judged by the object's validations; so the legal move goes in a `state_machine` rule on `status` (`draft: ['confirmed']`). It is not security: whoever may edit the record can still write the field through the API.",
+ "files": [],
+ "assertions": {
+ "must_contain": [
+ "uiReadonly: true",
+ "state_machine"
+ ],
+ "must_not_contain": []
+ }
}
]
}
diff --git a/skills/objectstack-data/rules/validation.md b/skills/objectstack-data/rules/validation.md
index b4b1fda4da0..e4cf5bbae77 100644
--- a/skills/objectstack-data/rules/validation.md
+++ b/skills/objectstack-data/rules/validation.md
@@ -198,25 +198,6 @@ is a **single** nested rule applied when it holds, `otherwise` (optional) a
single rule applied when it doesn't. There is no `validations: []` array —
compose multiple checks as multiple top-level rules or nested conditionals.
-```typescript
-validations: [
- {
- name: 'enterprise_requires_manager',
- type: 'conditional',
- when: P`record.type == 'enterprise'`,
- message: 'Enterprise account validation',
- then: {
- name: 'manager_required',
- type: 'script',
- condition: P`isBlank(record.account_manager)`,
- message: 'Enterprise accounts must have an account manager',
- },
- },
-]
-```
-
-With an `otherwise` branch:
-
```typescript
{
name: 'payment_validation',
@@ -364,13 +345,8 @@ export const Invoice = ObjectSchema.create({
- `showOnCreate: false` keeps a field off every create surface; edit, the
record page and lists keep it. Refused beside `required: true`.
-- Use `readonlyWhen` for state-locked fields; the ObjectQL write path ignores
- incoming changes when the predicate is `TRUE` (for everyone; per permission
- set → field permission `when`, rules/security.md).
-- **`readonly: true` governs the end-user surface, not trusted system writers.**
- A stripped write (REST/UI, and any `runAs:'user'` flow) reports success.
- Imports and migrations are system-context writes too. Keep the field `readonly` when automation maintains it; the flow
- side: [objectstack-automation → Failure routing & `runAs`](../../objectstack-automation/SKILL.md#failure-routing--runas).
+- `readonly`, `readonlyWhen` and the console-only lock:
+ [Locking a Field](#locking-a-field).
- Use `requiredWhen` for conditional requiredness; the ObjectQL validator
enforces it on submit. The removed `conditionalRequired` alias is a parse
error.
@@ -390,3 +366,56 @@ or `requiredWhen` refuses the write naming it, an option `visibleWhen` only a
write picking the option (forms still offer it); a `readonlyWhen` field stays
editable and the save succeeds without its change (logged); a formula reads
`null` (logged).
+
+## Locking a Field
+
+Two questions pick the key: who is kept out, and when.
+
+| | Every write | Only a person at the console |
+|:--|:--|:--|
+| Always | `readonly: true` (system writes pass) | `uiReadonly: true` |
+| While a `record.*` predicate is TRUE | `readonlyWhen` | `uiReadonlyWhen` |
+
+
+```typescript
+import { P } from '@objectstack/spec';
+import { ObjectSchema, Field } from '@objectstack/spec/data';
+
+export const SalesOrder = ObjectSchema.create({
+ name: 'sales_order',
+ sharingModel: 'public_read_write',
+ uiReadonlyWhen: P`record.status != 'draft'`, // once confirmed, only actions change the order
+ fields: {
+ status: Field.select({ // moved by the Confirm action, never typed
+ options: [{ label: 'Draft', value: 'draft' }, { label: 'Confirmed', value: 'confirmed' }],
+ defaultValue: 'draft',
+ uiReadonly: true,
+ }),
+ order_number: Field.text({ readonlyWhen: P`true` }), // set on create, then fixed
+ notes: Field.textarea({ uiReadonlyWhen: P`false` }), // editable on a confirmed order too
+ },
+});
+```
+
+- **Left column, the server lock: the value is dropped, the write is not
+ refused.** REST, the UI, an import, a declarative action and a
+ `runAs:'user'` flow answer success without the change
+ (`X-ObjectStack-Dropped-Fields` names the field). `readonly: true` lets a
+ system writer through (a seed, a migration, a system hook, a
+ `runAs:'system'` flow:
+ [objectstack-automation → Failure routing & `runAs`](../../objectstack-automation/SKILL.md#failure-routing--runas)),
+ so keep it on a field automation maintains. `readonlyWhen` holds for
+ everyone (per permission set: a field permission `when`,
+ [Security](./security.md)) and is not judged on a create.
+- **Right column, the hand lock: forms, inline edit, grid cells and board or
+ calendar drags do not offer the field, and every write still lands**,
+ judged by the validations (a `state_machine` on `status`). Under `readonly`
+ a declarative Confirm's write would be dropped. Not security: whoever may
+ edit the record can write the field through the API.
+- A console create leaves a `uiReadonly` field out: the record takes its
+ `defaultValue`, and a `required` field without one fails the create.
+- On the **object**, `uiReadonlyWhen` locks every field of an existing record.
+ A field's own `uiReadonly: true` or `uiReadonlyWhen` replaces it;
+ `uiReadonly: false` does not.
+- `uiReadonly` beside `readonly: true` is refused. Only read-only has a `ui`
+ twin: there is no `uiVisibleWhen`.
From da184dacd9d4f8ee66710453f235255e7fdee223 Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 01:39:53 +0000
Subject: [PATCH 013/162] fix(auth)!: createAuthClient().updateUser declares a
void result, matching better-auth's receipt (#38431)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Tesla** · [project
thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoAoNwrZVJoUEFfvMURpRPKJ)_
Fixes #36987
Supersedes #37433
Clause-②: no (narrowing)
Metadata-protocol: none
Skills-docs: none — no skill or doc page reads AuthClient.updateUser's
result
> **BREAKING** (published typing, shipped as `patch`):
`AuthClient.updateUser` in `@object-ui/auth` now resolves a promise of
`void` instead of a promise of `AuthUser`. Callers that read the result,
and hosts that implement `AuthClient` and pass it as
`AuthProviderOptions.client` with an `updateUser` that returns a user,
no longer type-check; read the session instead / return nothing. Runtime
behaviour that ever worked is unchanged (the server always answered `{
status: true }`).
## 维护者速读
- 用户无感:只改了认证包对外声明的返回类型,界面和资料保存的表现都不变。
- 为什么做:认证包对外说"改资料后会交回用户",实际服务器只回一个"成功"回执,对外的说明和实际对不上。
- 出错会怎样:只影响直接调用这个接口的外部代码,它们改读会话即可;改动可直接撤回。
- 要你做什么:在席位审核通过后批准合并(申报为收窄,需你批准)。
## What changes
This PR carries seat 5's draft #37433 (4 commits, cherry-picked in order
onto `origin/main` f42bcc18c, no conflict) and finishes it on the ruling
recorded on #37433 (maintainer ruling 7183687803, 「新增第八类」), now that
ADR-0087's eighth category `runtime-member-retyped` has landed (#38365,
f42bcc18c).
Arm (a): the declaration now says what the call returns.
`AuthClient.updateUser` in `@object-ui/auth` was declared as a `Promise`
of `AuthUser`. It is now a `Promise` of `void`, and
`createAuthClient().updateUser` resolves with nothing instead of handing
on better-auth's answer.
- FROM `(data: Partial of AuthUser) => Promise of AuthUser` TO `(data:
Partial of AuthUser) => Promise of void`.
- Premise (measured on #37433's base da7c559990, re-read on f42bcc18c):
better-auth's `dist/api/routes/update-user.mjs` ends `/update-user` with
`ctx.json({ status: true })`. `plugin-auth` passes the route through
unchanged (`auth-route-ledger.ts`, disposition `sdk`). The client cast
that receipt to `AuthUser` and returned it.
- Why (a) and not (b), where (b) means returning a real user with one
more session read:
- Census of `updateUser` readers (see Verification; re-run on this
head): the only in-repo caller of the client method is
`AuthProvider.updateUser`, which awaits the call and ignores the result.
`AuthContext.updateUser` and `useAuth().updateUser` already resolve with
nothing. `ProfilePage` calls `useAuth().updateUser` and never reads a
result. No reader needs the user.
- With (b), every profile write would cost one more round trip to fetch
a user that nobody reads. `updateUser` would also be the only write on
`AuthClient` that returns the entity; `changePassword`,
`setInitialPassword`, `verifyTotp` and the other writes all resolve with
nothing.
- `@objectstack/client` already types the same route as a status receipt
(`AuthStatusReceipt`). (a) brings the two published clients into
agreement about what the server answers.
- A refusal still rejects, as before. The `no data` guard stays, with a
one-line comment on why (N2).
- Changeset `.changeset/36987-auth-updateuser-returns-void.md`:
`@object-ui/auth` patch, `fix(auth)!:`, `Clause-②: no (narrowing)`,
`Metadata-protocol: none`, a `**BREAKING**` banner, the migration lines
for result readers and for host `AuthClient` implementations (S1), and
exactly one ADR-0087 marker, `not-required (runtime-member-retyped
@object-ui/auth#AuthClient.updateUser)`. Its FROM and TO are written on
ONE line, which the category's from-operands-named predicate reads. The
member is not rewritten as a method signature (ruling 7183687803).
- N1: the client doubles in `AuthProvider.test.tsx` and
`LoginForm.test.tsx` now resolve `updateUser` with nothing, as the
server does, instead of a user.
Read first (by risk):
1. `ui/packages/auth/src/types.ts`, the `AuthClient.updateUser`
declaration: the published typing that narrows.
2. `ui/packages/auth/src/createAuthClient.ts`, the `updateUser` hunk:
the runtime change (returns nothing).
3. `.changeset/36987-auth-updateuser-returns-void.md`: the disposition
marker and the one-line FROM ... TO that external callers read.
## Tests
- New `ui/packages/auth/src/__tests__/updateUser-return-36987.test.ts`
has two pins. The type pin checks that `ReturnType` of
`AuthClient['updateUser']` and of `createAuthClient()`'s `updateUser`
both equal a `Promise` of `void` (held by `tsc -p tsconfig.test.json`,
the package's `type-check`). The runtime pin checks that `{ status: true
}` from the wire resolves to `undefined`.
- The existing `createAuthClient.test.ts` case used to stub
`/update-user` with a `{ user }` body the server never sends and assert
`result.name`. It now stubs the real receipt and asserts that the call
resolves with `undefined`.
Package tests, type-check and build
(830cdac0a)
- Closure build under the verify lock: `pnpm --workspace-concurrency=2
--filter '@object-ui/auth^...' build`, `VERDICT command-exit 0`.
- `pnpm --filter @object-ui/auth type-check && pnpm --filter
@object-ui/auth test && pnpm --filter @object-ui/auth build`, `VERDICT
command-exit 0`. Tests: `Test Files 52 passed (52)`, `Tests 557 passed
(557)`.
Ablation: the old declaration plus the old cast
(one-off, no file kept)
- One ablation, three mutations through `scripts/ablation-replace.mjs`,
all landed by its own counts: `types.ts` back to the `AuthUser` promise
(anchor 1 to 0, blob 2d83741e to 5b271b75); in `createAuthClient.ts` the
`void` return annotation removed (anchor 1 to 0, blob e6af4260 to
e9aafd14) and `return data as unknown as AuthUser;` put back (anchor 1
to 0, blob e9aafd14 to 0e7700bb).
- Type leg: `tsc -p tsconfig.test.json` exited 2, TS2344 on both type
pins (`updateUser-return-36987.test.ts` lines 22 and 24).
- Runtime leg: vitest on the pin and `createAuthClient.test.ts` went
red: `Tests 2 failed | 42 passed (44)`, `AssertionError: expected {
status: true } to be undefined`.
- Restore: `git checkout HEAD --` on both paths; `git diff HEAD` empty,
blobs equal HEAD (2d83741e, e6af4260).
- The first attempt was a no-op: the third mutation's replacement
contained its anchor (count 1 to 1). The tool refused it and restored;
the run was repeated with a different anchor. Both pins import from
source, so no `dist/` is on the path.
## Acceptance notes
- The ProfilePage test doubles added since #37433's base
(`ProfilePage.passwordRefusal-37973.test.tsx` among them) stub
`useAuth().updateUser` as resolving nothing, which is the context
surface that was already void. They neither read the client method's
result nor implement `AuthClient`. Noted, nothing owed.
## Verification
ADR-0087 disposition (830cdac0a)
- `node scripts/check-adr-0087-registration.mjs --base origin/main`:
exit 0, `verified: @object-ui/auth#AuthClient.updateUser (updateUser:
(data: Partial of AuthUser) => Promise of AuthUser -> updateUser: (data:
Partial of AuthUser) => Promise of void,
ui/packages/auth/src/types.ts)`, tags
`[BREAKING+bang+clause-②-narrowing]`.
- Two earlier attempts on the way were refused on predicate 3
(from-operands-named): a FROM side spelled as a whole signature in one
code span, then a second code span between FROM and TO. The FROM side
now names `AuthClient.updateUser` alone and the signatures sit outside
it.
updateUser census on this head (ui/, apps/, examples/,
skills/, content/)
- 48 hits by `git grep -n updateUser` (CHANGELOGs excluded). Against
#37433's base da7c559990 the only new file is
`ProfilePage.passwordRefusal-37973.test.tsx`, a `useAuth()` double whose
`updateUser` resolves nothing (the context surface, already void).
- Client-method callers: `ui/packages/auth/src/AuthProvider.tsx:549`
only, awaiting and discarding. No code outside `ui/packages/auth`
implements `AuthClient.updateUser`.
`content/docs/frontend/data-source.mdx:121,150` is an unrelated
user-defined data-source method. Nothing under `examples/` or `skills/`.
Derived gate families (830cdac0a)
- `node scripts/pm/dispatch-gates.mjs --commands --repo
objectstack-ai/objectstack` derived 39 families; each was run and its
exit recorded.
- 38 exited 0 on the first pass, including `pnpm --dir ui exec vitest
run scripts/` (`Test Files 172 passed | 2 skipped (174)`, `Tests 5159
passed | 2 skipped (5161)`).
- `pnpm check:type-check-debt` exited 3 (PREREQUISITE NOT MET: its
closure build lost the lock turn to the dogfood run). Rerun under the
lock, appended: exit 0, `0 ledger entr(ies) re-measured ... none above
its recorded number`.
- `dispatch-gates --ran`: `39 derived famil(ies) accounted for — 38 run,
1 NOT-MEASURED` (the first-pass exit 3; the appended rerun is green).
- Also run: `pnpm check:changeset-fixed` (roster under `.changeset/`)
exit 0; `dispatch-gates --tier`: no path-derived mandate.
- `overlap-check --branch=HEAD --exclude-pr=37433` before the first
push: `VERDICT clean exit 0` (#37433 is the superseded draft and
overlaps by construction).
Dogfood battery (830cdac0a)
- Owed: the title carries `!` and the declaration a `(narrowing)` arm.
Closure `pnpm --filter '@objectstack/dogfood^...' build` then `pnpm
--filter @objectstack/dogfood test`, both under the lock, no shard and
no path.
- `VERDICT command-exit 0`, `Test Files 495 passed | 3 skipped (498)`,
`Tests 4183 passed | 68 skipped (4251)`. No failures.
Two-minute check: `pnpm --filter @object-ui/auth exec vitest run --root
../.. packages/auth/src/__tests__/updateUser-return-36987.test.ts`
should show 2 passing tests, and `node
scripts/check-adr-0087-registration.mjs --base origin/main` should print
a `verified:` line for `@object-ui/auth#AuthClient.updateUser`.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01L9qibx7DSQZnugnuX8CpCM)_
---------
Co-authored-by: Claude
---
.../36987-auth-updateuser-returns-void.md | 18 ++++++++
.../auth/src/__tests__/AuthProvider.test.tsx | 2 +-
.../auth/src/__tests__/LoginForm.test.tsx | 2 +-
.../src/__tests__/createAuthClient.test.ts | 10 ++---
.../__tests__/updateUser-return-36987.test.ts | 43 +++++++++++++++++++
ui/packages/auth/src/createAuthClient.ts | 12 ++++--
ui/packages/auth/src/types.ts | 8 +++-
7 files changed, 81 insertions(+), 14 deletions(-)
create mode 100644 .changeset/36987-auth-updateuser-returns-void.md
create mode 100644 ui/packages/auth/src/__tests__/updateUser-return-36987.test.ts
diff --git a/.changeset/36987-auth-updateuser-returns-void.md b/.changeset/36987-auth-updateuser-returns-void.md
new file mode 100644
index 00000000000..5901cd43445
--- /dev/null
+++ b/.changeset/36987-auth-updateuser-returns-void.md
@@ -0,0 +1,18 @@
+---
+'@object-ui/auth': patch
+---
+
+fix(auth)!: `createAuthClient().updateUser` declares `Promise`, because the server answers a receipt, not the user
+
+Clause-②: no (narrowing)
+Metadata-protocol: none
+
+
+
+**BREAKING** for a typed caller and for a host that implements `AuthClient` itself, shipped as `patch`: the change is not to the metadata protocol (`Metadata-protocol: none`). Nothing that worked at runtime breaks for a caller of `createAuthClient()`: the value it now drops was never a user.
+
+The published typing narrows. `AuthClient.updateUser` was declared to return the updated user, but better-auth's `POST /update-user` answers `{ status: true }`, and the client passed that answer on as if it were a user. A caller that trusted the type read a user with no `id`, `name` or `email`.
+
+- FROM `AuthClient.updateUser` declared to resolve the updated user TO `AuthClient.updateUser: (data: Partial) => Promise`, which resolves nothing (it was `(data: Partial) => Promise`). At runtime `createAuthClient().updateUser` resolves with `undefined` instead of the receipt. A refusal still rejects, as before.
+- **A caller that read the result** (`(await client.updateUser(data)).name`) no longer compiles. It read `undefined` at runtime. Read the stored fields with `getSession()` after the write. `useAuth().updateUser` already resolved with nothing and keeps the session user's identity, so React callers see no change.
+- **A host that builds its own `AuthClient` and passes it as `AuthProviderOptions.client`**, with an `updateUser` that returns the user (`async (data): Promise => …`), no longer assigns to the interface. Return nothing from it, or annotate it `Promise`. `AuthProvider` never read that value.
diff --git a/ui/packages/auth/src/__tests__/AuthProvider.test.tsx b/ui/packages/auth/src/__tests__/AuthProvider.test.tsx
index 83f9a2f33b7..26e22f3df7f 100644
--- a/ui/packages/auth/src/__tests__/AuthProvider.test.tsx
+++ b/ui/packages/auth/src/__tests__/AuthProvider.test.tsx
@@ -29,7 +29,7 @@ function createMockClient(overrides: Partial = {}): AuthClient {
getSession: vi.fn().mockResolvedValue(null),
forgotPassword: vi.fn().mockResolvedValue(undefined),
resetPassword: vi.fn().mockResolvedValue(undefined),
- updateUser: vi.fn().mockResolvedValue({ id: '1', name: 'Updated', email: 'test@test.com' }),
+ updateUser: vi.fn().mockResolvedValue(undefined),
...overrides,
// `AuthClient` declares ~38 methods; this double implements the eight the
// provider reaches on the paths under test, which is the same shape (and
diff --git a/ui/packages/auth/src/__tests__/LoginForm.test.tsx b/ui/packages/auth/src/__tests__/LoginForm.test.tsx
index 39e978fda01..fc25e54aedb 100644
--- a/ui/packages/auth/src/__tests__/LoginForm.test.tsx
+++ b/ui/packages/auth/src/__tests__/LoginForm.test.tsx
@@ -30,7 +30,7 @@ function createMockClient(
getSession: vi.fn().mockResolvedValue(null),
forgotPassword: vi.fn().mockResolvedValue(undefined),
resetPassword: vi.fn().mockResolvedValue(undefined),
- updateUser: vi.fn().mockResolvedValue({ id: '1', name: 'Updated', email: 'test@test.com' }),
+ updateUser: vi.fn().mockResolvedValue(undefined),
getConfig: vi.fn().mockResolvedValue(config),
...overrides,
} as unknown as AuthClient;
diff --git a/ui/packages/auth/src/__tests__/createAuthClient.test.ts b/ui/packages/auth/src/__tests__/createAuthClient.test.ts
index bc5717b23f7..678af230281 100644
--- a/ui/packages/auth/src/__tests__/createAuthClient.test.ts
+++ b/ui/packages/auth/src/__tests__/createAuthClient.test.ts
@@ -290,20 +290,18 @@ describe('createAuthClient', () => {
await expect(client.signIn({ email: 'x', password: 'y' })).rejects.toThrow();
});
- it('updateUser sends POST to /update-user and returns user', async () => {
+ it('updateUser sends POST to /update-user and resolves with nothing (objectstack#36987)', async () => {
const { mockFn, calls } = createMockFetch({
- '/update-user': {
- body: { user: { id: '1', name: 'Updated', email: 'test@test.com' } },
- },
+ // better-auth's real answer on this route: a receipt, not the user.
+ '/update-user': { body: { status: true } },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
- const result = await client.updateUser({ name: 'Updated' });
+ await expect(client.updateUser({ name: 'Updated' })).resolves.toBeUndefined();
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/update-user');
expect(calls[0].method).toBe('POST');
- expect(result.name).toBe('Updated');
});
});
diff --git a/ui/packages/auth/src/__tests__/updateUser-return-36987.test.ts b/ui/packages/auth/src/__tests__/updateUser-return-36987.test.ts
new file mode 100644
index 00000000000..4d0e927dc95
--- /dev/null
+++ b/ui/packages/auth/src/__tests__/updateUser-return-36987.test.ts
@@ -0,0 +1,43 @@
+/**
+ * objectstack#36987 — `AuthClient.updateUser` declares what it returns.
+ *
+ * better-auth's `POST /update-user` answers the receipt `{ status: true }`
+ * (`better-auth/dist/api/routes/update-user.mjs`), never the user. The
+ * published `AuthClient` used to declare `Promise` and the client
+ * cast the receipt to that type, so a caller that trusted it read a "user"
+ * with no `id`, `name` or `email` (objectstack#36972 was the in-repo case).
+ *
+ * The declaration is now `Promise`, the same as `AuthContext.updateUser`
+ * and the client's other writes, and the call resolves with nothing. The type
+ * leg is erased at runtime: `tsc -p tsconfig.test.json` (the package's
+ * `type-check`) is what holds it.
+ */
+
+import { describe, it, expect, expectTypeOf, vi } from 'vitest';
+import { createAuthClient } from '../createAuthClient';
+import type { AuthClient } from '../types';
+
+describe('updateUser declares and returns nothing (objectstack#36987)', () => {
+ it('declares Promise on the published AuthClient', () => {
+ expectTypeOf>().toEqualTypeOf>();
+ expectTypeOf['updateUser']>>().toEqualTypeOf<
+ Promise
+ >();
+ });
+
+ it('resolves with undefined on better-auth\'s receipt instead of passing it on', async () => {
+ const fetchFn = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ status: true }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+ const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn });
+
+ const answer: unknown = await client.updateUser({ name: 'Grace' });
+
+ expect(answer).toBeUndefined();
+ expect(fetchFn).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/packages/auth/src/createAuthClient.ts b/ui/packages/auth/src/createAuthClient.ts
index ca875ff8dd1..e6af42601e5 100644
--- a/ui/packages/auth/src/createAuthClient.ts
+++ b/ui/packages/auth/src/createAuthClient.ts
@@ -1129,17 +1129,21 @@ export function createAuthClient(config: AuthClientConfig): AuthClient {
}
},
- async updateUser(userData: Partial) {
+ async updateUser(userData: Partial): Promise {
const { data, error } = await betterAuth.updateUser(userData);
if (error) {
throw new Error(error.message ?? `Auth request failed with status ${error.status}`);
}
if (!data) {
+ // Kept although nothing is returned: an empty 2xx is still an anomaly
+ // a caller should hear about, not a silent success.
throw new Error('Update user returned no data');
}
- // The server response may wrap the user in a `user` key or return it directly
- const raw = data as unknown as Record;
- return (raw && typeof raw === 'object' && 'user' in raw ? raw.user : raw) as AuthUser;
+ // better-auth's `/update-user` answers the receipt `{ status: true }`,
+ // never the user (`dist/api/routes/update-user.mjs`), so nothing is
+ // passed on. It used to be cast to `AuthUser` and returned, and the
+ // provider installed it as the session user (objectstack#36972,
+ // objectstack#36987). Re-read the session for the stored fields.
},
/**
diff --git a/ui/packages/auth/src/types.ts b/ui/packages/auth/src/types.ts
index a4921a70f15..2d83741e392 100644
--- a/ui/packages/auth/src/types.ts
+++ b/ui/packages/auth/src/types.ts
@@ -530,8 +530,12 @@ export interface AuthClient {
setInitialPassword: (newPassword: string) => Promise;
/** Whether the current user has a local credential password configured. */
hasLocalPassword: () => Promise;
- /** Update user profile */
- updateUser: (data: Partial) => Promise;
+ /**
+ * Update the signed-in user's profile. Resolves with nothing: the server
+ * answers a `{ status: true }` receipt, not the user, so re-read the session
+ * (`getSession`) for the stored fields. A refusal rejects (objectstack#36987).
+ */
+ updateUser: (data: Partial) => Promise;
/** Fetch the public auth configuration from the server (providers, features) */
getConfig: () => Promise;
From 84477b9ec719643b4e80effb7af7340c6f87835d Mon Sep 17 00:00:00 2001
From: "objectstack-fleet[bot]"
<332303061+objectstack-fleet[bot]@users.noreply.github.com>
Date: Sun, 29 Nov 2026 01:48:49 +0000
Subject: [PATCH 014/162] feat(pm): topic board splits each row by grade and
state, adds an All / p1 / p2 / p3 switch and each topic's p1/p2 card list
(#38424)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XHogQ9ogKPxHhiFfT2UQgJi)_
Fixes #38400
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:你打开专题看板时,顶部多了「全部 / p1 / p2 /
p3」切换,所有数字跟着切;每行按可派、在做、阻塞、待你裁、搁置拆开;点开一个专题或「专题以外」一行,直接列出其中每张 p1、p2
卡,带状态、谁在做、在等什么。
- 为什么做:你说看板上的剩余任务和你自己在 GitHub 上查到的对不上;这次把「可派」单独算,并在页脚写清每个数字的口径和可以照着查的查询。
- 出错会怎样:只影响看板这一页的数字和列表,不改任何卡片;数字错了下一次刷新前会一直显示错的,撤掉这次改动即可回到原来的看板。
- 要你做的:无。
## Round 2 (head d3ab35aa55, answering L1 comment 7248641965)
1. **Cloud grade word.** The cloud lead's span is now
`data-draw="gradeWordC"`, drawn by the same function as `gradeWord`,
like every other cloud copy on the page. (The Data type's guide says
`dash.draw(name, fn)` runs `fn(el)` on each element carrying that name,
so one name did fill both; the rename removes the question.) Stand-in
render of the cloud tab, fed the objectstack datasets because this
session cannot read `objectstack-ai/cloud`: at p2 the cloud sentence
reads 「15 个专题在推进。共有 125 张未完成的 p2 卡;可派 50 张,在做 23 张,阻塞 28 张,等你裁决 9 张,搁置
15 张。」, at 全部 「19 个专题在推进。共有 357 张未完成的卡,其中 p1 15 张;可派 226 张,在做 27 张,阻塞 47
张,等你裁决 19 张,搁置 34 张。」; the cloud board shows and the objectstack board
hides; topic #35154's list opens with 6 rows; 0 page errors, 0 drawing
faults.
2. **One-writer: fixed in this PR.**
- The tab write moved. The repo tabs now toggle the class `eb-on-cloud`
on `.eb`, and the CSS keys off that class; `data-repo` is gone from the
HTML and the script. It was the one script write outside a drawing that
the guide does not allow, and it fired at load for a viewer whose last
tab was cloud.
- The grade switch's three writes stay in `dash.onData`, because the
guide lists exactly them as allowed: "Outside a drawing a script only
listens and sets `class`, `style`, `hidden`, `open`, `disabled`,
`checked`, `selected`, `value`, `tabindex` or `aria-*`. Any other write
there is a fault." For `hidden` on `.eb-allonly`, the container of the
`p1` drawing, it adds: "a drawing can't show itself or its container.
`dash.onData(fn)` runs before the drawings and can." Moving them into
drawings would make the switch buttons and the `.eb` root drawings and
put the switch's fixed labels into script, which the same guide rules
out. A comment at the `onData` call now says this.
- Reading: the stand-in records every script write outside a `data-draw`
element that is not on that allowed list. At 12dff8db75 it records
`attributes data-repo on DIV.eb` on a tab click, and at load when the
viewer last chose cloud. At d3ab35aa55 it records none. The only other
records, at both heads alike, are the harness's own parser insertions of
its trailing script elements. The live check is still the first refresh
with this template.
3. **Nit.** The case now asserts #717's own state through `classifyCard`
(`queued`) beside `p3_queued` = 1 and `p3_ready` = 1, and its name says
`p3_ready` is #711.
`origin/main` was merged in at be348bde60 (a plain merge: no generated
artifact on either side; no rebase, no force-push).
## What changes
- `scripts/pm/topic-board.mjs` — every topic row and area row now
carries a grade by state cross-count, one column per cell named
`GRADE_STATE`: grades `p1` (p0 counted with p1), `p2`, `p3`, `un` (no
grade label, so the four add up to the row); states `ready`
(dispatchable: `pm:queue`, no assignee, no open `Blocked-by:` target, a
column of its own), `queued` (`pm:queue` with an assignee, or only
`pm:triage` / `pm:retriage`), `waitq` (`pm:queue` with an open
`Blocked-by:` target, shown as blocked), `doing`, `merge`, `blocked`,
`hold`, `decide`, `none`. A topic row also carries `closed_GRADE` and
`unlinked_GRADE`, and every row a `cards` list of its open p1/p2 cards
(number, title, grade, state, holding seat, what it waits on), p1 first,
then dispatchable first. Every older column keeps its meaning and is a
sum of cells (the self-test pins that on every fixture row).
- Readers are imported from `check-half-states.mjs`, none re-spelled:
`blockerTargetsFor` (body and comment channels) and
`blockerResolutionFromRow` (a PR target releases only when merged) for
`Blocked-by:`; `latestClaimComment`,
`markerMatches(CLAIM_COMMENT_MARKER)`, `claimSeatNumber` and
`directiveValues(body, 'Seat')` for the holding seat. card-pick.mjs
reads targets through the same two functions, so this is the same
reading, not a second one.
- Reads stay bounded: one comment-thread read per open p1/p2 card the
board counts, and one row read per distinct `Blocked-by:` target named
by a listed p1/p2 card or a `pm:queue` card. p3 and ungraded cards are
judged on their body alone (stated in the page footnote). An unreadable
target is held as open and named in the run output, never read as
closed; a failed thread read fails the run (exit 3, nothing written),
like the existing reads.
- The self-test gains the battery roster, floor and verdict handshake
from AGENTS.md "Writing a `--self-test`" (copied from
`check-agent-model-declared.mjs`): 12 batteries, 74 cases.
- `scripts/pm/topic-board/page.html` — a 全部 / p1 / p2 / p3 switch at the
top; it is a page filter no query names (`dash.setParams({grade})`), so
a pick redraws at once and fetches nothing, and it is remembered per
viewer in `localStorage` inside try/catch. Every number follows it: the
summary sentence (now 可派 / 在做 / 阻塞 / 等你裁决 / 搁置), group headers, row
columns (new 可派, 在做, 阻塞, 待你裁, 搁置, 其他, 无状态; the p1/p2/p3 columns hide
under a single grade), stacked bars, done/total/unlinked. Each topic row
and each area's not-in-a-topic row gets a button that opens its p1/p2
card list (none under p3). The footnote states each definition in one
sentence and gives the GitHub query for the dispatchable column. A
dataset built by the old script shows a rebuild notice instead of zeros
passing as numbers.
- `scripts/pm/topic-board/README.md` — a "The columns" section only.
## Reconciliation with the maintainer's query
Live run, read-only, `node scripts/pm/topic-board.mjs --repo=objectstack
--out=SCRATCH` at 2026-11-29 00:19 UTC, tree
`objectstack-ai/objectstack` @ 095e93946c: 428 open issues, 30 topics.
| Reading | Count | Cards |
|:--|--:|:--|
| `state:open label:pm:queue label:priority:p2,priority:p1
label:area:ai` (read 00:19 UTC) | 5 | #38153, #37898, #36558, #36206,
#34869 |
| Board, AI group, p1+p2 dispatchable | 6 | the same five, plus #38373 |
- All five cards the query returns are dispatchable on the board (no
assignee, no open `Blocked-by:` target): #38153 and #37898 sit in the AI
area's "not in a topic" row, #36558, #36206 and #34869 in topic #35154
(an AI topic).
- The difference is #38373: it is labelled `area:cloud`, but it is a
member of topic #38346, whose own area is `ai`. The board groups a
topic's cards under the topic's area, not the card's own `area:*` label,
so it counts in the AI group and the query does not see it. The footnote
now says this in so many words.
- The query's own answer moved during this session as seats claimed and
relabelled cards (4 at about 00:10; 5 at 00:19; at 00:25 still 5 but a
different set, #38153 out and #36079 in), so the table compares the two
readings taken in the same minute. The queue query also counts cards
that are assigned or carry an open `Blocked-by:` target, which the
dispatchable column leaves out; for area:ai none of the five did at this
run.
Request footprint of that run: 302 GET requests = 49 listing +
sub-issues (what the script made before) + 140 thread pages for 140
p1/p2 cards + 113 `Blocked-by:` target rows, 4 of them unreadable from
this session (targets in `objectstack-ai/cloud` and
`objectstack-ai/docs.objectos.ai`, HTTP 403 here; held as open and
named). Wall time 2m14s.
## Tests
topic-board self-test (offline)
`node scripts/pm/topic-board.mjs --self-test` → `topic-board self-test:
all passed (12 batteries, 74 cases)`, exit 0 (re-run at d3ab35aa55 in
round 2, same line). New batteries: every state cell (dispatchable apart
from queued, needs-user-decision outranking pm:queue, pm:awaiting-merge,
pm:triage, ungraded); Blocked-by (open target holds, closed issue and
merged PR release, closed-unmerged PR and unreadable target hold,
comment-only line holds for a p2 card, a p3 card's thread is never
read); p0 counted with p1; legacy columns as sums of cells on every row
of both fixtures; the card list (order, no p3, seat from the newest
claim's `Seat:` line, login fallback, waits); the thread and target
reads (17 threads, 6 targets read once each, a failed thread read fails
the run naming the card).
Local gates at d3ab35aa55 (round 2; 32 derived by
dispatch-gates --commands, all exit 0)
Run under `scripts/pm/os-verify-lock.sh`, slot issue-38400 (VERDICT
command-exit 0). `dispatch-gates --ran` with each exit code recorded:
「32 derived famil(ies) accounted for — 32 run, 0 NOT-MEASURED (a DERIVED
zero)」. The derived list is the same 32 as round 1. `overlap-check`
before the push: clean against origin/main 28c2fe88b7.
- `node scripts/check-closing-keyword-parity.mjs` exit 0
- `node scripts/check-closing-keyword-parity.mjs --self-test` exit 0
- `node scripts/check-comment-mask-corpus.mjs` exit 0
- `node scripts/check-declaration-mirrors.mjs` exit 0
- `node scripts/check-declaration-mirrors.mjs --self-test` exit 0
- `node scripts/check-self-test-wired.mjs` exit 0
- `node scripts/check-self-test-wired.mjs --self-test` exit 0
- `node scripts/check-self-test-workflow-commands.mjs` exit 0
- `node scripts/check-self-test-workflow-commands.mjs --self-test` exit
0
- `node scripts/check-whole-set-label-write.mjs` exit 0
- `node scripts/check-whole-set-label-write.mjs --self-test` exit 0
- `node scripts/ci/plan-test-core-shards.mjs --self-test` exit 0
- `node scripts/pm/bare-root-worklist.mjs --self-test` exit 0
- `pnpm check:adr-anchors` exit 0
- `pnpm check:agent-test-spelling` exit 0
- `pnpm check:bash32-floor` exit 0
- `pnpm check:ci-filter-parity` exit 0
- `pnpm check:cli-command-ids` exit 0
- `pnpm check:cross-package-test-inputs` exit 0
- `pnpm check:driver-memory-census` exit 0
- `pnpm check:entry-guard` exit 0
- `pnpm check:gitlink-declared` exit 0
- `pnpm check:nul-bytes` exit 0
- `pnpm check:parse-guard` exit 0
- `pnpm check:pm-board-snapshot` exit 0
- `pnpm check:pm-dispatch-gates` exit 0
- `pnpm check:pnpm-filter-targets` exit 0
- `pnpm check:pnpm-flag-spellings` exit 0
- `pnpm check:ratchet-remedy-authority` exit 0
- `pnpm check:refd-timer-probe` exit 0
- `pnpm check:scripts-symbol-anchors` exit 0
- `pnpm check:watch-hint-literal` exit 0
## Acceptance notes
- The cloud tab's data was not rebuilt (out of scope; this session
cannot read `objectstack-ai/cloud`). The `--repo=cloud` path runs the
same code; until the next cloud rebuild the cloud tab shows the rebuild
notice.
- Rendered locally against the live objectstack datasets with a stand-in
for the Data type's runtime (switch at p2, topic #35154 opened; round 2
adds the cloud tab, see above): the p2 sentence read 「15 个专题在推进。共有 125
张未完成的 p2 卡;可派 50 张,在做 23 张,阻塞 28 张,等你裁决 9 张,搁置 15 张。」 and 全部 read 「19
个专题在推进。共有 357 张未完成的卡,其中 p1 15 张;可派 226 张……」, no page errors. The real
Data runtime was not exercised: the first refresh with this template is
where `dash.setParams` for a name no query uses gets its live reading.
- The repo-tab write that L1 flagged moved to a class toggle in round 2
(see Round 2, item 2). Nothing is left noted-but-untouched.
## Verification
Read first (by risk): `scripts/pm/topic-board.mjs` `classifyCard` and
`countedCards` (the state precedence and which cards buy reads), then
`page.html` `view` and `makeBoard` (what each column sums under a pick).
Two-minute check: `node scripts/pm/topic-board.mjs --self-test` — expect
`topic-board self-test: all passed (12 batteries, 74 cases)` and exit 0.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn
---------
Co-authored-by: Claude
---
scripts/pm/topic-board.mjs | 467 +++++++++++++++++++++++++++++--
scripts/pm/topic-board/README.md | 13 +
scripts/pm/topic-board/page.html | 308 +++++++++++++++-----
3 files changed, 688 insertions(+), 100 deletions(-)
diff --git a/scripts/pm/topic-board.mjs b/scripts/pm/topic-board.mjs
index 5c1db98767f..52049c07b75 100644
--- a/scripts/pm/topic-board.mjs
+++ b/scripts/pm/topic-board.mjs
@@ -35,7 +35,64 @@
* reference read every sub-issue's sub-issues unconditionally; this reads
* only those whose `sub_issues_summary.total` is above zero (or absent),
* which gives the same members with fewer requests.
- * No comment pagination and no search loops.
+ * - ONE comment-thread read (every page) per OPEN p1·p2 card the board
+ * counts — a topic member or an area-table card, p0 included, topic cards
+ * left out. Nothing else reads a thread: p3 and ungraded cards are judged
+ * on their body alone (see "Grade × state" below);
+ * - ONE row read per distinct `Blocked-by:` target, cross-repo included,
+ * named by a card the board counts that needs it: a card whose state label
+ * is `pm:queue` (any grade), or a listed p1·p2 card (any state).
+ * No search loops. A run prints how many requests of each kind it made.
+ *
+ * ## Grade × state
+ *
+ * Every topic row and every area row carries, besides the columns the page has
+ * always read, the cross-count of the cards it counts by GRADE and by STATE,
+ * one column per cell, named `_`:
+ *
+ * grades (`GRADES`): `p1` (p0 counted with p1), `p2`, `p3`, `un` (no grade
+ * label — counted only so that the four grades add up to the row);
+ * states (`CELL_STATES`), one per card: the state label is the FIRST of
+ * `STATES` the card carries (the order below), then
+ * `decide` needs-user-decision or pm:awaiting-maintainer;
+ * `doing` pm:dispatched;
+ * `merge` pm:awaiting-merge;
+ * `ready` pm:queue, no assignee, and no open `Blocked-by:` target —
+ * the DISPATCHABLE column, kept apart from `queued`;
+ * `waitq` pm:queue with an open `Blocked-by:` target (shown as blocked);
+ * `queued` pm:queue with an assignee and no open target, or only
+ * pm:retriage / pm:triage;
+ * `blocked` pm:blocked;
+ * `hold` pm:on-hold;
+ * `none` none of those labels.
+ *
+ * A `Blocked-by:` target is read with `check-half-states.mjs`'s readers
+ * (`blockerTargetsFor` over the body and, for a p1·p2 card, its comments;
+ * `blockerResolutionFromRow` over the target's row): it is OPEN while the row
+ * reads open, while a PR target is closed unmerged, and while the row could not
+ * be read at all (held, ⛔ never read as closed — the run names each such
+ * target). A topic row also carries `closed_` and `unlinked_`, so
+ * its done count, its total and its unlinked count follow a grade too.
+ *
+ * The columns the page read before stay, with the meaning they had, and each is
+ * a sum of cells (pinned by the self-test): `open` = every cell; `p1`/`p2`/`p3` =
+ * that grade's cells; `doing`, `blocked`, `hold`, `decide`, `merge`, `none` =
+ * that state's cells; `queue` = `ready` + `waitq` + `queued`; on a topic row
+ * `closed` = the `closed_` sum and `unlinked` the `unlinked_` sum.
+ *
+ * ## The card list
+ *
+ * Every topic row and every area row carries `cards`: its open p1·p2 cards,
+ * one object each — `number`, `title`, `grade`, `state` (a `CELL_STATES` key),
+ * `seat` and `waits` — p1 first, then by `LIST_STATE_ORDER` (dispatchable
+ * first), then by number. `seat` is empty for an unassigned card; otherwise it
+ * is the `Seat:` value of the thread's newest `Claim:` (`latestClaimComment`,
+ * `claimSeatNumber`, `directiveValues`), else the assignee login(s). `waits`
+ * names 「待你裁」 for a `decide` card and every open `Blocked-by:` target.
+ * p3 cards are never listed. A topic's list is the cards its numbers count, so
+ * a parent's list includes its descendant topics' cards.
+ *
+ * Every reader is borrowed from `check-half-states.mjs`, ⛔ none re-spelled.
*
* ## What counts as a topic
*
@@ -67,7 +124,9 @@
* row, zero or not, in list order; an area outside the list follows, then
* 「(未定 area)」. `topic` is 0 by construction (topic cards are left out; the
* field is kept for the page's shape) and `topic_skipped` counts the cards left
- * out for being in a topic.
+ * out for being in a topic. An area row's numbers are therefore NOT a
+ * `label:area:X` query: a card in a topic counts under the topic (grouped by the
+ * topic's own area), whatever its own `area:*` says.
*
* The reference's `lanes` output is retired and not ported.
*
@@ -76,7 +135,14 @@
* 0 done (or the self-test passed).
* 1 the self-test failed.
* 2 usage.
- * 3 a GitHub read failed; nothing was written.
+ * 3 a GitHub read failed (the listing, a sub-issues read or a thread);
+ * nothing was written. An unreadable `Blocked-by:` target is not one: it
+ * is held as open and named in the run's output.
+ *
+ * ## Self-test
+ *
+ * Offline, with the battery floor and the verdict handshake AGENTS.md
+ * § "Writing a `--self-test`" requires (copied, never imported).
*/
import { mkdirSync, writeFileSync } from 'node:fs';
@@ -84,6 +150,15 @@ import { join } from 'node:path';
import process from 'node:process';
import { isEntrypoint } from '../invoked-as.mjs';
+import {
+ CLAIM_COMMENT_MARKER,
+ blockerResolutionFromRow,
+ blockerTargetsFor,
+ claimSeatNumber,
+ directiveValues,
+ latestClaimComment,
+ markerMatches,
+} from './check-half-states.mjs';
import { ghApi, readAllPages } from './gh-pages.mjs';
export const EXIT_OK = 0;
@@ -124,9 +199,29 @@ export const STATES = Object.freeze([
const NO_STATE = '无状态';
const PRIORITIES = Object.freeze(['priority:p0', 'priority:p1', 'priority:p2', 'priority:p3']);
+/** The grade buckets of the cross-count: p0 counts with p1; `un` = no grade label. */
+export const GRADES = Object.freeze(['p1', 'p2', 'p3', 'un']);
+/** The grades whose cards are listed one by one. */
+export const LISTED_GRADES = Object.freeze(['p1', 'p2']);
+/** The state cells of the cross-count — exactly one per card (header "Grade × state"). */
+export const CELL_STATES = Object.freeze(['ready', 'queued', 'waitq', 'doing', 'merge', 'blocked', 'hold', 'decide', 'none']);
+/** The card list's order inside one grade: dispatchable first. */
+export const LIST_STATE_ORDER = Object.freeze(['ready', 'doing', 'merge', 'queued', 'waitq', 'blocked', 'hold', 'decide', 'none']);
+/** What `waits` says for a card that waits on the maintainer. */
+export const WAITS_ON_MAINTAINER = '待你裁';
+const QUEUE_LABEL = 'pm:queue';
+
const labelsOf = (i) => (i.labels || []).map((l) => (typeof l === 'string' ? l : l.name));
const hasAny = (labels, set) => labels.some((l) => set.includes(l));
+/** The state label that decides a card's state: the first of `STATES` it carries, or null. */
+const stateLabelOf = (labels) => STATES.find(([k]) => labels.includes(k))?.[0] ?? null;
const stateOf = (labels) => STATES.find(([k]) => labels.includes(k))?.[1] ?? NO_STATE;
+/** The grade bucket of a card's labels. */
+export const gradeOf = (labels) => {
+ const p = PRIORITIES.find((x) => labels.includes(x))?.slice(-2) ?? null;
+ return p === 'p0' || p === 'p1' ? 'p1' : p ?? 'un';
+};
+const cellKey = (g, s) => `${g}_${s}`;
const priorityOf = (labels) => PRIORITIES.find((p) => labels.includes(p))?.slice(-2) ?? null;
const areasOf = (labels) => labels.filter((l) => l.startsWith('area:')).map((l) => l.slice(5));
const hasOpenSubs = (i) => (i.sub_issues_summary?.total ?? 0) > (i.sub_issues_summary?.completed ?? 0);
@@ -151,12 +246,80 @@ function unlinkedPattern(repo, n) {
}
/**
- * The pure core. `issues` = open issues (pull requests already dropped);
- * `subsOf(n)` = the sub-issues read of card n (an array). Returns
- * `{ epics, areas }` rows exactly as the page reads them.
+ * Which open cards the board counts, and which of them buy a thread read —
+ * the read path and the build share this one answer, so the reads are exactly
+ * the ones the build looks up. `childOf` = `topicIndex(...).childOf`.
+ *
+ * Counted: an open card in a topic (topics themselves left out), or an open
+ * card in no topic that the area table keeps (no `AREA_EXCLUDED` label). Of those, a p1·p2 card is LISTED (and its
+ * thread read); a card needs its `Blocked-by:` targets when it is listed or
+ * its state label is `pm:queue`.
*/
-export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
- const byNo = new Map(issues.map((i) => [i.number, i]));
+export function countedCards(issues, childOf) {
+ // Mirrors the build: a topic member that is itself a topic is never counted under a topic, and the area table
+ // keeps every open card in no topic that carries no `AREA_EXCLUDED` label (a title-only topic included).
+ const counted = issues.filter((i) => (childOf.has(i.number) ? !isTopic(i) : !hasAny(labelsOf(i), AREA_EXCLUDED)));
+ const listed = counted.filter((i) => LISTED_GRADES.includes(gradeOf(labelsOf(i))));
+ const needsTargets = counted.filter((i) => LISTED_GRADES.includes(gradeOf(labelsOf(i))) || stateLabelOf(labelsOf(i)) === QUEUE_LABEL);
+ return { counted, listed, needsTargets };
+}
+
+/**
+ * The seat holding a card: empty when it has no assignee; else the `Seat:`
+ * value of the newest `Claim:` on its thread (the shared claim predicate and
+ * seat reader, ⛔ never re-spelled); else the assignee login(s).
+ */
+export function seatOf(issue, threadRows) {
+ const logins = (issue.assignees || []).map((a) => a?.login).filter(Boolean);
+ if (!logins.length) return '';
+ const rows = Array.isArray(threadRows) ? threadRows : [];
+ const newest = latestClaimComment(rows);
+ if (newest) {
+ const body = rows.filter((r) => markerMatches(CLAIM_COMMENT_MARKER, String(r?.body ?? '')) && (r?.created_at ?? null) === newest.createdAt).at(-1)?.body ?? '';
+ const seat = claimSeatNumber(body) === null ? undefined : directiveValues(body, 'Seat')[0];
+ // The value's first token, with any code/bold decoration around it dropped (display only — the seat was read above).
+ const shown = seat ? seat.split(/\s+/)[0].replace(/^[`*]+|[`*]+$/g, '') : '';
+ if (shown) return shown;
+ }
+ return logins.join(', ');
+}
+
+/**
+ * One card's place on the board: `{ grade, state, open }` where `open` names
+ * its open `Blocked-by:` targets (`#N`, or `owner/repo#N` across repos; an
+ * unreadable one marked 「(读不到)」). `threadRows` (undefined when its thread
+ * was not read) adds the comment channel; `targetOf(key)` answers a target's
+ * resolution, undefined meaning not read — held as open.
+ */
+export function classifyCard(issue, { ownerRepo, threadRows, targetOf = () => undefined }) {
+ const L = labelsOf(issue);
+ const grade = gradeOf(L);
+ const label = stateLabelOf(L);
+ const bodies = Array.isArray(threadRows) ? threadRows.map((r) => String(r?.body ?? '')) : undefined;
+ const open = [];
+ for (const t of blockerTargetsFor(issue, bodies, ownerRepo)) {
+ const res = targetOf(t.key);
+ const name = t.local ? `#${t.number}` : t.key;
+ if (!res || res.state === 'unresolved') open.push(`${name}(读不到)`);
+ else if (res.state !== 'closed' || res.unmerged) open.push(name);
+ }
+ const unassigned = !(issue.assignees || []).some((a) => a?.login);
+ const state = label === 'needs-user-decision' || label === 'pm:awaiting-maintainer' ? 'decide'
+ : label === 'pm:dispatched' ? 'doing'
+ : label === 'pm:awaiting-merge' ? 'merge'
+ : label === QUEUE_LABEL ? (open.length ? 'waitq' : unassigned ? 'ready' : 'queued')
+ : label === 'pm:retriage' || label === 'pm:triage' ? 'queued'
+ : label === 'pm:blocked' ? 'blocked'
+ : label === 'pm:on-hold' ? 'hold'
+ : 'none';
+ return { grade, state, open };
+}
+
+/** Zeroed `_` cells. */
+const emptyCells = () => Object.fromEntries(GRADES.flatMap((g) => CELL_STATES.map((s) => [cellKey(g, s), 0])));
+
+/** The topic index: topics, each topic's direct / linked / unlinked members, and open card -> its topics. */
+export function topicIndex({ repo, issues, subsOf }) {
const topics = issues.filter(isTopic).map((i) => i.number).sort((a, b) => a - b);
const info = new Map();
const childOf = new Map(); // open card number -> topics it belongs to
@@ -180,6 +343,33 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
childOf.get(s.number).add(n);
}
}
+ return { topics, info, childOf };
+}
+
+/**
+ * The pure core. `issues` = open issues (pull requests already dropped);
+ * `subsOf(n)` = the sub-issues read of card n (an array); `threads` = card
+ * number -> its comment rows (the listed cards); `targets` = target key -> its
+ * resolution. Returns `{ epics, areas }` rows exactly as the page reads them.
+ */
+export function buildBoard({ repo, issues, subsOf, threads = new Map(), targets = new Map(), now = new Date() }) {
+ const byNo = new Map(issues.map((i) => [i.number, i]));
+ const { topics, info, childOf } = topicIndex({ repo, issues, subsOf });
+ const ownerRepo = `${OWNER}/${repo}`;
+ const placed = new Map();
+ const place = (card) => {
+ if (!placed.has(card.number)) {
+ const c = classifyCard(card, { ownerRepo, threadRows: threads.get(card.number), targetOf: (k) => targets.get(k) });
+ if (LISTED_GRADES.includes(c.grade)) {
+ const waits = [...(c.state === 'decide' ? [WAITS_ON_MAINTAINER] : []), ...c.open];
+ c.item = { number: card.number, title: card.title, grade: c.grade, state: c.state, seat: seatOf(card, threads.get(card.number)), waits };
+ }
+ placed.set(card.number, c);
+ }
+ return placed.get(card.number);
+ };
+ const listOrder = (a, b) => LISTED_GRADES.indexOf(a.grade) - LISTED_GRADES.indexOf(b.grade)
+ || LIST_STATE_ORDER.indexOf(a.state) - LIST_STATE_ORDER.indexOf(b.state) || a.number - b.number;
// Tree: direct holder first, else any containing topic; the smallest wins; no cycles.
const size = (n) => info.get(n).linked.size + info.get(n).unlinked.size;
@@ -218,12 +408,21 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
const pr = new Map();
const ar = new Map();
const st = new Map();
+ const cells = emptyCells();
+ const cards = [];
for (const s of allOpen) {
const L = labelsOf(s);
bump(pr, priorityOf(L));
for (const a of areasOf(L)) bump(ar, a);
bump(st, stateOf(L));
+ const c = place(s);
+ cells[cellKey(c.grade, c.state)] += 1;
+ if (c.item) cards.push(c.item);
}
+ const closedBy = Object.fromEntries(GRADES.map((g) => [`closed_${g}`, 0]));
+ for (const s of d.values()) if (s.state !== 'open') closedBy[`closed_${gradeOf(labelsOf(s))}`] += 1;
+ const unlinkedBy = Object.fromEntries(GRADES.map((g) => [`unlinked_${g}`, 0]));
+ for (const [k, s] of info.get(n).unlinked) if (!info.has(k)) unlinkedBy[`unlinked_${gradeOf(labelsOf(s))}`] += 1;
const L = labelsOf(i);
const state = L.includes('pm:on-hold') || (i.title || '').includes('暂停') ? '暂停'
: total === 0 ? '未拆卡'
@@ -256,12 +455,17 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
// most common first; ties keep first-seen order (a stable sort over insertion order)
areas: [...ar].sort((a, b) => b[1] - a[1]).slice(0, 4).map(([a, c]) => `${a} ${c}`).join(' · '),
updated: String(i.updated_at || '').slice(0, 10),
+ ...cells,
+ ...closedBy,
+ ...unlinkedBy,
+ cards: cards.sort(listOrder),
});
}
// Area table: open cards in no topic.
const list = AREAS[repo];
const counts = new Map(list.map((a) => [a, new Map()]));
+ const areaCells = new Map(list.map((a) => [a, { cells: emptyCells(), cards: [] }]));
let topicSkipped = 0;
for (const i of issues) {
const L = labelsOf(i);
@@ -270,12 +474,17 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
const p = priorityOf(L);
const s = stateOf(L);
const al = areasOf(L);
+ const c = place(i);
for (const a of al.length ? al : [UNSET_AREA]) {
if (!counts.has(a)) counts.set(a, new Map());
+ if (!areaCells.has(a)) areaCells.set(a, { cells: emptyCells(), cards: [] });
const r = counts.get(a);
bump(r, s); bump(r, 'open');
if (p === 'p0' || p === 'p1') bump(r, 'p1');
else if (p) bump(r, p);
+ const x = areaCells.get(a);
+ x.cells[cellKey(c.grade, c.state)] += 1;
+ if (c.item) x.cards.push(c.item);
}
}
const rank = (a) => (a === UNSET_AREA ? 2 : list.includes(a) ? 0 : 1);
@@ -287,8 +496,10 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
const g = (k) => c.get(k) || 0;
return {
area: a, open: g('open'), p1: g('p1'), p2: g('p2'), p3: g('p3'), topic: 0, nontopic: g('open'),
- doing: g('在做'), queue: g('队列'), blocked: g('阻塞'), hold: g('搁置'), decide: g('待裁决'), none: g(NO_STATE),
+ doing: g('在做'), queue: g('队列'), blocked: g('阻塞'), hold: g('搁置'), decide: g('待裁决'), merge: g('待合并'), none: g(NO_STATE),
asof, topic_skipped: topicSkipped,
+ ...areaCells.get(a).cells,
+ cards: [...areaCells.get(a).cards].sort(listOrder),
};
});
return { epics, areas };
@@ -296,8 +507,11 @@ export function buildBoard({ repo, issues, subsOf, now = new Date() }) {
/**
* Every read the board needs, through `get` (default: `gh api`). Returns
- * `{ ok: true, issues, subs, requests }` or `{ ok: false, error, requests }`.
- * Sub-issue reads are memoised: a card under two topics is read once.
+ * `{ ok: true, issues, subs, threads, targets, unread, requests, kinds }` or
+ * `{ ok: false, error, requests }`. Sub-issue reads are memoised: a card under
+ * two topics is read once; a target named by several cards is read once.
+ * `kinds` splits `requests` into the listing + sub-issues reads (`list`), the
+ * thread pages (`threads`) and the target rows (`targets`).
*/
export function readBoard(repo, { get = ghApi } = {}) {
let requests = 0;
@@ -320,7 +534,36 @@ export function readBoard(repo, { get = ghApi } = {}) {
// Walk the same reads `buildBoard` will make, so a failure surfaces before anything is built or written.
for (const t of issues.filter(isTopic)) for (const s of subsOf(t.number)) if (mayHaveSubs(s)) subsOf(s.number);
if (failure) return { ok: false, error: failure, requests };
- return { ok: true, issues, subs, requests };
+ const kinds = { threads: 0, targets: 0 };
+
+ // The listed (p1·p2) cards' threads, then every Blocked-by target a counted card needs — the build's own sets.
+ const { childOf } = topicIndex({ repo, issues, subsOf });
+ const { listed, needsTargets } = countedCards(issues, childOf);
+ const threads = new Map();
+ for (const i of listed) {
+ const before = requests;
+ const r = readAllPages(`${R}/issues/${i.number}/comments`, { get: counted });
+ kinds.threads += requests - before;
+ if (!r.ok) return { ok: false, error: `#${i.number}'s thread: ${r.error}`, requests };
+ threads.set(i.number, r.value);
+ }
+ const ownerRepo = `${OWNER}/${repo}`;
+ const targets = new Map();
+ const unread = [];
+ for (const i of needsTargets) {
+ const rows = threads.get(i.number);
+ for (const t of blockerTargetsFor(i, rows ? rows.map((c) => String(c?.body ?? '')) : undefined, ownerRepo)) {
+ if (targets.has(t.key)) continue;
+ kinds.targets += 1;
+ const r = counted(`repos/${t.repo}/issues/${t.number}`);
+ if (r.ok) targets.set(t.key, blockerResolutionFromRow(t, r.value));
+ else {
+ targets.set(t.key, { ...t, state: 'unresolved', detail: r.error });
+ unread.push(`${t.key} (named by #${i.number}): ${String(r.error).split('\n')[0]}`);
+ }
+ }
+ }
+ return { ok: true, issues, subs, threads, targets, unread, requests, kinds: { ...kinds, list: requests - kinds.threads - kinds.targets } };
}
/** One row per line, so two builds diff by row. */
@@ -346,7 +589,7 @@ function run(o) {
console.error(`topic-board: a GitHub read failed after ${read.requests} request(s); nothing written.\n ${read.error}`);
return EXIT_READ;
}
- const { epics, areas } = buildBoard({ repo: o.repo, issues: read.issues, subsOf: (n) => read.subs.get(n) || [] });
+ const { epics, areas } = buildBoard({ repo: o.repo, issues: read.issues, subsOf: (n) => read.subs.get(n) || [], threads: read.threads, targets: read.targets });
const suf = SUFFIX[o.repo];
mkdirSync(o.out, { recursive: true });
const ef = join(o.out, `epics${suf}.json`);
@@ -354,8 +597,10 @@ function run(o) {
writeFileSync(ef, toJson(epics));
writeFileSync(af, toJson(areas));
for (const r of epics) console.log(`${' '.repeat(r.depth)}#${r.epic} ${r.state} open ${r.open}/${r.total} p1 ${r.p1} unlinked ${r.unlinked} · ${r.title.slice(0, 50)}`);
- for (const r of areas) console.log(`AREA ${r.area}: open ${r.open} p1 ${r.p1} doing ${r.doing} queue ${r.queue} none ${r.none}`);
- console.log(`topic-board: ${o.repo} · ${read.issues.length} open issues · ${epics.length} topics · ${areas.length} area rows · ${read.requests} GET request(s)\n wrote ${ef}\n wrote ${af}`);
+ for (const r of areas) console.log(`AREA ${r.area}: open ${r.open} p1 ${r.p1} doing ${r.doing} queue ${r.queue} none ${r.none} · p1+p2 dispatchable ${r.p1_ready + r.p2_ready}`);
+ for (const u of read.unread) console.log(`UNREAD Blocked-by target, held as open: ${u}`);
+ const k = read.kinds;
+ console.log(`topic-board: ${o.repo} · ${read.issues.length} open issues · ${epics.length} topics · ${areas.length} area rows · ${read.requests} GET request(s) = ${k.list} listing + sub-issues · ${k.threads} thread page(s) for ${read.threads.size} p1·p2 card(s) · ${k.targets} Blocked-by target row(s), ${read.unread.length} unreadable\n wrote ${ef}\n wrote ${af}`);
return EXIT_OK;
}
@@ -365,12 +610,41 @@ function run(o) {
const lab = (...names) => names.map((name) => ({ name }));
const card = (number, title, labels = [], extra = {}) => ({ number, title, labels: lab(...labels), state: 'open', body: '', updated_at: '2026-11-23T00:00:00Z', ...extra });
+// The battery roster and floor AGENTS.md § "Writing a `--self-test`" requires, copied from
+// `scripts/check-agent-model-declared.mjs` (never imported): every case registers against the battery
+// opened last; a declared battery below its pin, a case under an undeclared battery, or a roster below
+// `SELF_TEST_BATTERY_FLOOR` fails the run. The counts are floors, never equalities.
+const SELF_TEST_BATTERIES = Object.freeze({
+ 'topic detection': 8,
+ 'tree: parent choice, depth, cycles': 6,
+ 'rollup: topic columns': 8,
+ 'area table': 7,
+ 'read path: pacing and failure': 4,
+ 'arguments and output shape': 4,
+ 'grade × state: every state, dispatchable apart from queued': 12,
+ 'Blocked-by: open and unreadable targets hold, closed issue and merged PR release, comments read for p1·p2 only': 7,
+ 'p0 counts with p1': 2,
+ 'legacy columns stay derivable from the cells': 2,
+ 'card list: p1·p2 only, ordered, seat and waits': 9,
+ 'read path: thread and target reads': 5,
+});
+const SELF_TEST_BATTERY_FLOOR = 12;
+
+// Set as the self-test's last statement, after its success line; the dispatch refuses when it is unset.
+let selfTestReachedVerdict = false;
+
export function selfTest() {
let failed = 0;
- const t = (name, ok, detail = '') => { if (!ok) { failed++; console.error(` ✗ ${name}${detail ? `\n ${detail}` : ''}`); } else console.log(` ✓ ${name}`); };
+ let current = null;
+ const batterySeen = new Map();
+ const battery = (name) => { current = name; console.log(`· ${name}`); };
+ const t = (name, ok, detail = '') => {
+ batterySeen.set(current, (batterySeen.get(current) ?? 0) + 1);
+ if (!ok) { failed++; console.error(` ✗ ${name}${detail ? `\n ${detail}` : ''}`); } else console.log(` ✓ ${name}`);
+ };
const eq = (name, got, want) => t(name, JSON.stringify(got) === JSON.stringify(want), `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
- // Topic detection.
+ battery('topic detection');
eq('pm:epic is a topic', isTopic(card(1, 'x', ['pm:epic'])), true);
eq('[Epic] title is a topic', isTopic(card(1, '[Epic] x')), true);
eq('[专题 …] title is a topic', isTopic(card(1, '[专题 AI] x')), true);
@@ -412,9 +686,8 @@ export function selfTest() {
};
const { epics, areas } = buildBoard({ repo: 'objectstack', issues, subsOf: (n) => SUBS[n] || [], now: new Date('2026-11-23T15:00:00Z') });
const E = Object.fromEntries(epics.map((r) => [r.epic, r]));
- eq('topic set', epics.map((r) => r.epic), [100, 200, 300, 400, 500, 600]);
- // Parent choice.
+ battery('tree: parent choice, depth, cycles');
eq('200 under 100 (direct holder)', E[200].parent, 100);
eq('300 under 200: the direct holder wins over 100, which also contains it', E[300].parent, 200);
eq('depth follows the chain', [E[100].depth, E[200].depth, E[300].depth], [0, 1, 2]);
@@ -423,16 +696,18 @@ export function selfTest() {
eq('a lone topic has no parent', E[400].parent, null);
// Rollup: 300 holds 21; 200 holds 300's 21 + 12 + closed 13 + unlinked 41; 100 holds 11 + all of 200's.
+ battery('rollup: topic columns');
+ eq('topic set', epics.map((r) => r.epic), [100, 200, 300, 400, 500, 600]);
eq('leaf topic counts', [E[300].total, E[300].open, E[300].p1, E[300].decide], [1, 1, 1, 1]);
eq('middle topic rolls up its child and its unlinked card', [E[200].total, E[200].open, E[200].closed, E[200].unlinked], [4, 3, 1, 1]);
eq('top topic rolls up the whole tree', [E[100].total, E[100].open, E[100].p1, E[100].p2, E[100].doing], [5, 4, 2, 1, 1]);
eq('topic cards are never members', E[100].total, 5);
eq('area mix, most common first', E[100].areas, 'ai 2 · data 1 · ux 1');
- eq('states', [E[100].state, E[400].state], ['进行中', '暂停']);
- eq('own area', [E[100].area, E[400].area], ['ai', null]);
+ eq('states and own area', [E[100].state, E[400].state, E[100].area, E[400].area], ['进行中', '暂停', 'ai', null]);
eq('#2000 and #200号 in prose do not match #200', E[200].unlinked, 1);
// Area table: 11, 12, 21, 41 sit in topics and are left out; 31, 42, 51, 52 count; 53 (pm:seat) and topic cards skip.
+ battery('area table');
const A = Object.fromEntries(areas.map((r) => [r.area, r]));
eq('area rows: every listed area in order, then 未定', areas.map((r) => r.area), ['ai', 'build', 'data', 'workflow', 'ux', 'package', 'fleet', 'cloud', UNSET_AREA]);
eq('topic cards left out of the area table', [A.ai.open, A.data.open], [0, 1]);
@@ -442,7 +717,7 @@ export function selfTest() {
eq('a pm:seat card is skipped', A.fleet.open, 0);
eq('asof stamp', A.ai.asof, '2026-11-23 15:00 UTC');
- // Read path: pacing and failure.
+ battery('read path: pacing and failure');
const pages = {
'repos/objectstack-ai/cloud/issues?state=open&per_page=100&page=1': [
card(1, '[Epic] one', ['pm:epic']), card(2, 'child', ['area:ops']), { number: 3, title: 'a PR', labels: [], pull_request: {} },
@@ -454,24 +729,164 @@ export function selfTest() {
const get = (p) => { seen.push(p); return Object.hasOwn(pages, p) ? { ok: true, value: pages[p] } : { ok: false, error: `404 ${p}` }; };
const read = readBoard('cloud', { get });
eq('read: pull requests dropped', read.ok && read.issues.map((i) => i.number), [1, 2]);
- eq('read: one list + one sub-issues read per topic + one per sub-issue that has subs', read.requests, 3);
+ eq('read: one list + one sub-issues read per topic + one per sub-issue that has subs (no p1·p2 card, no thread)', read.requests, 3);
eq('read: a sub-issue without subs is not read', seen.some((p) => p.includes('/issues/2/sub_issues')), false);
const bad = readBoard('cloud', { get: (p) => (p.includes('/issues/1/sub_issues') ? { ok: false, error: 'HTTP 502' } : get(p)) });
eq('read: a failed sub-issues read fails the whole read', [bad.ok, bad.error], [false, 'HTTP 502']);
- // Arguments and output shape.
+ battery('arguments and output shape');
eq('args: default repo needs --out', parseArgs([]).error, '--out=DIR is required');
eq('args: unknown repo refused', Boolean(parseArgs(['--repo=hotcrm', '--out=x']).error), true);
eq('args: cloud', parseArgs(['--repo=cloud', '--out=d']), { repo: 'cloud', out: 'd', selfTest: false });
eq('json: one row per line, parses back', JSON.parse(toJson(areas)).length, areas.length);
+ // ---- The grade × state fixture, read end to end through `readBoard` with an injected `get`. ----
+ // Topic 700 holds 701–718 (open) and 719 (closed); 801–803 sit in no topic (area:build).
+ const R = 'repos/objectstack-ai/objectstack';
+ const who = (login) => ({ assignees: [{ login }] });
+ const gIssues = [
+ card(700, '[Epic] grades', ['pm:epic', 'area:ai']),
+ card(701, 'p1 queued, free', ['priority:p1', 'pm:queue']),
+ card(702, 'p0 queued, open blocker', ['priority:p0', 'pm:queue'], { body: 'Blocked-by: #790' }),
+ card(703, 'p2 queued, closed issue blocker', ['priority:p2', 'pm:queue'], { body: 'Blocked-by: #791' }),
+ card(704, 'p2 queued, assigned', ['priority:p2', 'pm:queue'], who('os-a')),
+ card(705, 'p2 dispatched', ['priority:p2', 'pm:dispatched'], who('os-b')),
+ card(706, 'p2 blocked', ['priority:p2', 'pm:blocked']),
+ card(707, 'p2 on hold', ['priority:p2', 'pm:on-hold']),
+ card(708, 'p1 decision + queue', ['priority:p1', 'needs-user-decision', 'pm:queue']),
+ card(709, 'p2 awaiting maintainer', ['priority:p2', 'pm:awaiting-maintainer']),
+ card(710, 'p2 no state', ['priority:p2']),
+ card(711, 'p3 queued, blocker only in a comment', ['priority:p3', 'pm:queue']),
+ card(712, 'p2 queued, blocker only in a comment', ['priority:p2', 'pm:queue']),
+ card(713, 'p2 queued, merged PR blocker', ['priority:p2', 'pm:queue'], { body: 'Blocked-by: #792' }),
+ card(714, 'p2 queued, unmerged PR blocker', ['priority:p2', 'pm:queue'], { body: 'Blocked-by: #793' }),
+ card(715, 'p2 queued, unreadable blocker', ['priority:p2', 'pm:queue'], { body: 'Blocked-by: #794' }),
+ card(716, 'p2 awaiting merge', ['priority:p2', 'pm:awaiting-merge']),
+ card(717, 'p3 triage', ['priority:p3', 'pm:triage']),
+ card(718, 'ungraded queued', ['pm:queue']),
+ card(801, 'area p2 queued', ['area:build', 'priority:p2', 'pm:queue']),
+ card(802, 'area p3 queued', ['area:build', 'priority:p3', 'pm:queue']),
+ card(803, 'area p1 blocked cross-repo', ['area:build', 'priority:p1', 'pm:blocked'], { body: 'Blocked-by: objectstack-ai/cloud#5' }),
+ ];
+ const noSubs = { sub_issues_summary: { total: 0, completed: 0 } };
+ const gPages = {
+ [`${R}/issues?state=open&per_page=100&page=1`]: gIssues,
+ [`${R}/issues/700/sub_issues?per_page=100&page=1`]: [
+ ...gIssues.filter((i) => i.number > 700 && i.number < 800).map((i) => ({ ...i, ...noSubs })),
+ { ...card(719, 'p3 done', ['priority:p3']), state: 'closed', ...noSubs },
+ ],
+ [`${R}/issues/790`]: { state: 'open' },
+ [`${R}/issues/791`]: { state: 'closed', closed_at: '2026-11-20T00:00:00Z' },
+ [`${R}/issues/792`]: { state: 'closed', pull_request: { merged_at: '2026-11-20T00:00:00Z' } },
+ [`${R}/issues/793`]: { state: 'closed', pull_request: { merged_at: null } },
+ 'repos/objectstack-ai/cloud/issues/5': { state: 'open' },
+ };
+ const claim = (seatLine, at) => ({ body: `repo:objectstack#3 · os-a · session_0123456789\nClaim: round 1\n${seatLine}`, created_at: at });
+ const THREADS = {
+ 704: [claim('Seat: repo:objectstack#9', '2026-11-20T00:00:00Z'), claim('Seat: `repo:objectstack#3`', '2026-11-21T00:00:00Z')],
+ 705: [claim('Branch: claude/issue-705-x', '2026-11-21T00:00:00Z')],
+ 711: [{ body: 'Blocked-by: #790', created_at: '2026-11-21T00:00:00Z' }],
+ 712: [{ body: 'Blocked-by: #790', created_at: '2026-11-21T00:00:00Z' }],
+ };
+ for (const i of gIssues) gPages[`${R}/issues/${i.number}/comments?per_page=100&page=1`] = THREADS[i.number] ?? [];
+ const gSeen = [];
+ const gGet = (p) => { gSeen.push(p); return Object.hasOwn(gPages, p) ? { ok: true, value: gPages[p] } : { ok: false, error: `HTTP 404 ${p}` }; };
+ const gRead = readBoard('objectstack', { get: gGet });
+ const g = gRead.ok
+ ? buildBoard({ repo: 'objectstack', issues: gRead.issues, subsOf: (n) => gRead.subs.get(n) || [], threads: gRead.threads, targets: gRead.targets, now: new Date('2026-11-23T15:00:00Z') })
+ : { epics: [], areas: [] };
+ const T = g.epics.find((r) => r.epic === 700) ?? {};
+ const B = g.areas.find((r) => r.area === 'build') ?? {};
+ const cardOf = (rows, n) => (rows.cards ?? []).find((c) => c.number === n);
+
+ battery('grade × state: every state, dispatchable apart from queued');
+ eq('free queued p1 card is dispatchable', T.p1_ready, 1);
+ eq('assigned queued card is queued, not dispatchable', [T.p2_queued, cardOf(T, 704)?.state], [1, 'queued']);
+ eq('pm:dispatched is in flight', T.p2_doing, 1);
+ eq('pm:blocked is blocked', T.p2_blocked, 1);
+ eq('pm:on-hold is on hold', T.p2_hold, 1);
+ eq('needs-user-decision outranks pm:queue: waiting on the maintainer', [T.p1_decide, cardOf(T, 708)?.state], [1, 'decide']);
+ eq('pm:awaiting-maintainer waits on the maintainer', T.p2_decide, 1);
+ eq('no state label is no state', T.p2_none, 1);
+ eq('pm:awaiting-merge keeps its own cell', T.p2_merge, 1);
+ eq('pm:triage is queued, never dispatchable (#717 alone in p3_queued; p3_ready is #711)', [classifyCard(gIssues.find((i) => i.number === 717), { ownerRepo: 'objectstack-ai/objectstack' }).state, T.p3_queued, T.p3_ready], ['queued', 1, 1]);
+ eq('an ungraded card lands in un', T.un_ready, 1);
+ eq('every open card is in exactly one cell', GRADES.flatMap((gr) => CELL_STATES.map((st) => T[cellKey(gr, st)] ?? 0)).reduce((a, b) => a + b, 0), 18);
+
+ battery('Blocked-by: open and unreadable targets hold, closed issue and merged PR release, comments read for p1·p2 only');
+ eq('⭐ a queued card with an open Blocked-by: target is blocked and NOT dispatchable', [cardOf(T, 702)?.state, T.p1_waitq, T.p1_ready], ['waitq', 1, 1]);
+ eq('a closed issue target releases', cardOf(T, 703)?.state, 'ready');
+ eq('a merged PR target releases', cardOf(T, 713)?.state, 'ready');
+ eq('a closed-unmerged PR target holds', [cardOf(T, 714)?.state, cardOf(T, 714)?.waits], ['waitq', ['#793']]);
+ eq('an unreadable target holds, named', [cardOf(T, 715)?.state, cardOf(T, 715)?.waits, gRead.unread?.length], ['waitq', ['#794(读不到)'], 1]);
+ eq('a p2 card\'s comment-only Blocked-by: line holds', cardOf(T, 712)?.state, 'waitq');
+ eq('a p3 card is judged on its body: its thread is never read', [T.p3_ready, gSeen.includes(`${R}/issues/711/comments?per_page=100&page=1`)], [1, false]);
+
+ battery('p0 counts with p1');
+ eq('p0 card lands in the p1 cells and the p1 list', [cardOf(T, 702)?.grade, T.p1], ['p1', 3]);
+ eq('the legacy p1 column holds p0 too (first fixture)', E[100].p1, 2);
+
+ battery('legacy columns stay derivable from the cells');
+ const sum = (r, gs, ss) => gs.reduce((a, gr) => a + ss.reduce((b, st) => b + (r[cellKey(gr, st)] ?? 0), 0), 0);
+ const drift = (r, topicRow) => {
+ const out = [];
+ const want = {
+ open: sum(r, GRADES, CELL_STATES), p1: sum(r, ['p1'], CELL_STATES), p2: sum(r, ['p2'], CELL_STATES), p3: sum(r, ['p3'], CELL_STATES),
+ doing: sum(r, GRADES, ['doing']), queue: sum(r, GRADES, ['ready', 'waitq', 'queued']), blocked: sum(r, GRADES, ['blocked']),
+ hold: sum(r, GRADES, ['hold']), decide: sum(r, GRADES, ['decide']), merge: sum(r, GRADES, ['merge']), none: sum(r, GRADES, ['none']),
+ ...(topicRow ? { closed: GRADES.reduce((a, gr) => a + r[`closed_${gr}`], 0), unlinked: GRADES.reduce((a, gr) => a + r[`unlinked_${gr}`], 0) } : {}),
+ };
+ for (const [k, v] of Object.entries(want)) if (r[k] !== v) out.push(`${topicRow ? `#${r.epic}` : r.area}.${k} ${r[k]} ≠ ${v}`);
+ return out;
+ };
+ eq('every row of both fixtures: open, p1–p3, every state, queue, closed, unlinked are sums of cells', [...epics, ...g.epics].flatMap((r) => drift(r, true)).concat([...areas, ...g.areas].flatMap((r) => drift(r, false))), []);
+ eq('closed members follow their grade', [T.closed_p3, T.closed, T.total], [1, 1, 19]);
+
+ battery('card list: p1·p2 only, ordered, seat and waits');
+ eq('⭐ topic list: p1 first, then dispatchable first, p3 and ungraded never listed', (T.cards ?? []).map((c) => c.number), [701, 702, 708, 703, 713, 705, 716, 704, 712, 714, 715, 706, 707, 709, 710]);
+ eq('a card carries number, title, grade, state, seat, waits', Object.keys(cardOf(T, 701) ?? {}), ['number', 'title', 'grade', 'state', 'seat', 'waits']);
+ eq('seat: the NEWEST claim\'s Seat: line', cardOf(T, 704)?.seat, 'repo:objectstack#3');
+ eq('seat: a claim with no Seat: line falls back to the assignee login', cardOf(T, 705)?.seat, 'os-b');
+ eq('seat: an unassigned card is held by nobody', cardOf(T, 701)?.seat, '');
+ eq('seat: a Seat: line that names no seat falls back to the login', seatOf(card(1, 'x', [], who('os-z')), [claim('Seat: tbd', '2026-11-21T00:00:00Z')]), 'os-z');
+ eq('waits: 待你裁 for a card waiting on the maintainer, the open target for a blocked one', [cardOf(T, 708)?.waits, cardOf(T, 702)?.waits, cardOf(T, 701)?.waits], [[WAITS_ON_MAINTAINER], ['#790'], []]);
+ eq('area list: the not-in-a-topic cards, p1 first, p3 left out', (B.cards ?? []).map((c) => c.number), [803, 801]);
+ eq('area list: a cross-repo target is named with its repo', cardOf(B, 803)?.waits, ['objectstack-ai/cloud#5']);
+
+ battery('read path: thread and target reads');
+ eq('read: the fixture reads clean', gRead.ok, true);
+ eq('read: one thread per listed p1·p2 card (15 in the topic, 2 in the area)', [gRead.threads?.size, gRead.kinds?.threads], [17, 17]);
+ eq('read: one row per distinct target (#790 named twice, read once)', [gRead.kinds?.targets, gSeen.filter((p) => p === `${R}/issues/790`).length], [6, 1]);
+ eq('read: the total adds up', [gRead.requests, gRead.kinds?.list + gRead.kinds?.threads + gRead.kinds?.targets], [25, 25]);
+ const gBad = readBoard('objectstack', { get: (p) => (p.includes('/issues/712/comments') ? { ok: false, error: 'HTTP 502' } : gGet(p)) });
+ eq('read: a failed thread read fails the whole read, the card named', [gBad.ok, gBad.error], [false, '#712\'s thread: HTTP 502']);
+
+ // ---- The floor: every declared battery ran, at least its pinned number of cases. ----
+ const floorFailure = (message) => { failed++; console.error(` ✗ self-test floor: ${message}`); };
+ const declared = Object.keys(SELF_TEST_BATTERIES);
+ if (declared.length < SELF_TEST_BATTERY_FLOOR) floorFailure(`SELF_TEST_BATTERIES declares ${declared.length} batteries, below the pinned ${SELF_TEST_BATTERY_FLOOR} — a battery deleted from the roster takes its own floor with it.`);
+ for (const [name, count] of batterySeen) if (!declared.includes(name)) floorFailure(`battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES.`);
+ for (const name of declared) {
+ const count = batterySeen.get(name) ?? 0;
+ if (count < SELF_TEST_BATTERIES[name]) floorFailure(count === 0 ? `battery "${name}" DID NOT RUN — 0 cases, ${SELF_TEST_BATTERIES[name]} pinned.` : `battery "${name}" registered ${count} case(s), below its floor of ${SELF_TEST_BATTERIES[name]} — cases that used to run no longer do.`);
+ }
+
if (failed) { console.error(`topic-board self-test: ${failed} FAILED`); return EXIT_SELF_TEST; }
- console.log('topic-board self-test: all passed');
+ console.log(`topic-board self-test: all passed (${declared.length} batteries, ${[...batterySeen.values()].reduce((a, b) => a + b, 0)} cases)`);
+ selfTestReachedVerdict = true;
return EXIT_OK;
}
if (isEntrypoint(import.meta.url)) {
const o = parseArgs(process.argv.slice(2));
if (o.error) { console.error(`topic-board: ${o.error}\n usage: node scripts/pm/topic-board.mjs --repo=objectstack|cloud --out=DIR | --self-test`); process.exit(EXIT_USAGE); }
- process.exit(o.selfTest ? selfTest() : run(o));
+ if (o.selfTest) {
+ const code = selfTest();
+ if (code === EXIT_OK && !selfTestReachedVerdict) {
+ console.error('topic-board self-test: selfTest() returned without reaching its verdict — refusing to report it as passed.');
+ process.exit(EXIT_SELF_TEST);
+ }
+ process.exit(code);
+ }
+ process.exit(run(o));
}
diff --git a/scripts/pm/topic-board/README.md b/scripts/pm/topic-board/README.md
index cf1da8e00ee..44208da30f0 100644
--- a/scripts/pm/topic-board/README.md
+++ b/scripts/pm/topic-board/README.md
@@ -10,6 +10,19 @@ reads the board back.
| [`../topic-board.mjs`](../topic-board.mjs) | Builds the datasets. Read-only GitHub reads; header doc says what counts as a topic, a member, a parent, and the area table. |
| [`page.html`](page.html) | The page template: a Data-type artifact page reading the datasets `epics`, `areas`, `epics_cloud`, `areas_cloud`. |
+## The columns
+
+Every topic row and area row carries one `