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/178] =?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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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/178] 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 `_` count per cell: grades `p1` (p0 included), `p2`, `p3` +and `un` (no grade label); states `ready` (dispatchable: `pm:queue`, no assignee, no open `Blocked-by:` target), +`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_` and `unlinked_`, and every row a `cards` list of its open p1·p2 cards (number, title, +grade, state, holding seat, what it waits on). The older columns (`open`, `p1`–`p3`, `doing`, `queue`, `blocked`, +`hold`, `decide`, `merge`, `none`, `closed`, `unlinked`) keep their meaning and are sums of the cells; the script's +header doc is the authority on each definition and on the reads they cost. The page's 全部 / p1 / p2 / p3 switch +picks which grades every number sums, and its footnote gives each definition and the GitHub query for the +dispatchable column. A dataset built by an older script has no cells: the page says so and asks for a rebuild. + ## Duty and cadence The triage seat refreshes the board every 3 hours, on the patrol fires at UTC hours 0, 3, 6, 9, 12, diff --git a/scripts/pm/topic-board/page.html b/scripts/pm/topic-board/page.html index 4bf3d581fad..8d507e14d6f 100644 --- a/scripts/pm/topic-board/page.html +++ b/scripts/pm/topic-board/page.html @@ -47,34 +47,57 @@ .eb-tabs button { all: unset; cursor: pointer; padding: 4px 12px; border-radius: 999px; border: 1px solid var(--color-border-line); font-size: var(--cds-font-size-caption); color: var(--color-fg-muted); } .eb-tabs button[aria-selected="true"] { color: var(--color-fg); border-color: currentColor; font-weight: var(--cds-font-weight-medium); } .eb-tabs button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } - .eb[data-repo="objectstack"] [data-repo-only="cloud"], .eb[data-repo="cloud"] [data-repo-only="objectstack"] { display: none; } + .eb:not(.eb-on-cloud) [data-repo-only="cloud"], .eb.eb-on-cloud [data-repo-only="objectstack"] { display: none; } + .eb-tabs button[aria-pressed="true"] { color: var(--color-fg); border-color: currentColor; font-weight: var(--cds-font-weight-medium); } + .eb.eb-graded .eb-gcol { display: none; } + .eb-cbtn { all: unset; cursor: pointer; display: inline-block; margin-top: 4px; font-size: var(--cds-font-size-caption); color: var(--color-fg-muted); border: 1px solid var(--color-border-line); border-radius: 999px; padding: 0 8px; white-space: nowrap; } + .eb-cbtn[aria-expanded="true"] { color: var(--color-fg); border-color: currentColor; } + .eb-cbtn:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } + tr.eb-cards > td { background: color-mix(in srgb, var(--color-panel) 96%, var(--color-fg) 4%); padding-top: 0; } + .eb-clist { width: 100%; border-collapse: collapse; font-size: var(--cds-font-size-caption); } + .eb-clist td { padding: 3px var(--cds-pad-sm); border-bottom: 1px dashed var(--color-border-line); vertical-align: top; } + .eb-clist tr:last-child td { border-bottom: 0; } + .eb-clist td.eb-ct { min-width: 14rem; } + .eb-clist td.eb-cm { color: var(--color-fg-muted); white-space: nowrap; } + .eb-clist a { color: inherit; font-variant-numeric: tabular-nums; } + .eb-defs { margin: 0; padding-left: 1.2rem; max-width: 80ch; } + .eb-defs li { margin: 2px 0; } + .eb-defs code { word-break: break-all; } [data-dash-source-state=refreshing] { opacity: .5; } -
+

ObjectStack 专题与任务看板

+
+ + + + +

— 个专题在推进。共有 - — 张未完成的卡,其中 p1 - — 张;在做 - — 张,排队 - — 张,阻塞 + — 张未完成的—卡,其中 p1 + — 张;可派 + — 张,在做 + — 张,阻塞 — 张,等你裁决 - — 张。 + — 张,搁置 + — 张。

— 个专题在推进。共有 - — 张未完成的卡,其中 p1 - — 张;在做 - — 张,排队 - — 张,阻塞 + — 张未完成的—卡,其中 p1 + — 张;可派 + — 张,在做 + — 张,阻塞 — 张,等你裁决 - — 张。 + — 张,搁置 + — 张。

@@ -88,9 +111,16 @@

ObjectStack 专题与任务看板

area · 专题 · 专题以外的任务 状态 未完成 - p1 - p2 - p3 + 可派 + 在做 + 阻塞 + 待你裁 + 搁置 + 其他 + 无状态 + p1 + p2 + p3 已完成 关联卡 未挂靠 @@ -99,7 +129,7 @@

ObjectStack 专题与任务看板

-

快照时间 —,分诊每 3 小时从 GitHub 重新读取。按北极星的 8 个 area 分组:每组先列这个 area 的专题(子专题缩进在父专题下,点 ▾ 收起),最后一行是这个 area 里不属于任何专题的未完成卡。组标题的数字 = 本组顶层专题的未完成卡 + 专题以外的卡。专题的「关联卡」= 子卡、子卡的子卡,加上正文写明属于该专题但没挂上的未完成卡(「未挂靠」列);父专题的数字包含子专题的卡。专题 = 标 pm:epic、标题以「专题」或 [Epic] 开头,或挂着未完成子卡的追踪卡;只列未关闭的。

+

快照时间 —,分诊每 3 小时从 GitHub 重新读取。按北极星的 8 个 area 分组:每组先列这个 area 的专题(子专题缩进在父专题下,点 ▾ 收起),最后一行是这个 area 里不属于任何专题的未完成卡。组标题的数字 = 本组顶层专题的未完成卡 + 专题以外的卡;页面上每个数字都跟着顶部的「全部 / p1 / p2 / p3」切换。点一行的「p1·p2」按钮,列出这一行里每张 p1、p2 卡。专题的「关联卡」= 子卡、子卡的子卡,加上正文写明属于该专题但没挂上的未完成卡(「未挂靠」列);父专题的数字包含子专题的卡。专题 = 标 pm:epic、标题以「专题」或 [Epic] 开头,或挂着未完成子卡的追踪卡;只列未关闭的。

@@ -111,9 +141,16 @@

ObjectStack 专题与任务看板

area · 专题 · 专题以外的任务 状态 未完成 - p1 - p2 - p3 + 可派 + 在做 + 阻塞 + 待你裁 + 搁置 + 其他 + 无状态 + p1 + p2 + p3 已完成 关联卡 未挂靠 @@ -122,7 +159,25 @@

ObjectStack 专题与任务看板

-

快照时间 —,分诊每 3 小时从 GitHub 重新读取。按 cloud 仓库的 9 个 area 分组(docs/strategy/core-functions.md):每组先列这个 area 的专题(子专题缩进在父专题下,点 ▾ 收起),最后一行是这个 area 里不属于任何专题的未完成卡。组标题的数字 = 本组顶层专题的未完成卡 + 专题以外的卡。专题的「关联卡」= 子卡、子卡的子卡,加上正文写明属于该专题但没挂上的未完成卡(「未挂靠」列);父专题的数字包含子专题的卡。专题 = 标 pm:epic、标题以「专题」或 [Epic] 开头,或挂着未完成子卡的追踪卡;只列未关闭的。

+

快照时间 —,分诊每 3 小时从 GitHub 重新读取。按 cloud 仓库的 9 个 area 分组(docs/strategy/core-functions.md):每组先列这个 area 的专题(子专题缩进在父专题下,点 ▾ 收起),最后一行是这个 area 里不属于任何专题的未完成卡。组标题的数字 = 本组顶层专题的未完成卡 + 专题以外的卡;页面上每个数字都跟着顶部的「全部 / p1 / p2 / p3」切换。点一行的「p1·p2」按钮,列出这一行里每张 p1、p2 卡。专题的「关联卡」= 子卡、子卡的子卡,加上正文写明属于该专题但没挂上的未完成卡(「未挂靠」列);父专题的数字包含子专题的卡。专题 = 标 pm:epic、标题以「专题」或 [Epic] 开头,或挂着未完成子卡的追踪卡;只列未关闭的。

+ + +
+

每个数字都能用 GitHub 查询复现,口径如下。每张卡只落一个状态,看它挂着的第一个状态标签,先后是 needs-user-decision / pm:awaiting-maintainer、pm:dispatched、pm:awaiting-merge、pm:queue、pm:blocked、pm:on-hold、pm:retriage / pm:triage:

+
    +
  • 级别:p1 含 p0,p2、p3 看 priority:* 标签;没有级别标签的卡只在「全部」里计数。
  • +
  • 待你裁 = 挂 needs-user-decision 或 pm:awaiting-maintainer 的卡。
  • +
  • 在做 = 挂 pm:dispatched 的卡。
  • +
  • 可派 = 挂 pm:queue、没有 assignee、且没有仍未解除的 Blocked-by 目标的卡。
  • +
  • 阻塞 = 挂 pm:blocked 的卡,加上挂 pm:queue 但有仍未解除的 Blocked-by 目标的卡。
  • +
  • 搁置 = 挂 pm:on-hold 的卡。
  • +
  • 其他 = 挂 pm:awaiting-merge(待合并)的卡、挂 pm:queue 但已有 assignee 的卡,以及只挂 pm:triage 或 pm:retriage 的卡。
  • +
  • 无状态 = 以上标签一个都没挂的卡,多半是漏了分诊。
  • +
  • Blocked-by 目标是卡正文或评论里行首 Blocked-by: #N 写的卡(p3 和无级别的卡只读正文),issue 关闭即解除、PR 合并才解除,读不到的目标按未解除算。
  • +
  • 可派的查询(p2,objectstack 仓库):repo:objectstack-ai/objectstack is:issue is:open label:pm:queue label:priority:p2 no:assignee -label:needs-user-decision -label:pm:awaiting-maintainer -label:pm:dispatched -label:pm:awaiting-merge,p1 把级别换成 label:priority:p1,priority:p0,cloud 把仓库换成 objectstack-ai/cloud,再从结果里去掉 Blocked-by 目标仍未解除的卡。
  • +
  • area 组按专题归组:专题里的卡跟着专题自己的 area 算,不看卡上的 area:* 标签,所以本组数字和加上 label:area:X 的查询会差出「本组专题里挂着别的 area 的卡」和「挂着本 area 却在别组专题里的卡」。
  • +
  • 点开的卡列表只列 p1、p2 卡(p1 在前,再按可派、在做、待合并、其他、阻塞、搁置、待你裁、无状态排),持有席位取最新一条 Claim: 评论的 Seat: 行,没有就写 assignee 账号,没有 assignee 就空着。
  • +
@@ -131,74 +186,128 @@

ObjectStack 专题与任务看板

const AREA_ORDER_C = ['control', 'environment', 'marketplace', 'ai', 'enterprise', 'security', 'ops', 'ux', 'fleet']; const AREA_NAME_C = { control: '云控制台', environment: '云环境', marketplace: '市场与发布', ai: '云端 AI', enterprise: '企业版', security: '云端安全', ops: '运维与上线', fleet: '车队工具', ux: '体验', '—': '未定 area' }; const AREA_NAME = { ai: 'AI', build: '搭建', data: '数据与权限', workflow: '流程与集成', ux: '体验', package: '包与安装', fleet: '车队', cloud: '云相关', '—': '未定 area' }; - const ST = ['doing', 'queue', 'blocked', 'hold', 'decide', 'none']; + // The datasets' grade × state cells (`topic-board.mjs` header "Grade × state"): one column per `_`. + const GRADES = ['p1', 'p2', 'p3', 'un']; + const CELLS = ['ready', 'queued', 'waitq', 'doing', 'merge', 'blocked', 'hold', 'decide', 'none']; + const PICKS = ['p1', 'p2', 'p3']; + const LISTED = ['p1', 'p2']; + const STATE_LABEL = { ready: '可派', queued: '排队·不可派', waitq: '阻塞(排队中)', doing: '在做', merge: '待合并', blocked: '阻塞', hold: '搁置', decide: '待你裁', none: '无状态' }; const segs = [ - { key: 'doing', label: '在做', color: () => dash.colors[0] }, - { key: 'queue', label: '排队', color: () => dash.colors[1] }, - { key: 'blocked', label: '阻塞', color: () => dash.colors[2] }, - { key: 'hold', label: '搁置', color: () => dash.colors[3] }, - { key: 'decide', label: '待裁决', color: () => dash.colors[4] }, - { key: 'none', label: '无状态', color: () => dash.colors[5] }, + { key: 'ready', label: '可派' }, + { key: 'doing', label: '在做' }, + { key: 'blocked', label: '阻塞' }, + { key: 'decide', label: '待你裁' }, + { key: 'hold', label: '搁置' }, + { key: 'other', label: '其他' }, + { key: 'none', label: '无状态' }, ]; + const segColor = (i) => dash.colors[i % dash.colors.length]; + const SEG_KEYS = segs.map((g) => g.key); + + /** The grade the switch picks: 'p1' | 'p2' | 'p3', or null for 全部. */ + const pickOf = (params) => (PICKS.includes(params?.grade) ? params.grade : null); + const gradesFor = (pick) => (pick ? [pick] : GRADES); + const cnt = (r, gs, ss) => { let n = 0; for (const g of gs) for (const s of ss) n += +r[g + '_' + s] || 0; return n; }; + /** A row's numbers under one pick: every column the table shows. */ + const view = (r, pick) => { + const gs = gradesFor(pick); + const c = (...ss) => cnt(r, gs, ss); + const open = c(...CELLS); + const closed = gs.reduce((a, g) => a + (+r['closed_' + g] || 0), 0); + return { + open, ready: c('ready'), doing: c('doing'), blocked: c('blocked', 'waitq'), decide: c('decide'), hold: c('hold'), + other: c('queued', 'merge'), none: c('none'), + p1: cnt(r, ['p1'], CELLS), p2: cnt(r, ['p2'], CELLS), p3: cnt(r, ['p3'], CELLS), + closed, total: open + closed, unlinked: gs.reduce((a, g) => a + (+r['unlinked_' + g] || 0), 0), + }; + }; const areaKey = (a) => (String(a || '').replace(/^(.*)$/, '') || '—'); const rootsOf = (epics) => { const known = new Set(epics.map((r) => r.epic)); return epics.filter((r) => r.parent == null || !known.has(r.parent)); }; - const total = (key) => (epics, areas) => d3.sum(rootsOf(epics), (r) => +r[key] || 0) + d3.sum(areas, (r) => +r[key] || 0); - dash.calc('activeCount', { inputs: ['epics'], title: '在推进的专题数', description: '状态为「进行中」的专题个数。', fn: (epics) => epics.filter((r) => r.state === '进行中').length }); - dash.calc('totOpen', { inputs: ['epics', 'areas'], title: '未完成卡数', description: '顶层专题的未完成关联卡 + 专题以外的未完成卡。', fn: total('open') }); - dash.calc('totP1', { inputs: ['epics', 'areas'], title: 'p1 卡数', description: '同上口径的 p1(含 p0)。', fn: total('p1') }); - dash.calc('totDoing', { inputs: ['epics', 'areas'], title: '在做卡数', description: '挂 pm:dispatched 的卡。', fn: total('doing') }); - dash.calc('totQueue', { inputs: ['epics', 'areas'], title: '排队卡数', description: '挂 pm:queue 的卡。', fn: total('queue') }); - dash.calc('totBlocked', { inputs: ['epics', 'areas'], title: '阻塞卡数', description: '挂 pm:blocked 的卡。', fn: total('blocked') }); - dash.calc('totDecide', { inputs: ['epics', 'areas'], title: '待裁决卡数', description: '挂 needs-user-decision 或 pm:awaiting-maintainer 的卡。', fn: total('decide') }); + const sumOver = (epics, areas, pick, states) => d3.sum(rootsOf(epics), (r) => cnt(r, gradesFor(pick), states)) + d3.sum(areas, (r) => cnt(r, gradesFor(pick), states)); + const activeOf = (epics, pick) => epics.filter((r) => r.state === '进行中' && (!pick || cnt(r, [pick], CELLS) > 0)).length; - dash.calc('activeCountC', { inputs: ['epics_cloud'], title: '在推进的专题数', description: '状态为「进行中」的专题个数。', fn: (epics) => epics.filter((r) => r.state === '进行中').length }); - dash.calc('totOpenC', { inputs: ['epics_cloud', 'areas_cloud'], title: '未完成卡数', description: '顶层专题的未完成关联卡 + 专题以外的未完成卡。', fn: total('open') }); - dash.calc('totP1C', { inputs: ['epics_cloud', 'areas_cloud'], title: 'p1 卡数', description: '同上口径的 p1(含 p0)。', fn: total('p1') }); - dash.calc('totDoingC', { inputs: ['epics_cloud', 'areas_cloud'], title: '在做卡数', description: '挂 pm:dispatched 的卡。', fn: total('doing') }); - dash.calc('totQueueC', { inputs: ['epics_cloud', 'areas_cloud'], title: '排队卡数', description: '挂 pm:queue 的卡。', fn: total('queue') }); - dash.calc('totBlockedC', { inputs: ['epics_cloud', 'areas_cloud'], title: '阻塞卡数', description: '挂 pm:blocked 的卡。', fn: total('blocked') }); - dash.calc('totDecideC', { inputs: ['epics_cloud', 'areas_cloud'], title: '待裁决卡数', description: '挂 needs-user-decision 或 pm:awaiting-maintainer 的卡。', fn: total('decide') }); + for (const [sfx, E, A] of [['', 'epics', 'areas'], ['C', 'epics_cloud', 'areas_cloud']]) { + dash.calc('activeCount' + sfx, { inputs: [E], title: '在推进的专题数', description: '状态为「进行中」的专题个数;选了级别时只数有这个级别未完成卡的专题。', fn: (epics) => activeOf(epics, pickOf(dash.params())) }); + dash.calc('totOpen' + sfx, { inputs: [E, A], title: '未完成卡数', description: '顶层专题的未完成关联卡 + 专题以外的未完成卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), CELLS) }); + dash.calc('totP1' + sfx, { inputs: [E, A], title: 'p1 卡数', description: '同上口径的 p1(含 p0)。', fn: (epics, areas) => sumOver(epics, areas, 'p1', CELLS) }); + dash.calc('totReady' + sfx, { inputs: [E, A], title: '可派卡数', description: '挂 pm:queue、没有 assignee、没有未解除 Blocked-by 目标的卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), ['ready']) }); + dash.calc('totDoing' + sfx, { inputs: [E, A], title: '在做卡数', description: '挂 pm:dispatched 的卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), ['doing']) }); + dash.calc('totBlocked' + sfx, { inputs: [E, A], title: '阻塞卡数', description: '挂 pm:blocked 的卡,加上挂 pm:queue 但有未解除 Blocked-by 目标的卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), ['blocked', 'waitq']) }); + dash.calc('totDecide' + sfx, { inputs: [E, A], title: '待裁决卡数', description: '挂 needs-user-decision 或 pm:awaiting-maintainer 的卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), ['decide']) }); + dash.calc('totHold' + sfx, { inputs: [E, A], title: '搁置卡数', description: '挂 pm:on-hold 的卡,按顶部选的级别。', fn: (epics, areas) => sumOver(epics, areas, pickOf(dash.params()), ['hold']) }); + } const fmt = d3.format(','); function single(name, id) { dash.draw(name, (el) => { const s = dash.data(id); el.textContent = s.status === 'ok' && s.data != null ? fmt(s.data) : '—'; }); } - single('active', 'activeCount'); single('open', 'totOpen'); single('p1', 'totP1'); - single('activeC', 'activeCountC'); single('openC', 'totOpenC'); single('p1C', 'totP1C'); - single('doingC', 'totDoingC'); single('queueC', 'totQueueC'); single('blockedC', 'totBlockedC'); single('decideC', 'totDecideC'); - single('doing', 'totDoing'); single('queue', 'totQueue'); single('blocked', 'totBlocked'); single('decide', 'totDecide'); + for (const sfx of ['', 'C']) { + single('active' + sfx, 'activeCount' + sfx); single('open' + sfx, 'totOpen' + sfx); single('p1' + sfx, 'totP1' + sfx); + single('ready' + sfx, 'totReady' + sfx); single('doing' + sfx, 'totDoing' + sfx); single('blocked' + sfx, 'totBlocked' + sfx); + single('decide' + sfx, 'totDecide' + sfx); single('hold' + sfx, 'totHold' + sfx); + } + for (const name of ['gradeWord', 'gradeWordC']) dash.draw(name, (el) => { const pick = pickOf(dash.params()); el.textContent = pick ? ` ${pick} ` : ''; }); dash.draw('asofCloud', (el) => { const s = dash.data('areas_cloud'); el.textContent = s.status === 'ok' && s.data.length ? s.data[0].asof : '—'; }); dash.draw('asof', (el) => { const s = dash.data('areas'); el.textContent = s.status === 'ok' && s.data.length ? s.data[0].asof : '—'; }); dash.draw('legend', (el) => { - el.replaceChildren(...segs.map((g) => { const s = document.createElement('span'); s.style.setProperty('--sw', g.color()); s.textContent = g.label; return s; })); + el.replaceChildren(...segs.map((g, i) => { const s = document.createElement('span'); s.style.setProperty('--sw', segColor(i)); s.textContent = g.label; return s; })); }); + // The grade switch: a page filter no query names, so a pick redraws at once and fetches nothing. + // One-writer: outside a drawing this page only listens and sets `class`, `style`, `hidden` and `aria-*` — + // the attributes the Data type's one-writer guide lists as a script's own outside a drawing; `onData` is + // where its guide puts the `hidden` that shows or hides a drawing's container (`.eb-allonly` wraps `p1`). + dash.onData(() => { + const pick = pickOf(dash.params()); + for (const b of document.querySelectorAll('.eb-grades [data-grade]')) b.setAttribute('aria-pressed', String((b.dataset.grade === 'all' ? null : b.dataset.grade) === pick)); + for (const el of document.querySelectorAll('.eb')) el.classList.toggle('eb-graded', pick !== null); + for (const el of document.querySelectorAll('.eb-allonly')) el.hidden = pick !== null; + }); + for (const b of document.querySelectorAll('.eb-grades [data-grade]')) { + b.addEventListener('click', () => { + dash.setParams({ grade: b.dataset.grade === 'all' ? null : b.dataset.grade }); + try { localStorage.setItem('eb-grade', b.dataset.grade); } catch (e) {} + }); + } + try { const saved = localStorage.getItem('eb-grade'); if (PICKS.includes(saved)) dash.setParams({ grade: saved }); } catch (e) {} + const head = document.getElementById('eb-head'); const setHH = () => document.documentElement.style.setProperty('--eb-hh', (window.matchMedia('(max-width: 760px)').matches ? 0 : head.offsetHeight) + 'px'); if (window.ResizeObserver) new ResizeObserver(setHH).observe(head); setHH(); - const stack = (r) => { - const n = d3.sum(ST, (k) => +r[k] || 0); + const stack = (v) => { + const n = d3.sum(SEG_KEYS, (k) => v[k] || 0); const bar = document.createElement('div'); bar.className = 'eb-stack'; if (!n) return bar; - for (const g of segs) { - const v = +r[g.key] || 0; if (!v) continue; - const i = document.createElement('i'); i.style.width = (100 * v / n).toFixed(1) + '%'; i.style.background = g.color(); - i.title = `${g.label} ${v}`; bar.appendChild(i); - } + segs.forEach((g, idx) => { + const x = v[g.key] || 0; if (!x) return; + const i = document.createElement('i'); i.style.width = (100 * x / n).toFixed(1) + '%'; i.style.background = segColor(idx); + i.title = `${g.label} ${x}`; bar.appendChild(i); + }); return bar; }; const pillClass = { '进行中': 'run', '暂停': 'hold', '子卡已清空': 'done', '未拆卡': 'done' }; const collapsed = new Set(); + const opened = new Set(); + /** A row's listed cards: an array in the dataset (a JSON text is read too, never trusted further). */ + const cardsOf = (r) => { + let c = r.cards; + if (typeof c === 'string') { try { c = JSON.parse(c); } catch (e) { c = []; } } + return Array.isArray(c) ? c : []; + }; + const listedFor = (r, pick) => (pick && !LISTED.includes(pick) ? [] : cardsOf(r).filter((c) => (pick ? c.grade === pick : LISTED.includes(c.grade)))); - const makeBoard = (EID, AID, ORDER, NAMES) => (tb) => { + const makeBoard = (EID, AID, ORDER, NAMES, REPO) => (tb) => { const se = dash.data(EID), sa = dash.data(AID); tb.replaceChildren(); if (se.status !== 'ok' || sa.status !== 'ok') return; const epics = se.data, areas = sa.data; + const pick = pickOf(dash.params()); + const V = new Map(); + const v = (r) => { if (!V.has(r)) V.set(r, view(r, pick)); return V.get(r); }; const rank = { '进行中': 0, '暂停': 1, '未拆卡': 2, '子卡已清空': 3 }; - const order = (a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9) || b.open - a.open || a.epic - b.epic; + const order = (a, b) => (rank[a.state] ?? 9) - (rank[b.state] ?? 9) || v(b).open - v(a).open || a.epic - b.epic; const known = new Set(epics.map((r) => r.epic)); const kids = new Map(); for (const r of epics) { const p = r.parent != null && known.has(r.parent) ? r.parent : null; if (!kids.has(p)) kids.set(p, []); kids.get(p).push(r); } @@ -209,6 +318,8 @@

ObjectStack 专题与任务看板

for (const a of rest.keys()) if (!groups.has(a)) groups.set(a, []); const keys = [...groups.keys()].sort((a, b) => (ORDER.indexOf(a) + 1 || 99) - (ORDER.indexOf(b) + 1 || 99)); const countDesc = (n) => (kids.get(n) || []).reduce((x, r) => x + 1 + countDesc(r.epic), 0); + const legacy = [...epics, ...areas].some((r) => !('p1_ready' in r)); + const COLS = 17; const row = (cls, key) => { const tr = document.createElement('tr'); if (cls) tr.className = cls; tr.dataset.key = key; return tr; }; const cell = (tr, text, cls) => { const c = document.createElement('td'); if (cls) c.className = cls; c.textContent = text; tr.appendChild(c); return c; }; @@ -219,18 +330,59 @@

ObjectStack 专题与任务看板

t.addEventListener('click', () => { open ? collapsed.add(key) : collapsed.delete(key); render(); }); return t; }; - const nums = (tr, r, withProgress) => { - cell(tr, String(r.open ?? 0), 'num'); cell(tr, String(r.p1 ?? 0), +r.p1 > 0 ? 'num eb-p1' : 'num'); - cell(tr, String(r.p2 ?? 0), 'num'); cell(tr, String(r.p3 ?? 0), 'num'); - if (withProgress) { cell(tr, String(r.closed), 'num'); cell(tr, String(r.total), 'num'); cell(tr, String(r.unlinked ?? 0), +r.unlinked > 0 ? 'num eb-warn' : 'num zero'); } + const cardsButton = (key, list) => { + const open = opened.has(key); + const b = document.createElement('button'); b.className = 'eb-cbtn'; b.type = 'button'; + b.setAttribute('aria-expanded', String(open)); + b.textContent = `${pick || 'p1·p2'} ${list.length} 张 ${open ? '▾' : '▸'}`; + b.addEventListener('click', () => { open ? opened.delete(key) : opened.add(key); render(); }); + return b; + }; + const cardRows = (key, list) => { + const tr = row('eb-cards', key + ':cards'); + cell(tr, '', 'num'); + const td = document.createElement('td'); td.colSpan = COLS - 1; + const t = document.createElement('table'); t.className = 'eb-clist'; + for (const c of list) { + const r = document.createElement('tr'); + const n = document.createElement('td'); n.className = 'eb-cm'; + if (Number.isInteger(c.number)) { + const a = document.createElement('a'); a.href = `https://github.com/objectstack-ai/${REPO}/issues/${c.number}`; + a.target = '_blank'; a.rel = 'noopener'; a.textContent = '#' + c.number; n.appendChild(a); + } + r.appendChild(n); + const ti = document.createElement('td'); ti.className = 'eb-ct'; ti.textContent = String(c.title ?? ''); r.appendChild(ti); + const g = document.createElement('td'); g.className = c.grade === 'p1' ? 'eb-cm eb-p1' : 'eb-cm'; g.textContent = String(c.grade ?? ''); r.appendChild(g); + const st = document.createElement('td'); st.className = 'eb-cm'; st.textContent = STATE_LABEL[c.state] || String(c.state ?? ''); r.appendChild(st); + const se2 = document.createElement('td'); se2.className = 'eb-cm'; se2.textContent = c.seat ? '持有:' + c.seat : '无人持有'; r.appendChild(se2); + const w = document.createElement('td'); w.className = 'eb-cm'; + const waits = Array.isArray(c.waits) ? c.waits.map(String) : []; + w.textContent = waits.length ? '等:' + waits.join('、') : ''; r.appendChild(w); + t.appendChild(r); + } + td.appendChild(t); tr.appendChild(td); + return tr; + }; + const numCell = (tr, x, cls = '') => cell(tr, String(x), `num ${cls} ${x ? '' : 'zero'}`.trim()); + const nums = (tr, x, withProgress) => { + numCell(tr, x.open); numCell(tr, x.ready); numCell(tr, x.doing); numCell(tr, x.blocked); numCell(tr, x.decide); + numCell(tr, x.hold); numCell(tr, x.other); numCell(tr, x.none); + numCell(tr, x.p1, x.p1 > 0 ? 'eb-gcol eb-p1' : 'eb-gcol'); numCell(tr, x.p2, 'eb-gcol'); numCell(tr, x.p3, 'eb-gcol'); + if (withProgress) { cell(tr, String(x.closed), 'num'); cell(tr, String(x.total), 'num'); cell(tr, String(x.unlinked), x.unlinked > 0 ? 'num eb-warn' : 'num zero'); } else { cell(tr, '', 'num zero'); cell(tr, '', 'num zero'); cell(tr, '', 'num zero'); } }; const render = () => { tb.replaceChildren(); + if (legacy) { + const tr = row('', EID + ':legacy'); cell(tr, '', 'num'); + const c = cell(tr, '这份数据是旧格式,没有按级别和状态拆开的列,表里的数字都会是 0:请照 README 用新脚本重建数据。', 'eb-warn'); + c.colSpan = COLS - 1; tb.appendChild(tr); + } const walk = (list, depth) => { list.forEach((r, idx) => { const sub = kids.get(r.epic) || []; + const x = v(r); const tr = row(depth > 0 ? 'eb-child' : '', EID + r.epic); cell(tr, String(r.epic), 'num'); const name = document.createElement('td'); name.className = 'eb-name'; @@ -239,24 +391,29 @@

ObjectStack 专题与任务看板

else if (depth > 0) { const g = document.createElement('span'); g.className = 'eb-branch'; g.textContent = idx === list.length - 1 ? '└' : '├'; name.appendChild(g); } name.append(document.createTextNode(r.title)); if (sub.length) { const k = document.createElement('span'); k.className = 'eb-kids'; k.textContent = `· ${sub.length} 个子专题`; name.appendChild(k); } - if (+r.total > 0) { + if (x.total > 0) { const bar = document.createElement('div'); bar.className = 'eb-bar'; - const fill = document.createElement('i'); fill.style.width = (100 * r.closed / r.total).toFixed(1) + '%'; fill.style.background = dash.colors[0]; + const fill = document.createElement('i'); fill.style.width = (100 * x.closed / x.total).toFixed(1) + '%'; fill.style.background = segColor(0); bar.appendChild(fill); name.appendChild(bar); } - if (+r.open > 0) name.appendChild(stack(r)); + if (x.open > 0) name.appendChild(stack(x)); + const listed = listedFor(r, pick); + const ck = EID + ':cards:' + r.epic; + if (listed.length) name.appendChild(cardsButton(ck, listed)); const upd = document.createElement('small'); upd.textContent = '最近更新 ' + r.updated; name.appendChild(upd); tr.appendChild(name); const st = document.createElement('td'); const pill = document.createElement('span'); pill.className = 'eb-pill ' + (pillClass[r.state] || 'done'); pill.textContent = r.state; st.appendChild(pill); tr.appendChild(st); - nums(tr, r, true); + nums(tr, x, true); tb.appendChild(tr); + if (listed.length && opened.has(ck)) tb.appendChild(cardRows(ck, listed)); if (sub.length && !collapsed.has(EID + r.epic)) walk(sub, depth + 1); }); }; for (const a of keys) { const list = groups.get(a), rr = rest.get(a) || {}; - const sum = {}; for (const k of ['open', 'p1', 'p2', 'p3', ...ST]) sum[k] = d3.sum(list, (r) => +r[k] || 0) + (+rr[k] || 0); + const xr = v(rr); + const sum = {}; for (const k of Object.keys(xr)) sum[k] = d3.sum(list, (r) => v(r)[k]) + xr[k]; const g = EID + ':area:' + a; const tr = row('eb-group', g); cell(tr, '', 'num'); @@ -264,37 +421,40 @@

ObjectStack 专题与任务看板

name.appendChild(toggle(g, ' ' + (NAMES[a] || a))); name.append(document.createTextNode(NAMES[a] || a)); const m = document.createElement('span'); m.className = 'eb-gmeta'; - m.textContent = `area:${a} · ${list.length + list.reduce((x, r) => x + countDesc(r.epic), 0)} 个专题 · 专题以外 ${+rr.open || 0} 张`; + m.textContent = `area:${a} · ${list.length + list.reduce((x, r) => x + countDesc(r.epic), 0)} 个专题 · 专题以外 ${xr.open} 张`; name.appendChild(m); name.appendChild(stack(sum)); tr.appendChild(name); cell(tr, ''); nums(tr, sum, false); tb.appendChild(tr); if (collapsed.has(g)) continue; walk(list, 0); - if (+rr.open > 0) { + if (xr.open > 0) { const t2 = row('eb-rest', 'rest:' + a); cell(t2, '', 'num'); const n2 = document.createElement('td'); n2.className = 'eb-name'; n2.style.paddingLeft = 'calc(var(--cds-pad-md) + 1.4rem)'; const tag = document.createElement('span'); tag.className = 'eb-tag'; tag.textContent = '专题以外'; n2.appendChild(tag); n2.append(document.createTextNode('不属于任何专题的未完成卡')); - n2.appendChild(stack(rr)); - if (+rr.none > 0) { const w = document.createElement('small'); w.className = 'eb-warn'; w.textContent = `${rr.none} 张没有 pm 状态,漏了分诊`; n2.appendChild(w); } + n2.appendChild(stack(xr)); + const listed = listedFor(rr, pick); + const ck = EID + ':cards:rest:' + a; + if (listed.length) n2.appendChild(cardsButton(ck, listed)); + if (xr.none > 0) { const w = document.createElement('small'); w.className = 'eb-warn'; w.textContent = `${xr.none} 张没有 pm 状态,漏了分诊`; n2.appendChild(w); } t2.appendChild(n2); cell(t2, ''); - nums(t2, rr, false); + nums(t2, xr, false); tb.appendChild(t2); + if (listed.length && opened.has(ck)) tb.appendChild(cardRows(ck, listed)); } } }; render(); }; - dash.draw('boardRows', makeBoard('epics', 'areas', AREA_ORDER, AREA_NAME)); - dash.draw('boardRowsCloud', makeBoard('epics_cloud', 'areas_cloud', AREA_ORDER_C, AREA_NAME_C)); + dash.draw('boardRows', makeBoard('epics', 'areas', AREA_ORDER, AREA_NAME, 'objectstack')); + dash.draw('boardRowsCloud', makeBoard('epics_cloud', 'areas_cloud', AREA_ORDER_C, AREA_NAME_C, 'cloud')); - const root = document.querySelector('.eb'); const pick = (repo) => { - root.dataset.repo = repo; + for (const el of document.querySelectorAll('.eb')) el.classList.toggle('eb-on-cloud', repo === 'cloud'); for (const b of document.querySelectorAll('.eb-tabs [data-tab]')) b.setAttribute('aria-selected', String(b.dataset.tab === repo)); try { localStorage.setItem('eb-repo', repo); } catch (e) {} setHH(); From 1afd9c133815ee818c7a50fd8547b9ca816c1777 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:51:07 +0000 Subject: [PATCH 015/178] perf(app-shell): an object list loads the package ask, the view settings panel and the create-view dialog only when opened (#38429) 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_01AXsQkLFKRdQCqQ3RTr6JaoLA64Pdo43CcX7aDR1Nooow)_ Part of #37444. This is the first cut: the object list page stops loading authoring code before its first screen. The card stays open, because this cut alone is not expected to bring the list page under 2.5 s; a second cut waits for this PR's reading and a claim amendment. Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户打开对象列表页时少下载约 180 KB 的编辑类代码,首屏更快;页面上看到和保存的内容都不变。 - 属于「控制台首屏 2.5 秒内打开」专题,这是列表页的第一刀。 - 出错时,第一次打开选包框、视图设置面板或新建视图框会多等一下,或者打不开;撤回这个 PR 即可恢复。 - 无。 ## What changes The object list route (`ObjectView`) pulled about 69 chunks (~183 KB brotli, measured on `ff69bcab`) of authoring code before its first screen: 1. `objectViewViewCrud.tsx` and `objectViewViewSharing.ts` imported `metadata-admin/PackageCreateAsk` and `metadata-admin/i18n` statically (since #38204). `usePackageCreateAsk` drew a closed `PackageCreateAskDialog` on every list, and that dialog imports the package page's create dialog, `PackageFormDialog`, `SchemaForm` and the Studio catalogue. 2. `ViewConfigPanel` and `CreateViewDialog` are `React.lazy`, but were rendered closed on every list, so their chunks were fetched on every list load too. Now: - `useDeferredPackageCreateAsk` (in `objectViewViewCrud.tsx`) keeps the same `ask(request) => Promise` contract. It mounts a lazy `PackageCreateAskDialog` on the first ask and keeps it mounted afterwards, so it closes the way it did before. A newer ask still resolves the older one with `null`, and unmount still resolves a pending ask with `null`. - `reportViewNotSaved(err, locale)` still answers synchronously whether the error was a runtime-create refusal. The refusal text, the designer locale mapping and the Studio catalogue load on the refusal, and the toast shows once they arrive. A cancelled ask still shows nothing. - Both hooks read the locale from `useObjectTranslation()` instead of `useMetadataLocale()`; `designerLocaleOf` maps it at refusal time. - `ObjectView.tsx` mounts `ViewConfigPanel` and `CreateViewDialog` the first time each opens (`useOpenedOnce`), and keeps them mounted after that. No exported shape changes, no spec or metadata change. ## Tests - New `objectViewListRoute.deferredAuthoring-37444.test.tsx` pins the load order with counted `vi.mock` factories: importing `./ObjectView` evaluates none of `PackageCreateAsk`, `PackagesPage`, `SchemaForm`, `metadata-admin/i18n`, `ViewConfigPanel`, `CreateViewDialog`; the ask loads its dialog on the first ask, answers it and stays mounted closed; a refused create toasts once its words load, a cancelled one never toasts. - `ObjectView.readOnlyPackageViewSaves-35974.test.tsx` and `ObjectView.viewConfigSaveWiring-10210.test.tsx` read the panel's props; they now open the panel first, since a closed panel is no longer mounted. The personal-view case now asserts the closed panel is not mounted.
Pin ablation Committed first, then `scripts/ablation-replace.mjs` on `objectViewViewCrud.tsx`: the anchor `import type { PackageAskRequest } from './metadata-admin/PackageCreateAsk.js';` replaced with a value import of `PackageCreateAskDialog` (`void`-used). Result: case 1 (`packageAsk` 0 → 1) and case 2 red, case 3 green: 2 failed, 1 passed. Restored: blob equals HEAD, `git diff HEAD` empty. What is not separately pinned: the `CreateViewDialog` render deferral in `ObjectView` (its module-load count is pinned at import time only; no case opens the dialog). The `ViewConfigPanel` render deferral is pinned by the 35974 personal-view case.
## Acceptance notes - Read first: `objectViewViewCrud.tsx` (`useDeferredPackageCreateAsk`: the resolve-older-ask and unmount paths), then `ObjectView.tsx` (`useOpenedOnce` and the two mount sites), then `objectViewViewSharing.ts` (the catch path). - Two-minute check: on a list page, open the browser's network panel, load the list: no `PackagesPage`, `SchemaForm` or `CreateViewDialog` chunk. Click the view settings gear: the panel opens after one chunk fetch. - Found while testing, not changed here: the toolbar Settings path opens the config panel on the first grid view (`all`), not on the open view (unit-level evidence only). ## Verification LCP on this PR's build (`bd4f2071`) against main, by the card's method: production builds, HTTP/2 TLS front, Lighthouse 13.6.0 desktop preset, signed in, blocks main-1, pr-1, pr-2, main-2 of 5 runs per page. The record page got a reversed round on top. p is a two-sided permutation test on the median difference. Full runs: card comment 7248989586. | page | main median (ms) | PR median (ms) | delta | p | |:--|--:|--:|--:|--:| | home (10 vs 10) | 2080.5 | 2115.5 | +35 | 0.33 | | object list (10 vs 10) | 2647 | 2551 | −96 | 0.03 | | record (20 vs 20) | 2444.5 | 2478.5 | +34 | 0.30 | On the list page, the scripts fetched before the first screen go from 274 to 225: 171.6 KB less gzip as served, or 188 KB less brotli by the dist's `.br` files. Home and record fetch the same script count on both builds. The list is still 51 ms over 2500, so the card stays open for a second cut.
Gates - `node scripts/pm/dispatch-gates.mjs --commands`: 38 derived, all 38 exit 0. `--ran`: 38 run, 0 NOT-MEASURED, 0 UNRUN. - `--tier`: no path-derived mandate; 356 changed lines (under 3000). - `overlap-check`: merges cleanly onto `origin/main`, VERDICT clean. - `cd ui && pnpm exec vitest run` on 23 affected app-shell files: 265/265 passed. - eslint on the 6 changed source and test files: 0 errors.
## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint on the changed files: 0 errors. - [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: n/a. - [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 with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibxzGFPvShbd2qnkdEv Co-authored-by: Claude --- .../37444-list-route-defers-authoring.md | 13 ++ ...ew.readOnlyPackageViewSaves-35974.test.tsx | 17 +- .../app-shell/src/views/ObjectView.tsx | 30 +++- ...ctView.viewConfigSaveWiring-10210.test.tsx | 36 +++- ...ListRoute.deferredAuthoring-37444.test.tsx | 162 ++++++++++++++++++ .../src/views/objectViewViewCrud.tsx | 81 ++++++++- .../src/views/objectViewViewSharing.ts | 17 +- 7 files changed, 327 insertions(+), 29 deletions(-) create mode 100644 .changeset/37444-list-route-defers-authoring.md create mode 100644 ui/packages/app-shell/src/views/objectViewListRoute.deferredAuthoring-37444.test.tsx diff --git a/.changeset/37444-list-route-defers-authoring.md b/.changeset/37444-list-route-defers-authoring.md new file mode 100644 index 00000000000..be1e1fffc56 --- /dev/null +++ b/.changeset/37444-list-route-defers-authoring.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +perf(app-shell): an object list stops loading the package ask, the view settings panel and the create-view dialog before its first screen + +Clause-②: no +Metadata-protocol: none + +An object list page fetched about 183 KB (brotli) of authoring code before its first screen, though it only needs that code when someone opens it. Three pieces did this. The "pick or create a package" ask that a view create may open was drawn closed on every list, and it brought in the package page's create dialog, its form and the Studio strings. The view settings panel and the create-view dialog were also drawn closed on every list. Now each one loads the first time it is opened, and after that it stays mounted, so closing it works as before. When a view create is refused, the reason loads with the refusal, and its toast shows once those strings arrive. + +Nothing a user sees or saves changes, apart from a short wait the first time one of these opens. Nothing to migrate. diff --git a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx index 3923624e214..843eee170cb 100644 --- a/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.readOnlyPackageViewSaves-35974.test.tsx @@ -273,9 +273,13 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o expect(panelProps.current?.readOnly).toBe(false); }); + // objectstack#37444: the panel mounts the first time it is opened, so the + // cases below that read the open view's panel open it, through that view's + // own row (the door that opens the panel on a given view). it('the panel opens on the shipped view read-only', async () => { mount(SHIPPED.name); await settle(); + await clickConfig(SHIPPED.name); await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(SHIPPED.name)); await waitFor(() => expect(panelProps.current?.readOnly).toBe(true)); }); @@ -283,15 +287,18 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o it('the panel on a shared view saved into the customization package is not read-only', async () => { mount(CUSTOM.name); await settle(); + await clickConfig(CUSTOM.name); await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(CUSTOM.name)); expect(panelProps.current?.readOnly).toBe(false); }); - it('on the reader\'s own view the panel is not read-only and Manage views is unchanged', async () => { + it('on the reader\'s own view the closed panel is not mounted and Manage views is unchanged', async () => { mount(PERSONAL.id); await settle(); - await waitFor(() => expect(panelProps.current?.activeView?.id).toBe(PERSONAL.id)); - expect(panelProps.current?.readOnly).toBe(false); + // objectstack#37444: closed, the panel is not mounted at all (it used to be, + // and this case read the verdict a closed panel was handed). Its own view is + // no row of Manage views, so no row opens the panel on it. + expect(panelProps.current).toBeNull(); // My views are no row of Manage views; the shared rows are judged as ever. expect(screen.queryByTestId(`manage-views-row-${PERSONAL.id}`)).toBeNull(); await waitFor(async () => expect(await rowOffers(SHIPPED.name)).toEqual(FACTORY_OFFERS)); @@ -304,6 +311,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o await settle(); await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); expect(panelProps.current?.readOnly).toBe(false); }); @@ -313,6 +322,8 @@ describe('objectstack#35974 — a read-only package\'s view: no Delete, a read-o await settle(); await waitFor(() => expect(screen.getByTestId(`manage-views-row-${SHIPPED.name}`)).toBeTruthy()); expect(await rowOffers(SHIPPED.name)).toEqual(OFFERED); + await clickConfig(SHIPPED.name); + await waitFor(() => expect(panelProps.current?.open).toBe(true)); expect(panelProps.current?.readOnly).toBe(false); }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index ac9e9bc4207..35cd99e333b 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -43,8 +43,9 @@ import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; // objectstack#33293: the view config panel loads with the first list, not with // the console. Statically, it held the view-variant inspector, `SchemaForm` and // the Studio form widgets in the EAGER closure, so a dashboard route downloaded -// them too. It is drawn on every list (closed, it draws nothing), so its chunk -// is fetched as the list mounts, before any admin can open it. +// them too. objectstack#37444: it mounts the first time it is opened, not with +// every list, so the list's first screen no longer fetches it (see +// `useOpenedOnce` below). const ViewConfigPanel = lazy(() => import('./ViewConfigPanel.js').then((m) => ({ default: m.ViewConfigPanel })), ); @@ -53,9 +54,24 @@ import { dropPublishedViewList } from './metadata-admin/viewListDrop.js'; // objectstack#33582: the create-view dialog loads with the first list, as the // view config panel above does. Statically, it held the dataset catalogue and, // through it, the Studio `en` string namespace in the EAGER closure. +// objectstack#37444: like the panel, it mounts on its first opening. const CreateViewDialog = lazy(() => import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })), ); + +/** + * objectstack#37444 — `true` from the first render `open` is, and from then on. + * A lazy panel or dialog behind it loads only when someone opens it (closed, it + * draws nothing, so mounting it with every list only fetched its chunk before + * the list's first screen), and stays mounted after, so closing it animates and + * keeps its state as before. The state is adjusted during render, React's way of + * deriving state from a prop, so the opening render already mounts it. + */ +function useOpenedOnce(open: boolean): boolean { + const [opened, setOpened] = useState(open); + if (open && !opened) setOpened(true); + return opened || open; +} import { usePreviewDrafts, } from '../preview/PreviewModeContext.js'; @@ -308,6 +324,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // refuses with 403. `isAdmin` alone still gates what only reads. const canAuthorMetadata = useCanAuthorMetadata(); const canManageViews = mayManageViews(isAdmin, canAuthorMetadata); + const viewConfigPanelMounted = useOpenedOnce(showViewConfigPanel && canManageViews); + const createViewDialogMounted = useOpenedOnce(showCreateViewDialog && canManageViews); // Get Object Definition. The outer ObjectView wrapper already guards the // missing-object case, so this always resolves while this component is @@ -1710,7 +1728,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0' }`} > - + {viewConfigPanelMounted && { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }} @@ -1725,9 +1743,9 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co onAfterChange={handleDraftBarChange} readOnly={viewConfigPanelReadOnly} /> - + } - + {createViewDialogMounted && handleViewCreate(cfg)} /> - + } { if (!open) setPersonalViewDialog(null); }} diff --git a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx index de66d7dfa6f..29bb97dec32 100644 --- a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx @@ -21,7 +21,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, act, screen, fireEvent } from '@testing-library/react'; +import { render, cleanup, act, screen, fireEvent, waitFor } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { ViewMetadataSchema } from '@objectstack/spec/ui'; @@ -116,6 +116,27 @@ vi.mock('./ViewConfigPanel', () => { // The view's source reaches a dynamic import of `@objectstack/lint`: pay its // load at collection, never inside a case's clocked window (`check:test-source-alias`). +// objectstack#37444: the list's Settings view action, drawn beside the real +// plugin view (whose own view switcher the console hides), so a case can open +// the panel the way the action does. +vi.mock('@object-ui/plugin-view', async (importOriginal) => { + const actual = await importOriginal(); + const Real = actual.ObjectView; + return { + ...actual, + ObjectView: (props: React.ComponentProps) => ( + <> +
+ )} + + )} + + {passes && ( +
+

{t('engine.looseMove.confirm.dryRunNote', locale)}

+

{t('engine.looseMove.confirm.undoNote', locale)}

+
+ )} + + + + {step.kind === 'failed' ? ( + + ) : ( + + )} + + + + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx index d1b4e25de11..e0e25e348f3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx @@ -58,6 +58,12 @@ export interface PackageAskRequest { preselect?: string | null; /** The type being created, as the reader reads it; names the question. */ typeLabel?: string; + /** + * The question and its explanation, for an ask that is not a create + * (objectstack#38150: where loose items move to). Absent, the create's own. + */ + title?: string; + description?: string; } /** The packages the ask offers: the server's writable verdict, kernel packages out, by name. */ @@ -73,6 +79,8 @@ export function PackageCreateAskDialog({ open, preselect, typeLabel, + title: askTitle, + description: askDescription, onAnswer, readPackages = fetchPackages, }: PackageAskRequest & { @@ -117,7 +125,9 @@ export function PackageCreateAskDialog({ }; const options = list.status === 'read' ? list.options : []; - const title = typeLabel + const title = askTitle + ? askTitle + : typeLabel ? tFormat('engine.packageAsk.titleNamed', locale, { type: typeLabel }) : t('engine.packageAsk.title', locale); @@ -132,7 +142,7 @@ export function PackageCreateAskDialog({ {title} - {t('engine.packageAsk.description', locale)} + {askDescription ?? t('engine.packageAsk.description', locale)} {list.status === 'loading' && (

@@ -244,6 +254,8 @@ export function usePackageCreateAsk(): { open={!!pending} preselect={pending?.preselect ?? null} typeLabel={pending?.typeLabel} + title={pending?.title} + description={pending?.description} onAnswer={onAnswer} /> ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index 6f52037de24..1eac052a20f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -139,6 +139,7 @@ import { ProtocolCheckSkippedNote } from '../../console/marketplace/ProtocolChec import type { InstalledPackageAtEitherStage } from '@objectstack/spec/api-assembled'; import type { PackagePublishResult } from '@objectstack/spec/system'; import { studioHomePath } from '../studio-design/studioAddress.js'; +import { LooseItemsBanner } from './LooseItemsBanner.js'; import { PackageCustomizationsPanel } from '../studio-design/PackageCustomizationsPanel.js'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; import { @@ -2054,6 +2055,10 @@ export function PackagesPage() {

)} + {/* objectstack#38150 — the items of this environment that belong to no + package, counted per type, each a link to its "Loose" list. */} + + {importMsg && (
[] = [ + { name: 'loose_none', label: 'No package' }, + { name: 'loose_empty', label: 'Empty package', _packageId: '' }, + { name: 'loose_sentinel', label: 'Sentinel', _packageId: 'sys_metadata' }, + { name: 'packaged_flow', label: 'Packaged', _packageId: PKG }, + { name: 'pair_flow', label: 'Pair item', _packageId: `${PKG}.custom` }, + { name: 'overlay_flow', label: 'Overlay', _packageId: 'com.shipped' }, +]; +const RAW: unknown[] = ITEMS.map((item) => (item.name === 'overlay_flow' ? { item, source: 'overlay' } : item)); +const LOOSE = ['loose_none', 'loose_empty', 'loose_sentinel']; +const NOT_LOOSE = ['packaged_flow', 'pair_flow', 'overlay_flow']; + +const CLIENT = { + list: async (type: string) => (type === TYPE ? RAW : []), +}; +const ENTRY = { type: TYPE, label: 'Flow', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; + +let canAuthor = true; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: [ENTRY] }), +})); +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); +vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => canAuthor })); +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [{ id: PKG, name: 'Alpha', writable: true, namespace: 'alpha' }], +})); + +import { MetadataResourceListPage } from './ResourceListPage'; +import { MetadataAreaHostContext, type MetadataAreaHost } from './metadataAreaHost'; + +const ALL: MetadataAreaHost = { packageId: null, readOnly: false, basePath: '/studio/~all/metadata' }; +const ON_PKG: MetadataAreaHost = { packageId: PKG, readOnly: false, basePath: `/studio/${PKG}/metadata` }; + +/** Every move-in call the page made: its package and body. */ +let moveCalls: Array<{ url: string; body: any }> = []; + +beforeEach(() => { + canAuthor = true; + moveCalls = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url.includes('/move-in')) { + const body = JSON.parse(String(init?.body ?? '{}')); + moveCalls.push({ url, body }); + const moved = body.items.map((i: { type: string; name: string }) => ({ + type: i.type, + name: i.name, + states: ['active'], + environmentAddress: `_env/${i.name}`, + qualifiedAddress: `alpha/${i.name}`, + })); + return new Response( + JSON.stringify({ + success: true, + data: { outcome: body.dryRun ? 'would_move' : 'moved', targetPackageId: PKG, moved, refused: [] }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ); + } + return new Response(JSON.stringify({ object: 'x', records: [], hasMore: false }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + }), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function mount(host: MetadataAreaHost, search: string) { + return render( + + + + } /> + + + , + ); +} + +const shown = (names: readonly string[]) => names.filter((n) => screen.queryByText(n) !== null); + +describe('the cross-package list: "Loose" (objectstack#38150)', () => { + it('?source=loose lists exactly the package-less rows, never a .custom pair item or an overlay', async () => { + mount(ALL, '?source=loose'); + await waitFor(() => expect(shown(LOOSE)).toEqual(LOOSE)); + expect(shown(NOT_LOOSE)).toEqual([]); + }); + + it('control: with no source filter the list holds every row', async () => { + mount(ALL, ''); + await waitFor(() => expect(shown([...LOOSE, ...NOT_LOOSE])).toEqual([...LOOSE, ...NOT_LOOSE])); + expect(screen.queryByTestId('loose-selection-bar')).toBeNull(); + }); + + it('draws a select box per row and the selection bar for an author', async () => { + mount(ALL, '?source=loose'); + await screen.findByTestId('loose-selection-bar'); + for (const name of LOOSE) expect(await screen.findByTestId(`loose-select-${name}`)).toBeInTheDocument(); + expect(screen.getByTestId('loose-move-start')).toBeDisabled(); + }); + + it('control: a reader who may not author sees the loose rows, with no select box and no bar', async () => { + canAuthor = false; + mount(ALL, '?source=loose'); + await waitFor(() => expect(shown(LOOSE)).toEqual(LOOSE)); + expect(screen.queryByTestId('loose-selection-bar')).toBeNull(); + expect(screen.queryByTestId('loose-select-loose_none')).toBeNull(); + }); + + it('select all, Move into package…: the ask opens with nothing picked, the confirm reads a dry run, and Move moves the selection', async () => { + mount(ALL, '?source=loose'); + fireEvent.click(await screen.findByTestId('loose-select-all')); + expect(screen.getByTestId('loose-selected-count')).toHaveTextContent('3'); + fireEvent.click(screen.getByTestId('loose-move-start')); + + const ask = await screen.findByTestId('package-create-ask'); + const option = await within(ask).findByTestId(`package-create-ask-option-${PKG}`); + expect(option).toHaveAttribute('data-state', 'unchecked'); + expect(within(ask).getByText('Which package should the selected items move into?')).toBeInTheDocument(); + fireEvent.click(option); + fireEvent.click(within(ask).getByTestId('package-create-ask-continue')); + + const dialog = await screen.findByTestId('loose-move-dialog'); + await within(dialog).findByTestId('loose-move-items'); + expect(moveCalls).toHaveLength(1); + expect(moveCalls[0].url).toContain(`/packages/${encodeURIComponent(PKG)}/move-in`); + expect(moveCalls[0].body.dryRun).toBe(true); + expect(moveCalls[0].body.items.map((i: { name: string }) => i.name).sort()).toEqual([...LOOSE].sort()); + expect(moveCalls[0].body.items.every((i: { type: string }) => i.type === TYPE)).toBe(true); + expect(within(dialog).getByText('_env/loose_none')).toBeInTheDocument(); + expect(within(dialog).getByText('alpha/loose_none')).toBeInTheDocument(); + expect(within(dialog).getByTestId('loose-move-notes')).toBeInTheDocument(); + expect(within(dialog).getByText('Move into Alpha')).toBeInTheDocument(); + + fireEvent.click(within(dialog).getByTestId('loose-move-confirm')); + await waitFor(() => expect(moveCalls).toHaveLength(2)); + expect(moveCalls[1].body.dryRun).toBeUndefined(); + expect(moveCalls[1].body.items).toEqual(moveCalls[0].body.items); + await waitFor(() => expect(screen.queryByTestId('loose-move-dialog')).toBeNull()); + }); + + it('one row selected moves that row alone', async () => { + mount(ALL, '?source=loose'); + fireEvent.click(await screen.findByTestId('loose-select-loose_sentinel')); + expect(screen.getByTestId('loose-selected-count')).toHaveTextContent('1'); + fireEvent.click(screen.getByTestId('loose-move-start')); + const ask = await screen.findByTestId('package-create-ask'); + fireEvent.click(await within(ask).findByTestId(`package-create-ask-option-${PKG}`)); + fireEvent.click(within(ask).getByTestId('package-create-ask-continue')); + await screen.findByTestId('loose-move-items'); + expect(moveCalls[0].body.items).toEqual([{ type: TYPE, name: 'loose_sentinel' }]); + }); + + it("control: a package's own leg offers no \"Loose\": ?source=loose is ignored and draws no selection", async () => { + mount(ON_PKG, '?source=loose'); + await waitFor(() => expect(shown(['packaged_flow', 'pair_flow'])).toEqual(['packaged_flow', 'pair_flow'])); + expect(screen.queryByTestId('loose-selection-bar')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 8496b81b667..6188e1050da 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -13,7 +13,7 @@ import * as React from 'react'; import { Link, Navigate, useLocation, useNavigate, useNavigationType, useParams, useSearchParams } from 'react-router-dom'; -import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, X } from 'lucide-react'; +import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, PackagePlus, X } from 'lucide-react'; import { Button, NeutralIconTile, @@ -26,6 +26,7 @@ import { } from '@object-ui/components'; import { Input } from '@object-ui/components'; import { Badge } from '@object-ui/components'; +import { Checkbox } from '@object-ui/components'; import { toast } from 'sonner'; import { Select, @@ -44,6 +45,9 @@ import { navEntryTitle } from './navEntryTitle.js'; import { getIcon } from '../../utils/getIcon.js'; import { MetadataTypeActions } from './MetadataTypeActions.js'; import { PACKAGE_PICKED_STATE, usePackageCreateAsk } from './PackageCreateAsk.js'; +import { LooseMoveDialog } from './LooseMoveDialog.js'; +import { isLooseRow, looseItemKey, type LooseItem } from './looseMove.js'; +import { fetchPackages } from '../studio-design/packages-io.js'; import { useMetadataClient, useMetadataTypes, @@ -303,6 +307,14 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // names no package and never repairs one into the URL (`?package=X` would // move it onto X's leg, `areaLocationRedirect`); only create picks one. const allLeg = !!host && host.packageId === null && !envScope; + // objectstack#38150 (ADR-0084's amendment of 2026-11-26) — the cross-package + // leg offers a "Loose" source value: the rows bound to no package, read by + // `isPackageLessItem` exactly (never `classifyProvenance`, which files a + // `.custom` pair item and a served overlay as runtime too). Under it a person + // who may author selects loose items and moves them into a package. + const looseOffered = allLeg; + const [looseSelected, setLooseSelected] = React.useState>(() => new Map()); + const [looseMove, setLooseMove] = React.useState<{ target: { id: string; label: string }; items: LooseItem[] } | null>(null); // objectstack ADR-0146 D3 (#28568) — "On top, one surface": with a base open // in the area, its list holds the base's items and its paired // `.custom` package's items together, each item of the pair marked @@ -794,6 +806,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, q) => matchesQuery(row.item, q, searchableFields), source: sourceOf, + ...(looseOffered ? { loose: (row: ItemRow) => isLooseRow(row.item) } : {}), ...(showCustomizedFilter && !studioList ? { customized: (row: ItemRow) => markOf(row) !== null } : {}), // objectstack#37359 — a type whose rows name the object they serve is // narrowed to one object by `?targetObject=` (the import wizard's Manage). @@ -838,9 +851,10 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // Compute source + invalid counts for filter / header stats. const sourceCounts = React.useMemo(() => { - const c = { all: scopedItems.length, artifact: 0, runtime: 0 }; + const c = { all: scopedItems.length, artifact: 0, runtime: 0, loose: 0 }; for (const r of scopedItems) { c[sourceOf(r)]++; + if (isLooseRow(r.item)) c.loose++; } return c; }, [scopedItems, sourceOf]); @@ -917,6 +931,61 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string }; const refresh = () => setRefreshKey((k) => k + 1); + + // objectstack#38150 — under "Loose", a person who may author selects rows + // and moves them: the picker (#38149's ask, nothing pre-selected), then the + // confirm step, which reads the door's dry run (`LooseMoveDialog`). + const looseSelecting = looseOffered && sourceFilter === 'loose' && canAuthor && !walled; + const looseItemOf = React.useCallback( + (row: ItemRow): LooseItem => { + const member = bundleMemberOf(row.item, config.bundleMemberField); + return { type, name: String(row.item[primaryKey] ?? ''), ...(member ? { member } : {}) }; + }, + [type, primaryKey, config.bundleMemberField], + ); + // A selection belongs to one type's loose list; leaving it drops it. + React.useEffect(() => { + setLooseSelected(new Map()); + }, [type, looseSelecting]); + const looseRows = looseSelecting ? filtered : []; + const looseAllSelected = looseRows.length > 0 && looseRows.every((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const looseSomeSelected = !looseAllSelected && looseRows.some((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const toggleLoose = (item: LooseItem, on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + return next; + }); + }; + const toggleAllLoose = (on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + for (const row of looseRows) { + const item = looseItemOf(row); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + } + return next; + }); + }; + const startLooseMove = async () => { + const items = [...looseSelected.values()]; + if (items.length === 0) return; + const target = await askPackage({ + preselect: null, + title: tFormat('engine.looseMove.pick.title', locale, { count: items.length }), + description: t('engine.looseMove.pick.description', locale), + }); + if (!target) return; + // The confirm names the package as the ask listed it (the list read is the + // ask's own, already held); its id when the name cannot be read. + const label = await fetchPackages().then( + (entries) => entries.find((p) => p.id === target)?.name ?? target, + () => target, + ); + setLooseMove({ target: { id: target, label }, items }); + }; // objectstack#36896 — × / Back from a detail lands where the list was: the // position is kept per list address and restored once the rows are drawn. const scrollAnchorRef = useListScrollRestore( @@ -1020,12 +1089,14 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // its package, lock and diagnostics are looked up here, never carried on // the grid's row. const rowInfos = new Map(); + // objectstack#38150 — under "Loose" the table leads with the select column. + const leadColumns = looseSelecting ? 1 : 0; const gridRowsAll = filtered.map((row, i) => { const info = metadataRowInfo(row, i); rowInfos.set(info.id, info); const values: Record = { id: info.id }; shownColumns.forEach((c, ci) => { - values[metadataGridField(ci)] = gridValue(valueAtPath(row.item, c.key)); + values[metadataGridField(ci + leadColumns)] = gridValue(valueAtPath(row.item, c.key)); }); return values; }); @@ -1107,6 +1178,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string return seen; }; const gridColumns: MetadataGridColumn[] = [ + ...(looseSelecting ? [{ key: SELECT_COLUMN, label: t('engine.looseMove.col.select', locale), width: '64px' }] : []), ...shownColumns.map((c, ci) => ({ key: c.key, // The Studio list heads its label-first column by the identity it @@ -1332,8 +1404,25 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); }; const cellDraws: Record React.ReactNode> = {}; + if (looseSelecting) cellDraws[metadataGridField(0)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + const item = looseItemOf(info.row); + return ( + + toggleLoose(item, on === true)} + // The row's click opens the item; the box only selects it. + onClick={(e) => e.stopPropagation()} + aria-label={tFormat('engine.looseMove.select', locale, { name: info.name })} + data-testid={`loose-select-${info.name}`} + /> + + ); + }; shownColumns.forEach((c, ci) => { - cellDraws[metadataGridField(ci)] = (_value, rec) => { + cellDraws[metadataGridField(ci + leadColumns)] = (_value, rec) => { const info = rowInfoOf(rec); if (!info) return null; if (ci === 0) return firstCell(info, c); @@ -1490,6 +1579,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {tFormat('engine.list.sourceFilter.system', locale, { count: sourceCounts.artifact })} + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )}
@@ -1573,6 +1667,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {t('engine.list.allSources', locale)} ({sourceCounts.all}) {t('engine.list.source.artifact', locale)} ({sourceCounts.artifact}) {t('engine.list.source.runtime', locale)} ({sourceCounts.runtime}) + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )} {activation && ( @@ -1771,6 +1870,50 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string )} )} + {/* objectstack#38150 — the "Loose" list's selection bar: select every + row the filter shows, and move the selection into a package. */} + {!loading && looseSelecting && filtered.length > 0 && ( +
+ + + {tFormat('engine.looseMove.selected', locale, { count: looseSelected.size })} + + +
+ )} + setLooseMove(null)} + onMoved={(answer) => { + setLooseMove(null); + setLooseSelected(new Map()); + toast.success( + tFormat('engine.looseMove.moved', locale, { count: answer.moved.length, package: answer.targetPackageId }), + ); + refresh(); + }} + /> {!loading && filtered.length > 0 && ( // objectstack#36897 — every type's list is the same table: the // record list's `ObjectGrid`, fed the rows above in their order @@ -1937,6 +2080,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string /** The page columns after the list's own (`metadataListGrid.ts` keys none of them as a field). */ const CHANGED_COLUMN = '__changed'; +/** objectstack#38150 — the select column of the "Loose" list, first when drawn. */ +const SELECT_COLUMN = '__select'; +const EMPTY_LOOSE_ITEMS: readonly LooseItem[] = []; const SOURCE_COLUMN = '__source'; const CONTROLS_COLUMN = '__controls'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts new file mode 100644 index 00000000000..d102781ef55 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 PR-A2 — the "Loose" source value in the list's address + * state, and the console's call to the move door (`looseMove.ts`). Pinned, + * each with its control: + * + * - `source=loose` round-trips through the codec; an unknown value reads as + * every source; + * - under `loose` the list keeps the rows the reader's `loose` member keeps; + * with no such member the filter is not offered and keeps every row; + * - the move door's 422 refusal resolves as the door's own answer; any other + * failure throws with the server's sentence; + * - the references a refusal names are added once, the selection's own items + * never twice. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +// The source reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import { + applyListState, + decodeListState, + DEFAULT_LIST_STATE, + writeListState, + type ListRowReader, +} from './metadataListState'; +import { isLooseRow, moveLooseItems, referencesLeftBehind, withLooseItems } from './looseMove'; + +afterEach(() => vi.unstubAllGlobals()); + +interface Row { + item: Record; +} +const ROWS: Row[] = [ + { item: { name: 'a' } }, + { item: { name: 'b', _packageId: 'sys_metadata' } }, + { item: { name: 'c', _packageId: 'app.alpha' } }, + { item: { name: 'd', _packageId: 'app.alpha.custom' } }, +]; +const base: ListRowReader = { + name: (r) => String(r.item.name), + label: () => undefined, + matches: () => true, + source: (r) => (r.item._packageId === 'app.alpha' ? 'artifact' : 'runtime'), +}; + +describe('the list state: "loose" (objectstack#38150)', () => { + it('round-trips source=loose', () => { + const state = decodeListState(new URLSearchParams('source=loose')); + expect(state.source).toBe('loose'); + expect(writeListState(new URLSearchParams(), state).toString()).toBe('source=loose'); + }); + + it('control: an unknown source reads as every source', () => { + expect(decodeListState(new URLSearchParams('source=org')).source).toBe('all'); + }); + + it('keeps the rows the reader reads as loose, never a .custom pair row the runtime source would keep', () => { + const state = { ...DEFAULT_LIST_STATE, source: 'loose' as const }; + const kept = applyListState(ROWS, state, { ...base, loose: (r) => isLooseRow(r.item) }, 'en-US'); + expect(kept.map((r) => r.item.name)).toEqual(['a', 'b']); + const runtime = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'runtime' }, base, 'en-US'); + expect(runtime.map((r) => r.item.name)).toEqual(['a', 'b', 'd']); + }); + + it('control: with no loose member the filter is not offered and keeps every row', () => { + const kept = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'loose' }, base, 'en-US'); + expect(kept).toHaveLength(ROWS.length); + }); +}); + +function answer(status: number, payload: unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json' } })), + ); +} + +describe('the move door call (objectstack#38150)', () => { + const ITEMS = [{ type: 'flow', name: 'f1' }]; + + it('a 422 refusal resolves as the door answer, every item with its own code', async () => { + const refused = { + outcome: 'refused', + targetPackageId: 'com.probe.ghost', + moved: [], + refused: [{ type: 'flow', name: 'f1', code: 'WRITABLE_PACKAGE_REQUIRED', error: 'Not installed.' }], + }; + answer(422, { success: false, error: { code: 'WRITABLE_PACKAGE_REQUIRED', message: 'Not installed.', details: refused } }); + await expect(moveLooseItems('com.probe.ghost', ITEMS, true)).resolves.toEqual(refused); + }); + + it('control: a failure that is not an answer throws with the server sentence', async () => { + answer(403, { success: false, error: { code: 'FORBIDDEN', message: 'Moving loose metadata is refused here.' } }); + await expect(moveLooseItems('app.alpha', ITEMS, true)).rejects.toThrow('Moving loose metadata is refused here.'); + }); + + it('sends the selection, with dryRun only on a dry run', async () => { + const fetchMock = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify({ success: true, data: { outcome: 'moved', targetPackageId: 'app.alpha', moved: [], refused: [] } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + await moveLooseItems('app.alpha', ITEMS, true); + await moveLooseItems('app.alpha', ITEMS, false); + const bodies = fetchMock.mock.calls.map((c) => JSON.parse(String(c[1]?.body))); + expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v1/packages/app.alpha/move-in'); + expect(bodies).toEqual([{ items: ITEMS, dryRun: true }, { items: ITEMS }]); + }); +}); + +describe('the selection (objectstack#38150)', () => { + it('adds what a refusal names as left behind once, never an item the selection holds', () => { + const items = [{ type: 'flow', name: 'f1' }, { type: 'dataset', name: 'ds1' }]; + const more = referencesLeftBehind(items, [ + { type: 'flow', name: 'f1', code: 'REFERENCE_LEFT_BEHIND', error: 'x', references: [{ type: 'dataset', name: 'ds1' }, { type: 'dataset', name: 'ds2' }] }, + { type: 'flow', name: 'f2', code: 'REFERENCE_LEFT_BEHIND', error: 'y', references: [{ type: 'dataset', name: 'ds2' }] }, + ]); + expect(more).toEqual([{ type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, more)).toEqual([...items, { type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, items)).toEqual(items); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts new file mode 100644 index 00000000000..890b6a9caaf --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 — the console's half of the move door (ADR-0084's + * amendment of 2026-11-26, "Loose items stay where they are, and one door + * moves them"; ruling 7184753035, question 3): a selection of loose items, + * one, several or every loose item of a type, moved into one package through + * `POST /api/v1/packages/:id/move-in`. + * + * Invariants: + * - What is loose is `isPackageLessItem` on the served `_packageId`, the one + * reading; never `classifyProvenance`, which also files a `.custom` pair + * item and a served overlay as "runtime". + * - The answer is the server's. A refusal arrives as a 422 whose details are + * the whole answer (`outcome: 'refused'`, every item's own code and + * sentence), and is returned as that answer, never re-worded here. Any + * other failure throws. + * - The confirm step reads a dry run, which runs the judgement made before any + * door (loose, target, the object judges, the set) and writes nothing, so a + * save-door judge can still refuse the real move. The confirm says so. + */ + +import type { + MoveIntoPackageItem, + MoveIntoPackageRefusedItem, + MoveIntoPackageResponse, +} from '@objectstack/spec/api'; +import { PACKAGES_API, packagesApiJson } from './packageActions.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; + +export type LooseItem = MoveIntoPackageItem; + +/** One loose item's key in a selection: its type, name and bundle member. */ +export function looseItemKey(item: { type: string; name: string; member?: string | null }): string { + return `${item.type}\u0000${item.name}\u0000${item.member ?? ''}`; +} + +/** Whether a served row is loose: bound to no package (`isPackageLessItem`). */ +export function isLooseRow(item: { _packageId?: unknown } | null | undefined): boolean { + return isPackageLessItem(item); +} + +/** `items` with `more` added, each once, in the order first named. */ +export function withLooseItems(items: readonly LooseItem[], more: readonly LooseItem[]): LooseItem[] { + const seen = new Set(items.map(looseItemKey)); + const out = [...items]; + for (const item of more) { + const key = looseItemKey(item); + if (seen.has(key)) continue; + seen.add(key); + out.push(item); + } + return out; +} + +/** + * The loose items a refused answer names as left behind + * (`REFERENCE_LEFT_BEHIND`'s `references`) that the selection does not hold + * yet: what "add them and check again" adds. + */ +export function referencesLeftBehind(items: readonly LooseItem[], refused: readonly MoveIntoPackageRefusedItem[]): LooseItem[] { + const held = new Set(items.map(looseItemKey)); + const out: LooseItem[] = []; + for (const r of refused) { + for (const ref of r.references ?? []) { + const item = { type: ref.type, name: ref.name }; + const key = looseItemKey(item); + if (held.has(key)) continue; + held.add(key); + out.push(item); + } + } + return out; +} + +function isMoveAnswer(value: unknown): value is MoveIntoPackageResponse { + const v = value as Partial | null | undefined; + return ( + !!v && + typeof v === 'object' && + (v.outcome === 'moved' || v.outcome === 'would_move' || v.outcome === 'refused') && + Array.isArray(v.moved) && + Array.isArray(v.refused) + ); +} + +/** + * Ask the move door: `dryRun` answers what the move would do and writes + * nothing. Resolves with the door's answer, a refusal included; throws on any + * other failure (the gates' refusals, a fault), with the server's sentence. + */ +export async function moveLooseItems( + targetPackageId: string, + items: readonly LooseItem[], + dryRun: boolean, +): Promise { + try { + return await packagesApiJson( + `${PACKAGES_API}/${encodeURIComponent(targetPackageId)}/move-in`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ items, ...(dryRun ? { dryRun: true } : {}) }), + }, + ); + } catch (err) { + const details = (err as { details?: unknown } | null)?.details; + if (isMoveAnswer(details) && details.outcome === 'refused') return details; + throw err; + } +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts index 5c0386b4f3d..69a03b5b472 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts @@ -31,7 +31,11 @@ import { compareChangedAt } from './listChangedAt.js'; /** The search text. */ export const LIST_QUERY_PARAM = 'q'; -/** The source filter: `artifact` or `runtime`; absent = every source. */ +/** + * The source filter: `artifact`, `runtime` or `loose`; absent = every source. + * `loose` (objectstack#38150) is offered on the cross-package leg only: the + * rows bound to no package, read by `isPackageLessItem` exactly. + */ export const LIST_SOURCE_PARAM = 'source'; /** "Only customizations": `1`; absent = off. */ export const LIST_CUSTOMIZED_PARAM = 'customized'; @@ -57,7 +61,10 @@ export const LIST_STATE_PARAMS: readonly string[] = [ LIST_TARGET_OBJECT_PARAM, ]; -export type ListSourceFilter = 'all' | 'artifact' | 'runtime'; +export type ListSourceFilter = 'all' | 'artifact' | 'runtime' | 'loose'; + +/** The source filter's value for the loose rows (objectstack#38150). */ +export const LIST_LOOSE_SOURCE = 'loose'; export type ListStatusFilter = 'all' | 'active' | 'inactive'; /** @@ -127,7 +134,7 @@ export function decodeListState(params: URLSearchParams): MetadataListState { const targetObject = params.get(LIST_TARGET_OBJECT_PARAM)?.trim(); return { query: params.get(LIST_QUERY_PARAM) ?? '', - source: source === 'artifact' || source === 'runtime' ? source : 'all', + source: source === 'artifact' || source === 'runtime' || source === LIST_LOOSE_SOURCE ? source : 'all', customizedOnly: params.get(LIST_CUSTOMIZED_PARAM) === '1', status: status === 'active' || status === 'inactive' ? status : 'all', sort: decodeListSort(params.get(LIST_SORT_PARAM)), @@ -180,6 +187,12 @@ export interface ListRowReader { matches(row: R, query: string): boolean; /** Where the row comes from. */ source(row: R): 'artifact' | 'runtime'; + /** + * The "Loose" source value is offered (objectstack#38150, the cross-package + * leg): is the row bound to no package? Absent, `source=loose` is not + * offered and reads as every source, as an unoffered filter does. + */ + loose?: (row: R) => boolean; /** "Only customizations" is offered: is the row a customization? */ customized?: (row: R) => boolean; /** @@ -238,7 +251,9 @@ export function applyListState( const collator = collatorFor(locale); const kept = rows.filter((row) => { if (state.query && !read.matches(row, state.query)) return false; - if (state.source !== 'all' && read.source(row) !== state.source) return false; + if (state.source === LIST_LOOSE_SOURCE) { + if (read.loose && !read.loose(row)) return false; + } else if (state.source !== 'all' && read.source(row) !== state.source) return false; if (state.targetObject && read.targetObject && read.targetObject(row) !== state.targetObject) return false; if (state.customizedOnly && read.customized && !read.customized(row)) return false; if (state.status !== 'all' && read.active) { diff --git a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts index a6e41f4d4f7..172f911b891 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts @@ -34,6 +34,7 @@ import { holdersOfName, servedHolderOf } from './permission-set-holder.js'; import { usePackageCustomizations } from '../studio-design/CustomizationMark.js'; import { customizationMarkOf, customizationTotal } from '../studio-design/customizationMarks.js'; import { classifyProvenance } from './ResourceListPage.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; import { useListChangedAt } from './listChangedAt.js'; import { useInSetupApp } from '../../console/setupApp.js'; import { studioListSource, studioSourceKind } from './studioListSource.js'; @@ -101,6 +102,8 @@ export function useListOrderedNames(type: string): ListOrderedNames { const locale = useMetadataLocale(); const activePackage = envScope ? null : host ? host.packageId : urlPackage; const unscoped = envScope || activePackage === null; + // objectstack#38150 — the cross-package leg (`ResourceListPage`'s `allLeg`) offers "Loose". + const looseOffered = !!host && host.packageId === null && !envScope; const pairId = React.useMemo(() => { if (!host?.packageId || envScope) return null; const pair = customizationPackageId(host.packageId); @@ -185,6 +188,8 @@ export function useListOrderedNames(type: string): ListOrderedNames { label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, query) => matchesQuery(row.item, query, searchKey.split('\n')), source: (row) => (studioList ? studioListSource(studioSourceKind(row.source, markOf(row))) : row.source), + // objectstack#38150 — the list offers "Loose" on the area's cross-package leg alone. + ...(looseOffered ? { loose: (row: Row) => isPackageLessItem(row.item) } : {}), changedAt: (row) => changedAt?.[String(row.item[primaryKey] ?? '')], ...(customizedOffered && !studioList ? { customized: (row: Row) => markOf(row) !== null } : {}), ...(envScope && hasCatalogActivation(type) @@ -201,5 +206,5 @@ export function useListOrderedNames(type: string): ListOrderedNames { }; return { status: 'ready', names: orderedListNames(scoped, state, read, locale), fromList }; // Keyed on the config members read, never on `config`, rebuilt every render. - }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList]); + }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList, looseOffered]); } diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index fdd127b22c9..433960bee6d 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4107,6 +4107,36 @@ const STUDIO_EN: Record = { 'engine.packageAsk.systemApp.view': 'A shared view can’t be saved in a system app: it ships with the platform and has no package for your changes. Save it to My views instead, or add the view in one of your business apps.', 'engine.packageAsk.systemApp.report': 'A report can’t be saved in a system app: it ships with the platform and has no package for your changes. Create the report in one of your business apps instead.', 'engine.packageAsk.callerRefused': 'This can’t be saved in the app’s package for you: {reason}', + // objectstack#38150 — the move door's console half: the "Loose" list's selection, the confirm step, the Packages page banner. + 'engine.looseMove.col.select': 'Select', + 'engine.looseMove.select': 'Select {name}', + 'engine.looseMove.selectAll': 'Select all ({count})', + 'engine.looseMove.selected': 'Selected: {count}', + 'engine.looseMove.start': 'Move into package…', + 'engine.looseMove.pick.title': 'Which package should the selected items move into?', + 'engine.looseMove.pick.description': 'Loose items belong to no package. Moving puts each one in the package you choose, checked as a save into that package is. Choose one of your packages, or create a new one.', + 'engine.looseMove.confirm.title': 'Move into {package}', + 'engine.looseMove.confirm.description': 'Each item is checked as a save into the package is. The move is whole or nothing: if any item is refused, nothing moves.', + 'engine.looseMove.confirm.checking': 'Checking what the move would do…', + 'engine.looseMove.confirm.failed': 'The move could not be checked: {error}', + 'engine.looseMove.confirm.draftOnly': '(draft only)', + 'engine.looseMove.confirm.address': 'Address:', + 'engine.looseMove.confirm.aiFace': 'Name AI clients see:', + 'engine.looseMove.confirm.refused': 'These items can’t move, so nothing will move:', + 'engine.looseMove.confirm.refusedOnMove': 'The move was refused, and nothing moved:', + 'engine.looseMove.confirm.addReferences': 'Add the loose items they use and check again: {items}', + 'engine.looseMove.confirm.dryRunNote': 'This is a check, not the move. Some save checks run only when the move is made, so an item can still be refused then; if one is, nothing moves.', + 'engine.looseMove.confirm.undoNote': 'To undo the move later: reverting its package commit takes these items out of the package. It does not make them loose again.', + 'engine.looseMove.confirm.cancel': 'Cancel', + 'engine.looseMove.confirm.retry': 'Try again', + 'engine.looseMove.confirm.moving': 'Moving…', + 'engine.looseMove.confirm.move': 'Move', + 'engine.looseMove.moved': 'Moved into {package}: {count}.', + 'engine.looseItems.banner': '{count} items belong to no package', + 'engine.looseItems.bannerOne': '1 item belongs to no package', + 'engine.looseItems.bannerHint': 'Open a type to select its loose items and move them into a package.', + 'engine.looseItems.typeCount': '{type} ({count})', + 'engine.looseItems.unread': 'These types could not be counted: {types}', 'engine.list.refresh': 'Refresh', 'engine.list.search': 'Search name, label, description…', 'engine.list.empty': 'No items yet.', @@ -4144,6 +4174,7 @@ const STUDIO_EN: Record = { 'engine.list.sourceFilter.all': 'All sources ({count})', 'engine.list.sourceFilter.changed': 'Modified and new ({count})', 'engine.list.sourceFilter.system': 'System-shipped ({count})', + 'engine.list.sourceFilter.loose': 'Loose ({count})', 'engine.list.col.name': 'Name', 'engine.list.col.label': 'Label', 'engine.list.col.source': 'Source', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 797a94b4075..84a37c31e5f 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3637,6 +3637,36 @@ const STUDIO_ZH: Record = { 'engine.packageAsk.systemApp.view': '系统应用里不能保存共享视图:系统应用随平台提供,没有存放你改动的软件包。请改存到「我的视图」,或者到你的业务应用里添加这个视图。', 'engine.packageAsk.systemApp.report': '系统应用里不能保存报表:系统应用随平台提供,没有存放你改动的软件包。请到你的业务应用里新建这份报表。', 'engine.packageAsk.callerRefused': '无法替你存进这个应用的软件包:{reason}', + // objectstack#38150 — the move door's console half: the "Loose" list's selection, the confirm step, the Packages page banner. + 'engine.looseMove.col.select': '选择', + 'engine.looseMove.select': '选择 {name}', + 'engine.looseMove.selectAll': '全选({count})', + 'engine.looseMove.selected': '已选:{count}', + 'engine.looseMove.start': '移入软件包…', + 'engine.looseMove.pick.title': '选中的项移入哪个软件包?', + 'engine.looseMove.pick.description': '散落项不属于任何软件包。移入后,每一项都放进你选的软件包,并像保存进这个软件包一样接受检查。请选择一个软件包,或新建一个。', + 'engine.looseMove.confirm.title': '移入 {package}', + 'engine.looseMove.confirm.description': '每一项都像保存进这个软件包一样接受检查。移入是整批的:只要有一项被拒,就一项都不移。', + 'engine.looseMove.confirm.checking': '正在检查移入后会怎样…', + 'engine.looseMove.confirm.failed': '无法检查这次移入:{error}', + 'engine.looseMove.confirm.draftOnly': '(仅草稿)', + 'engine.looseMove.confirm.address': '地址:', + 'engine.looseMove.confirm.aiFace': 'AI 看到的名称:', + 'engine.looseMove.confirm.refused': '以下各项不能移入,所以这次一项都不会移:', + 'engine.looseMove.confirm.refusedOnMove': '移入被拒,一项都没有移:', + 'engine.looseMove.confirm.addReferences': '把它们用到的散落项一起加上,再检查一次:{items}', + 'engine.looseMove.confirm.dryRunNote': '这只是检查,还没有移入。有些保存检查要真正移入时才做,所以那时某一项仍可能被拒;一旦被拒,一项都不移。', + 'engine.looseMove.confirm.undoNote': '以后要撤销:回退这次移入的软件包提交,会把这些项从软件包里删掉,不会让它们重新变回散落项。', + 'engine.looseMove.confirm.cancel': '取消', + 'engine.looseMove.confirm.retry': '重试', + 'engine.looseMove.confirm.moving': '正在移入…', + 'engine.looseMove.confirm.move': '移入', + 'engine.looseMove.moved': '已移入 {package}:{count} 项。', + 'engine.looseItems.banner': '有 {count} 个散落项,不属于任何软件包', + 'engine.looseItems.bannerOne': '有 1 个散落项,不属于任何软件包', + 'engine.looseItems.bannerHint': '打开一种类型,勾选它的散落项,再移入软件包。', + 'engine.looseItems.typeCount': '{type}({count})', + 'engine.looseItems.unread': '以下类型没能计数:{types}', 'engine.list.refresh': '刷新', 'engine.list.search': '搜索名称、显示名或描述…', 'engine.list.empty': '暂无数据。', @@ -3673,6 +3703,7 @@ const STUDIO_ZH: Record = { 'engine.list.sourceFilter.all': '全部来源({count})', 'engine.list.sourceFilter.changed': '已修改和新建({count})', 'engine.list.sourceFilter.system': '系统自带({count})', + 'engine.list.sourceFilter.loose': '散落项({count})', 'engine.list.col.name': '名称', 'engine.list.col.label': '显示名', 'engine.list.col.source': '来源', From dccf836a866b953234fd473e490147d3cc8847fa Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:16:43 +0000 Subject: [PATCH 041/178] feat(pm): seat readers accept LANE@ACCOUNT beside LANE#N (readers first, no writer switches) (#38472) 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)_ Part of #38415 Clause-②: no Metadata-protocol: none Rule-change: ruled Ruling-ref: 7249169754 · Q3 A · 「同意,立卡派发」 answering 「先改读法再切签名,旧认领不重发,1 号空座贴关掉」 · the maintainer, area o5-fleet thread, 2026-11-29T00:37:31Z ## 维护者速读 - 用户能看到什么变化:用户无感。车队的工具现在同时读得懂「车道#编号」和「车道@账号」两种座位写法,签名和座位贴一个字都没换。 - 为什么做:这是「座位按账号命名」切换的第一步,按你定的顺序先让读的一方两种都认,再切签名。 - 出错会怎样:最坏是某个工具把一条认领算到别的座位头上;每个改过的工具都加了对照用例,旧编号认领仍算原编号座位,账号甲的签名不会算成账号乙的座位。撤回这一个改动即可复原。 - 要你做什么:这是规则文件改动,请你亲自看过后合并。 This is the first of the two pull requests the card produces: readers accept both forms. The second one carries the rule text and the writers, and the lane-by-lane switch follows it. This half leaves the card open. **Round 2** (head `c299a96dae`, after the contract review of `14a32e86a5`, which asked for two changes on this branch): - S1: the `Request: contract-review` knock check in `scripts/pm/post-stamped.mjs` (`triageContractReviewKnock`) judged its target by a numbered-seat prefix, so a knock to `triage@ACCOUNT` passed while the same knock to `triage#1` was refused. It now judges the lane word before either mark, through the shared `SEAT_MARK_SOURCE`. Three rows added. - S2: the stale-seat-post finding in `scripts/pm/check-half-states.mjs` (`h38SeatPostStale`) printed an account mark loose, and the patrol writes that row into its anchor issue. It now prints the mark in a code span; a numbered seat prints bare as before. The row that pinned the loose spelling is changed, and a control row is added. - The half-states self-test now also pins the cross-account guard of `readSignatureLine` itself (the first review's note). - `origin/main` is merged again (`d89d3e2356`). ## What changes A seat id now reads in two forms: `LANE#N` (a numbered seat, as before) and `LANE@ACCOUNT` (a seat named by its account). No writer default and no signature changes: every writer still prints `LANE#N`, and a writer that takes the seat as input accepts either. **The model.** A seat is its lane AND its mark. The mark is the number for `#N`, or the lower-cased string `@account` for `@ACCOUNT`; two marks name one seat only when they are equal. `seatMark` and `seatIdOf` in `scripts/pm/check-half-states.mjs` are the one source, beside the existing `SEAT_SIGNATURE_LINE` and `readSignatureLine`. - A `#N` record keeps reading as that numbered seat, whoever signed it. It is never moved to the account seat of the login on it. - A `LANE@ACCOUNT` record is that account's seat. It is not account Y's seat of the same lane, and not any numbered seat's. - The signature line stays three parts: `LANE@ACCOUNT · ACCOUNT · SESSION`. It is a signature only when the seat's account is the signing account (case folded). Under another account it is a near miss: readers return nothing, and the writers refuse it before the write and say why. **Readers and writers changed** (the card's eleven, then the further ones found by grep): | File | What reads the second form | | --- | --- | | `scripts/pm/check-half-states.mjs` | the signature grammar, `seatMark`, `seatIdOf`, the seat post title (`seatTitleAccount`, `seatLane`, `seatIntakeKeys`), the claim's `Seat:` line (`claimSeatNumber`), the writers' near-miss refusal, the stale-seat-post finding's printed mark (round 2) | | `scripts/pm/mailbox-open.mjs` | `seatKey` (the `To:` line, doorbell and mailbox key), `--seat`, `mailboxOwner` | | `scripts/pm/record-recognisers.mjs` | hand-off targets, `readSeat`, `Notify: seat-online`, the session roster keys | | `scripts/pm/card-pick.mjs` | `--seat`, the claim reason | | `scripts/pm/round-open.mjs` | `--seat`, the post title, the claim's seat, the three readings | | `scripts/pm/fleet-roster.mjs` | the seat row, the signed trace, the mailbox column, review claims, epic seats, the rendered cell | | `scripts/pm/fleet-write/ops.mjs` | the advisory note's signature shape, the landing seat's printed name | | `scripts/pm/fleet-write/dispatch.mjs` | the advisory note's first line, the trailer near-miss text | | `scripts/pm/post-stamped.mjs` | the contract-review knock check's triage target (round 2) | | `scripts/pm/check-owed-reviews.mjs` (found by grep) | the record's signer, the L2 seat roster names, the L2 test on a hand-off target | | `scripts/pm/check-handover.mjs` (found by grep) | the seat a held claim names | Rows only, no code change (the reader was already correct through the shared grammar): `scripts/pm/check-prior-rulings.mjs`, `scripts/pm/issue-create.mjs`, `scripts/pm/fleet-write/validate.mjs`, `scripts/pm/fleet-write/execute.mjs`. Read and left untouched: `topic-board.mjs`, `l1-face.mjs`, `label-write.mjs`. **One data-model change, in `fleet-roster.mjs`.** A row's `seat` was always a number. It is now a mark: a number, or `@account`. Rows sort the numbered seats first, then the account seats by name. The rendered cell prints an account mark in a code span, because a loose at-sign login in an issue body becomes a mention. **Three choices a reviewer should see.** 1. The mailbox slug of an account seat is the lane slug, an underscore, the account, then `-0`. A login carries no underscore and no numbered slug ends in `-0`, so the slugs stay one to one. It fits the relay's branch shape. 2. In a seat post title, `LANE@ACCOUNT` with no space before the at-sign is an account seat. With a space it is still the sibling-board suffix, as every measured post has it. 3. A claim's `Seat:` line naming an account seat reads as `@account`. It is read before the number rule, so an epic seat named by account is not seat N of its epic. **Rule text** (two files, readings only): - `.claude/skills/pm-dispatch/references/seat-post-protocol.md`: the signature line names `LANE@ACCOUNT` as a reading (+33 bytes). Paid in the same file by removing the aside in the handover checklist's heading (-36 bytes). 7719 to 7716 bytes; the ratchet row drops 7720 to 7716. - `.claude/agents/os-dev.md`: the trailer line names `LANE@ACCOUNT` as a reading (+30 bytes). Paid in the same file by removing the lock entry's second copy of the slot rule, which the queueing clause states in full (-31 bytes). 33492 to 33491 bytes; the ratchet row drops 33492 to 33491. No ceiling is raised. The seat-per-account rule, the retirement of takeover, the review-lane merge and the readings the ruling record lists as not ruled word for word are not in this text. ## Tests Every touched script that has a self-test gained rows for both forms, a control row (a `#N` claim by a vacant seat still reads as that seat's, not as the new account's) and a row showing that a `LANE@ACCOUNT` signature by account X is not read as account Y's seat in the same lane. Battery floors rise with the rows.
Rows added, per file | File | Rows | Result at c299a96dae | | --- | --- | --- | | `scripts/pm/check-half-states.mjs` | 16 | exit 0 · 5443 cases pass | | `scripts/pm/mailbox-open.mjs` | 9 | exit 0 · 102 cases in 11 batteries pass | | `scripts/pm/record-recognisers.mjs` | 16 | exit 0 · 483 cases pass | | `scripts/pm/card-pick.mjs` | 4 | exit 0 · 67 cases pass | | `scripts/pm/round-open.mjs` | 5 | exit 0 · 46 cases pass | | `scripts/pm/fleet-roster.mjs` | 10 | exit 0 · 160 cases in 13 batteries pass | | `scripts/pm/fleet-write/dispatch.mjs` | 4 | exit 0 · 439 cases pass | | `scripts/pm/fleet-write/validate.mjs` | 1 | exit 0 · 497 cases pass | | `scripts/pm/fleet-write/execute.mjs` | 2 | exit 0 · 476 cases pass | | `scripts/pm/check-owed-reviews.mjs` | 3 | exit 0 · 99 cases pass | | `scripts/pm/check-handover.mjs` | 1 | exit 0 · 115 cases pass | | `scripts/pm/check-prior-rulings.mjs` | 1 | exit 0 · 186 cases pass | | `scripts/pm/issue-create.mjs` | 2 | exit 0 · 67 cases pass | | `scripts/pm/post-stamped.mjs` | 6 | exit 0 · 828 cases pass | `fleet-write/ops.mjs` has no self-test of its own; its shapes are exercised by the `dispatch`, `validate` and `execute` rows.
No test file names an edited script as its subject (one `ui/scripts` census test spells a path as a fixture string). Scripts are not ablated. ## Acceptance notes - Not touched, by the card's order: live seat posts, the vacant seat 1 post, any claim on any card. - After a post is renamed, the seat's own earlier `#N` claims keep reading as the numbered seat's. For example `card-pick --seat repo:objectstack@os-project-manager` reports a card claimed by `repo:objectstack#5` as another seat's. The ruling record lists the attribution of old records to the account in their signature as not ruled word for word, so this pull request does not do it. The second pull request or the switch has to settle it before a lane switches. - Only the three-part signature is read. If the second pull request wants a shorter line, the readers need one more lap first. - How GitHub renders a word followed by an at-sign login in a comment was not measured. ## Verification Head `c299a96dae`.
Local gates `node scripts/pm/dispatch-gates.mjs --commands` derived 78 commands at this head (merge base `d89d3e235`). All ran in one batch under the verify lock, after `pnpm exec turbo run build --filter=@objectstack/formula --filter=@objectstack/lint --concurrency=2` in the same hold (exit 0). 77 exited 0. 1 is NOT MEASURED: `pnpm check:i18n-coverage` exited 3 (PREREQUISITE NOT MET). Its scan half lints the example apps through the built CLI and needs the build closure of the CLI and every example, which was not built on this box. Its self-test half ran and passed, and that is the half this diff can reach (the gate matches these paths only through an import chain into `check-half-states.mjs`). CI runs the scan; on the first head its lint jobs concluded success. Lock verdict: `VERDICT command-exit 0 · held the lock 1296s (21m36s) · waited 398s (6m38s)`. `node scripts/pm/dispatch-gates.mjs --ran`: `78 derived famil(ies) accounted for — 77 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3)`, exit 0. `node scripts/check-nul-bytes.mjs`: exit 0. `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0`. ``` 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-issue-citations.mjs :: exit 0 node scripts/check-platform-checklist-watchdog.mjs :: exit 0 node scripts/check-platform-checklist-watchdog.mjs --self-test :: exit 0 node scripts/check-release-section-coverage.mjs :: exit 0 node scripts/check-release-section-coverage.mjs --strict :: 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-skills-token-ratchet.mjs :: exit 0 node scripts/check-skills-token-ratchet.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/ci/scheduled-full-run-card.mjs --self-test :: exit 0 node scripts/ci/scheduled-full-run.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/bare-root-worklist.mjs --self-test :: exit 0 node scripts/pm/board-snapshot.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/check-harness-current.mjs --self-test :: exit 0 node scripts/pm/sweep-closed-cards.mjs --self-test :: exit 0 node scripts/render-release-coverage-anchor.mjs --self-test :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:agent-model-declared :: 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:closing-target-claim :: exit 0 pnpm check:commit-card-trailers :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:declared-population-live :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:entry-guard :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:i18n-coverage :: exit 3 pnpm check:issue-citations :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:parse-guard :: exit 0 pnpm check:partof-closing-keyword :: exit 0 pnpm check:platform-checklist :: exit 0 pnpm check:pm-board-snapshot :: exit 0 pnpm check:pm-close-cards :: exit 0 pnpm check:pm-dispatch-gates :: exit 0 pnpm check:pm-expected-skips :: exit 0 pnpm check:pm-fleet-token :: exit 0 pnpm check:pm-fleet-write-dispatch :: exit 0 pnpm check:pm-fleet-write-execute :: exit 0 pnpm check:pm-fleet-write-validate :: exit 0 pnpm check:pm-governed-merges :: exit 0 pnpm check:pm-governed-prose :: exit 0 pnpm check:pm-half-states :: exit 0 pnpm check:pm-issue-create :: exit 0 pnpm check:pm-issue-transfer :: exit 0 pnpm check:pm-label-write :: exit 0 pnpm check:pm-post-stamped :: exit 0 pnpm check:pm-prior-rulings :: exit 0 pnpm check:pm-record-recognisers :: exit 0 pnpm check:pm-settings-deny-roster :: exit 0 pnpm check:pm-skill-id-lint :: exit 0 pnpm check:pm-skill-ratchet :: exit 0 pnpm check:pm-write-pace :: 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:single-claim-paths :: exit 0 pnpm check:skill-frame-sync :: exit 0 pnpm check:watch-hint-literal :: exit 0 ```
Two-minute check: `node scripts/pm/record-recognisers.mjs --self-test` prints a pass line, and its battery named for the seat mark holds the both-forms, control and cross-account rows. Read first, by risk: 1. `scripts/pm/check-half-states.mjs`: `readSignatureLine` and `claimSeatNumber` (every other reader stands on these two). 2. `scripts/pm/mailbox-open.mjs`: `seatKey` (the slug of an account seat). 3. `scripts/pm/fleet-roster.mjs`: `parseSeat` and `bySeatMark` (the row's seat is now a mark). --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_ --------- Co-authored-by: Claude --- .claude/agents/os-dev.md | 4 +- .../references/seat-post-protocol.md | 4 +- scripts/pm/card-pick.mjs | 24 +++- scripts/pm/check-half-states.mjs | 124 +++++++++++++++--- scripts/pm/check-handover.mjs | 7 +- scripts/pm/check-owed-reviews.mjs | 20 ++- scripts/pm/check-prior-rulings.mjs | 5 +- scripts/pm/check-skill-line-ratchet.mjs | 4 +- scripts/pm/fleet-roster.mjs | 85 ++++++++---- scripts/pm/fleet-write/dispatch.mjs | 19 ++- scripts/pm/fleet-write/execute.mjs | 7 +- scripts/pm/fleet-write/ops.mjs | 17 ++- scripts/pm/fleet-write/validate.mjs | 4 +- scripts/pm/issue-create.mjs | 7 +- scripts/pm/mailbox-open.mjs | 39 +++++- scripts/pm/post-stamped.mjs | 23 +++- scripts/pm/record-recognisers.mjs | 60 +++++++-- scripts/pm/round-open.mjs | 41 ++++-- 18 files changed, 387 insertions(+), 107 deletions(-) diff --git a/.claude/agents/os-dev.md b/.claude/agents/os-dev.md index 4c1071ee066..566257b11f3 100644 --- a/.claude/agents/os-dev.md +++ b/.claude/agents/os-dev.md @@ -85,7 +85,7 @@ model: opus 1. **重活串行,共享验证锁只有一个入口。** 每次 build/test 都从这里走。 - `bash scripts/pm/os-verify-lock.sh -c ''`(或 `-- `);⛔ 永不手搓 `flock`/lockfile。 - - 一次前台调用领全部等待预算,阻塞到拿锁或 99;⛔ 不轮询重试,恒设 `OS_VERIFY_LOCK_SLOT`。 + - 一次前台调用领全部等待预算,阻塞到拿锁或 99;⛔ 不轮询重试。 - 它不保证机器空闲:`check:*` 门禁、install、dev server 不走它,与持锁同核并跑。 - 超前台上限者(`check:pm-dispatch-gates`、全量 dogfood):`nohup … > LOG 2>&1 &` 后 `tail --pid`。 - 锁下墙钟绝对值是共享盒读数;只包命令本身,不包你的阅读与判断。 @@ -270,7 +270,7 @@ model: opus - 全文 ⛔ 不出现 HTML 注释:sanitizer 落库后吃短尖括号片段,连反引号里的也吃。 - 例外二:harness 自写 PR 正文首行归属注释原样留、只报,`Fixes #` 紧随;派发令要求才独占 - 末个非空行写 ``(`PR_BODY_TRAILER_SHAPE`);其余 dev 自写仍禁。 + 末个非空行写 ``(`PR_BODY_TRAILER_SHAPE`,读方亦认 `LANE@ACCOUNT`);其余 dev 自写仍禁。 - 凡要上 GitHub 的文本,尖括号形状片段一律改占位词拼写(`FIELD`、`IDENT.MEMBER` 一类)。 - 各派发模式(`mode:subagent`、`mode:cloud`、`mode:thread`)下 GitHub 都是报告的权威源。 - 评论、PR 正文都读回到尾:只认首行标记保不住正文,sanitizer 可从首个 tag 形片段吃到尾。 diff --git a/.claude/skills/pm-dispatch/references/seat-post-protocol.md b/.claude/skills/pm-dispatch/references/seat-post-protocol.md index 071e661bca2..0cefb947285 100644 --- a/.claude/skills/pm-dispatch/references/seat-post-protocol.md +++ b/.claude/skills/pm-dispatch/references/seat-post-protocol.md @@ -26,7 +26,7 @@ - 会话座位查最新产出评论的时间戳;回收 = 改正文 + 审计评论。 - 可跑读法:本车道 `pm:dispatched` 卡按 `updated_at` 降序一搜,或读最新认领评论。 - 写侧刷新三时刻:派发、收班、暂停或交接前;时间戳恒取自 `post-stamped.mjs`。 -- 帖与卡正文首行恒为署名 `LANE#N · ACCOUNT · SESSION`;缺即写工具拒发(`post-stamped.mjs` 头注)。 +- 帖与卡正文首行恒为署名 `LANE#N · ACCOUNT · SESSION`(读方亦认 `LANE@ACCOUNT`);缺即写工具拒发(`post-stamped.mjs` 头注)。 - PR 正文末非空行署 ``,整篇经 `dispatch.mjs` 的 `issue_patch`。 - 刷新前回执敲门;`--body` 拦截:评论晚于末次戳 ⇒ `--ack-through=ID`;空座欠账无卡号 ⇒ 拒写。 - 耐久状态只住正文或以 App 写入;正文守中继上限 60,000 字节,超大贴由半状态巡查浮出。 @@ -43,7 +43,7 @@ - 巡查改绑 = 继任自建自绑并删旧,`Patrol:` 换号;前任笔迹归继任不自退,旧会话即结束。 - 上下文读数:`get_session`(无参)`external_metadata.context_usage.used_tokens`;读不到或 0 归协调者读。 -## 交接收尾清单(漏一步就是留残缺现场) +## 交接收尾清单 1. 立即停止新派发。 2. 认领卡落地,或同笔 `Release:`+`Resume-from:`+清 assignee 交回 `pm:queue`;`needs_decision` 进决策箱。 diff --git a/scripts/pm/card-pick.mjs b/scripts/pm/card-pick.mjs index 98613497bad..c752c9f6aca 100644 --- a/scripts/pm/card-pick.mjs +++ b/scripts/pm/card-pick.mjs @@ -105,6 +105,8 @@ import { labelNames, markerMatches, readSignatureLine, + seatIdOf, + seatMark, subIssueParentPath, } from './check-half-states.mjs'; import { ghApi, readAllPages } from './gh-pages.mjs'; @@ -181,13 +183,14 @@ export function parseOrder(text) { /** * `--seat LANE#N` parsed by the seat signature's own grammar (`SEAT_SIGNATURE_LINE`, borrowed, never re-spelled), so - * every lane a signature can carry is accepted, an epic seat's `epic:#N#1` included. Pure. + * every lane a signature can carry is accepted, an epic seat's `epic:#N#1` included — and both seat marks: + * `LANE@ACCOUNT` names the seat by its account (`seat` is then `@account`, `seatMark`'s reading). Pure. */ export function parseSeat(text) { const v = String(text ?? ''); if (/\s/.test(v)) return null; const m = SEAT_SIGNATURE_LINE.exec(`${v}${SEAT_SIGNATURE_SEPARATOR}seat${SEAT_SIGNATURE_SEPARATOR}session_parseseat`); - return m ? { lane: m[1], seat: Number(m[2]), name: `${m[1]}#${m[2]}` } : null; + return m ? { lane: m[1], seat: seatMark(m[2]), name: seatIdOf(m[1], seatMark(m[2])) } : null; } const GRADE_NAMES = Object.freeze(['p0', 'p1', 'p2', 'p3']); @@ -309,7 +312,8 @@ export function claimReason(comments, seat) { if (own === null || own.kind === 'release') return null; const sig = own.signature; if (!sig) return 'Claim: (unsigned) — another session holds it unless the claim names you'; - const who = `${sig.lane}#${sig.seat}`; + // Lane AND mark: a `#N` claim is that numbered seat's, an `@ACCOUNT` claim that account's — never each other's. + const who = seatIdOf(sig.lane, sig.seat); if (seat && seat.name === who) return `Claim: by this seat (${who}) — already yours, not a new pick`; return `Claim: by ${who}`; } @@ -588,7 +592,7 @@ export function fixtureGet(fixture, repo) { const USAGE = [ 'card-pick — which ready cards a seat takes next (read-only; the claim re-read still arbitrates).', '', - ' node scripts/pm/card-pick.mjs --order epic:#N,area:NAME,… [--seat LANE#N] [--repo OWNER/NAME]', + ' node scripts/pm/card-pick.mjs --order epic:#N,area:NAME,… [--seat LANE#N|LANE@ACCOUNT] [--repo OWNER/NAME]', ' [--limit N] [--why] [--json] [--fixture FILE] [--now ISO]', ' node scripts/pm/card-pick.mjs --self-test', '', @@ -620,7 +624,7 @@ export function parseArgs(argv) { } else if (flag === '--seat') { const v = take(); opts.seat = parseSeat(v); - if (!opts.seat) return { error: `--seat must be LANE#N (a seat signature's first part), got \`${v}\`` }; + if (!opts.seat) return { error: `--seat must be LANE#N or LANE@ACCOUNT (a seat signature's first part), got \`${v}\`` }; } else if (flag === '--limit') { const v = take(); if (!/^[1-9][0-9]*$/.test(String(v ?? ''))) return { error: `--limit must be a positive integer, got \`${v}\`` }; @@ -682,9 +686,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ "p3: an area's close-out after every p2 of that item; an epic's children keep their child order": 7, 'Blocked-by: an open target holds, a closed-unmerged PR holds, a merged PR and a closed issue release, cross-repo is read': 7, 'the same-grade order and the epic child order': 5, - 'the candidate definition: label reasons, claims and the triage audit': 9, + 'the candidate definition: label reasons, claims and the triage audit': 12, 'the walk: every page, the count checked, the limit and --why': 11, - 'the CLI: usage, exits and the footer': 13, + 'the CLI: usage, exits and the footer': 14, }); const SELF_TEST_BATTERY_FLOOR = 8; const UNATTRIBUTED_BATTERY = '(unattributed)'; @@ -859,6 +863,11 @@ export async function selfTest() { t('⭐ another seat\'s Claim: excludes', claimReason([claim(SIG)], parseSeat('repo:objectstack#5')), 'Claim: by repo:objectstack#1'); t('this seat\'s own Claim: reads as already yours', claimReason([claim(SIG)], parseSeat('repo:objectstack#1')), 'Claim: by this seat (repo:objectstack#1) — already yours, not a new pick'); t('a Release: after the Claim: frees the card', claimReason([claim(SIG), { body: 'Release: session gone · back to queue', created_at: '2026-11-18T05:00:00Z' }], null), null); + // The second seat mark (ruling record 7249169754): a seat is its lane AND its mark, `#N` or `@ACCOUNT`. + const ACC = 'repo:objectstack@os-bill · os-bill · session_01ABCDEFGH'; + t('⭐ a claim signed `LANE@ACCOUNT` reads as that account\'s seat: already yours for it, another seat\'s for everyone else', [claimReason([claim(ACC)], parseSeat('repo:objectstack@os-bill')), claimReason([claim(ACC)], parseSeat('repo:objectstack@OS-Bill')), claimReason([claim(ACC)], parseSeat('repo:objectstack#5'))], ['Claim: by this seat (repo:objectstack@os-bill) — already yours, not a new pick', 'Claim: by this seat (repo:objectstack@os-bill) — already yours, not a new pick', 'Claim: by repo:objectstack@os-bill']); + t('⛔ account X\'s claim is not read as account Y\'s seat of the same lane — and X signing Y\'s seat is no signature at all', [claimReason([claim(ACC)], parseSeat('repo:objectstack@os-warren')), claimReason([claim('repo:objectstack@os-bill · os-warren · session_01ABCDEFGH')], parseSeat('repo:objectstack@os-bill'))], ['Claim: by repo:objectstack@os-bill', 'Claim: (unsigned) — another session holds it unless the claim names you']); + t('⭐ CONTROL — a `#1` claim by a vacant seat still reads as seat 1\'s: ⛔ not as the account seat of the login on it, nor of any other account', [claimReason([claim(SIG)], parseSeat('repo:objectstack@os-warren')), claimReason([claim(SIG)], parseSeat('repo:objectstack@os-bill')), claimReason([claim(SIG)], parseSeat('repo:objectstack#1'))], ['Claim: by repo:objectstack#1', 'Claim: by repo:objectstack#1', 'Claim: by this seat (repo:objectstack#1) — already yours, not a new pick']); const fleetCard = card(['area:ux', 'priority:p2'], { user: APP }); const r = await run({ issues: [fleetCard], comments: { [fleetCard.number]: [{ body: 'just a note' }] } }); t('⭐ a fleet card with no triage audit record is not a candidate', r.others[0]?.reasons, ['no triage audit — knock triage']); @@ -902,6 +911,7 @@ export async function selfTest() { t('both spellings of an option are read', [parseArgs(['--order=area:ux', '--limit=2']).opts.limit, parseArgs(['--order', 'epic:#7']).opts.order[0].number], [2, 7]); t('--order as the last argument with no value is a usage error; --order "" is the p0/p1-only order', [Boolean(parseArgs(['--order']).error), parseArgs(['--order', '']).opts?.order], [true, []]); t('--seat reads every lane a seat signature carries, an epic seat\'s epic:#N included', [parseSeat('epic:#35205#1')?.name, parseSeat('domain:ui#2')?.name, parseSeat('area:ux#1'), parseSeat('repo:objectstack#5 x')], ['epic:#35205#1', 'domain:ui#2', null, null]); + t('--seat reads both seat marks: `LANE@ACCOUNT` names the seat by its account, lower-cased, an epic seat\'s included; `LANE@` and both marks at once are refused', [parseSeat('repo:objectstack@OS-Bill'), parseSeat('epic:#35205@os-bill')?.name, parseSeat('repo:objectstack#5')?.seat, parseSeat('repo:objectstack@'), parseSeat('repo:objectstack#5@os-bill'), Boolean(parseArgs(['--order', 'area:ux', '--seat', 'repo:objectstack@os-bill']).opts?.seat), parseArgs(['--order', 'area:ux', '--seat', 'os-bill']).error?.includes('LANE#N or LANE@ACCOUNT')], [{ lane: 'repo:objectstack', seat: '@os-bill', name: 'repo:objectstack@os-bill' }, 'epic:#35205@os-bill', 5, null, null, true, true]); t('⭐ the footer names lane ownership and the sub-epic an area item holds, beside the five legs it named before', [UNREAD_LEGS.length, UNREAD_LEGS.some((l) => l.startsWith('lane ownership — ')), UNREAD_LEGS.some((l) => l.startsWith('an area item that holds a sub-epic — '))], [7, true, true]); t('⛔ the lane-ownership leg reads `domain:*` as file ownership, never as the seat\'s lane: lanes are seats and epics', [UNREAD_LEGS.some((l) => /outside this seat's lane|against your lane/.test(l)), UNREAD_LEGS.some((l) => l.startsWith('lane ownership — ') && l.includes('file ownership only'))], [false, true]); const c = card(['area:ux', 'priority:p2', 'domain:ui']); diff --git a/scripts/pm/check-half-states.mjs b/scripts/pm/check-half-states.mjs index 8c39144e7de..d99a068a201 100644 --- a/scripts/pm/check-half-states.mjs +++ b/scripts/pm/check-half-states.mjs @@ -1295,6 +1295,11 @@ export const RELEASE_COMMENT_MARKER = /^\s*>?\s*Release\s*:/mi; // name (`domain:engine-core` carries a hyphen, measured on the label set), // `epic:#` plus the parent card, `triage`, `director`, `coordinator`, `security`, `l2-review` (old spelling `review`), `qa`, `eval` or `queue` // N the seat number, from 1 +// @ACCOUNT in place of `#N` is the SECOND accepted seat mark (ruling record 7249169754): a seat named by +// the account that holds it, `repo:objectstack@os-justin · os-justin · session_01…`. Its account is +// the signing ACCOUNT, compared lower-cased; under another account the line is a near miss. Readers +// accept both marks; every writer's default is still `#N`. A seat is its lane AND its mark: `#N` +// reads as that numbered seat, `@ACCOUNT` as that account's, and neither is read as the other. // ACCOUNT the login a claim's `Account:` line carries — GitHub's own login rule // SESSION the full id, in the relay envelope's shape (`SESSION_SHAPE`, fleet-write/ops.mjs, // mirrored here because this module may not import that one; the record-recognisers @@ -1319,6 +1324,8 @@ export const RELEASE_COMMENT_MARKER = /^\s*>?\s*Release\s*:/mi; /** The four parts' patterns, unanchored, in order — the ONE spelling every reader and writer composes from. */ const SIGNATURE_LANE_SOURCE = '(?:domain:[a-z][a-z0-9-]*|repo:[a-z][a-z0-9-]*|epic:#[1-9][0-9]*|triage|director|coordinator|security|l2-review|review|qa|eval|queue)'; const SIGNATURE_ACCOUNT_SOURCE = '[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}'; +/** The seat mark after the lane, capture-free: `#N`, or `@ACCOUNT` (the banner's second accepted mark). */ +export const SEAT_MARK_SOURCE = `(?:#[1-9][0-9]*|@${SIGNATURE_ACCOUNT_SOURCE})`; /** The relay envelope's session shape without its anchors — `SESSION_SHAPE` in `fleet-write/ops.mjs`. */ export const SEAT_SIGNATURE_SESSION_SOURCE = 'session_[A-Za-z0-9]{6,}'; /** The separator, exactly. */ @@ -1326,17 +1333,36 @@ export const SEAT_SIGNATURE_SEPARATOR = ' · '; /** The signature line's pattern, unanchored and capture-free — what a marker composes when it admits one leading signature. */ export const SEAT_SIGNATURE_SOURCE = - `${SIGNATURE_LANE_SOURCE}#[1-9][0-9]*${SEAT_SIGNATURE_SEPARATOR}${SIGNATURE_ACCOUNT_SOURCE}${SEAT_SIGNATURE_SEPARATOR}${SEAT_SIGNATURE_SESSION_SOURCE}`; + `${SIGNATURE_LANE_SOURCE}${SEAT_MARK_SOURCE}${SEAT_SIGNATURE_SEPARATOR}${SIGNATURE_ACCOUNT_SOURCE}${SEAT_SIGNATURE_SEPARATOR}${SEAT_SIGNATURE_SESSION_SOURCE}`; -/** ONE line, whitespace around it trimmed, is a signature — with the four parts captured. ⛔ No `g` or `m` flag. */ +/** + * ONE line, whitespace around it trimmed, is a signature — with the four parts captured; the second is the seat mark + * as written, `#N` or `@ACCOUNT` (`seatMark` reads it). ⛔ No `g` or `m` flag. The pattern alone does not hold an + * `@ACCOUNT` mark to the signing account: `readSignatureLine` does, so a writer's gate asks that reader. + */ export const SEAT_SIGNATURE_LINE = new RegExp( - `^(${SIGNATURE_LANE_SOURCE})#([1-9][0-9]*)${SEAT_SIGNATURE_SEPARATOR}(${SIGNATURE_ACCOUNT_SOURCE})${SEAT_SIGNATURE_SEPARATOR}(${SEAT_SIGNATURE_SESSION_SOURCE})$`, + `^(${SIGNATURE_LANE_SOURCE})(${SEAT_MARK_SOURCE})${SEAT_SIGNATURE_SEPARATOR}(${SIGNATURE_ACCOUNT_SOURCE})${SEAT_SIGNATURE_SEPARATOR}(${SEAT_SIGNATURE_SESSION_SOURCE})$`, 'u', ); /** The shape, as a refusal prints it — placeholders only, so it survives a GitHub body unchanged. */ export const SEAT_SIGNATURE_SHAPE = 'LANE#N · ACCOUNT · SESSION — e.g. `domain:skills#2 · os-justin · session_01…`'; +/** + * A seat mark as every reader carries it: the NUMBER for `#N`, the string `@account` (lower-cased, GitHub logins + * fold case) for `@ACCOUNT`, null for anything else. Two marks name one seat exactly when they are `===`. Pure. + * + * @returns {number | string | null} + */ +export function seatMark(text) { + const m = new RegExp(`^${SEAT_MARK_SOURCE}$`, 'u').exec(String(text ?? '').trim()); + if (!m) return null; + return m[0].startsWith('#') ? Number(m[0].slice(1)) : m[0].toLowerCase(); +} + +/** A seat's id from its lane and its mark (`seatMark`'s reading): `LANE#N` or `LANE@account`. Pure. */ +export const seatIdOf = (lane, mark) => (typeof mark === 'string' ? `${lane}${mark}` : `${lane}#${mark}`); + /** The index of a line list's first non-blank line, or -1. */ function firstNonBlankIndex(lines) { return lines.findIndex((line) => line.trim() !== ''); @@ -1347,7 +1373,10 @@ function firstNonBlankIndex(lines) { * not one (an empty body included). Pure. * * @param {string} body - * @returns {{ lane: string, seat: number, account: string, session: string, line: string } | null} + * `seat` is the seat mark (`seatMark`): the number for `#N`, `@account` for a seat named by its account — and such + * a line is a signature only under that same account. + * + * @returns {{ lane: string, seat: number | string, account: string, session: string, line: string } | null} */ export function readSignatureLine(body) { const lines = String(body ?? '').split(/\r?\n/); @@ -1355,7 +1384,10 @@ export function readSignatureLine(body) { if (at < 0) return null; const line = lines[at].trim(); const m = SEAT_SIGNATURE_LINE.exec(line); - return m ? { lane: m[1], seat: Number(m[2]), account: m[3], session: m[4], line } : null; + if (!m) return null; + const seat = seatMark(m[2]); + if (typeof seat === 'string' && seat !== `@${m[3].toLowerCase()}`) return null; + return { lane: m[1], seat, account: m[3], session: m[4], line }; } /** @@ -1385,11 +1417,11 @@ export function signatureRefusal(body) { const at = firstNonBlankIndex(lines); const line = at < 0 ? '(the body is empty)' : lines[at].trim(); // A line naming a seat number AND a session id is a signature typed wrong — named as such, so the fix is the spelling. - const near = at >= 0 && /#[1-9]/u.test(line) && /\bsession_/u.test(line); + const near = at >= 0 && /#[1-9]|\S@[A-Za-z0-9]/u.test(line) && /\bsession_/u.test(line); return { line: line.length > 160 ? `${line.slice(0, 160)}…` : line, why: near - ? 'the first non-empty line reads like a signature and is not one — check the lane, the `#N` seat number, the login, the full session id, and that each separator is exactly ` · `' + ? 'the first non-empty line reads like a signature and is not one — check the lane, the `#N` seat number (or an `@ACCOUNT` seat, which only that same account signs), the login, the full session id, and that each separator is exactly ` · `' : 'the first non-empty line is not a signature — the reader cannot tell which lane, seat, account or session wrote this', }; } @@ -8101,6 +8133,20 @@ export function seatDeclaresWait(markerBody) { return SEAT_WAIT_MARKERS.some((term) => text.includes(term)); } +/** A seat title's lane half that opens `LANE@ACCOUNT`, the account attached with no space on either side. */ +const SEAT_TITLE_ACCOUNT = new RegExp(`^([^\\s@]+)@(${SIGNATURE_ACCOUNT_SOURCE})(?=\\s|$)`, 'u'); + +/** + * The account a seat title's lane half names its seat by, or null: `{ lane, mark, rest }`, `mark` the seat mark + * `@account` and `rest` the half with the account taken off, so every reader below sees the text a bare post + * carries. `domain:ui @ objectui` (a space before the `@`) names a board, not an account, and reads null. Pure. + */ +export function seatTitleAccount(half) { + const text = String(half ?? '').trim(); + const m = SEAT_TITLE_ACCOUNT.exec(text); + return m ? { lane: m[1], mark: `@${m[2].toLowerCase()}`, rest: `${m[1]}${text.slice(m[0].length)}` } : null; +} + /** * The lane a seat post speaks for, parsed from its title, plus whether that * lane is READABLE FROM THIS BOARD. @@ -8122,6 +8168,11 @@ export function seatDeclaresWait(markerBody) { * bare post does, and seat 1 keeps the bare title (an absent suffix reads as * seat 1 — every seat post written before the suffix existed is seat 1). * + * A seat named by its account opens `LANE@ACCOUNT`, the account attached to + * the lane with no space (`seatTitleAccount`): that is its seat mark + * (`@account`, `seatMark`'s spelling), never seat 1 and never a board. The + * board suffix above is written after a space on every measured post. + * * The `foreign` flag is the load-bearing half and it exists for the same reason * H19 refuses to guess at a cross-repo 404: this sweep reads ONE repo. A seat * whose lane lives in a sibling repo has an inventory this patrol cannot see at @@ -8131,19 +8182,22 @@ export function seatDeclaresWait(markerBody) { * changes. `repo:*`-scoped and lane-less seats (`triage`) are foreign for the * same reason: there is no `domain:*` label to count a lane inventory against. * - * @returns {{ lane: string|null, foreign: boolean, seat: number|null }} — - * `seat` is the seat number (1 when the title carries no `· seat N`), or - * null when the title does not parse as a seat post at all. + * @returns {{ lane: string|null, foreign: boolean, seat: number|string|null }} — + * `seat` is the seat mark: the number (1 when the title carries no + * `· seat N`), `@account` for a `LANE@ACCOUNT` title, or null when the title + * does not parse as a seat post at all. */ export function seatLane(issue) { const m = /^\[PM seat\]\s*(.*?)\s*—\s*(.*)$/u.exec(issue?.title ?? ''); if (!m) return { lane: null, foreign: true, seat: null }; let raw = m[1].trim(); + const named = seatTitleAccount(raw); + if (named) raw = named.rest; // The `· seat N` suffix (free-claim multi-seat) is a seat NUMBER, wherever // it sits in the lane half; taken out first so the lane test below sees the // same text a bare post would. Absent ⇒ seat 1. const seatM = /\s*·\s*seat\s+(\d+)\b/iu.exec(raw); - const seat = seatM ? Number(seatM[1]) : 1; + const seat = named ? named.mark : seatM ? Number(seatM[1]) : 1; if (seatM) raw = (raw.slice(0, seatM.index) + raw.slice(seatM.index + seatM[0].length)).trim(); // An `@ ` suffix names the board the lane lives on. Present ⇒ the lane // is only READABLE there, whatever its `domain:*` spelling says here. @@ -8164,7 +8218,7 @@ export function seatLane(issue) { * for each `epic #N` / `epic:#N` (`· epic #34571`). * * Only a seat on THIS board's repo lane has an intake here: `repo:NAME` - * (`#N` or `· seat N` beside it) whose NAME is the swept repo's, with no + * (`#N`, `@ACCOUNT` or `· seat N` beside it) whose NAME is the swept repo's, with no * `@ elsewhere`. A `repo:cloud` seat's cards live on another board, and a * `domain:*` seat post takes no card by label any more, so both answer `[]` * — never guessed. Pure. @@ -8177,7 +8231,7 @@ export function seatIntakeKeys(issue, repo = SWEEP_REPO.repo) { const title = String(issue?.title ?? ''); const m = /^\[PM seat\]\s*(.*?)\s*—\s*(.*)$/u.exec(title); if (!m) return []; - const name = m[1].trim(); + const name = seatTitleAccount(m[1])?.rest ?? m[1].trim(); const lane = /^repo:([A-Za-z0-9._-]+)/u.exec(name); const own = String(repo).split('/')[1] ?? ''; const at = /@\s*(\S+)/u.exec(name); @@ -9556,6 +9610,11 @@ export function seatPostLastEventMs(seat, commentRows) { * · Otherwise the number the line names: the FIRST `#` of the payload, so a * trailing note (`… (#35205)`) never moves it — except the epic shape * `epic:##`, whose first `#` is the epic and whose seat is `k`. + * · A seat named by its account (`Seat: repo:@`, the lane and + * the account attached) answers the seat mark `@account` (`seatMark`'s + * spelling), never a number: it is no numbered seat's claim, seat 1's least + * of all. Read before the number, so an epic seat's `epic:#@` + * is not seat N. * * ⚠️ The second spelling of the second answer is the repair, and the cost it * removes is measured: a wrong answer that is a REAL seat does not surface as @@ -9581,14 +9640,18 @@ const CLAIM_SEAT_KEY_LINE = /^[ \t]*(?:[-*+][ \t]+)?>?[ \t]*(?:\*\*)?`?Seat`?(?: * Pinned to the measured shapes; an unmeasured variant it misses falls back to * 1, which is the defect, so widen it on evidence rather than narrowing it. */ -const CLAIM_SEAT_DECLARATION_ANYWHERE = /(?:\*\*)?`?Seat`?(?:\*\*)?[ \t]*:[ \t]*`?(?:domain:[a-z0-9_-]+|repo:[A-Za-z0-9._-]+|epic:#[1-9][0-9]*)[ \t]*#\d/; +const CLAIM_SEAT_DECLARATION_ANYWHERE = /(?:\*\*)?`?Seat`?(?:\*\*)?[ \t]*:[ \t]*`?(?:domain:[a-z0-9_-]+|repo:[A-Za-z0-9._-]+|epic:#[1-9][0-9]*)(?:[ \t]*#\d|@[A-Za-z0-9])/; +/** A `Seat:` payload naming its seat by account: the lane, then `@ACCOUNT` attached. */ +const CLAIM_SEAT_ACCOUNT = new RegExp(`^\`?(?:epic:#[1-9][0-9]*|[A-Za-z][A-Za-z0-9:._-]*)@(${SIGNATURE_ACCOUNT_SOURCE})(?![A-Za-z0-9@-])`, 'u'); -/** @returns {number|null} the seat number, 1 when NO declaration is present at all, null when one is present but unreadable. */ +/** @returns {number|string|null} the seat mark — the seat number, or `@account` for a seat named by its account; 1 when NO declaration is present at all, null when one is present but unreadable. */ export function claimSeatNumber(body) { const text = String(body ?? ''); const m = CLAIM_SEAT_KEY_LINE.exec(text); if (!m) return CLAIM_SEAT_DECLARATION_ANYWHERE.test(text) ? null : 1; const payload = String(m[1] ?? ''); + const named = CLAIM_SEAT_ACCOUNT.exec(payload); + if (named) return `@${named[1].toLowerCase()}`; // An epic seat names its epic first: `epic:##` is seat k, never seat N. const epic = /^`?epic:#[1-9][0-9]*#(\d+)\b/.exec(payload); if (epic) return Number(epic[1]); @@ -9631,7 +9694,7 @@ export function claimSeatNumber(body) { * a lone key may be passed bare. * @param {Iterable} issues — open cards this sweep already listed. * @param {Map} commentsByNumber — threads already in the cache. - * @param {number} [seat=1] — the seat number whose claims count (`seatLane(post).seat`). + * @param {number|string} [seat=1] — the seat mark whose claims count (`seatLane(post).seat`): a number, or `@account`. * @returns {{ number: number, at: number }|null} the newest claim, or null. */ export function newestLaneClaim(intake, issues, commentsByNumber, seat = 1) { @@ -9682,8 +9745,11 @@ export function h38SeatPostStale(seat, seatAt, claim) { if (claim.at <= seatAt) return null; const behindHours = (claim.at - seatAt) / 3_600_000; + // An account mark is printed in a code span: this row is written into the patrol's anchor issue, where a loose + // `@login` is a mention. A seat number is printed bare, as it always was. + const seatWord = typeof seatNo === 'string' ? `\`${seatNo}\`` : seatNo; return ( - `\`pm:seat\` post is STALE — its intake ${lane} (seat ${seatNo}) carries a \`Claim:\` on #${claim.number} written ` + + `\`pm:seat\` post is STALE — its intake ${lane} (seat ${seatWord}) carries a \`Claim:\` on #${claim.number} written ` + `${behindHours.toFixed(1)}h AFTER this post's last event (claim ${new Date(claim.at).toISOString()}, ` + `post ${new Date(seatAt).toISOString()}). A shift dispatched work and did not record it, so every ` + 'number the post states — 在飞 / 队列 / 决策箱 / the round number — describes a round that has since ' + @@ -33467,6 +33533,30 @@ async function selfTest() { t('H38 seat: a seat-2 post behind a same-seat claim -> finding', typeof h38SeatPostStale(seat38(seat2Area), SEAT_AT_38, claim38(13398, '2026-08-30T07:30:00Z')), 'string'); t('H38 seat: …and the finding names the seat', h38row(seat38(seat2Area), SEAT_AT_38, claim38(13398, '2026-08-30T07:30:00Z')).includes('seat 2'), true); t('H38 seat: …while the bare post names seat 1', h38row(seat38(), SEAT_AT_38, claim38(13398, '2026-08-30T07:30:00Z')).includes('seat 1'), true); + // The second seat mark (ruling record 7249169754): `LANE@ACCOUNT` names a seat by its account. Readers take both + // marks; a seat is its lane AND its mark, so `#N` keeps reading as that numbered seat and `@ACCOUNT` as that + // account's — neither as the other. Every writer's default is still `#N`. + const J38 = (v) => JSON.stringify(v); + const acctArea = `[PM seat] repo:${OWN_BOARD}@os-b — 🟢 os-b (session_y) · area:data`; + t('H38 seat (account mark): a `LANE@ACCOUNT` title carries the mark `@account`, lower-cased — ⛔ never seat 1', J38([seatLane(seat38(acctArea)).seat, seatLane(seat38(`[PM seat] repo:${OWN_BOARD}@OS-B — 🟢 os-b`)).seat]), J38(['@os-b', '@os-b'])); + t('H38 seat (account mark): …a `domain:` lane named by account reads as its lane, on this board', J38([seatLane(seat38('[PM seat] domain:services@os-b — 🟢 os-b')).lane, seatLane(seat38('[PM seat] domain:services@os-b — 🟢 os-b')).foreign, seatLane(seat38('[PM seat] domain:services@os-b — 🟢 os-b')).seat]), J38(['domain:server', false, '@os-b'])); + t('H38 seat (account mark): …while the board suffix, written after a space, is still a board and still seat 1', J38([seatLane(seat38('[PM seat] domain:ui @ objectui — 🟢 os-b')).foreign, seatLane(seat38('[PM seat] domain:ui @ objectui — 🟢 os-b')).seat, seatTitleAccount('domain:ui @ objectui')]), J38([true, 1, null])); + t('H38 seat (account mark): `seatTitleAccount` takes the account off the lane and leaves the rest as a bare post carries it', J38([seatTitleAccount('repo:objectstack@OS-B · area:data'), seatTitleAccount('repo:objectstack · seat 2'), seatTitleAccount('repo:objectstack@os-b.x')]), J38([{ lane: 'repo:objectstack', mark: '@os-b', rest: 'repo:objectstack · area:data' }, null, null])); + t('H38 seat (account mark): the intake of an account seat reads as the numbered post\'s does — its account is no board', J38(seatIntakeKeys(seat38(acctArea), `objectstack-ai/${OWN_BOARD}`)), J38(['area:data'])); + t('H38 seat (account mark): `Seat: repo:NAME@ACCOUNT` reads the mark `@account`', J38([claimSeatNumber('Claim: x\nSeat: `repo:objectstack@os-b`'), claimSeatNumber('- > **Seat**: repo:objectstack@OS-B (was seat 2, #35205)')]), J38(['@os-b', '@os-b'])); + t('H38 seat (account mark): an epic seat named by account is ⛔ not seat N of its epic', claimSeatNumber('Claim: x\nSeat: epic:#31527@os-b'), '@os-b'); + t('H38 seat (account mark): a mid-line account declaration is unreadable, ⛔ not seat 1', claimSeatNumber('**Claim:** by the seat. `Seat: repo:objectstack@os-b` · claimed'), null); + const acctClaim = new Map([[1, seatRow('Seat: `repo:objectstack@os-b`', '2026-08-30T00:00:00Z')]]); + t('H38 seat (account mark): the account seat\'s post sees its own account\'s claim', newestLaneClaim('area:data', oneCard, acctClaim, seatLane(seat38(acctArea)).seat).number, 1); + t('H38 seat (account mark): ⛔ account X\'s claim is not read as account Y\'s seat of the same lane', newestLaneClaim('area:data', oneCard, acctClaim, '@os-c'), null); + t('H38 seat (account mark): ⛔ …nor as any numbered seat\'s, seat 1 included', J38([newestLaneClaim('area:data', oneCard, acctClaim, 1), newestLaneClaim('area:data', oneCard, acctClaim, 2)]), J38([null, null])); + // CONTROL: vacant seat 1's standing `#1` claim (declared, or with no `Seat:` line at all) is seat 1's and stays so. + const vacantSeat1 = new Map([[1, seatRow('Seat: `repo:objectstack#1`', '2026-08-30T00:00:00Z')]]); + t('H38 seat (account mark): CONTROL — a `#1` claim by a vacant seat still reads as seat 1\'s', J38([newestLaneClaim('area:data', oneCard, vacantSeat1, 1).number, newestLaneClaim('area:data', oneCard, seat1Claim, 1).number]), J38([1, 1])); + t('H38 seat (account mark): CONTROL — …and ⛔ never as the account seat\'s, so the new account\'s post is not rowed over it', J38([newestLaneClaim('area:data', oneCard, vacantSeat1, '@os-b'), newestLaneClaim('area:data', oneCard, seat1Claim, '@os-b'), newestLaneClaim('area:data', oneCard, seat2Claim, '@os-b')]), J38([null, null, null])); + t('H38 seat (account mark): the finding on an account seat\'s post names its mark in a code span — ⛔ never a loose `@login`, which the anchor issue turns into a mention', J38([h38row(seat38(acctArea), SEAT_AT_38, claim38(13398, '2026-08-30T07:30:00Z')).includes('(seat `@os-b`)'), /(? clean', h38SeatPostStale(seat38(seat2Area), SEAT_AT_38, newestLaneClaim('area:data', oneCard, seat1Claim, 2)), null); // -- Lane label aliases — the domain:server merge (maintainer ruling 2026-10-22, letter 乙) -- diff --git a/scripts/pm/check-handover.mjs b/scripts/pm/check-handover.mjs index 5e24a5df90e..e083c2af4bf 100644 --- a/scripts/pm/check-handover.mjs +++ b/scripts/pm/check-handover.mjs @@ -181,6 +181,7 @@ import { proxyRearmPlan, readSignatureLine, resolveSweepRepo, + seatIdOf, stripMarkdownCode, stripSignatureLine, } from './check-half-states.mjs'; @@ -453,7 +454,7 @@ export function stayBehindText(reported) { export const EXIT_SURFACE_UNREAD = 5; /** How many `inflight: ` self-test cases must register — the mode's battery floor (AGENTS.md, writing a `--self-test`). */ -const INFLIGHT_CASE_FLOOR = 46; +const INFLIGHT_CASE_FLOOR = 47; /** * The claim template's `File surface:` key line (SKILL.md 〈模板与表〉), read one line at a time. A qualifier in @@ -872,7 +873,7 @@ export function inflightSurface(issue, comments) { const paths = [...current]; const excluded = [...excludedAll]; const sig = readSignatureLine(String(claim?.body ?? '')); - return { verdict: 'held', claim, session: claimSession(claim?.body), seat: sig ? `${sig.lane}#${sig.seat}` : null, declared, paths, excluded }; + return { verdict: 'held', claim, session: claimSession(claim?.body), seat: sig ? seatIdOf(sig.lane, sig.seat) : null, declared, paths, excluded }; } /** `--paths=a,b` → the dispatch's surface entries (code-span backticks tolerated), or the usage error. */ @@ -1578,6 +1579,8 @@ export function selfTest() { const IF_CARD = (labels = ['pm:dispatched'], extra = {}) => ({ number: 37064, title: 'dispatch-gates', state: 'open', labels: labels.map((name) => ({ name })), assignees: [{ login: 'os-tesla' }], ...extra }); const heldIf = inflightSurface(IF_CARD(), [IF_CLAIM('File surface: `scripts/pm/dispatch-gates.mjs`, `scripts/pm/dispatch-gates.data.mjs`. (stop on breach)')]); t('inflight: ⭐ a held claim names its session (the `Session:` line), its seat (the signature) and its paths', heldIf.verdict === 'held' && heldIf.session === 'session_01L9qibyUSf2nKJWW6qBemSU' && heldIf.seat === 'repo:objectstack#3' && heldIf.paths.join() === 'scripts/pm/dispatch-gates.mjs,scripts/pm/dispatch-gates.data.mjs'); + const acctClaim = (sig) => inflightSurface(IF_CARD(), [comment(40, 0, `${sig}\n\nClaim: PM loop round 1 · 2026-11-27T07:39Z\nSession: \`session_01L9qibyUSf2nKJWW6qBemSU\`\nFile surface: \`scripts/pm/dispatch-gates.mjs\``)]); + t('inflight: ⭐ a held claim signed by a seat named by its account names that seat `lane@account` (ruling record 7249169754); ⛔ a `#N` claim stays the numbered seat\'s, and a line signed for another account\'s seat names no seat', acctClaim('repo:objectstack@os-tesla · os-tesla · session_01L9qibyUSf2nKJWW6qBemSU').seat === 'repo:objectstack@os-tesla' && acctClaim('repo:objectstack@Os-Tesla · os-tesla · session_01L9qibyUSf2nKJWW6qBemSU').seat === 'repo:objectstack@os-tesla' && heldIf.seat === 'repo:objectstack#3' && acctClaim('repo:objectstack@os-bill · os-tesla · session_01L9qibyUSf2nKJWW6qBemSU').seat === null); const amended = inflightSurface(IF_CARD(), [IF_CLAIM('File surface: `scripts/pm/card-pick.mjs`'), comment(41, 60, `${IF_SIG}\n\nClaim amendment: slice 2 · 2026-11-19T15:06Z\nFile surface: slice 2 only: \`scripts/pm/landing-k.mjs\` (new). Not \`card-pick.mjs\`.`)]); t('inflight: a later `Claim amendment` re-declares the surface — its paths join the claim\'s, its fence (a bare name too) removes from the union', amended.paths.join() === 'scripts/pm/landing-k.mjs' && amended.excluded.join() === 'card-pick.mjs' && inflightSurface(IF_CARD(), [IF_CLAIM('File surface: `scripts/pm/card-pick.mjs`'), comment(41, 60, `${IF_SIG}\n\nClaim amendment: rider\nFile surface: \`package.json\` added.`)]).paths.join() === 'scripts/pm/card-pick.mjs,package.json'); t('inflight: ⛔ not in flight — a `Release:` newer than the claim (whoever wrote it), no claim, another state, a closed card', inflightSurface(IF_CARD(), [IF_CLAIM('File surface: `a/b.mjs`'), comment(42, 90, 'Release: back to the queue')]).verdict === 'released' && inflightSurface(IF_CARD(), [comment(43, 0, 'a note')]).verdict === 'unclaimed' && inflightSurface(IF_CARD(['pm:queue']), [IF_CLAIM('File surface: `a/b.mjs`')]).verdict === 'out' && inflightSurface(IF_CARD(undefined, { state: 'closed' }), [IF_CLAIM('File surface: `a/b.mjs`')]).verdict === 'out'); diff --git a/scripts/pm/check-owed-reviews.mjs b/scripts/pm/check-owed-reviews.mjs index 3d61702e249..82a46d6d0ff 100644 --- a/scripts/pm/check-owed-reviews.mjs +++ b/scripts/pm/check-owed-reviews.mjs @@ -110,7 +110,7 @@ import process from 'node:process'; import { isEntrypoint } from '../invoked-as.mjs'; -import { cardIntakeKeys, CONTRACT_REVIEW_HEADING_MARKER, contractReviewVerdictLines, latestMarkedComment, readSignatureLine, seatIntakeKeys } from './check-half-states.mjs'; +import { cardIntakeKeys, CONTRACT_REVIEW_HEADING_MARKER, contractReviewVerdictLines, latestMarkedComment, readSignatureLine, seatIdOf, seatIntakeKeys } from './check-half-states.mjs'; import { repoIdForSlug } from './check-governed-merges.mjs'; import { GOVERNED_APPROVERS, NARROWING_FACE_LINE, narrowingDeclarationsIn, recordAuthorTrusted, recordTrustedAuthors } from './check-governed-queue-guard.mjs'; import { FLEET_BOT_LOGIN } from './check-handover.mjs'; @@ -283,12 +283,13 @@ export function recordReading(pull, trusted = RECORD_AUTHORS) { } /** - * The seat that signed a record — its first line's seat signature (`readSignatureLine`), as `lane#N`, - * the spelling `reviewSeatsOf` names a seat with — or null when it carries none. Pure. + * The seat that signed a record — its first line's seat signature (`readSignatureLine`), as `lane#N` (or + * `lane@account` for a seat named by its account), the spelling `reviewSeatsOf` names a seat with — or null when + * it carries none. Pure. */ export function signerSeatOf(body) { const sig = readSignatureLine(body); - return sig === null ? null : `${sig.lane}#${sig.seat}`; + return sig === null ? null : seatIdOf(sig.lane, sig.seat); } /** The limbs owe on the declaration face ALONE (`Clause-②: yes`, no schema and no governed path): `TIER_DEFAULT`. Pure. */ @@ -323,7 +324,8 @@ export function laneSeatOf(cardKeys, seats) { export function reviewSeatsOf(seats) { if (!Array.isArray(seats)) return { state: 'unknown', seated: [] }; const rows = seats.filter((s) => isL2ReviewLane(s?.lane)); - const name = (s) => `${String(s.lane).trim().toLowerCase()}#${Number(s.seat) > 0 ? Number(s.seat) : 1}`; + // A seat named by its account (`seat` is `@account`, fleet-roster's `parseSeat`) keeps that name: ⛔ never seat 1. + const name = (s) => (typeof s.seat === 'string' && s.seat.startsWith('@') ? seatIdOf(String(s.lane).trim().toLowerCase(), s.seat) : `${String(s.lane).trim().toLowerCase()}#${Number(s.seat) > 0 ? Number(s.seat) : 1}`); // `lanes/l2-review.md` 独立性: the pair is two SESSIONS, ⛔ never two accounts (ruling A on #33258) — // a seat's account is not read, so one on the PR's own implementing or dispatching account is seated like any other. const seated = rows.filter((s) => s.status === 'seated').map(name).sort(); @@ -416,7 +418,7 @@ export function takerOf(status, handoff, lane, review = { state: 'unknown', seat const seat = lane?.lane ? `the ${lane.lane} seat` : 'the lane seat'; const laneGone = lane?.seat === 'stood-down' || lane?.seat === 'absent'; const laneTaker = laneGone ? `${seat} next on duty` : seat; - const isL2 = (name) => typeof name === 'string' && isL2ReviewLane(name.split('#')[0]); + const isL2 = (name) => typeof name === 'string' && isL2ReviewLane(name.split(/[#@]/)[0]); const handedTo = handoff?.state === 'handed' && typeof handoff.to === 'string' ? handoff.to : null; if (declarationFaceOnly(limbs)) { if (handedTo !== null && !isL2(handedTo)) return handedTo; @@ -635,7 +637,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ // 24 → 18 (#34400, ruling A on #33258): the account bar is gone — its eight cases (S2, S4, the area-lease note, the // own delta of a now-barred signer) retire with it; one case pins same account, different session ⇒ seated and named, // and one keeps the unread-card-thread reading (the record unjudged, no own delta), which never needed the bar. - 'the L2 seat is the fallback: named by a hand-off or on its own delta, never on (b), (c), the label or the TIER_DEFAULT face': 18, + 'the L2 seat is the fallback: named by a hand-off or on its own delta, never on (b), (c), the label or the TIER_DEFAULT face': 21, 'a live claim holds the head and a record settles it; a lapsed claim holds nothing': 6, 'the live instance: two Tier H drafts with a hand-off on the current head list as TAKE under (a)': 4, 'the live read: every read through one reader; a failed read is INCOMPLETE, never clean': 6, @@ -774,6 +776,10 @@ export function selfTest() { t('the TIER_DEFAULT face: a hand-off to a SIBLING lane seat still names it; its own delta and (b) name the lane; the face is read off the limbs — the label beside it keeps it, a schema or governed path beside it ends it', rv({ ...DECLARED, headCommittedAt: fresh, comments: [handoff(HEAD, '2026-10-28T12:40:00Z', 'domain:ui#2')] }).taker === 'domain:ui#2' && rv({ ...DECLARED, comments: [signed(HEAD2, MICKEY)] }).taker === `the area:ux seat (${TIER_DEFAULT_FACE_NOTE})` && rv({ ...DECLARED, headCommittedAt: oneRound }).taker === `the area:ux seat (${TIER_DEFAULT_FACE_NOTE})` && [['declaration'], ['declaration', 'label'], ['rules', 'declaration'], ['schema', 'declaration'], ['label'], [], null].map(declarationFaceOnly).join() === 'true,true,false,false,false,false,false'); t('⭐ the delta of its OWN record: a record on an earlier head signed by a seated L2 seat ⇒ that seat takes the head; with no record on an earlier head the same row ⇒ the lane', (() => { const r = rv({ comments: [signed(HEAD2, MICKEY)] }); return r.status === 'TAKE' && r.record.state === 'stale' && r.record.seat === 'review#1' && r.taker === 'review#1 (the delta of its own record 6911000001)' && rv({}).taker === LANE_TAKES; })()); t('⛔ not its own delta ⇒ the lane: the signer stood down or is not seated, the record signed by a lane seat, or carrying no signature; the signer read off the first line, a signature the reader refuses naming nobody', rv({ comments: [signed(HEAD2, MICKEY)] }, [...SEATED, { lane: 'review', seat: 1, status: 'paused' }, { lane: 'review', seat: 2, status: 'seated' }]).taker === LANE_TAKES && rv({ comments: [signed(HEAD2, `domain:ui#1 · os-bill · ${LANE}`)] }).taker === LANE_TAKES && rv({ comments: [recordRow(HEAD2, 'FAIL', 11)] }).taker === LANE_TAKES && signerSeatOf(signed(HEAD2, `review#2 · os-mickey · ${REVIEWER}`).body) === 'review#2' && signerSeatOf(signed(HEAD2, `Review#2 · os-mickey · ${REVIEWER}`).body) === null && signerSeatOf(recordRow(HEAD).body) === null); + const ACCT_REVIEW = [...SEATED, { lane: 'l2-review', seat: '@os-mickey', status: 'seated' }, { lane: 'review', seat: 1, status: 'seated' }]; + t('⭐ a seat named by its account (ruling record 7249169754): the roster names it `lane@account` beside the numbered one, never as seat 1; a hand-off naming it names it and is an L2 seat on the TIER_DEFAULT face', (() => { const s = reviewSeatsOf(ACCT_REVIEW); const h = rv({ headCommittedAt: fresh, comments: [handoff(HEAD, '2026-10-28T12:40:00Z', 'l2-review@os-mickey')] }, ACCT_REVIEW); const d = rv({ ...DECLARED, headCommittedAt: fresh, comments: [handoff(HEAD, '2026-10-28T12:40:00Z', 'l2-review@os-mickey')] }, ACCT_REVIEW); return s.state === 'seated' && s.seated.join() === 'l2-review@os-mickey,review#1' && h.status === 'TAKE' && h.taker === 'l2-review@os-mickey' && d.taker === `the area:ux seat (${TIER_DEFAULT_FACE_NOTE})`; })()); + t('⭐ its own delta by either mark: a record signed `l2-review@os-mickey · os-mickey` is that seat\'s and it takes the head; the signer is read off the first line in both forms', (() => { const r = rv({ comments: [signed(HEAD2, `l2-review@os-mickey · os-mickey · ${REVIEWER}`)] }, ACCT_REVIEW); return r.record.seat === 'l2-review@os-mickey' && r.taker === 'l2-review@os-mickey (the delta of its own record 6911000001)' && signerSeatOf(signed(HEAD2, `l2-review@Os-Mickey · os-mickey · ${REVIEWER}`).body) === 'l2-review@os-mickey' && signerSeatOf(signed(HEAD2, MICKEY).body) === 'review#1'; })()); + t('⛔ control — neither mark reads as the other: a `review#1` record stays the numbered seat\'s when only an account seat is seated (the lane takes), an `l2-review@os-mickey` record is not `l2-review@os-bill`\'s, and a line signed for another account\'s seat names nobody', (() => { const ONLY_ACCT = [...SEATED, { lane: 'review', seat: '@os-mickey', status: 'seated' }]; const BILL = [...SEATED, { lane: 'l2-review', seat: '@os-bill', status: 'seated' }]; return rv({ comments: [signed(HEAD2, MICKEY)] }, ONLY_ACCT).taker === LANE_TAKES && reviewSeatsOf(ONLY_ACCT).seated.join() === 'review@os-mickey' && rv({ comments: [signed(HEAD2, `l2-review@os-mickey · os-mickey · ${REVIEWER}`)] }, BILL).taker === LANE_TAKES && signerSeatOf(signed(HEAD2, `l2-review@os-bill · os-mickey · ${REVIEWER}`).body) === null; })()); t('a record on THIS head is DONE — no taker at all, the signer\'s or anyone\'s', (() => { const r = rv({ comments: [signed(HEAD, MICKEY)] }); return r.status === 'DONE' && r.taker === null && r.record.seat === 'review#1'; })()); const ATTR = '\n_Requested by **Y**_\n\nPart of #25922\n\nClause-②: no\nMetadata-protocol: none'; const CLAIMED = [{ id: 7, created_at: '2026-10-28T09:00:00Z', body: 'domain:skills#3 · os-zhuang · session_01Abcdefgh\n\nClaim: PM loop round 1 · 2026-10-28T09:00Z\nBranch: `claude/x`' }]; diff --git a/scripts/pm/check-prior-rulings.mjs b/scripts/pm/check-prior-rulings.mjs index 3d09c88f943..3e5a3ab8c3f 100644 --- a/scripts/pm/check-prior-rulings.mjs +++ b/scripts/pm/check-prior-rulings.mjs @@ -1092,7 +1092,9 @@ const ownerOf = (repo) => String(repo).split('/')[0].toLowerCase(); /** * Every issue or PR a card's body and thread name, in order, deduplicated, the card itself left out. A bare `#N` - * must not touch a word character on its left, so a seat signature's `LANE#N` and a `repo:x#5` name nothing. Each + * must not touch a word character on its left, so a seat signature's `LANE#N` and a `repo:x#5` name nothing; a + * seat named by its account, `LANE@ACCOUNT`, carries no `#N` and names nothing either (an epic seat's + * `epic:#N@ACCOUNT` names its epic, as `epic:#N#k` does). Each * ref carries its scope against the swept repository: `local` (that repository), `sameOwner` (another repository of * its owner), `foreign` (any other owner) or `rejected` (an `owner/repo` that is not two plain names). Pure. */ @@ -2144,6 +2146,7 @@ export async function selfTest() { t('--paths: readRefRow refuses a name that is not plain without a request', J([refused.ok, calls.length]), J([false, 0])); t('--paths: ⭐ the unread faces are named under the run, URL refs and refs on ruling-hit lines by number', J([UNREAD_FACES.every((f) => text.includes(f)), text.includes('URL refs: #77'), text.includes('refs on ruling-hit lines: #31491')]), J([true, true, true])); t('--paths: card refs — a signature\'s LANE#N names nothing, dedup, scope per ref, the card itself out', J(cardRefs(['repo:objectstack#5 · os-bill · session_01ABCDEF\nsee #12 and #12, epic:#35205#1, objectstack-ai/cloud#7, PR #99 and #500 itself'], 'objectstack-ai/objectstack', 500).map((r) => [r.key, r.scope])), J([['objectstack-ai/objectstack#12', 'local'], ['objectstack-ai/objectstack#35205', 'local'], ['objectstack-ai/cloud#7', 'sameOwner'], ['objectstack-ai/objectstack#99', 'local']])); + t('--paths: card refs — both seat marks name nothing: a signature\'s `LANE@ACCOUNT` like its `LANE#N`, an account with digits included; an epic seat names its epic once under either mark', J(cardRefs(['repo:objectstack@os-bill · os-bill · session_01ABCDEF\nrepo:objectstack#5 · os-bill · session_01ABCDEF\nTo: repo:cloud@user-42, by review@os-9 — see #12, epic:#35205@os-bill and epic:#35205#1'], 'objectstack-ai/objectstack', 500).map((r) => r.key)), J(['objectstack-ai/objectstack#12', 'objectstack-ai/objectstack#35205'])); t('--paths: a PR is read as merged, closed unmerged or open; an issue names its assignees', J([refStateOf({ state: 'closed', pull_request: { merged_at: 'x' } }).state, refStateOf({ state: 'closed', pull_request: { merged_at: null } }).state, refStateOf({ state: 'open', assignees: [{ login: 'os-bill' }] }).assignees]), J(['merged', 'closed unmerged', ['os-bill']])); const cap = Array.from({ length: SURFACE_HIT_NAME_CAP + 3 }, (_, k) => h(k + 1, 'a ruling')); const capText = renderPremise({ paths: ['a/**'], rev: 'origin/main', todayUtc: '2000-01-01', byPattern: { ruling: cap, 'Ruling-ref': [], maintainer: [], '⛔': [] }, unmatchedPaths: [], verdict: surfaceVerdict({ ruling: cap }), log: { commits: [], sameDay: [] }, refs: null }); diff --git a/scripts/pm/check-skill-line-ratchet.mjs b/scripts/pm/check-skill-line-ratchet.mjs index 3accb78fe39..d3fa0e80c53 100644 --- a/scripts/pm/check-skill-line-ratchet.mjs +++ b/scripts/pm/check-skill-line-ratchet.mjs @@ -101,7 +101,7 @@ export const CEILINGS = new Map([ ['.claude/skills/pm-dispatch/references/review-checklist.md', 79], ['.claude/skills/pm-dispatch/references/landing-operations.md', 10705], ['.claude/skills/pm-dispatch/references/release-aftercare.md', 3526], - ['.claude/skills/pm-dispatch/references/seat-post-protocol.md', 7720], + ['.claude/skills/pm-dispatch/references/seat-post-protocol.md', 7716], // lowered 7720 → 7716 by the #38415 seat-mark readers PR (the signature line names `LANE@ACCOUNT` as a reading, paid by the checklist heading's aside; the file's landed size, headroom 0) ['.claude/skills/pm-dispatch/references/true-green.md', 2068], ['.claude/skills/pm-dispatch/references/compile-surfaces.md', 2488], ['.claude/skills/pm-dispatch/references/seat-lifecycle.md', 9070], // raised 9070 → 9076 (+6) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): card-pick --why every patrol round; lowered 9076 → 9070 by the PR that moved the tier and effort values to the one home @@ -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', 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/agents/os-dev.md', 33491], // lowered 33492 → 33491 by the #38415 seat-mark readers PR (the trailer line names `LANE@ACCOUNT` as a reading, paid by the lock entry's second copy of the slot rule; the file's landed size, headroom 0); before that: 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/fleet-roster.mjs b/scripts/pm/fleet-roster.mjs index 20fa09b1c62..f977729dbfd 100644 --- a/scripts/pm/fleet-roster.mjs +++ b/scripts/pm/fleet-roster.mjs @@ -58,7 +58,10 @@ * lane = the name's first token (`domain:x`, `repo:x`, * `director`, `triage`); seat = `· seat N` or `repo:x#N`, * else 1; repo = `repo:x`'s repo, else `@ `, else the - * repo the post lives on. + * repo the post lives on. A name opening `LANE@ACCOUNT` (the + * account attached, `seatTitleAccount`) is a seat named by + * its account: seat = `@account`, a row of its own, never + * seat 1 and never a board. * epic rows an open `pm:epic` PARENT — sub-issues under it AND a * `session_…` registration in its body, the paired * delegation signal (`seat-lifecycle.md` 〈Epic 子树车道〉; @@ -173,7 +176,7 @@ import { isL2ReviewLane, L2_REVIEW_LANE, LEDGER_EXCLUSION, MAILBOX_BRANCH_PREFIX // re-spells it. The relay that imports `ROSTER_MARKER` from here (`fleet-write/dispatch.mjs`) already imports // check-half-states itself, so this import loads nothing new there. The opener's lane-word lists cannot import it // (the patrol loads the opener lazily, so that edge would be a cycle); the self-test holds the two equal. -import { GOVERNED_PR_AWAITING_MERGE_LABEL, SEAT_SIGNATURE_LINE } from './check-half-states.mjs'; +import { GOVERNED_PR_AWAITING_MERGE_LABEL, readSignatureLine, SEAT_SIGNATURE_LINE, seatIdOf, seatTitleAccount } from './check-half-states.mjs'; // `--health`'s reverse read and the inbox label: the shared `Blocked-by:` reader (body and thread, cross-repo keyed) // and the decision label, imported, never re-spelled. import { blockerTargetsFor, DECISION_INBOX_LABEL } from './check-half-states.mjs'; @@ -271,10 +274,13 @@ export function parseSeat(post, board) { if (!m) return null; const [, name, statusText] = m; const owner = board.split('/')[0]; - const token = SEAT_TITLE_TOKEN.exec(name)?.[1] ?? name.split(/\s/)[0]; + // `LANE@ACCOUNT`: the seat's mark is its account, and the rest reads as a bare post's name does. + const named = seatTitleAccount(name); + const read = named ? named.rest : name; + const token = SEAT_TITLE_TOKEN.exec(read)?.[1] ?? read.split(/\s/)[0]; const lane = token.replace(/#\d+$/, ''); - const seat = Number(/·\s*seat\s+(\d+)/.exec(name)?.[1] ?? /^repo:[A-Za-z0-9._-]+#(\d+)/.exec(name)?.[1] ?? 1); - const at = /@\s*([A-Za-z0-9._/-]+)/.exec(name)?.[1] ?? null; + const seat = named ? named.mark : Number(/·\s*seat\s+(\d+)/.exec(read)?.[1] ?? /^repo:[A-Za-z0-9._-]+#(\d+)/.exec(read)?.[1] ?? 1); + const at = /@\s*([A-Za-z0-9._/-]+)/.exec(read)?.[1] ?? null; const repo = lane.startsWith('repo:') ? `${owner}/${lane.slice(5)}` : at ? (at.includes('/') ? at : `${owner}/${at}`) : board; const mark = Object.keys(STATUS_BY_MARK).find((k) => statusText.startsWith(k)) ?? null; const status = mark ? STATUS_BY_MARK[mark] : 'unknown'; @@ -343,23 +349,29 @@ const isEpicRegistered = (i) => /session_[A-Za-z0-9]{4,}/.test(String(i?.body ?? export const isSeatedFreshEpic = (i, held) => held.size > 0 && isEpicRegistered(i); /** * Epic `lane`'s seats holding an open mailbox, seat → login, matched by `seatKey`'s slug `epic--` exactly as the - * mailbox column matches — a `Mailbox-of:` line or a head-only `mailbox//epic--` alike. Pure. + * mailbox column matches — a `Mailbox-of:` line or a head-only `mailbox//epic--` alike. A seat named + * by its account (`epic:#@`) is matched the same way, by that key's own slug, and maps its mark. Pure. */ export function epicSeatsHeld(lane, mailboxes) { const stem = seatKey(lane).slug.replace(/1$/, ''); return new Map(mailboxes.flatMap((m) => { + const named = m.login ? seatKey(`${lane}@${m.login}`) : null; + if (named && named.slug === m.slug) return [[`@${named.account}`, m.login]]; const k = m.slug?.startsWith(stem) ? m.slug.slice(stem.length) : null; return k !== null && seatKey(`${lane}#${k}`)?.slug === m.slug ? [[Number(k), m.login]] : []; })); } const isEpicLane = (lane) => lane.startsWith(`${SEAT_EPIC_KIND}:`); -/** The seat a body is signed by — its FIRST non-empty line, `readSignatureLine`'s reading — as `LANE#N`, or null. Pure. */ +/** The seat a body is signed by — its FIRST non-empty line, `readSignatureLine`'s reading — as `LANE#N` or `LANE@account`, or null. Pure. */ export function signedSeatOf(body) { - const line = String(body ?? '').split(/\r?\n/).find((l) => l.trim() !== ''); - const m = line === undefined ? null : SEAT_SIGNATURE_LINE.exec(line.trim()); - return m ? `${m[1]}#${m[2]}` : null; + const signed = readSignatureLine(body); + return signed ? seatIdOf(signed.lane, signed.seat) : null; } +/** A seat id's lane: everything before its mark, `#N` or `@account`. */ +const laneOfSeatId = (id) => id.slice(0, Math.max(id.lastIndexOf('#'), id.lastIndexOf('@'))); +/** Seat marks in row order: the numbered seats by number, then the seats named by an account, by name. */ +const bySeatMark = (a, b) => (typeof a === typeof b ? (a < b ? -1 : a > b ? 1 : 0) : typeof a === 'number' ? -1 : 1); /** The newest signed-comment time per seat, `LANE#N` → ISO, over every repo's `recentComments`. Pure. */ export function signedActivity(snapshot) { @@ -391,7 +403,7 @@ export function reviewClaims(snapshot, { now }) { const heads = new Map((s.pulls ?? []).filter((p) => p.state !== 'closed' && p?.head?.sha).map((p) => [p.number, p.head.sha])); for (const c of s.recentComments ?? []) { const seat = signedSeatOf(c?.body); - if (seat === null || !isL2ReviewLane(seat.slice(0, seat.lastIndexOf('#')))) continue; + if (seat === null || !isL2ReviewLane(laneOfSeatId(seat))) continue; const number = Number(/\/issues\/(\d+)$/.exec(String(c?.issue_url ?? ''))?.[1]); const claim = readContractReviewClaim(c?.body); if (!heads.has(number) || claim.state !== 'read') continue; @@ -406,7 +418,7 @@ export function reviewClaims(snapshot, { now }) { export const activitySince = (now) => new Date(Date.parse(now) - STALE_HOURS * 3_600_000).toISOString().replace(/\.\d{3}Z$/, 'Z'); /** A seat row's mailbox slug — its `LANE#N` as the opener spells it in a ref — or null. Pure. */ -const seatSlugOf = (row) => seatKey(`${row.lane}#${row.seat}`)?.slug ?? null; +const seatSlugOf = (row) => seatKey(seatIdOf(row.lane, row.seat))?.slug ?? null; /** Every open `pm:mailbox` pull in the snapshot, with whose it is (`mailboxOwner`), ordered by ref. Pure. */ export function readMailboxes(snapshot) { @@ -484,7 +496,7 @@ export function buildRows(snapshot, { now }) { pullUpdatedAt.set(keyOf(ref(repo, p.number)), p.updated_at ?? null); } } - rows.sort((a, b) => (a.repo !== b.repo ? (a.repo < b.repo ? -1 : 1) : a.lane !== b.lane ? (a.lane < b.lane ? -1 : 1) : a.seat !== b.seat ? a.seat - b.seat : a.post - b.post)); + rows.sort((a, b) => (a.repo !== b.repo ? (a.repo < b.repo ? -1 : 1) : a.lane !== b.lane ? (a.lane < b.lane ? -1 : 1) : a.seat !== b.seat ? bySeatMark(a.seat, b.seat) : a.post - b.post)); const landing = new Map(); // card key → [pull refs] for (const { repo, pr, comments } of pulls) { @@ -503,7 +515,7 @@ export function buildRows(snapshot, { now }) { const out = rows.map((row) => { const acct = lc(row.account); // An L2 seat's claims are signed per seat, so it never shares: its in-flight is the pulls its live claims hold. - const claims = isL2ReviewLane(row.lane) ? (claimed.get(`${row.lane}#${row.seat}`) ?? []).sort(byRef) : null; + const claims = isL2ReviewLane(row.lane) ? (claimed.get(seatIdOf(row.lane, row.seat)) ?? []).sort(byRef) : null; // One account on two seats of one lane: the cards cannot say which seat, so the lowest seat shows them once. const first = row.account && claims === null ? rows.find((r) => r.repo === row.repo && r.lane === row.lane && lc(r.account) === acct) : row; const sharesWith = first !== row ? first.seat : null; @@ -513,7 +525,7 @@ export function buildRows(snapshot, { now }) { // Per seat, never per account: one account holds several seats, and each seat opens its own. const mailbox = mailboxes.filter((m) => m.slug !== null && m.slug === seatSlugOf(row)).map((m) => m.ref); // The seat's own traces: a seat sharing its lane's account with a lower seat has no in-flight cards of its own. - const times = [row.updatedAt, ...inFlight.map((c) => c.updatedAt), ...(claims ?? []).map((m) => pullUpdatedAt.get(keyOf(m))), ...mailbox.map((m) => pullUpdatedAt.get(keyOf(m))), signed.get(`${row.lane}#${row.seat}`)].filter(Boolean).sort(); + const times = [row.updatedAt, ...inFlight.map((c) => c.updatedAt), ...(claims ?? []).map((m) => pullUpdatedAt.get(keyOf(m))), ...mailbox.map((m) => pullUpdatedAt.get(keyOf(m))), signed.get(seatIdOf(row.lane, row.seat))].filter(Boolean).sort(); const lastActivity = times.at(-1) ?? null; const ageHours = lastActivity && Number.isFinite(nowMs) ? (nowMs - Date.parse(lastActivity)) / 3_600_000 : null; return { @@ -596,9 +608,11 @@ export function renderBody(rows, { now, repos, session = null, unassigned = [], const who = r.routine ? 'Routine' : r.account ? `\`${r.account}\`` : '—'; const account = `${r.mark ?? '?'} ${who}${r.project ? ` · 由 ${r.project} 账户的项目负责` : ''}`; const wall = r.wallNote ?? (r.suspectedWall ? `⚠️ ${SUSPECTED_WALL}` : '—'); - const inFlight = r.sharesWith !== null ? `= seat ${r.sharesWith}` : refs(r.inFlight); + // A seat named by an account prints its mark in a code span: a loose `@login` in an issue body is a mention. + const mark = (seat) => (typeof seat === 'string' ? `\`${seat}\`` : seat); + const inFlight = r.sharesWith !== null ? `= seat ${mark(r.sharesWith)}` : refs(r.inFlight); lines.push( - `| ${r.repo.split('/')[1]} | ${cell(r.lane)} | [${r.seat}](https://github.com/${r.board}/issues/${r.post}) | ${cell(account)} | ${inFlight} | ${refs(r.awaitingRuling)} | ${refs(r.awaitingMerge)} | ${refs(r.awaitingLanding)} | ${cell(wall)} | ${age(r.lastActivity, now)} | ${refs(r.mailbox)} |`, + `| ${r.repo.split('/')[1]} | ${cell(r.lane)} | [${mark(r.seat)}](https://github.com/${r.board}/issues/${r.post}) | ${cell(account)} | ${inFlight} | ${refs(r.awaitingRuling)} | ${refs(r.awaitingMerge)} | ${refs(r.awaitingLanding)} | ${cell(wall)} | ${age(r.lastActivity, now)} | ${refs(r.mailbox)} |`, ); } const seated = rows.filter((r) => r.status === 'seated'); @@ -1093,6 +1107,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'a repo-lane seat owns its repo\'s cards by account: in flight, landing, merge, ruling': 7, // 13 → 14: the lane-grammar pin (the signature alternation equals the opener's lane-word lists, `coordinator` aside). 'one account on two seats of a lane: the second seat reads its own traces': 14, + 'a seat named by its account: `LANE@ACCOUNT` is a row of its own, read by lane AND account beside `LANE#N` (ruling record 7249169754)':10, 'the rendered body: marker, columns, footer, determinism': 11, 'refusing to overwrite what is not the roster': 6, 'the CLI: fixture runs offline, usage errors are exit 2': 6, @@ -1101,7 +1116,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ // 25 → 28: 发版阻塞 reads the two release boards whatever `--repos` holds; a board that does not answer is a gap. '--health: five indicators off one walk, every count checked, every gap named': 28, }); -const SELF_TEST_BATTERY_FLOOR = 12; +const SELF_TEST_BATTERY_FLOOR = 13; async function selfTest() { let failed = 0; @@ -1286,14 +1301,40 @@ async function selfTest() { return [line.includes('| = seat 1 |'), line.includes(SUSPECTED_WALL)]; })(), [true, false]); t('the comment read starts STALE_HOURS before now, and the footer names it', [activitySince(NOW), readsFor([R]).some((q) => q.startsWith(`GET /repos/${R}/issues/comments?since=`))], ['2026-11-01T22:00:00Z', true]); - const { readSignatureLine } = await import('./check-half-states.mjs'); - t('the signature pattern is check-half-states\' SEAT_SIGNATURE_LINE, imported — no second spelling of the lane alternation in this file (and the awaiting-merge label rides the same import, no second spelling of it either)', [/^import \{ GOVERNED_PR_AWAITING_MERGE_LABEL, SEAT_SIGNATURE_LINE \} from '\.\/check-half-states\.mjs';$/mu.test(readFileSync(SELF_PATH, 'utf8')), readFileSync(SELF_PATH, 'utf8').includes(['triage', 'director', 'coordinator'].join('|')), readFileSync(SELF_PATH, 'utf8').includes(["'pm:", 'awaiting-merge', "'"].join(''))], [true, false, false]); + t('the signature pattern is check-half-states\' SEAT_SIGNATURE_LINE, imported — no second spelling of the lane alternation in this file (and the awaiting-merge label rides the same import, no second spelling of it either)', [/^import \{ GOVERNED_PR_AWAITING_MERGE_LABEL, readSignatureLine, SEAT_SIGNATURE_LINE, seatIdOf, seatTitleAccount \} from '\.\/check-half-states\.mjs';$/mu.test(readFileSync(SELF_PATH, 'utf8')), readFileSync(SELF_PATH, 'utf8').includes(['triage', 'director', 'coordinator'].join('|')), readFileSync(SELF_PATH, 'utf8').includes(["'pm:", 'awaiting-merge', "'"].join(''))], [true, false, false]); // The lane grammar's two remaining owners, held equal here (the only file that imports both): the signature's // alternation and the opener's lane-word lists. `coordinator` is the one lane that signs and has no mailbox. - const signatureLanes = (/^\^\(\(\?:([^()]*)\)\)#/u.exec(SEAT_SIGNATURE_LINE.source)?.[1] ?? '').split('|'); + const signatureLanes = (/^\^\(\(\?:([^()]*)\)\)\(/u.exec(SEAT_SIGNATURE_LINE.source)?.[1] ?? '').split('|'); t('⭐ the lane grammar is ONE set: the signature\'s kinds are the opener\'s kinds plus `epic`, its bare words the opener\'s bare lanes plus `coordinator` — a lane added to one side alone reds here', [signatureLanes.filter((a) => a.includes(':')).map((a) => a.slice(0, a.indexOf(':'))).sort(), signatureLanes.filter((a) => !a.includes(':')).sort(), signatureLanes.length], [[...mailboxOpen.SEAT_LANE_KINDS, SEAT_EPIC_KIND].sort(), [...mailboxOpen.SEAT_BARE_LANES, 'coordinator'].sort(), mailboxOpen.SEAT_LANE_KINDS.length + 1 + mailboxOpen.SEAT_BARE_LANES.length + 1]); const corpus = ['', sig('domain:server#2'), `\n\n ${sig('domain:engine-core#3')}\r\nbody`, `body\n${sig('triage#1')}`, sig('security#1'), 'epic:#27293#1 · sunhaolin · session_017xRBcVBKAFk1ntXSjvPt7U', 'domain:server#0 · os-pm · session_01SharedSeatSess', 'domain:server#2 · os-pm · cse_01SharedSeatSess']; - t('signedSeatOf reads every body as readSignatureLine does', corpus.map(signedSeatOf), corpus.map((b) => { const r = readSignatureLine(b); return r ? `${r.lane}#${r.seat}` : null; })); + t('signedSeatOf reads every body as readSignatureLine does', corpus.map(signedSeatOf), corpus.map((b) => { const r = readSignatureLine(b); return r ? seatIdOf(r.lane, r.seat) : null; })); + } + + battery('a seat named by its account: `LANE@ACCOUNT` is a row of its own, read by lane AND account beside `LANE#N` (ruling record 7249169754)'); + { + const NOW = '2026-11-02T04:00:00Z'; + const R = 'objectstack-ai/objectstack'; + const fresh = '2026-11-02T03:00:00Z'; // 1 h before NOW + const sig = (laneSeat, account) => `${laneSeat} · ${account} · session_01AccountSeatSess`; + const named = seat('[PM seat] repo:objectstack@OS-Bill — 🟢 os-bill · area:fleet'); + t('⭐ the title `LANE@ACCOUNT`: lane, the seat mark `@account` (lower-cased), the lane\'s repo — ⛔ never seat 1, and its account is no board', [named.lane, named.seat, named.repo, named.status, named.account], ['repo:objectstack', '@os-bill', 'objectstack-ai/objectstack', 'seated', 'os-bill']); + t('…on a `domain:` lane and a bare lane too, while a board suffix written after a space is still a board and still seat 1', [seat('[PM seat] domain:ui@os-bill — 🟢 os-bill').seat, seat('[PM seat] domain:ui@os-bill — 🟢 os-bill').repo, seat('[PM seat] l2-review@os-bill — 🟢 os-bill').lane, seat('[PM seat] l2-review@os-bill — 🟢 os-bill').seat, ui.seat, ui.repo], ['@os-bill', 'objectstack-ai/objectstack', 'l2-review', '@os-bill', 5, 'objectstack-ai/objectui']); + // Seat 1 is vacant with its old `#1` traces standing; os-bill's seat and os-elon's are named by their accounts. + const snap = (comments = [], pulls = []) => ({ repos: { [R]: { seats: [ + { number: 500, title: '[PM seat] repo:objectstack@os-elon — 🟢 os-elon', body: '', labels: ['pm:seat'], assignees: ['os-elon'], updated_at: '2026-10-30T00:00:00Z' }, + { number: 400, title: '[PM seat] repo:objectstack@os-bill — 🟢 os-bill', body: '', labels: ['pm:seat'], assignees: ['os-bill'], updated_at: '2026-10-30T00:00:00Z' }, + { number: 100, title: '[PM seat] repo:objectstack — ⏳ vacant', body: '', labels: ['pm:seat'], assignees: [], updated_at: '2026-10-30T00:00:00Z' }, + { number: 200, title: '[PM seat] repo:objectstack · seat 2 — 🟢 os-pm', body: '', labels: ['pm:seat'], assignees: ['os-pm'], updated_at: '2026-10-30T00:00:00Z' }, + ], dispatched: [], rulings: [], pulls, comments: {}, recentComments: comments } } }); + const rowOf = (s, post) => buildRows(s, { now: NOW }).find((r) => r.post === post); + t('the rows order the numbered seats by number, then the seats named by an account, by name', buildRows(snap(), { now: NOW }).map((r) => r.seat), [1, 2, '@os-bill', '@os-elon']); + t('⭐ a comment signed `LANE@ACCOUNT` is that seat\'s trace — and ⛔ not account Y\'s seat of the same lane, nor a numbered seat\'s', (() => { const s = snap([{ body: sig('repo:objectstack@os-bill', 'os-bill'), updated_at: fresh }]); return [rowOf(s, 400).lastActivity, rowOf(s, 500).lastActivity, rowOf(s, 100).lastActivity, rowOf(s, 200).lastActivity]; })(), [fresh, '2026-10-30T00:00:00Z', '2026-10-30T00:00:00Z', '2026-10-30T00:00:00Z']); + t('⛔ account X signing account Y\'s seat signs nothing: no seat reads the trace', (() => { const s = snap([{ body: sig('repo:objectstack@os-bill', 'os-elon'), updated_at: fresh }]); return [rowOf(s, 400).lastActivity, rowOf(s, 500).lastActivity]; })(), ['2026-10-30T00:00:00Z', '2026-10-30T00:00:00Z']); + t('⭐ CONTROL — a `#1` comment by the vacant seat still reads as seat 1\'s, whoever signed it: ⛔ not as that login\'s account seat', (() => { const s = snap([{ body: sig('repo:objectstack#1', 'os-elon'), updated_at: fresh }]); return [rowOf(s, 100).lastActivity, rowOf(s, 500).lastActivity, signedSeatOf(sig('repo:objectstack#1', 'os-elon')), signedSeatOf(sig('repo:objectstack@os-elon', 'os-elon'))]; })(), [fresh, '2026-10-30T00:00:00Z', 'repo:objectstack#1', 'repo:objectstack@os-elon']); + t('⭐ the mailbox column by lane AND account: the account seat\'s own mailbox, read off the body line or the head, and never seat 1\'s nor another account\'s', (() => { const s = snap([], [{ number: 601, state: 'open', head: { ref: 'claude/project-thread-1' }, body: 'Mailbox-of: repo:objectstack@os-bill · os-bill', labels: ['pm:mailbox'], updated_at: fresh }, { number: 602, state: 'open', head: { ref: 'mailbox/os-elon/repo-objectstack_os-elon-0' }, body: '', labels: ['pm:mailbox'], updated_at: fresh }, { number: 603, state: 'open', head: { ref: 'mailbox/os-old/repo-objectstack-1' }, body: 'Mailbox-of: repo:objectstack#1 · os-old', labels: ['pm:mailbox'], updated_at: fresh }]); return [400, 500, 100, 200].map((post) => rowOf(s, post).mailbox.map((m) => m.number)); })(), [[601], [602], [603], []]); + t('⭐ an L2 seat named by its account holds its own claims\' pulls, under either lane word — keyed `LANE@account`, ⛔ never a numbered review seat\'s', [...reviewClaims({ repos: { r: { pulls: [{ number: 1, state: 'open', head: { sha: 'a'.repeat(40) } }], recentComments: ['l2-review@os-bill', 'review@os-bill', 'l2-review#2'].map((laneSeat) => ({ issue_url: 'x/issues/1', created_at: NOW, body: `${sig(laneSeat, 'os-bill')}\n\nContract-review-claim: session_01AccountSeatSess · head ${'a'.repeat(40)} · ${NOW}` })) } } }, { now: NOW }).entries()].map(([k, v]) => `${k}=${v.map((x) => x.number)}`), ['l2-review@os-bill=1', 'review@os-bill=1', 'l2-review#2=1']); + t('⭐ an epic seat named by its account is that epic\'s seat, matched by its own slug under its own login; the numbered epic seat reads as before', [...epicSeatsHeld(`${SEAT_EPIC_KIND}:#27293`, [{ slug: 'epic-27293_sunhaolin-0', login: 'sunhaolin' }, { slug: 'epic-27293-2', login: 'os-x' }, { slug: 'epic-27293_other-0', login: 'sunhaolin' }])], [['@sunhaolin', 'sunhaolin'], [2, 'os-x']]); + t('the rendered seat cell prints an account mark in a code span — ⛔ never a loose `@login`, which an issue body turns into a mention', (() => { const line = renderBody(buildRows(snap(), { now: NOW }), { now: NOW, repos: [R] }).split('\n').find((l) => l.includes('/issues/400)')); return [line.includes('[`@os-bill`](https://github.com/objectstack-ai/objectstack/issues/400)'), / @os-/.test(line)]; })(), [true, false]); } battery('the rendered body: marker, columns, footer, determinism'); diff --git a/scripts/pm/fleet-write/dispatch.mjs b/scripts/pm/fleet-write/dispatch.mjs index b6fc55d0388..19fc658f7d1 100644 --- a/scripts/pm/fleet-write/dispatch.mjs +++ b/scripts/pm/fleet-write/dispatch.mjs @@ -941,7 +941,7 @@ function trailerWhy(body) { if (read === null) return { line: '(the body is empty)', why: 'there is no last line to carry the trailer' }; const line = read.line.length > 160 ? `${read.line.slice(0, 160)}…` : read.line; return read.shaped - ? { line, why: "the last non-empty line is the trailer's comment, but its inside is not a signature — check the lane, the `#N` seat number, the login, the full session id, and that each separator is exactly ` · `" } + ? { line, why: "the last non-empty line is the trailer's comment, but its inside is not a signature — check the lane, the `#N` seat number (or an `@ACCOUNT` seat, which only that same account signs), the login, the full session id, and that each separator is exactly ` · `" } : { line, why: 'the last non-empty line is not the trailer' }; } @@ -1718,7 +1718,7 @@ const strictNoteUtf8 = new TextDecoder('utf-8', { fatal: true }); /** * Why `section` is not a note's section, or null when it is (`ops.mjs`, "The one row that APPENDS"): line 1 the seat's - * signature line (`SEAT_SIGNATURE_LINE`, exactly), line 2 a stamp in `ADVISORY_NOTE_STAMP_SHAPE`, line 3 blank, then + * signature line (`SEAT_SIGNATURE_LINE`, exactly, and a signature to `readSignatureLine`: either seat mark), line 2 a stamp in `ADVISORY_NOTE_STAMP_SHAPE`, line 3 blank, then * a note that is not blank and ends in no whitespace; no control character but the tab and the newline; at most * `MAX_ADVISORY_NOTE_BYTES`. This door judges it before the seal and the executor again after the open — so ⛔ no * sentence carries a byte of it: the executor's lines reach a public log. Pure. @@ -1729,7 +1729,7 @@ export function advisoryNoteSectionFailure(section) { if (bytes > MAX_ADVISORY_NOTE_BYTES) return `the section is ${bytes} bytes, over its cap of ${MAX_ADVISORY_NOTE_BYTES}`; if (NOTE_CONTROL_SHAPE.test(section)) return 'the section carries a control character other than a tab or a newline (a carriage return among them)'; const lines = section.split('\n'); - if (!SEAT_SIGNATURE_LINE.test(lines[0])) return `its first line is not a seat signature line — ${SEAT_SIGNATURE_SHAPE}`; + if (!SEAT_SIGNATURE_LINE.test(lines[0]) || readSignatureLine(lines[0]) === null) return `its first line is not a seat signature line — ${SEAT_SIGNATURE_SHAPE}`; if (lines.length < 4 || !ADVISORY_NOTE_STAMP_SHAPE.test(lines[1])) return 'its second line is not the UTC stamp the door writes, YYYY-MM-DDThh:mm:ssZ'; if (lines[2] !== '') return 'its third line is not blank'; const note = lines.slice(3).join('\n'); @@ -1748,7 +1748,7 @@ export function advisoryNoteSection(text, stamp) { if (text.includes('\r')) return { refusal: 'it carries a carriage return — save it with LF line endings' }; const lines = text.split('\n'); const signature = lines[0].trim(); - if (!SEAT_SIGNATURE_LINE.test(signature)) return { refusal: `its first line is not your signature line — write ${SEAT_SIGNATURE_SHAPE} as the FIRST line, alone` }; + if (readSignatureLine(signature) === null) return { refusal: `its first line is not your signature line — write ${SEAT_SIGNATURE_SHAPE} as the FIRST line, alone` }; const rest = lines.slice(1); while (rest.length && rest[0].trim() === '') rest.shift(); if (rest.length && TYPED_STAMP_SHAPE.test(rest[0].trim())) return { refusal: 'the line after the signature is a typed stamp — delete it: this door writes the stamp from its own clock' }; @@ -2783,8 +2783,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ "the started run: an action naming a workflow is read back as the newest workflow_dispatch run of that file created since the dispatch — the target repo's run list, read after the relay run completed and re-read within a bounded window; found is success naming id, url and actor; none in the window or an unreadable list is UNCONFIRMED (6) after ONE dispatch; a stroke naming no workflow reads none": 13, "the release.yml refresh at the seat: the stroke packs with inputs refresh_version_pr true and travels in ONE dispatch; its started run is read back from release.yml's own run list; force, false, absent or any other input is refused before anything is sent, exit 2": 6, "the batch gap at the seat: content creation read off the op table; a stroke at or above write-pace's threshold is batched through its last content-creating write and waited for exactly that much longer; a stroke whose pacing the relay job cannot hold is refused before anything is sent, naming the per-op doors; the job's timeout mirrors the workflow's": 13, - "the signature at the seat's door: a comment_edit or issue_patch body opens with the seat's signature line or the file is usage (2), nothing packed; generated, body-less and the other doors' ops are left alone": 13, - "the pull request body at the seat's door: an issue_patch body signed only by its LAST-line trailer passes when the platform answers its target is a pull request, before the dry-run exit; an issue, an unread target and a trailer-less body are refused; comment_edit takes no trailer": 19, + "the signature at the seat's door: a comment_edit or issue_patch body opens with the seat's signature line or the file is usage (2), nothing packed; generated, body-less and the other doors' ops are left alone": 15, + "the pull request body at the seat's door: an issue_patch body signed only by its LAST-line trailer passes when the platform answers its target is a pull request, before the dry-run exit; an issue, an unread target and a trailer-less body are refused; comment_edit takes no trailer": 20, "the kind rule at the relay's adding doors: a pm state on pr_create or on a labels_add whose target READS as a pull request, and pm:awaiting-merge on issue_create or on a labels_add whose target reads as an issue, are refused before the dry-run exit with label-write's own sentence, case-insensitively and for the whole file; an unread kind is never a pass; labels_remove and an ungoverned labels_add read nothing": 18, "the run_rerun_failed stroke at the seat: it packs as ONE action carrying run_id alone and travels in ONE dispatch; beside any other action, or with a key that widens it, it is refused before anything is sent; it creates no content, carries no body and names no workflow, so nothing is read back here — a success run is the executor's confirmation; a run that failed at the relay's fence is exit 5 after ONE dispatch, never re-sent": 6, "the hierarchy link at the seat: an epic's children pack as sub_issue_add actions carrying the parent and the child by number alone, beside other issue ops in ONE dispatch; a self-link, an id or a replace_parent is refused before anything is sent; neither row creates content, carries a body or names a workflow, so the stroke is paced at rule ①'s gap and nothing is read back here — a success run is the executor's confirmation; a run that failed at the relay's fence is exit 5 after ONE dispatch, never re-sent": 5, @@ -2792,7 +2792,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ "retired lane aliases at the seat's door: a domain:engine / services / cli / rest label on labels_add, issue_create or pr_create is written as domain:server and said on stderr, a dry run included; a live domain:* label, a non-lane label and labels_remove pass untouched; the rewrite never refuses": 13, "advisory_read at the seat: the key pair made in this process per read — its public half in the action, its private half a KeyObject never exported, written or printed, and a key from the file refused; no byte read-back, said where the read-back is decided; the run's notice parts read back exactly, reassembled 1..n once each and opened with that key byte for byte, end to end through the real executor; what does not open is UNVERIFIED (6) with nothing printed; the text reaches this process's stdout on --reveal alone, never stderr or --json": 17, "advisory_list at the seat: derived from the table into the sealed-read path, so its key pair is made here and a key from the file refused, with no byte read-back, said where the read-back is decided; the real executor's ten notice parts read back, reassembled and opened under the listing's own associated data — never a read's — byte for byte on the padded plaintext; what does not open is UNVERIFIED (6) with nothing printed; --reveal alone prints it, its pad trimmed for that op's display alone, never on stderr or --json": 9, - "advisory_note at the seat: the note read from the file note_file names, composed under the seat's signature line and this door's own stamp, judged, then sealed HERE with a one-time digest key to the relay's committed half under the stroke's request id — the payload carrying the seal alone; a seal from the file, a file inside any git repository, and a missing, unreadable or unjudged one refused and a null committed half a prerequisite, all before anything is sent; the run's ONE notice confirmed against the byte count and keyed digest only this process holds, anything else UNVERIFIED, exit 6 — and no byte of the note on any line the seat prints": 22, + "advisory_note at the seat: the note read from the file note_file names, composed under the seat's signature line and this door's own stamp, judged, then sealed HERE with a one-time digest key to the relay's committed half under the stroke's request id — the payload carrying the seal alone; a seal from the file, a file inside any git repository, and a missing, unreadable or unjudged one refused and a null committed half a prerequisite, all before anything is sent; the run's ONE notice confirmed against the byte count and keyed digest only this process holds, anything else UNVERIFIED, exit 6 — and no byte of the note on any line the seat prints": 23, "advisory_rewrite at the seat: the summary and/or description read from the files summary_file and description_file name, each placed outside every git repository by the note's own check, spelled as one JSON object with no signature or stamp and judged — an empty description refused — then sealed HERE through the note's path with a one-time digest key under the rewrite's own associated data, the payload carrying the seal alone; the real executor's ONE notice confirmed against that digest, a mismatch UNVERIFIED, exit 6 — and no byte of either text on any line the seat prints": 12, }); // Raised 21 → 22 with the run_rerun_failed seat battery, 22 → 23 with the signature battery, 23 → 24 with the @@ -3990,6 +3990,7 @@ export async function selfTest() { // The section. t("the stamp is this door's clock read to the second in UTC, in the one spelling the section's check reads", [advisoryNoteStamp(NOW), ADVISORY_NOTE_STAMP_SHAPE.test(advisoryNoteStamp(NOW))], [STAMP, true]); t("⭐ the section: the file's first line — the seat's signature line, trimmed — then this door's stamp, a blank line and the rest of the file, its leading blank lines and trailing whitespace dropped; the check passes it", [advisoryNoteSection(FILE_TEXT, STAMP), advisoryNoteSectionFailure(SECTION)], [{ section: SECTION }, null]); + t("⭐ both seat marks sign a note: a file opening `LANE@ACCOUNT` composes and passes the check as the `LANE#N` one does; ⛔ that seat under another account is no signature line, at the door and at the check", (() => { const ACC = `security@os-dev-a · os-dev-a · ${SESSION}`; const OTHER = `security@os-dev-a · os-dev-b · ${SESSION}`; const made = advisoryNoteSection(`${ACC}\n${MARKER}`, STAMP); return [made.section === `${ACC}\n${STAMP}\n\n${MARKER}`, advisoryNoteSectionFailure(made.section ?? ''), advisoryNoteSection(`${OTHER}\n${MARKER}`, STAMP).refusal?.includes('not your signature line'), advisoryNoteSectionFailure(`${OTHER}\n${STAMP}\n\n${MARKER}`)?.includes('not a seat signature line')]; })(), [true, null, true, true]); const sectionRefusals = [ `${SIG}\r\n${MARKER}`, `${MARKER}\n${SIG}`, @@ -4513,6 +4514,9 @@ export async function selfTest() { t('…each row carries the line it read and why', unsignedEditBodies([{ op: 'comment_edit', comment_id: 7, body: '\n\nEdited.' }])[0]?.line, 'Edited.'); t('signed bodies pass, blank lines above the signature included', ROWS([{ op: 'comment_edit', comment_id: 7, body: `${SIG}\nEdited.` }, { op: 'issue_patch', issue: 3, body: `\n${SIG}\n\nSeat post` }]), []); t('⛔ a signature on a LATER line is not one: the first non-empty line decides', ROWS([{ op: 'issue_patch', issue: 3, body: `Seat post\n${SIG}` }]), ['1:issue_patch']); + // The second seat mark (ruling record 7249169754): `LANE@ACCOUNT` is read beside `LANE#N`; the shape the refusal prints is still `#N`. + t('⭐ both seat marks open an edit body: one signed `LANE@ACCOUNT` passes as the `LANE#N` one does', ROWS([{ op: 'comment_edit', comment_id: 7, body: `repo:objectstack@os-justin · os-justin · ${SESSION}\nEdited.` }, { op: 'issue_patch', issue: 3, body: `repo:objectstack#5 · os-justin · ${SESSION}\nSeat post` }]), []); + t('⛔ account X signing account Y\'s seat is refused, named a near miss — the body is never packed as Y\'s seat', (() => { const rows = unsignedEditBodies([{ op: 'issue_patch', issue: 3, body: `repo:objectstack@os-justin · os-elon · ${SESSION}\nSeat post` }]); return [rows.map((r) => `${r.action}:${r.op}`), rows[0]?.why.includes('only that same account signs')]; })(), [['1:issue_patch'], true]); t('an issue_patch that carries no body (a close) is not judged', ROWS([{ op: 'issue_patch', issue: 3, state: 'closed', state_reason: 'completed' }]), []); t("the other doors' ops are not judged here — comment and issue_create refuse at post-stamped and issue-create, pr_create's first line is `Fixes #n`", ROWS([{ op: 'comment', issue: 1, body: 'x' }, { op: 'issue_create', title: 't', body: 'x' }, { op: 'pr_create', title: 't', head: 'h', base: 'main', body: 'Fixes #1' }]), []); t('the roster body is generated, and exempt by the marker its generator writes — imported, never restated', [GENERATED_BODY_MARKERS.includes(ROSTER_MARKER), ROWS([{ op: 'issue_patch', issue: 9, body: `${ROSTER_MARKER}\n\n| seat | holder |` }])], [true, []]); @@ -4616,6 +4620,7 @@ export async function selfTest() { const CANDS = (actions) => pullRequestBodyCandidates(actions).map((r) => `${r.action}:${r.issue}`); t('the trailer parses with the existing signature reader: the same four parts as the bare line', [readPrBodyTrailer(PR_BODY)?.shaped, readPrBodyTrailer(PR_BODY)?.signature], [true, readSignatureLine(SIG)]); t('…trailing blank lines are not the last line, and spaces inside the comment are trimmed', readPrBodyTrailer(`x\n\n\n\n`)?.signature?.session, SESSION); + t('⭐ the trailer reads both seat marks: `LANE@ACCOUNT` names the landing seat by its account (`@account`), and under another account it is shaped but no signature', [readPrBodyTrailer(`x\n`)?.signature?.seat, readPrBodyTrailer(`x\n`)?.signature?.seat, readPrBodyTrailer(`x\n`)?.shaped, readPrBodyTrailer(`x\n`)?.signature], ['@marchtian', 5, true, null]); t('⛔ the trailer on an EARLIER line is not one: the last non-empty line decides', readPrBodyTrailer(`${TRAILER}\nMore prose`)?.signature ?? null, null); t('⛔ a bare signature on the last line, or the comment around a near miss, is no trailer — the near miss still reads as shaped', [readPrBodyTrailer(`x\n${SIG}`)?.shaped, readPrBodyTrailer(`x\n`)?.shaped, readPrBodyTrailer(`x\n`)?.signature], [false, true, null]); t('a trailer-only issue_patch body is a candidate for the platform read, and not a first-line refusal', [CANDS([{ op: 'issue_patch', issue: 29200, body: PR_BODY }]), ROWS([{ op: 'issue_patch', issue: 29200, body: PR_BODY }])], [['1:29200'], []]); diff --git a/scripts/pm/fleet-write/execute.mjs b/scripts/pm/fleet-write/execute.mjs index 92817b6061b..5eae3d4f9fb 100644 --- a/scripts/pm/fleet-write/execute.mjs +++ b/scripts/pm/fleet-write/execute.mjs @@ -2928,12 +2928,12 @@ const SELF_TEST_BATTERIES = Object.freeze({ "the pr_enqueue_front: the pull's own GET, its whole file list and its base's queue read immediately before ONE enqueuePullRequest mutation with jump true and the expected head — open, ready, its head, not Version Packages, no governed path, at most the human-merge line count, a queue read whole with no jumped entry; each fence refused with the mutation not sent; GraphQL errors FAILED naming the missing grant; the 200 confirmed only by reading the queue back with the pull jumped and nothing ahead; queued without the jump or behind another is FAILED, never re-sent; the queue read unpaced; no annotation": 20, // 9 → 12 with a carrying comment that opens with a seat signature refused, its other way, and no reader carrying nothing; // the other way flipped (still 12) when a signature on ANY line refused the carry, not only the first. - "the pr_enqueue_front SIZE lift: a pull over the human-merge line is jumped only on an authorised APPROVED review on its current head, or an earlier one carried to the head by an authorised comment on the pull naming it — the reviews read only over the line, a full page or an unread list lifting nothing, a non-approver, an approval elsewhere, a comment naming another head or pull or holding a seat signature on any line refused with the mutation not sent": 12, + "the pr_enqueue_front SIZE lift: a pull over the human-merge line is jumped only on an authorised APPROVED review on its current head, or an earlier one carried to the head by an authorised comment on the pull naming it — the reviews read only over the line, a full page or an unread list lifting nothing, a non-approver, an approval elsewhere, a comment naming another head or pull or holding a seat signature on any line refused with the mutation not sent": 13, // 16 → 27 with seat-asks bound to the landing seat (another seat, the relay's own audit, no trailer, the pure match), // the pull read back open and unmerged (merged, closed, a late read, the pure reading) and the node id from the first read; // 27 → 28 with the second pull read one interval later, a merge that shows only there refused; // 28 → 29 with a failed second pull read starting the pair over. - "the pr_dequeue: the pull's own GET, its base's queue with each entry's merge-group rollup and, for seat-asks alone, its comments read before ONE audit comment and ONE dequeuePullRequest mutation — open, its head, not Version Packages, a queue read whole that lists it, and the cause holding on those reads (conflict: dirty; own-failure: UNMERGEABLE or a failing rollup, never an unread one; seat-asks: a relay comment signed by the landing seat its body's trailer names, under the dispatching session — another seat's comment refused); each fence refused with nothing written; no audit comment, no mutation; GraphQL errors FAILED naming the grant; the 200 confirmed only by reading the queue back without the pull and the pull still open and unmerged on two reads one interval apart, a merge or close inside the window FAILED, UNCONFIRMED after the window": 29, + "the pr_dequeue: the pull's own GET, its base's queue with each entry's merge-group rollup and, for seat-asks alone, its comments read before ONE audit comment and ONE dequeuePullRequest mutation — open, its head, not Version Packages, a queue read whole that lists it, and the cause holding on those reads (conflict: dirty; own-failure: UNMERGEABLE or a failing rollup, never an unread one; seat-asks: a relay comment signed by the landing seat its body's trailer names, under the dispatching session — another seat's comment refused); each fence refused with nothing written; no audit comment, no mutation; GraphQL errors FAILED naming the grant; the 200 confirmed only by reading the queue back without the pull and the pull still open and unmerged on two reads one interval apart, a merge or close inside the window FAILED, UNCONFIRMED after the window": 30, "the hierarchy link: sub_issue_add and sub_issue_remove read the parent's and the child's own answers, then the child's parent (add) or the parent's whole list (remove), immediately before ONE write whose body is the child's REST id from its own answer — never its number, never replace_parent; a pull, a transferred or unread card, a child under another parent, one the parent does not list, or a read that is neither answer is zero writes; a child already under this parent is a no-op landed on the list; the answer confirmed only when the parent's list reads the child back (or no longer does) inside the window; a refused write, a list that never settles or never reads whole is FAILED; no annotation, and the rows ride a stroke beside other ops": 20, "the advisory rows: advisory_report and advisory_create are ONE POST of their body each, landed on a 2xx carrying an id — a draft's reading state draft — that the row and a notice annotation name; advisory_collaborators_add, advisory_versions and advisory_state read the advisory first and send ONE PATCH — every existing login kept with the missing ones added, an all-present list a no-op, the versions entries alone, or the one state a legal transition reaches, the reopen and the publish among them — or nothing at all on a fence: an unread, other or wrong-state advisory, an illegal move, a list the versions may not replace or a publish whose versions are not set; each lands only when its answer shows the result, a publish only read back as published with the versions it was sent, and a landed publish alone is annotated with its id; ⛔ the marker in a report's or a draft's summary, description and packages and in every advisory answer's summary, description and vulnerabilities reaches no log line, row, step summary or annotation": 46, "the mailbox branch delete: the pull's own answer, the open pulls on its head and the ref read immediately before ONE DELETE of the ref under the App token — an open, unlabelled, other-headed or forked pull, an open pull on that head, a ref moved off the pull's head, or a read that does not answer is zero writes with every failing fence named; the DELETE lands only when the ref reads back absent, a ref already gone an idempotent landing and one still there FAILED; and mailbox-open's close stroke — comment, close, delete — leaves no branch, while a head outside claude/mailbox-* sends no DELETE": 7, @@ -3949,6 +3949,8 @@ export async function selfTest() { t('⛔ CARRIED, refused: the approver\'s comment naming the head but opening with a SEAT signature (an agent-operated account\'s knock or record) carries nothing, the reading naming the seat', [await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: seatSigned }, { approval_comment: 71 }), (await run(stroke({ approval_comment: 71 }), { ...happy, [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: seatSigned })).rows[0]?.result.includes('a seat\'s comment is no carried approval')], [refused, true]); const signedLower = commentOf({ body: `The approval carries to ${HEAD.slice(0, 9)}.\n\ntriage#1 · ${APPROVER} · session_01ABCDEFGHJKMNPQRSTVWXYZ` }); t('⛔ CARRIED, refused on ANY line: the same approver\'s comment with the seat signature further down, not first, carries nothing either — the reading naming the seat', [await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: signedLower }, { approval_comment: 71 }), (await run(stroke({ approval_comment: 71 }), { ...happy, [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: signedLower })).rows[0]?.result.includes('holds the seat signature triage#1')], [refused, true]); + const signedNamed = commentOf({ body: `The approval carries to ${HEAD.slice(0, 9)}.\n\nrepo:objectstack@${APPROVER} · ${APPROVER} · session_01ABCDEFGHJKMNPQRSTVWXYZ` }); + t('⛔ CARRIED, refused under the second seat mark too: a comment holding a `LANE@ACCOUNT` signature is a seat\'s comment — the reading naming that seat', [await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: signedNamed }, { approval_comment: 71 }), (await run(stroke({ approval_comment: 71 }), { ...happy, [REVIEWS]: reviewsOf(review(APPROVER, EARLIER)), [COMMENT]: signedNamed })).rows[0]?.result.includes(`holds the seat signature repo:objectstack@${APPROVER.toLowerCase()} · ${APPROVER}`)], [refused, true]); const pastApproval = { state: 'approved', approvals: [{ login: APPROVER, commitId: EARLIER }] }; t('enqueueFrontSizeLift with no signature reader carries nothing — the opening line unjudged is never a pass', [enqueueFrontSizeLift({ verdict: pastApproval, headSha: HEAD, comment: commentOf(), pull: PULL, approvers: GOVERNED_APPROVERS }).lifts, enqueueFrontSizeLift({ verdict: pastApproval, headSha: HEAD, comment: commentOf(), pull: PULL, approvers: GOVERNED_APPROVERS, signatureOf: () => null }).lifts], [false, true]); t('⛔ an approval by an account outside GOVERNED_APPROVERS, or one the approver later dismissed, lifts nothing even on the head', [await verdict({ [REVIEWS]: reviewsOf(review('os-support-ai', HEAD)) }), await verdict({ [REVIEWS]: reviewsOf(review(APPROVER, HEAD), review(APPROVER, HEAD, 'DISMISSED')) })], [refused, refused]); @@ -4014,6 +4016,7 @@ export async function selfTest() { const noTrailer = await run(stroke({ cause: 'seat-asks' }), { ...happy, ...asks(signed(RELAY_COMMENT_AUTHOR, SESSION)), [PULL_GET]: pullAt({ mergeable: true, mergeable_state: 'blocked', body: prBody.replace(//u, '') }) }); t('⛔ seat-asks, refused: a pull body whose last line is no signed trailer names no landing seat — refused unread, its comments never walked, the sentence naming the trailer', [noTrailer.exit, writes(noTrailer.seen).filter((x) => x.call !== GQL).length, noTrailer.seen.filter((x) => x.call === COMMENTS).length, noTrailer.rows[0]?.result.includes("signed trailer names no seat")], [EXIT_ACTION_FAILED, 0, 0, true]); t('signedByLandingSeat: one seat, account and session holds; any one of the four parts different, or either reading missing, does not', [signedByLandingSeat({ lane: 'domain:server', seat: 5, account: 'a', session: 's' }, { lane: 'domain:server', seat: 5, account: 'a', session: 'other' }, 's'), ...[{ lane: 'queue' }, { seat: 6 }, { account: 'b' }, { session: 't' }].map((d) => signedByLandingSeat({ lane: 'domain:server', seat: 5, account: 'a', session: 's', ...d }, { lane: 'domain:server', seat: 5, account: 'a' }, 's')), signedByLandingSeat(null, { lane: 'x', seat: 1, account: 'a' }, 's'), signedByLandingSeat({ lane: 'x', seat: 1, account: 'a', session: 's' }, null, 's')], [true, false, false, false, false, false, false]); + t('⭐ signedByLandingSeat reads both seat marks, by lane AND mark: an account seat\'s signature is its own landing seat\'s; ⛔ never a numbered seat\'s of the lane (CONTROL: a `#5` signature stays seat 5\'s, whoever signed it), nor another account\'s', (() => { const acct = readSignatureLine('repo:objectstack@os-a · os-a · session_01ABCDEF'); const num = readSignatureLine('repo:objectstack#5 · os-a · session_01ABCDEF'); const other = readSignatureLine('repo:objectstack@os-b · os-b · session_01ABCDEF'); return [signedByLandingSeat(acct, acct, 'session_01ABCDEF'), signedByLandingSeat(num, num, 'session_01ABCDEF'), signedByLandingSeat(num, acct, 'session_01ABCDEF'), signedByLandingSeat(acct, num, 'session_01ABCDEF'), signedByLandingSeat(other, acct, 'session_01ABCDEF'), readSignatureLine('repo:objectstack@os-a · os-b · session_01ABCDEF')]; })(), [true, true, false, false, false, null]); const unreadComments = await run(stroke({ cause: 'seat-asks' }), { ...happy, ...asks({ status: 502, json: { message: 'Bad Gateway' } }) }); t('⛔ seat-asks with the comments unread: nothing written, the read named — an unread list is never unsigned', [unreadComments.exit, writes(unreadComments.seen).filter((x) => x.call !== GQL).length, mutations(unreadComments.seen).length, unreadComments.rows[0]?.result.includes('comments could not be read')], [EXIT_ACTION_FAILED, 0, 0, true]); const noAudit = await run(stroke(), { ...happy, [AUDIT]: { status: 403, json: { message: 'Resource not accessible by integration' } } }); diff --git a/scripts/pm/fleet-write/ops.mjs b/scripts/pm/fleet-write/ops.mjs index cb4d12bdc06..5c21491f9b0 100644 --- a/scripts/pm/fleet-write/ops.mjs +++ b/scripts/pm/fleet-write/ops.mjs @@ -1676,7 +1676,7 @@ export function enqueueFrontSizeLift({ verdict = null, headSha = null, comment = if (typeof signatureOf !== 'function') return { lifts: false, way: null, reading: `${earlier}; the approval_comment's lines were not judged for a seat signature` }; // Every line is read, not only the first: a signature lower down is a seat's record all the same (header). const seat = String(c.body ?? '').split(/\r?\n/u).map((line) => signatureOf(line)).find(Boolean) ?? null; - if (seat) return { lifts: false, way: null, reading: `${earlier}; the approval_comment by ${author} holds the seat signature ${seat.lane}#${seat.seat} · ${seat.account} — a seat's comment is no carried approval` }; + if (seat) return { lifts: false, way: null, reading: `${earlier}; the approval_comment by ${author} holds the seat signature ${seatOf(seat)} — a seat's comment is no carried approval` }; const tokens = String(c.body ?? '').match(/\b[0-9a-f]{7,40}\b/giu) ?? []; const carries = head !== '' && tokens.some((tok) => tok.length >= CARRIED_HEAD_MIN_CHARS && head.startsWith(tok.toLowerCase())); if (!carries) return { lifts: false, way: null, reading: `${earlier}; the approval_comment by ${author} names no prefix of the current head` }; @@ -1704,11 +1704,15 @@ export const DEQUEUE_FAILED_ROLLUPS = Object.freeze(['FAILURE', 'ERROR']); export const MAX_DEQUEUE_REASON_BYTES = 1000; const entryOf = (c) => (c.queue?.entries ?? []).find((e) => e.number === c.number) ?? null; -const seatOf = (sig) => `${sig.lane}#${sig.seat} · ${sig.account}`; +/** A signature reading's seat and account as text; `seat` is the reader's seat mark — a number (`#N`) or `@account`. */ +function seatOf(sig) { + return `${sig.lane}${typeof sig.seat === 'string' ? sig.seat : `#${sig.seat}`} · ${sig.account}`; +} /** - * Is `signature` (a `readSignatureLine` reading) the pull's landing seat — the same lane, seat number and account - * as `landing`, the reading of the pull body's signed trailer — under `session`? The `seat-asks` proof (header). Pure. + * Is `signature` (a `readSignatureLine` reading) the pull's landing seat — the same lane, seat mark (the number, or + * `@account` for a seat named by its account: the two never match each other) and account as `landing`, the + * reading of the pull body's signed trailer — under `session`? The `seat-asks` proof (header). Pure. */ export function signedByLandingSeat(signature, landing, session) { return Boolean(signature && landing) && signature.session === session && signature.lane === landing.lane && signature.seat === landing.seat && signature.account === landing.account; @@ -2243,14 +2247,15 @@ const publishes = (c) => c.to === ADVISORY_PUBLISHED_STATE; export const ADVISORY_NOTE_STAMP_SHAPE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/; /** - * A seat signature line in ANY lane — `LANE#N · ACCOUNT · SESSION`, the lane any word without a space. A superset of + * A seat signature line in ANY lane — `LANE#N · ACCOUNT · SESSION`, or `LANE@ACCOUNT` as its seat (the second + * accepted seat mark), the lane any word without a space. A superset of * `SEAT_SIGNATURE_LINE` (`check-half-states.mjs`): every line that check accepts, this one does too * (`validate.mjs --self-test` pins it). Looser on purpose: retiring a lane word from that list would let notes already * signed under it pass a fence that read the live list, so lane words are only ever added there, and this shape does * not depend on them. Public text carries no signature line (the rewrite's contract), so the extra reach refuses no * legitimate publish. */ -export const ADVISORY_SEAT_SIGNATURE_SHAPE = /^\S+#[1-9][0-9]* · [A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38} · session_[A-Za-z0-9]{6,}$/u; +export const ADVISORY_SEAT_SIGNATURE_SHAPE = /^\S+(?:#[1-9][0-9]*|@[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}) · [A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38} · session_[A-Za-z0-9]{6,}$/u; /** * How many seat signature lines `description` carries (header: "The rows that write a security advisory", the diff --git a/scripts/pm/fleet-write/validate.mjs b/scripts/pm/fleet-write/validate.mjs index f8fdf5c9b1e..eb32e586bdb 100644 --- a/scripts/pm/fleet-write/validate.mjs +++ b/scripts/pm/fleet-write/validate.mjs @@ -1183,7 +1183,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ "the pr_dequeue row: pull, expected_head_sha, a cause from the closed three and a bounded reason, and nothing that widens them; ONE dequeuePullRequest mutation behind the pull's node id; a stroke of exactly that one action; merge-queues write minted for that stroke, EMPTY for every other; contents and issues its literal alsoSpends; the fences on the pull, its queue and the cause named and left to the executor": 11, "the hierarchy rows: sub_issue_add and sub_issue_remove name a parent and a child by NUMBER — two different positive integers and nothing that widens them; one POST to the parent's sub_issues and one DELETE to its sub_issue, the body left to the executor; issues write, riding any stroke on the literal grants; the fences on the two cards, each accepted and refused — an issue on the repository, never a pull or a transferred card, the child free of any other parent or listed by this one; and the read-back's judgment by the child's id": 23, "the event file: the workflow carries client_payload in no step's env, and the payload is read from GITHUB_EVENT_PATH": 6, - "the advisory rows: advisory_report, advisory_create, advisory_collaborators_add, advisory_versions and advisory_state — closed keys, a malformed id, package or versions entry refused before any request, a refusal that names the key and the byte count and never echoes a value, published reached by advisory_state alone, from draft alone and through the versions fence; one request each, the draft's and the versions' bodies naming no state and the two other PATCH bodies left to the executor; each a stroke of its own, repository-advisories write minted for it and EMPTY for every other; the bare collection reached by the draft's POST alone and every other security-advisories path refused; the fences, the transitions, the merge and the five read-backs, printing nothing of an answer but the id, the state, the logins and counts": 90, + "the advisory rows: advisory_report, advisory_create, advisory_collaborators_add, advisory_versions and advisory_state — closed keys, a malformed id, package or versions entry refused before any request, a refusal that names the key and the byte count and never echoes a value, published reached by advisory_state alone, from draft alone and through the versions fence; one request each, the draft's and the versions' bodies naming no state and the two other PATCH bodies left to the executor; each a stroke of its own, repository-advisories write minted for it and EMPTY for every other; the bare collection reached by the draft's POST alone and every other security-advisories path refused; the fences, the transitions, the merge and the five read-backs, printing nothing of an answer but the id, the state, the logins and counts": 91, "advisory_read: ghsa_id and public_key alone — the key its own kind, an X25519 key in base64 SPKI DER; a malformed key or id refused before any request and never echoed; ONE GET of one advisory; a stroke of its own whose token alone carries repository-advisories READ; the seal opening byte for byte for its own read and key alone, the parts inside the runner's caps, the sender gate's one setting with every other closed, and the fences, printing no id, state or field": 28, "advisory_list: public_key alone — no state, page, cursor or query the caller can pass; a stroke of its own whose token alone carries repository-advisories READ under the read's sender gate; the listing page's one path shape per listed state; the next cursor taken only from one rel=next link on this API's collection and this state, in its closed shape; each page fenced; each advisory projected to five fields before the seal; the JSON padded to one constant sealed size, ten parts, whatever the count, and one more advisory than fits refused; the shared associated data, advisory_read's byte for byte; and no id, count, state or cursor in any sentence": 28, "advisory_note: ghsa_id and sealed_note alone — the note its own kind, ciphertext of a capped length in canonical base64url, refused before any request and never echoed or opened here; ONE PATCH of one advisory whose body is the executor's; a stroke of its own minting repository-advisories write and marked advisory_note=yes, EMPTY for every other; the workflow handing the relay's note key to the execute step for that stroke alone, and no artifact; the seal opening for its own request, action, advisory and key alone and never as a read; the key judged against the committed half; the fences, the description, the read-back and the keyed digest, printing no byte of either text": 22, @@ -2268,6 +2268,8 @@ export async function selfTest() { const { SEAT_SIGNATURE_LINE } = await import('../check-half-states.mjs'); const LIVE = ['domain:security#2 · os-dev-a · session_01ABCDEFGHJKMNPQRSTVWXYZ', 'triage#1 · sunhaolin · session_01ABCDEF', 'epic:#36662#3 · os-x · session_ABCDEFG', 'l2-review#12 · a-b-c · session_0123456789', 'repo:hotcrm#2 · x · session_abcdef']; t('the shape is a SUPERSET of the live signature check: every line SEAT_SIGNATURE_LINE accepts is counted — so retiring a lane word from that list never lets a note signed under it through', [LIVE.map((l) => SEAT_SIGNATURE_LINE.test(l)), LIVE.map((l) => advisoryNoteSectionCount(`public text\n${l}`))], [LIVE.map(() => true), LIVE.map(() => 1)]); + const NAMED = ['repo:objectstack@os-dev-a · os-dev-a · session_01ABCDEFGHJKMNPQRSTVWXYZ', 'security@a-b-c · a-b-c · session_0123456789', 'epic:#36662@os-x · os-x · session_ABCDEFG', 'repo:objectstack@os-dev-a · os-dev-b · session_01ABCDEFGHJKMNPQRSTVWXYZ']; + t('⭐ …and of BOTH seat marks: a note signed `LANE@ACCOUNT` (ruling record 7249169754) is counted as the `LANE#N` one is, that seat under another account — which no reader takes for a signature — included, so no note leaves by the second mark', [NAMED.map((l) => SEAT_SIGNATURE_LINE.test(l)), NAMED.map((l) => advisoryNoteSectionCount(`public text\n${l}`)), advisoryNoteSectionCount('mail os@example · me · session_none'), advisoryNoteSectionCount('ping @os-dev-a · os-dev-a · session_01ABCDEF')], [NAMED.map(() => true), NAMED.map(() => 1), 0, 0]); const publishFence = (description, to = 'published') => advisoryFenceFailures({ ghsaId: GHSA, answer: answer(advisory({ state: to === 'published' ? 'draft' : 'closed', description, vulnerabilities: onWire(VERSION) })), from: ADVISORY_TRANSITIONS[to], to }); const noted = publishFence(`NOTES MARKER: the finder's text${ADVISORY_NOTE_SEPARATOR}${SECTION(1)}`); t("⛔ fence notes, judged for a publish alone: a draft whose description still carries a seat signature line is refused by the notes fence, naming the count and no byte of the text; a description that is neither text nor none is refused too; the same draft rewritten passes; a reopen to draft with a note in it is not judged by it", [noted.map((f) => f.fence), advisoryFenceText(noted).includes('still carries 1 seat signature line(s)'), advisoryFenceText(noted).includes('MARKER'), publishFence(['NOTES MARKER']).map((f) => f.fence), advisoryFenceText(publishFence({ text: 'NOTES MARKER' })).includes('is object, so it cannot be judged free of seat notes'), publishFence('NOTES MARKER: the public text').map((f) => f.fence), publishFence(null).map((f) => f.fence), publishFence(SECTION(1), 'draft').map((f) => f.fence)], [['notes'], true, false, ['notes'], true, [], [], []]); diff --git a/scripts/pm/issue-create.mjs b/scripts/pm/issue-create.mjs index ef76dcbc7ec..ad166e34a1a 100644 --- a/scripts/pm/issue-create.mjs +++ b/scripts/pm/issue-create.mjs @@ -453,7 +453,7 @@ export async function relayMissProbe({ route, send, pace }) { const SELF_TEST_BATTERIES = Object.freeze({ 'the arguments: files not argv for prose, exactly one title source, a repo shape': 10, 'the payload: title trimmed to one line, labels and assignees de-duplicated, nothing invented': 5, - "the signature: a card body opens with the seat's signature line, or the plan is refused before any request": 8, + "the signature: a card body opens with the seat's signature line, or the plan is refused before any request": 10, 'the transport: a fake platform, and what each answer does to the exit code': 9, 'dry-run: no request leaves, and the plan is printed': 4, 'the wiring: both halves around the one POST, on the write verb only': 4, @@ -494,6 +494,9 @@ export async function selfTest() { 'unsigned.md': 'Evidence: a repro.\n\n- step one\n', 'unsigned-stamped.md': 'Reading time {{NOW}}\n', 'near-miss.md': 'domain:skills#2 - os-justin - session_01ABCDEFGHJKMNPQRSTVWXYZ\nEvidence.\n', + // The second seat mark (ruling record 7249169754): a seat named by its account, and that seat under another account. + 'account-seat.md': 'repo:objectstack@os-justin · os-justin · session_01ABCDEFGHJKMNPQRSTVWXYZ\nEvidence: a repro.\n', + 'account-seat-other.md': 'repo:objectstack@os-justin · os-elon · session_01ABCDEFGHJKMNPQRSTVWXYZ\nEvidence.\n', 'second-line.md': 'Evidence: a repro.\n\ndomain:skills#2 · os-justin · session_01ABCDEFGHJKMNPQRSTVWXYZ\n', }; const read = (p) => { @@ -540,6 +543,8 @@ export async function selfTest() { t('…and the refusal names the shape to write and the line it read', unsigned.errors.some((e) => e.includes('no signature line') && e.includes('LANE#N · ACCOUNT · SESSION') && e.includes('`Evidence: a repro.`'))); t('a signed body plans, and the signature is SENT as written — nothing stripped, nothing inserted', [plan('body.md').ok, plan('body.md').payload.body.split('\n')[0]], [true, SIG]); t('a near miss (hyphens for the ` · ` separator) is refused, and named as one', plan('near-miss.md').errors.some((e) => e.includes('reads like a signature and is not one'))); + t('⭐ both seat marks are accepted: a body signed `LANE@ACCOUNT` plans as one signed `LANE#N` does, sent as written', [plan('account-seat.md').ok, plan('account-seat.md').payload.body.split('\n')[0], plan('body.md').ok], [true, 'repo:objectstack@os-justin · os-justin · session_01ABCDEFGHJKMNPQRSTVWXYZ', true]); + t('⛔ account X signing account Y\'s seat is refused as a near miss — never posted as Y\'s seat', [plan('account-seat-other.md').ok, plan('account-seat-other.md').errors.some((e) => e.includes('reads like a signature and is not one') && e.includes('only that same account signs'))], [false, true]); t('⛔ a signature on a LATER line is not a signature: the first non-empty line decides', plan('second-line.md').ok, false); const both = plan('unsigned-stamped.md').errors; t('a body breaking BOTH rules hears both, in one refusal', [both.some((e) => e.includes('{{NOW}}')), both.some((e) => e.includes('no signature line'))], [true, true]); diff --git a/scripts/pm/mailbox-open.mjs b/scripts/pm/mailbox-open.mjs index bda4f3c3c63..0cda3fa773c 100644 --- a/scripts/pm/mailbox-open.mjs +++ b/scripts/pm/mailbox-open.mjs @@ -55,6 +55,15 @@ * lane may be named `triage`, `director`, `security`, `l2-review`, `review`, `qa`, `eval`, `queue`, `repo-…` or `epic-…` — `seatKey` * refuses one — which keeps the slug one-to-one. * + * `LANE@ACCOUNT` is the second accepted spelling (ruling record 7249169754; the + * grammar's banner is `check-half-states.mjs`'s): a seat named by the account + * that holds it, `repo:objectstack@os-bill`. Its key keeps that spelling, + * lower-cased, and is its own seat: never the numbered seat its account sits, + * and never another account's. Its slug is the lane's, `_`, the account, then + * `-0` (`repo-objectstack_os-bill-0`): a login carries no `_`, so the last one + * splits lane from account, and no numbered slug ends in `-0`. Such a seat's + * mailbox opens only under its own `--login`. + * * ## What it does, in order (open) * * ① READ the open pulls and REFUSE (exit 4) when one already carries @@ -214,7 +223,7 @@ export const L2_REVIEW_LANE_WORDS = Object.freeze([L2_REVIEW_LANE, 'review']); export const isL2ReviewLane = (lane) => L2_REVIEW_LANE_WORDS.includes(String(lane ?? '').trim().toLowerCase()); /** The epic lane's kind: `epic:#` names the `pm:epic` parent card's number, never a word (`epic:#27293#1`). */ export const SEAT_EPIC_KIND = 'epic'; -const SEAT_SHAPE = new RegExp(`^((?:${SEAT_LANE_KINDS.join('|')}):[a-z0-9._-]+|${SEAT_EPIC_KIND}:#[1-9][0-9]*|${SEAT_BARE_LANES.join('|')})(?:#([1-9][0-9]*))?$`); +const SEAT_SHAPE = new RegExp(`^((?:${SEAT_LANE_KINDS.join('|')}):[a-z0-9._-]+|${SEAT_EPIC_KIND}:#[1-9][0-9]*|${SEAT_BARE_LANES.join('|')})(?:#([1-9][0-9]*)|@(${LOGIN_SHAPE.source.slice(1, -1).replace(/A-Z/g, '')}))?$`); // What a `domain:` lane may NOT be named, so the slug stays one-to-one (header): a bare lane word (`domain:triage` // would slug to `triage-1`, the triage seat's), or another kind's name with its colon turned into the hyphen the slug // uses (`domain:repo-cloud` would slug to `repo-cloud-1`, `repo:cloud#1`'s; `domain:epic-12` to `epic-12-1`, `epic:#12#1`'s). @@ -229,14 +238,17 @@ const LEGACY_OWNER_LINE = /^(?:To|Mailbox-of):[ \t]*(\S+)$/; * number always spelled (`triage` → `triage#1`); `slug` is the key as one ref segment (header). A `domain:` lane * named after a reserved lane word (`domain:triage`, `domain:repo-cloud`) is not a seat either: its slug would be * another seat's, and the header's one-to-one promise is kept here, not assumed. This is the fleet's ONE seat - * grammar — the mailbox `To:` line and the doorbell keys' `LANE#N` fields read with it, never a second shape. Pure. + * grammar — the mailbox `To:` line and the doorbell keys' `LANE#N` fields read with it, never a second shape. A + * seat spelled `LANE@ACCOUNT` (header) reads `{ key, slug, account }`, the account lower-cased. Pure. */ export function seatKey(text) { const m = SEAT_SHAPE.exec(String(text ?? '').trim().toLowerCase()); if (!m) return null; if (m[1].startsWith('domain:') && RESERVED_DOMAIN_LANE.test(m[1].slice('domain:'.length))) return null; + const lane = m[1].replace(/^domain:/, '').replace(/:#?/g, '-'); + if (m[3] !== undefined) return { key: `${m[1]}@${m[3]}`, slug: `${lane}_${m[3]}-0`, account: m[3] }; const n = m[2] ?? '1'; - return { key: `${m[1]}#${n}`, slug: `${m[1].replace(/^domain:/, '').replace(/:#?/g, '-')}-${n}` }; + return { key: `${m[1]}#${n}`, slug: `${lane}-${n}` }; } /** `mailbox//`; `seat` is a `seatKey` reading. */ @@ -286,6 +298,7 @@ export function parseArgs(argv) { else if (!seat) opts.errors.push(`--seat ${JSON.stringify(opts.seat)} is not a seat — spell it LANE#N, e.g. domain:ui#4 or epic:#27293#1`); if (!opts.login) opts.errors.push('--login is required to open a mailbox'); else if (!LOGIN_SHAPE.test(opts.login)) opts.errors.push(`--login ${JSON.stringify(opts.login)} is not a GitHub login`); + else if (seat?.account !== undefined && seat.account !== opts.login.toLowerCase()) opts.errors.push(`--seat ${JSON.stringify(opts.seat)} is named by another account than --login ${JSON.stringify(opts.login)} — a seat named by an account opens under that account only`); else if (seat && opts.head === null && !BRANCH_SHAPE.test(mailboxBranch(opts.login, seat))) opts.errors.push(`the seat's branch ${JSON.stringify(mailboxBranch(opts.login, seat))} is not a legal ref`); if (opts.head !== null && !BRANCH_SHAPE.test(opts.head)) opts.errors.push(`--head ${JSON.stringify(opts.head)} is not a branch name`); if (opts.base !== null && !BRANCH_SHAPE.test(opts.base)) opts.errors.push(`--base ${JSON.stringify(opts.base)} is not a branch name`); @@ -377,7 +390,9 @@ export function mailboxOwner(pr) { if (!labelNames(pr).includes(MAILBOX_LABEL)) return null; const first = firstLine(pr?.body); const perSeat = MAILBOX_OF_LINE.exec(first); - const seat = perSeat && LOGIN_SHAPE.test(perSeat[2]) ? seatKey(perSeat[1]) : null; + const named = perSeat && LOGIN_SHAPE.test(perSeat[2]) ? seatKey(perSeat[1]) : null; + // A seat named by an account is that account's alone: under another login the line names no seat. + const seat = named && (named.account === undefined || named.account === perSeat[2].toLowerCase()) ? named : null; if (seat) return { seat: seat.key, slug: seat.slug, login: perSeat[2] }; const ref = String(pr?.head?.ref ?? ''); const parts = ref.startsWith(MAILBOX_BRANCH_PREFIX) ? ref.slice(MAILBOX_BRANCH_PREFIX.length).split('/') : []; @@ -575,12 +590,13 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the close plan: comment then close, then the delete of a claude/mailbox-* head, judged by the validator': 7, 'whose mailbox a pull is: the seat on the body line or the head, a legacy login, neither': 8, "finding a seat's open mailbox: by seat, never by login": 10, + 'a seat named by its account: `LANE@ACCOUNT` is its own key and slug beside `LANE#N` (ruling record 7249169754)': 9, 'refusing to close what is not an open mailbox': 4, 'the ledger exclusion and the footer': 4, 'the CLI: dry run prints the actions file and sends nothing': 8, 'paging: a three-page read through the loop equals the slurped array': 4, }); -const SELF_TEST_BATTERY_FLOOR = 10; +const SELF_TEST_BATTERY_FLOOR = 11; async function selfTest() { let failed = 0; @@ -701,6 +717,19 @@ async function selfTest() { t('without the label it is not a mailbox', openMailboxesOf([pr({ labels: [], head: { ref: 'mailbox/os-bill/ui-4' } })], UI4).length, 0); t('a closed one does not block a new one', openMailboxesOf([pr({ state: 'closed', head: { ref: 'mailbox/os-bill/ui-4' } })], UI4).length, 0); + battery('a seat named by its account: `LANE@ACCOUNT` is its own key and slug beside `LANE#N` (ruling record 7249169754)'); + t('⭐ both forms read: the account form keeps its spelling, lower-cased, and names its account; the numbered form is unchanged, no account on it', [seatKey('Repo:ObjectStack@OS-Bill'), seatKey('epic:#27293@sunhaolin'), seatKey('l2-review@os-bill'), seatKey('repo:objectstack#5'), seatKey('triage')], [{ key: 'repo:objectstack@os-bill', slug: 'repo-objectstack_os-bill-0', account: 'os-bill' }, { key: 'epic:#27293@sunhaolin', slug: 'epic-27293_sunhaolin-0', account: 'sunhaolin' }, { key: 'l2-review@os-bill', slug: 'l2-review_os-bill-0', account: 'os-bill' }, { key: 'repo:objectstack#5', slug: 'repo-objectstack-5' }, { key: 'triage#1', slug: 'triage-1' }]); + t('⛔ what is not an account seat: no account, a space, a doubled or edge hyphen, both marks, a reserved `domain:` lane, a login alone', ['repo:objectstack@', 'repo:objectstack @os-bill', 'repo:objectstack@os--bill', 'repo:objectstack@-os', 'repo:objectstack@os-', 'repo:objectstack#1@os-bill', 'repo:objectstack@os-bill#1', 'domain:triage@os-bill', '@os-bill', 'os-bill'].map(seatKey), [null, null, null, null, null, null, null, null, null, null]); + t('⭐ the slug stays one-to-one across BOTH forms — a login carries no `_` and no numbered slug ends in `-0`, so the look-alikes differ', (() => { const keys = ['repo:objectstack@os-bill', 'repo:objectstack#1', 'repo:objectstack#10', 'domain:ui@bill-3', 'domain:ui_bill#3', 'domain:ui_bill-3@a', 'domain:ui-os@bill', 'domain:ui@os-bill', 'domain:ui@os', 'epic:#12@os-bill', 'epic:#12#1', 'triage@a', 'triage#1']; const slugs = keys.map((k) => seatKey(k)?.slug); return [slugs.every(Boolean), new Set(slugs).size]; })(), [true, 13]); + t('the slug is a legal ref segment on both heads: the default mailbox// and a cloud seat\'s claude/mailbox-', [mailboxBranch('os-bill', seatKey('repo:objectstack@os-bill')), BRANCH_SHAPE.test(mailboxBranch('os-bill', seatKey('repo:objectstack@os-bill'))), MAILBOX_BRANCH_SHAPE.test(`claude/mailbox-${seatKey('repo:objectstack@os-bill').slug}`), MAILBOX_BRANCH_SHAPE.test(`claude/mailbox-${seatKey('epic:#27293@sunhaolin').slug}`)], ['mailbox/os-bill/repo-objectstack_os-bill-0', true, true, true]); + t('⭐ --seat takes either form; an account seat opens under its own --login only (case folded) — ⛔ account X never opens account Y\'s seat', [parseArgs(['--repo', 'o/r', '--seat', 'repo:objectstack@os-bill', '--login', 'OS-Bill']).errors, parseArgs(['--repo', 'o/r', '--seat', 'repo:objectstack@os-bill', '--login', 'os-elon']).errors.some((e) => e.includes('named by another account')), parseArgs(['--repo', 'o/r', '--seat', 'repo:objectstack#5', '--login', 'os-elon']).errors], [[], true, []]); + const ACC = planOpen({ repo: 'objectstack-ai/objectstack', seat: 'repo:objectstack@os-bill', login: 'os-bill', session: 'cse_01ABC' }); + t('the open plan of an account seat: its branch, its title, a body the owner reader reads back as that seat, and a stroke the relay validator accepts', [ACC.errors, ACC.branch, ACC.actions[0].title, ACC.actions[0].body.split('\n')[0], mailboxOwner(pr({ body: ACC.actions[0].body, head: { ref: 'claude/project-thread-1' } }))], [[], 'mailbox/os-bill/repo-objectstack_os-bill-0', 'pm:mailbox — repo:objectstack@os-bill · os-bill', 'Mailbox-of: repo:objectstack@os-bill · os-bill', { seat: 'repo:objectstack@os-bill', slug: 'repo-objectstack_os-bill-0', login: 'os-bill' }]); + t('⛔ a `Mailbox-of:` line naming account Y\'s seat under login X names NO seat — never Y\'s, never X\'s', mailboxOwner(pr({ body: 'Mailbox-of: repo:objectstack@os-bill · os-elon', head: { ref: 'claude/project-thread-2' } })), { seat: null, slug: null, login: null }); + const BOXES = [opened('repo:objectstack@os-bill', 'os-bill', 21), opened('repo:objectstack#1', 'os-elon', 22)]; + t('⭐ found by lane AND account: os-bill\'s seat finds its own mailbox, and neither another account\'s seat of the lane nor a numbered seat finds it', [openMailboxesOf(BOXES, seatKey('repo:objectstack@os-bill')).map((x) => x.number), openMailboxesOf(BOXES, seatKey('repo:objectstack@os-elon')).length, openMailboxesOf(BOXES, seatKey('repo:objectstack#5')).length, openMailboxesOf([pr({ head: { ref: ACC.branch } })], seatKey('repo:objectstack@os-bill')).length], [[21], 0, 0, 1]); + t('⭐ CONTROL — vacant seat 1\'s `#1` mailbox still reads as seat 1\'s, whoever opened it: found by `repo:objectstack#1` (and the bare lane), ⛔ not by the account seat of the login on it', [openMailboxesOf(BOXES, seatKey('repo:objectstack#1')).map((x) => x.number), openMailboxesOf(BOXES, seatKey('repo:objectstack')).map((x) => x.number), openMailboxesOf(BOXES, seatKey('repo:objectstack@os-elon')).length, mailboxOwner(BOXES[1]).seat], [[22], [22], 0, 'repo:objectstack#1']); + battery('refusing to close what is not an open mailbox'); t('an open pm:mailbox PR may be closed', closeRefusal(pr({}), 1), null); t('a PR without the label is refused', /does not carry pm:mailbox/.test(closeRefusal(pr({ labels: [{ name: 'bug' }] }), 1)), true); diff --git a/scripts/pm/post-stamped.mjs b/scripts/pm/post-stamped.mjs index 317422baf0e..d8f056505f8 100644 --- a/scripts/pm/post-stamped.mjs +++ b/scripts/pm/post-stamped.mjs @@ -962,6 +962,7 @@ import { H56_STAMP_TOLERANCE_MIN, ISSUE_BODY_LIMIT, PROXY_FLAG, + SEAT_MARK_SOURCE, claimSeatNumber, contractReviewHeadSha, h56EstimatedStamp, @@ -2680,6 +2681,9 @@ export function decisionFacetRefusalText(rows) { ); } +/** The triage lane's seat key under either seat mark: the lane word, then `check-half-states.mjs`'s `SEAT_MARK_SOURCE`. */ +const TRIAGE_SEAT_KEY = new RegExp(`^triage${SEAT_MARK_SOURCE}$`, 'u'); + /** * A contract-review knock addressed to triage — the route the rule text closes (`references/contract-review.md` * 〈L2 归属与资格〉): a lane that cannot take `CONTRACT_REVIEW_TIER` sends `Request: contract-review` to a seated @@ -2691,11 +2695,14 @@ export function decisionFacetRefusalText(rows) { * `id` and `to` parsed before the template failed, and a malformed knock to triage is still a knock to triage. A * comment the reader refuses outright (no `To:` seat, a key outside the table) names no contract-review knock at * all and passes, as it does today. Comments only. Answers the reading, or null. Pure. + * + * The target is judged by its LANE WORD, before either seat mark (`TRIAGE_SEAT_KEY`): a triage seat named by its + * account (`triage@ACCOUNT`) is triage exactly as `triage#N` is. */ export function triageContractReviewKnock(body) { const knock = readMailboxLine(String(body ?? '')); if ((knock.state !== 'read' && knock.state !== 'unreadable') || knock.id !== 'request:contract-review') return null; - return /^triage#/u.test(knock.to) ? knock : null; + return TRIAGE_SEAT_KEY.test(knock.to) ? knock : null; } /** The refusal a caller reads, from `triageContractReviewKnock`'s reading. */ @@ -4362,8 +4369,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the relay transport: the same act as one op, the comment found on the board, the exit register kept apart': 13, "the size route: over the relay's body cap under auto THIS write goes direct with one line naming bytes, cap and identity; at or under it the relay; explicit dispatch refuses naming the bytes; nothing else re-routes": 13, 'the signature: every body opens with LANE#N · ACCOUNT · SESSION or is refused, beside the stamp contract; one leading signature changes no reading': 11, - 'the one judge: every body refusal on ONE path — `main` and `label-write.mjs --comment-file` call `judgeBody`, never a copy': 8, - 'the review route: a `Request: contract-review` knock addressed to triage is refused; to a review or sibling seat, and every other key to triage, it passes': 10, + 'the one judge: every body refusal on ONE path — `main` and `label-write.mjs --comment-file` call `judgeBody`, never a copy': 11, + 'the review route: a `Request: contract-review` knock addressed to triage is refused; to a review or sibling seat, and every other key to triage, it passes': 13, 'the record tier: a record naming `CONTRACT_REVIEW_TIER` is written only on a transcript `verify-review-tier.mjs` passes; another tier and a non-record comment are untouched': 16, 'the claim stroke: a comment opening `Claim:` is refused on every route but `direct`, pointing at the `label-write` fold; the same body through that fold passes': 21, }); @@ -5913,6 +5920,13 @@ export function selfTest() { const SIG = 'domain:skills#2 · os-justin · session_01QSeKYmhU5KEj1nukYhp1Tg'; const ok = judgeBody(`${SIG}\nClaim: PM loop round 1 · {{NOW}}\nSeat: \`domain:skills#2\`\nContainer & model: \`S\`, \`mode:subagent\`, \`model: ${TIER_DEFAULT}\`, \`effort: medium\``, { mode: 'comment' }, NOW_MS); t('⭐ a signed, stamped claim passes and comes back RENDERED — the clock this act read is in it', ok.ok && ok.rendered.substituted === 1 && ok.rendered.body.includes(ok.rendered.stamp) && !ok.rendered.body.includes(STAMP_TOKEN)); + // The second seat mark (ruling record 7249169754): readers take `LANE@ACCOUNT` beside `LANE#N`; the writers' printed shape is still `#N`. + const ACC = 'repo:objectstack@os-justin · os-justin · session_01QSeKYmhU5KEj1nukYhp1Tg'; + const claimOf = (sig, seat) => `${sig}\nClaim: PM loop round 1 · {{NOW}}\nSeat: \`${seat}\`\nContainer & model: \`S\`, \`mode:subagent\`, \`model: ${TIER_DEFAULT}\`, \`effort: medium\``; + t('⭐ both seat marks pass the one judge: a claim signed `LANE@ACCOUNT` whose `Seat:` line names that seat is accepted exactly as the `LANE#N` one is — signature and keyed line both read', [judgeBody(claimOf(ACC, 'repo:objectstack@os-justin'), { mode: 'comment' }, NOW_MS).ok, judgeBody(claimOf(ACC, 'repo:objectstack@os-justin'), { mode: 'body' }, NOW_MS).ok, claimKeyedLineRefusals(claimOf(ACC, 'repo:objectstack@os-justin')).length, claimSeatNumber(claimOf(ACC, 'repo:objectstack@os-justin')), claimSeatNumber(claimOf(SIG, 'domain:skills#2'))].join() === [true, true, 0, '@os-justin', 2].join()); + const other = judgeBody(claimOf('repo:objectstack@os-justin · os-elon · session_01QSeKYmhU5KEj1nukYhp1Tg', 'repo:objectstack@os-justin'), { mode: 'comment' }, NOW_MS); + t('⛔ account X signing account Y\'s seat is REFUSED before the write, as a near miss — it is never posted as Y\'s seat', !other.ok && other.text.includes('reads like a signature and is not one') && other.text.includes('only that same account signs')); + t('⛔ a `Seat:` line naming an account seat off the line start is still refused by its owner — present, unreadable, ⛔ never seat 1', claimKeyedLineRefusals(`${ACC}\nClaim: PM loop round 1 — dispatched. Seat: repo:objectstack@os-justin — R1.`).some((r) => r.key === 'Seat') && !claimKeyedLineRefusals(claimOf(ACC, 'repo:objectstack@os-justin')).some((r) => r.key === 'Seat')); const unsigned = judgeBody('Claim: PM loop round 1 · {{NOW}}', { mode: 'comment' }, NOW_MS, 'label-write'); t('⭐ an unsigned comment is refused, and the refusal names the SENDER it was handed', !unsigned.ok && unsigned.text.startsWith('label-write: REFUSED') && unsigned.text.includes('opens with no signature line')); const typed = judgeBody(`${SIG}\nClaim: PM loop round 1 · 2026-09-10T06:37Z`, { mode: 'comment' }, NOW_MS); @@ -6003,6 +6017,9 @@ export function selfTest() { t('⭐ …and the refusal names the L2 seat\'s mailbox, the sibling fallback, the owed-review list and the rule\'s home', refused.text.includes('`To: l2-review#N`') && refused.text.includes('`Mailbox:`') && refused.text.includes('sibling lane seat') && refused.text.includes('check-owed-reviews.mjs') && refused.text.includes('references/contract-review.md') && refused.text.includes('Nothing was written')); t('⭐ a MALFORMED knock to triage is refused too — no reason, a bare PR number, a second line: the reader\'s unreadable reading still names the key and the seat', [`Request: contract-review · PR #26766 · head ${HEAD}`, 'Request: contract-review · 26766 · rationed', `Request: contract-review · PR #26766 · head ${HEAD} · rationed\nbecause fable is short today`].every((key) => { const r = judged('triage#1', key); return !r.ok && r.text.includes('`To: triage#1`'); }) && judged('review#1', `Request: contract-review · PR #26766 · head ${HEAD}`).ok); t('a bare `To: triage` reads as `triage#1` (the doorbell reader\'s seat spelling) and is refused the same way', !judged('triage').ok && !judged('Triage#2').ok); + t('⭐ both seat marks: the same knock addressed to a triage seat named by its account (`triage@ACCOUNT`) is refused exactly as `triage#1` is, whatever the case of the account, and the refusal names the seat as addressed', (() => { const r = judged('triage@os-help'); return !r.ok && r.text.startsWith('post-stamped: REFUSED') && r.text.includes('`To: triage@os-help`') && !judged('Triage@OS-Help').ok && !judged('triage#1').ok; })()); + t('⭐ …a MALFORMED knock to it is refused too, and every other key to it passes, as for the numbered seat', !judged('triage@os-help', `Request: contract-review · PR #26766 · head ${HEAD}`).ok && judged('triage@os-help', 'Request: urgent-triage · #26766 · main red on Test Core').ok && judged('triage@os-help', 'Request: triage · #26766 · which lane takes it').ok); + t('⛔ control — the lane word is what is judged, not the mark: an L2 or a sibling lane seat named by its account passes as its numbered seat does, and a lane that only starts with the word is not triage', judged('l2-review@os-bill').ok && judged('review@os-bill').ok && judged('domain:server@os-bill').ok && judged('repo:objectstack@os-help').ok && ['triage#1', 'triage@os-help'].every((to) => triageContractReviewKnock(KNOCK(to))?.to === to) && [KNOCK('l2-review@os-help'), KNOCK('repo:triage@os-help'), KNOCK('repo:triage#1')].every((b) => triageContractReviewKnock(b) === null)); t('⭐ the same knock addressed to an L2 seat passes — under its lane word `l2-review` and under the old spelling `review`', judged('l2-review#1').ok && judged('l2-review#2').ok && judged('review#1').ok && judged('review#2').ok); t('…and to a sibling lane seat, the fallback while no L2 seat is seated', judged('domain:server#2').ok); t('⛔ every other key to triage is untouched: `Request: urgent-triage` and `Request: triage` pass', judged('triage#1', 'Request: urgent-triage · #26766 · main red on Test Core').ok && judged('triage#1', 'Request: triage · #26766 · which lane takes it').ok); diff --git a/scripts/pm/record-recognisers.mjs b/scripts/pm/record-recognisers.mjs index 3f2723b3882..8a7d3204248 100644 --- a/scripts/pm/record-recognisers.mjs +++ b/scripts/pm/record-recognisers.mjs @@ -102,6 +102,7 @@ import { directiveValues, labelNames, readSignatureLine, + seatIdOf, refsTargets, RELEASE_COMMENT_MARKER, releaseAnswersClaim, @@ -906,9 +907,11 @@ const CONTRACT_REVIEW_HANDOFF_MARKER = new RegExp(CONTRACT_REVIEW_HANDOFF_LINE.s * `repo:#N` (a repo name may carry `.` and `-`, `repo:www.objectos.ai#2`), an epic seat `epic:##` (seat * k of epic N, both numbers required) or a retired domain seat `domain:#N`, the seat number required -- a * separator (an em dash, a hyphen pair, a hyphen or a colon), then the rest. `triage` and every other seat word - * match nothing. + * match nothing. Each lane also reads with the second seat mark, `@ACCOUNT` in place of `#N` (`l2-review@os-bill`, + * `repo:objectstack@os-bill`; `check-half-states.mjs`'s banner): that account's seat, lower-cased like the rest. */ -const HANDOFF_TARGET = new RegExp(`^((?:${L2_REVIEW_LANE_WORDS.join('|')})#[1-9][0-9]*|(?:repo:[a-z0-9][a-z0-9._-]*|domain:[a-z][a-z0-9._-]*|epic:#[1-9][0-9]*)#[1-9][0-9]*)(?![0-9])[ \\t]*(?:—|--|-|:)?[ \\t]*(.*)$`, 'i'); +const HANDOFF_SEAT_MARK = '(?:#[1-9][0-9]*(?![0-9])|@[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}(?![A-Za-z0-9]))'; +const HANDOFF_TARGET = new RegExp(`^((?:${L2_REVIEW_LANE_WORDS.join('|')}|repo:[a-z0-9][a-z0-9._-]*|domain:[a-z][a-z0-9._-]*|epic:#[1-9][0-9]*)${HANDOFF_SEAT_MARK})[ \\t]*(?:—|--|-|:)?[ \\t]*(.*)$`, 'i'); /** `(reason, UTC time)` then ` · head SHA` -- the time is the LAST comma-separated item in the parentheses. */ const HANDOFF_TAIL = /^\(([^()]*?)[ \t]*,[ \t]*([^,()]+)\)[ \t]*·[ \t]*head[ \t]+`?([0-9a-fA-F]{7,40})`?[ \t]*$/; @@ -1451,11 +1454,13 @@ const FOOTER_LINE = /^_Generated by \[Claude Code\]\(https:\/\/claude\.ai\/code( * A key's `LANE#N` field → `{ key, lane, n }`, or null. Read with `seatKey`, the ONE seat grammar (#27891): the * lane is `domain:`, `repo:`, `triage` or `director`, so the short form `skills#2` is refused here exactly * as on the `To:` line, an absent number is seat 1 (`triage` → `triage#1`), and a `domain:` lane named after a - * reserved lane word is no seat. `key` is the canonical spelling; `lane` and `n` are its two halves. + * reserved lane word is no seat. `key` is the canonical spelling; `lane` and `n` are its two halves. A seat named + * by its account (`LANE@ACCOUNT`, `seatKey`'s second spelling) has no number: `n` is null and `account` names it. */ function readSeat(part) { const s = seatKey(part); if (!s) return null; + if (s.account !== undefined) return { key: s.key, lane: s.key.slice(0, s.key.lastIndexOf('@')), n: null, account: s.account }; const at = s.key.lastIndexOf('#'); return { key: s.key, lane: s.key.slice(0, at), n: Number(s.key.slice(at + 1)) }; } @@ -1571,6 +1576,8 @@ const MAILBOX_FIELD_READERS = Object.freeze({ const mailbox = MAILBOX_REF.exec(p[3]); const patrol = PATROL_REF.exec(p[4]); const takes = readList(p[5], 'takes'); + // A seat named by an account comes online under that account only. + if (seat?.account !== undefined && seat.account !== String(login ?? '').toLowerCase()) return null; return seat && login && mailbox && patrol && takes ? { seat, login, mailbox: Number(mailbox[1]), patrol: patrol[1], takes, numbers: [Number(mailbox[1]), ...takes] } : null; }, 'notify:seat-offline': (p) => { @@ -1843,7 +1850,7 @@ function claimDelegate(card, rows) { const { row, index } = live[newest.index]; if (releaseAnswersClaim(latestMarkedComment(rows, RELEASE_COMMENT_MARKER), { ...newest, index })) return null; const signed = readSignatureLine(row?.body); - const seat = signed ? seatKey(`${signed.lane}#${signed.seat}`) : null; + const seat = signed ? seatKey(seatIdOf(signed.lane, signed.seat)) : null; const session = claimThreadSession(row?.body); if (!seat || !session) return null; return { seat: seat.key, session, where: `claim on #${card.number} (comment ${row?.id ?? '?'}) Thread session` }; @@ -1898,7 +1905,7 @@ export function seatSessionRoster({ posts, mailboxes, claims = [] } = {}) { for (const post of posts) { if (!post || post.state !== 'open' || post.pull_request || !labelNames(post).includes('pm:seat') || !seatOnDuty(post)) continue; const signed = readSignatureLine(post.body); - const seat = signed ? seatKey(`${signed.lane}#${signed.seat}`) : null; + const seat = signed ? seatKey(seatIdOf(signed.lane, signed.seat)) : null; if (!seat) continue; list(seat.key, signed.session, `seat post #${post.number}`); for (const value of directiveValues(post.body, 'Successor-of')) { @@ -1936,8 +1943,8 @@ export function knockSignature(body, roster) { } const signed = readSignatureLine(body); if (!signed) return unlisted('the knock opens with no seat signature line'); - const seat = seatKey(`${signed.lane}#${signed.seat}`)?.key ?? null; - if (!seat) return unlisted(`\`${signed.lane}#${signed.seat}\` names no seat a mailbox serves`); + const seat = seatKey(seatIdOf(signed.lane, signed.seat))?.key ?? null; + if (!seat) return unlisted(`\`${seatIdOf(signed.lane, signed.seat)}\` names no seat a mailbox serves`); const listed = roster.seats.get(seat); if (!listed || listed.size === 0) return unlisted(`${seat} lists no session (no held seat post signed by it, no open mailbox opening, no open claim naming its card thread)`); if (!listed.has(signed.session)) return unlisted(`${signed.session} is not a session ${seat} lists`); @@ -2912,6 +2919,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // The card-thread delegate (#34013 remainder 2): a claim's `Thread session:` line, one spelling, joins its signing seat's roster. '⭐ the card-thread delegate: the session an open claim names on its `Thread session:` line joins the roster of the seat that signed it — one spelling, dropped when released, superseded or closed': 17, '⭐ the signature line: the reader reads LANE#N · ACCOUNT · SESSION exactly, and one leading signature changes no first-line reading': 22, + // Readers first: every writer's default is still `#N`. + '⭐ the seat mark: `LANE@ACCOUNT` reads beside `LANE#N` (ruling record 7249169754) — a seat is its lane AND its mark, and neither mark reads as the other': 16, '⭐ the `Contract-review-claim:` line — session, FULL head, time; lapses on a moved head or after two hours; the earliest live claim holds': 24, '⭐ the `Contract-review-hold:` line — session, head, reason, until; a new head clears it; at 24 hours it reads overdue and still holds': 23, // The tie relation: the cards a fold's equal closing keywords deliver, for the `--land` dogfood gate, which reads @@ -2942,7 +2951,8 @@ const SELF_TEST_BATTERIES = Object.freeze({ // Raised 17 → 18 with the knock-signature battery (#33789 item 3, split to #34013): one battery, one row. // Raised 18 → 19 with the card-thread delegate battery (#34013 remainder 2): one battery, one row. // Raised 19 → 20 with the tie-relation battery (`deliveredCardsAtStrongest`): one battery, one row. -const SELF_TEST_BATTERY_FLOOR = 20; +// Raised 20 → 21 with the seat-mark battery (`LANE@ACCOUNT` beside `LANE#N`, ruling record 7249169754): one battery, one row. +const SELF_TEST_BATTERY_FLOOR = 21; // 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 @@ -3821,6 +3831,40 @@ export async function selfTest() { t('the act\'s OPENING-line stamp (H56, which post-stamped\'s positional refusal imports) is the same reading under a signature', hs.h56StampedReadings('Claim: x · 2026-10-28T12:44Z\nbody').length === 1 && same(hs.h56StampedReadings, 'Claim: x · 2026-10-28T12:44Z\nbody')); } + battery('⭐ the seat mark: `LANE@ACCOUNT` reads beside `LANE#N` (ruling record 7249169754) — a seat is its lane AND its mark, and neither mark reads as the other'); + { + const hs = await import('./check-half-states.mjs'); + const SESS = 'session_01QSeKYmhU5KEj1nukYhp1Tg'; + const NUM = `repo:objectstack#1 · os-elon · ${SESS}`; + const ACC = `repo:objectstack@os-justin · os-justin · ${SESS}`; + const J = (v) => JSON.stringify(v); + t('⭐ both forms read: `#N` gives the seat number, `@ACCOUNT` the mark `@account`, lower-cased — lane, account and session as before', J([hs.readSignatureLine(NUM), hs.readSignatureLine(ACC), hs.readSignatureLine(`repo:objectstack@OS-Justin · os-justin · ${SESS}`)?.seat]) === J([{ lane: 'repo:objectstack', seat: 1, account: 'os-elon', session: SESS, line: NUM }, { lane: 'repo:objectstack', seat: '@os-justin', account: 'os-justin', session: SESS, line: ACC }, '@os-justin'])); + t('every lane a signature carries reads with the account mark — a hyphenated lane, an epic (its `#N` is the epic, never a seat), triage, the L2 seat under both words, coordinator', ['domain:engine-core', 'repo:cloud', 'epic:#26000', 'triage', 'l2-review', 'review', 'coordinator'].every((lane) => { const r = hs.readSignatureLine(`${lane}@os-zhuang · os-zhuang · ${SESS}`); return r?.lane === lane && r.seat === '@os-zhuang' && hs.seatIdOf(r.lane, r.seat) === `${lane}@os-zhuang`; })); + t('⛔ account X signing account Y\'s seat is NOT a signature — never read as Y\'s seat, nor as X\'s — and the writers\' refusal names the cause', hs.readSignatureLine(`repo:objectstack@os-justin · os-elon · ${SESS}`) === null && hs.signatureRefusal(`repo:objectstack@os-justin · os-elon · ${SESS}\nbody`)?.why.includes('only that same account signs') === true && hs.signatureRefusal(`${ACC}\nbody`) === null); + t('⛔ the near misses of the account mark: no account, a space around the `@`, a doubled or trailing hyphen, both marks at once', [`repo:objectstack@ · os-justin · ${SESS}`, `repo:objectstack @os-justin · os-justin · ${SESS}`, `repo:objectstack@ os-justin · os-justin · ${SESS}`, `repo:objectstack@os--justin · os--justin · ${SESS}`, `repo:objectstack@os-justin- · os-justin · ${SESS}`, `repo:objectstack#1@os-justin · os-justin · ${SESS}`].every((line) => hs.readSignatureLine(line) === null)); + t('⭐ CONTROL — a `#N` signature keeps reading as that numbered seat: seat 1\'s line is `repo:objectstack#1`, whoever signed it, and is no account\'s seat; the two ids of one lane differ', hs.seatIdOf('repo:objectstack', hs.readSignatureLine(NUM).seat) === 'repo:objectstack#1' && hs.seatIdOf('repo:objectstack', hs.readSignatureLine(`repo:objectstack#1 · os-justin · ${SESS}`).seat) === 'repo:objectstack#1' && hs.seatIdOf('repo:objectstack', hs.readSignatureLine(ACC).seat) === 'repo:objectstack@os-justin' && hs.seatMark('#1') !== hs.seatMark('@1')); + t('`seatMark` reads the two marks and nothing else: a number, `@account`, else null', J(['#12', '@Os-Bill', '#0', '@', 'os-bill', '#1@a', ''].map(hs.seatMark)) === J([12, '@os-bill', null, null, null, null, null])); + t('one leading account-seat signature changes no first-line reading: the strip, the `os-dev-report` marker, the doorbell', hs.stripSignatureLine(`${ACC}\n\nClaim: x`) === 'Claim: x' && hs.OS_DEV_REPORT_MARKER.test(`${ACC}\nos-dev-report\n{}`) && JSON.stringify(readMailboxLine(`${ACC}\n${DB.cr}`)) === JSON.stringify(readMailboxLine(DB.cr))); + const claimOf = (seatLine) => `Claim: PM loop round 1 · 2026-11-29T03:08Z\nSession: \`${SESS}\`\n${seatLine}\nBranch: \`claude/issue-1-x\``; + t('⭐ the claim\'s `Seat:` line reads both forms: `repo:NAME#5` is 5, `repo:NAME@ACCOUNT` is `@account`, and an epic seat named by account is ⛔ never seat N of its epic', J([hs.claimSeatNumber(claimOf('Seat: `repo:objectstack#5`')), hs.claimSeatNumber(claimOf('Seat: `repo:objectstack@os-justin`')), hs.claimSeatNumber(claimOf('Seat: epic:#35205@OS-Justin (see #12)')), hs.claimSeatNumber(claimOf('Seat: repo:objectstack#5 (asked by os@example)'))]) === J([5, '@os-justin', '@os-justin', 5])); + t('⛔ an account-seat declaration off the line start is present-but-unreadable (null), ⛔ never seat 1', hs.claimSeatNumber('Claim: round 1 — dispatched. Seat: repo:objectstack@os-justin — R1.') === null && hs.claimSeatNumber('Claim: round 1 — dispatched.') === 1); + t('⭐ `seatKey` — the doorbell\'s ONE grammar — reads the account form as its own key, lower-cased; the numbered key, and a bare lane as seat 1, read as before', J([seatKey('Repo:ObjectStack@OS-Bill')?.key, seatKey('epic:#12@os-bill')?.key, seatKey('repo:objectstack#5')?.key, seatKey('triage')?.key, seatKey('repo:objectstack@')]) === J(['repo:objectstack@os-bill', 'epic:#12@os-bill', 'repo:objectstack#5', 'triage#1', null])); + t('⭐ `To: LANE@ACCOUNT` addresses that seat, and a key\'s seat field reads it: no number, the account named', (() => { const r = readMailboxLine(MSG('Notify: split · repo:objectstack@os-bill · takes: #27077 · leaves: none', 'repo:objectstack@os-bill')); return r.state === 'read' && r.to === 'repo:objectstack@os-bill' && SAME(r.seat, { key: 'repo:objectstack@os-bill', lane: 'repo:objectstack', n: null, account: 'os-bill' }); })()); + t('⛔ `Notify: seat-online` of an account seat reads under that account only — another login on the line is unreadable', [readMailboxLine(MSG('Notify: seat-online · repo:objectstack@os-bill · OS-Bill · mailbox #27120 · patrol none · takes: none')).state, readMailboxLine(MSG('Notify: seat-online · repo:objectstack@os-bill · os-elon · mailbox #27120 · patrol none · takes: none')).state].join() === 'read,unreadable'); + const HO = (to) => readContractReviewHandoff(`${CONTRACT_REVIEW_HANDOFF_KEY}: ${to} — ${CONTRACT_REVIEW_TIER_NAME} unavailable (HTTP 429, 2026-11-29T03:00Z) · head 1b03a9c3`); + t('⭐ a hand-off target reads with either mark, lower-cased: an L2 seat, a repo seat and an epic seat named by account — and `triage@ACCOUNT` stays unreadable, as `triage#1` is', J([HO('l2-review@OS-Bill').to, HO('review@os-bill').to, HO('repo:objectstack@os-bill').to, HO('epic:#35205@os-bill').to, HO('l2-review#2').to, HO('triage@os-bill').state, HO('l2-review@').state]) === J(['l2-review@os-bill', 'review@os-bill', 'repo:objectstack@os-bill', 'epic:#35205@os-bill', 'l2-review#2', 'unreadable', 'unreadable'])); + // The knock roster: seat 1 is vacant with its old `#1` record standing; os-bill's seat is named by its account. + const S_OLD = 'session_01SeatOneVacantAaaaaaaa'; + const S_NEW = 'session_01AccountSeatBbbbbbbbbb'; + const SIGN = (seat, account, session) => `${seat} · ${account} · ${session}`; + const POST = (number, title, body) => ({ number, state: 'open', title, labels: [{ name: 'pm:seat' }], body }); + const roster = seatSessionRoster({ posts: [POST(34366, '[PM seat] repo:objectstack — 🟢 os-elon', `${SIGN('repo:objectstack#1', 'os-elon', S_OLD)}\n`), POST(35217, '[PM seat] repo:objectstack@os-bill — 🟢 os-bill', `${SIGN('repo:objectstack@os-bill', 'os-bill', S_NEW)}\n`)], mailboxes: [] }); + const knock = (seat, account, session) => readMailboxComment(DB_ROW(`${SIGN(seat, account, session)}\n${MSG('Notify: landed · #28562', 'repo:objectstack#1')}`), roster).signature; + t('⭐ the roster keys each post by the seat its signature names: the account seat lists its session under `LANE@account`, the numbered seat under `LANE#1`', J([...roster.seats.keys()].sort()) === J(['repo:objectstack#1', 'repo:objectstack@os-bill']) && knock('repo:objectstack@os-bill', 'os-bill', S_NEW).state === 'listed' && knock('repo:objectstack@os-bill', 'os-bill', S_NEW).seat === 'repo:objectstack@os-bill'); + t('⭐ CONTROL — seat 1\'s `#1` record still reads as seat 1\'s: its session is listed by `repo:objectstack#1` alone, and ⛔ not by the account seat of the same lane', knock('repo:objectstack#1', 'os-elon', S_OLD).state === 'listed' && knock('repo:objectstack#1', 'os-elon', S_OLD).seat === 'repo:objectstack#1' && roster.seats.get('repo:objectstack@os-bill').has(S_OLD) === false); + t('⛔ account X\'s knock is never read as account Y\'s seat: os-elon signing `@os-bill` is no signature at all, and os-elon\'s OWN account seat — a different seat of the same lane — lists nothing', knock('repo:objectstack@os-bill', 'os-elon', S_NEW).reason?.includes('opens with no seat signature line') === true && knock('repo:objectstack@os-elon', 'os-elon', S_NEW).reason?.includes('repo:objectstack@os-elon lists no session') === true); + } + // -- #18042: the copyable record TEMPLATE ---------------------------------- // // `references/contract-review.md` DESCRIBES the record in prose and once diff --git a/scripts/pm/round-open.mjs b/scripts/pm/round-open.mjs index 94aad98b48d..389a7635b99 100644 --- a/scripts/pm/round-open.mjs +++ b/scripts/pm/round-open.mjs @@ -80,6 +80,10 @@ import { labelNames, markerMatches, readSignatureLine, + SEAT_MARK_SOURCE, + seatIdOf, + seatMark, + seatTitleAccount, seatIntakeKeys, } from './check-half-states.mjs'; import { ghApi, readAllPages } from './gh-pages.mjs'; @@ -126,18 +130,23 @@ export const UNREAD_LEGS = Object.freeze([ // The pure core // --------------------------------------------------------------------------- -/** `LANE#N`: an executing seat — `repo:NAME#N`, `epic:#N#k` or a retired `domain:LANE#N`. `null` otherwise. Pure. */ +/** + * `LANE#N`: an executing seat — `repo:NAME#N`, `epic:#N#k` or a retired `domain:LANE#N` — or the same lane with the + * second seat mark, `LANE@ACCOUNT`, a seat named by its account (`seat` is then `@account`). `null` otherwise. Pure. + */ export function parseSeat(text) { const v = String(text ?? '').trim().toLowerCase(); - const m = /^(repo:[a-z0-9][a-z0-9._-]*|epic:#[1-9][0-9]*|domain:[a-z][a-z0-9-]*)#([1-9][0-9]*)$/u.exec(v); - return m ? { lane: m[1], seat: Number(m[2]), name: `${m[1]}#${m[2]}` } : null; + const m = new RegExp(`^(repo:[a-z0-9][a-z0-9._-]*|epic:#[1-9][0-9]*|domain:[a-z][a-z0-9-]*)(${SEAT_MARK_SOURCE})$`, 'u').exec(v); + return m ? { lane: m[1], seat: seatMark(m[2]), name: `${m[1]}${m[2]}` } : null; } -/** The seat a `[PM seat] …` title names — `LANE · seat N`, `LANE#N`, or bare `LANE` for seat 1. Pure. */ +/** The seat a `[PM seat] …` title names — `LANE@ACCOUNT`, `LANE · seat N`, `LANE#N`, or bare `LANE` for seat 1. Pure. */ export function seatOfPostTitle(title) { const m = /^\[PM seat\]\s*(.*?)\s*—/u.exec(String(title ?? '')); if (!m) return null; const half = m[1].trim(); + const named = seatTitleAccount(half); + if (named) return `${named.lane.toLowerCase()}${named.mark}`; const numbered = /^(\S+?)\s*·\s*seat\s+([1-9][0-9]*)\b/iu.exec(half); if (numbered) return `${numbered[1].toLowerCase()}#${numbered[2]}`; const hashed = /^(\S+?)#([1-9][0-9]*)(?:\s|$)/u.exec(half); @@ -162,13 +171,13 @@ const stampOf = (row) => { return Number.isFinite(ms) ? ms : null; }; -/** The seat a claim declares: its `Seat:` line, else its signature's `LANE#N`; `null` when neither reads. Pure. */ +/** The seat a claim declares: its `Seat:` line, else its signature's `LANE#N` or `LANE@ACCOUNT`; `null` when neither reads. Pure. */ export function claimSeat(body) { const text = String(body ?? ''); - const keyed = /^[ \t]*(?:[-*+][ \t]+)?>?[ \t]*(?:\*\*)?`?Seat`?(?:\*\*)?[ \t]*:[ \t]*`?((?:repo:[A-Za-z0-9._-]+|epic:#[1-9][0-9]*|domain:[a-z0-9_-]+)#[1-9][0-9]*)/imu.exec(text); + const keyed = new RegExp(`^[ \\t]*(?:[-*+][ \\t]+)?>?[ \\t]*(?:\\*\\*)?\`?Seat\`?(?:\\*\\*)?[ \\t]*:[ \\t]*\`?((?:repo:[A-Za-z0-9._-]+|epic:#[1-9][0-9]*|domain:[a-z0-9_-]+)${SEAT_MARK_SOURCE})`, 'imu').exec(text); if (keyed) return keyed[1].toLowerCase(); const sig = readSignatureLine(text); - return sig ? `${sig.lane}#${sig.seat}`.toLowerCase() : null; + return sig ? seatIdOf(sig.lane, sig.seat).toLowerCase() : null; } /** The session a comment speaks for: a `Session:` line, else its signature's, else the first session id; or null. */ @@ -193,7 +202,7 @@ export function postReadings(rows, seatName, own = new Set()) { for (const row of list) { if (row === brief || !after(row)) continue; const sig = readSignatureLine(String(row?.body ?? '')); - if (!sig || `${sig.lane}#${sig.seat}`.toLowerCase() !== seatName || own.has(sig.session)) continue; + if (!sig || seatIdOf(sig.lane, sig.seat).toLowerCase() !== seatName || own.has(sig.session)) continue; if (marker === null || (stampOf(row) ?? 0) >= (stampOf(marker) ?? 0)) marker = row; } return { brief, marker }; @@ -471,7 +480,7 @@ export function fixtureGet(fixture, repo) { const USAGE = [ 'round-open — the round-open mutex at fire start, before the first write (read-only).', '', - ' node scripts/pm/round-open.mjs --seat LANE#N --session SESSION [--own SESSION,…] [--post N]', + ' node scripts/pm/round-open.mjs --seat LANE#N|LANE@ACCOUNT --session SESSION [--own SESSION,…] [--post N]', ' [--intake area:NAME,epic:#N] [--round-minutes N] [--repo OWNER/NAME]', ' [--json] [--fixture FILE] [--now ISO]', ' node scripts/pm/round-open.mjs --self-test', @@ -500,7 +509,7 @@ export function parseArgs(argv) { } else if (flag === '--seat') { const v = take(); opts.seat = parseSeat(v); - if (!opts.seat) return { error: `--seat must be an executing seat, repo:NAME#N or epic:#N#k (the director and the review chains hold no round mutex), got \`${v}\`` }; + if (!opts.seat) return { error: `--seat must be an executing seat, repo:NAME#N or epic:#N#k, or either lane with @ACCOUNT in place of the number (the director and the review chains hold no round mutex), got \`${v}\`` }; } else if (flag === '--session') { const v = String(take() ?? ''); if (!SESSION_ONLY.test(v)) return { error: `--session must be ONE session id, got \`${v}\`` }; @@ -580,8 +589,8 @@ export function main(argv, deps = {}) { const SELF_TEST_BATTERIES = Object.freeze({ // 3 → 4 (#35237 item 21c): the exported ROUND_RULE is stateless — no `g`, so repeated `.test()` answers the same. 'the rule text: every phrase this file is built from is in the file that writes it': 4, - 'readings 1 and 2: the newest stand-down brief, the newest seat-signed comment after it': 7, - 'reading 3: the newest claim of this seat by another session, and a push on a lane branch': 10, + 'readings 1 and 2: the newest stand-down brief, the newest seat-signed comment after it': 10, + 'reading 3: the newest claim of this seat by another session, and a push on a lane branch': 12, 'reading 4: the first closed lane card with a claim of this seat, timed by its session': 4, 'the verdict: foreign, un-clocked-out and under a round yields; own, clocked-out or older does not; a gap is never clear': 8, 'the CLI: usage, exits and the footer': 8, @@ -667,12 +676,20 @@ export function selfTest() { t('⭐ a seat-signed comment after the brief is reading 2, whatever its headline', postReadings([BRIEF, late], 'repo:objectstack#8').marker?.id, late.id); t('N1 — an OWN comment newer than another session\'s marker does not hide it: reading 2 is the newest by a session outside own', postReadings([BRIEF, late, c(`${sig(ME)}\n\nSeat audit`, 10)], 'repo:objectstack#8', new Set([ME])).marker?.id, late.id); t('the seat a post title names: `LANE · seat N`, `LANE#N`, bare LANE for seat 1', [seatOfPostTitle(POST.title), seatOfPostTitle('[PM seat] repo:cloud#1 — 🟢 os-warren'), seatOfPostTitle('[PM seat] review — ⏳ vacant'), seatOfPostTitle('not a post')], ['repo:objectstack#8', 'repo:cloud#1', 'review#1', null]); + // The second seat mark (ruling record 7249169754): `LANE@ACCOUNT`. A seat is its lane AND its mark. + const ASEAT = 'repo:objectstack@os-mickey'; + t('⭐ both seat marks read: `--seat LANE@ACCOUNT` names the seat by its account, lower-cased, and a `LANE@ACCOUNT` post title names that seat — ⛔ never seat 1, while a board suffix after a space still does', [parseSeat('Repo:ObjectStack@OS-Mickey'), parseSeat('epic:#35205@os-mickey')?.name, parseSeat('repo:objectstack#8')?.seat, parseSeat('repo:objectstack@'), parseSeat('review@os-mickey'), seatOfPostTitle('[PM seat] repo:objectstack@OS-Mickey — 🟢 os-mickey · area:fleet'), seatOfPostTitle('[PM seat] domain:ui @ objectui — 🟢 os-b')], [{ lane: 'repo:objectstack', seat: '@os-mickey', name: ASEAT }, 'epic:#35205@os-mickey', 8, null, null, ASEAT, 'domain:ui#1']); + const amark = c(`${sig(OTHER, ASEAT)}\n\n## Seated`, 30); + t('⭐ reading 2 by lane AND account: the account seat reads its own signed comment; ⛔ account X\'s seat does not read account Y\'s, and seat 8 does not read either', [postReadings([BRIEF, amark], ASEAT).marker?.id, postReadings([BRIEF, amark], 'repo:objectstack@os-other').marker, postReadings([BRIEF, amark], 'repo:objectstack#8').marker, postReadings([BRIEF, c(`${sig(OTHER, ASEAT, 'os-other')}\n\n## Seated`, 20)], ASEAT).marker], [amark.id, null, null, null]); + t('⭐ CONTROL — a `#8` comment keeps reading as seat 8\'s: ⛔ not as the account seat of the login that signed it', [postReadings([BRIEF, late], 'repo:objectstack#8').marker?.id, postReadings([BRIEF, late], ASEAT).marker], [late.id, null]); } battery('reading 3: the newest claim of this seat by another session, and a push on a lane branch'); { t('a claim\'s seat is its `Seat:` line, else its signature; its session the `Session:` line, else the signature', [claimSeat(claim(OTHER, 5).body), claimSeat(`${sig(OTHER, 'epic:#35205#1')}\n\nClaim: x`), claimSeat('Claim: x'), commentSession(`${sig(OTHER)}\n\nClaim: x`)], ['repo:objectstack#8', 'epic:#35205#1', null, OTHER]); + t('a claim\'s seat reads with either mark, from the `Seat:` line or the signature, lower-cased', [claimSeat(claim(OTHER, 5, 'repo:objectstack@os-mickey').body), claimSeat('Claim: x\nSeat: `epic:#35205@OS-Mickey`'), claimSeat(`${sig(OTHER, 'epic:#35205@os-mickey')}\n\nClaim: x`), claimSeat('Claim: x\nSeat: `repo:objectstack#8`')], ['repo:objectstack@os-mickey', 'epic:#35205@os-mickey', 'epic:#35205@os-mickey', 'repo:objectstack#8']); const own = new Set([ME]); + t('⭐ CONTROL — reading 3 by lane AND mark: a `#8` claim by another session is seat 8\'s activity and ⛔ not the account seat\'s; the account seat\'s claim is its own and ⛔ not seat 8\'s nor another account\'s', [claimReadings([claim(OTHER, 30)], 'repo:objectstack#8', own).foreign?.created_at, claimReadings([claim(OTHER, 30)], 'repo:objectstack@os-mickey', own).foreign ?? null, claimReadings([claim(OTHER, 20, 'repo:objectstack@os-mickey')], 'repo:objectstack@os-mickey', own).foreign?.created_at, claimReadings([claim(OTHER, 20, 'repo:objectstack@os-mickey')], 'repo:objectstack#8', own).foreign ?? null, claimReadings([claim(OTHER, 20, 'repo:objectstack@os-mickey')], 'repo:objectstack@os-other', own).foreign ?? null], [ago(30), null, ago(20), null, null]); const cr = claimReadings([claim(OTHER, 30), claim(ME, 10), claim(OTHER, 5, 'repo:objectstack#3')], 'repo:objectstack#8', own); t('⭐ the newest claim of THIS seat by ANOTHER session — the own session\'s and another seat\'s are not it', cr.foreign?.created_at, ago(30)); const live = card(['pm:dispatched', 'area:fleet'], 20); From a2205a85a3554881bc917be79ea46797e45726c3 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:24:04 +0000 Subject: [PATCH 042/178] fix(rest): the cached by-name meta read revalidates across a translation change (#38495) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #38288 Clause-②: no Metadata-protocol: none ## 维护者速读 用户能看到什么变化:前台和接口客户端在翻译更新后,再次打开对象或报表时会立刻看到新的显示名称,翻译故障恢复后提示也会随之消失;以前要强制刷新才行。 为什么做:多语言显示的缓存漏洞,翻译变了而缓存校验没变,客户端一直沿用旧文字(来自翻译故障提示那张卡的复审发现)。 出错会怎样:最坏情况是客户端多拿一次完整内容、少一次缓存命中,不会出现错误数据;本改动可以直接撤回。 要你做什么:无 ## What changes The default by-name metadata read (`GET /meta/:type/:name`, the cached door, `metadata.enableCache: true`) issued an `ETag` the protocol computed from the stored document and the locale, and translated the item only after `If-None-Match` was judged against it. A translation edit, or a translation fault beginning or clearing, moved no byte of that validator, so a revalidating client was answered `304` and kept the old labels, or kept a `translationWarning` after the fault had cleared. ADR-0156 D3 (verbatim: "The per-caller gate, the field mask, translation into the caller's locale and the `ETag` are computed on every request, over the cached part.") decides the shape: the door now translates on every request BEFORE it judges the request, and folds what the translation contributed into the validator. - `packages/rest/src/meta-item-read-routes.ts` (the landing point; the validator's input must come from the REST door because the translation happens there and the protocol has no i18n): the cached arm never hands the protocol `ifNoneMatch` any more and judges `If-None-Match` itself for every type, after `translateMetaEnvelope`. A new `cachedTranslationFingerprint` (the translated item and the fault warning, hashed) is folded into the validator with the existing folds. It is EMPTY when the translation changed nothing and reported no fault, so such a read keeps the exact `ETag` it had before. The action arm's early `304` moved into the common judgment for the same reason. The nested fold chain became one ordered list; the fold order, and so every existing `ETag` value, is unchanged. - `packages/metadata-protocol/src/protocol-search-and-cache.ts`: comment only, at the validator: the locale is all of the translation it holds, so a door that translates must not hand it `ifNoneMatch`. - Why a hash of the translated output and not a bundle version: none exists. `II18nService` declares no version or change counter, and ADR-0156 lists translation bundles among the sources "with no counter". The translation also reads the packaged base, the pair's and the patching packages' translations; only its output says what all of them produced. Adding a counter would be a new contract surface. - The translated answer is not cached; only the validator changes. ## Tests New `packages/rest/src/meta-item-cached-translation-etag.test.ts`: the real REST route over the real `ObjectStackProtocolImplementation` over a real `SchemaRegistry`, with an i18n double whose bundles are replaced in place and whose read can be made to fail. For `object` (the arm that already judged its own validator, before translating) and `report` (an arm the protocol judged): 1. The card's round trip: read, update the translation, revalidate with the earlier `ETag` → `200` with the new label and a new `ETag`; the new `ETag` then revalidates to `304`. 2. Control: an unchanged translation revalidates to `304`. 3. A read served during a translation fault, revalidated after the fault clears → `200`, no `translationWarning`, translated label. 4. A fault that begins after a healthy read → `200` with the warning.
Reproduction on unfixed code, fix, ablation (head 02ae5c54) - Before the fix (test file only, on base 7e1b2229): `Tests 6 failed | 2 passed (8)`, each failure `expected 304 to be 200`; the two controls passed. - With the fix: `Tests 8 passed (8)`. - Ablation via `scripts/ablation-replace.mjs` (fingerprint forced empty): anchor 1 to 0, blob 003518b11531 to 1a5a24f60025, `Tests 6 failed | 2 passed (8)`, the same six; restored, blob equals HEAD, `git diff HEAD` empty. - `@objectstack/rest` local project, whole package: `Test Files 438 passed (438)`, `Tests 9025 passed | 351 skipped (9376)` (lock VERDICT command-exit 0; run at e626f844, the later commit removes one unused binding and adds the changeset). - `pnpm --filter @objectstack/rest typecheck` and `pnpm --filter @objectstack/metadata-protocol typecheck`: VERDICT command-exit 0 at 02ae5c54.
Derived gates (dispatch-gates --commands, 68 families, at 02ae5c54) - 66 exit 0, including `check:nul-bytes`, `check:durability-log-level`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:adr-anchors`, `check:doc-authoring`, `check:issue-citations`, `check-adr-0087-registration --base origin/main`, `check-empty-changeset`, `check-changeset-no-major`. - NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT MET (reads every package's dist; this worktree built only the rest closure). CI runs it. - NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason: its pinned fixture commit is outside this shallow clone (checker health, not a verdict on this diff). - `--ran` reconciliation: 68 derived, 68 run, 0 UNRUN.
## Acceptance notes - One-time revalidation miss: for a translated read (a locale whose translation changes the item), the `ETag` gains a fold, so each client gets one `200` after this deploys, then `304`s as before. A read the translation does not change keeps its `ETag` byte for byte. - Cost: a revalidation that the protocol used to answer `304` without translating now translates first (the ADR-0156 D3 rule) plus up to two `JSON.stringify` of the item. NOT MEASURED: per-request latency, reason: no load harness in scope; the uncached doors already hash the full served body per request. - `GET /meta/:type/:name` wire behaviour moves (when a `304` is answered); no spec schema, export or error code changes. ## Verification Read first, by risk: `packages/rest/src/meta-item-read-routes.ts` (the cached arm: `cacheRequest`, the translate-before-judge block, the fold list and the `304` condition; then `cachedTranslationFingerprint` at the bottom), then the new test file. Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/meta-item-cached-translation-etag.test.ts` → `Tests 8 passed (8)`. Account: os-project-manager --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pH8MaBBP5T2dVcTHL)_ --------- Co-authored-by: Claude --- .changeset/38288-meta-etag-translation.md | 12 ++ .../src/protocol-search-and-cache.ts | 9 + .../meta-item-cached-translation-etag.test.ts | 185 ++++++++++++++++++ packages/rest/src/meta-item-read-routes.ts | 169 ++++++++++------ 4 files changed, 314 insertions(+), 61 deletions(-) create mode 100644 .changeset/38288-meta-etag-translation.md create mode 100644 packages/rest/src/meta-item-cached-translation-etag.test.ts diff --git a/.changeset/38288-meta-etag-translation.md b/.changeset/38288-meta-etag-translation.md new file mode 100644 index 00000000000..cec0931fe53 --- /dev/null +++ b/.changeset/38288-meta-etag-translation.md @@ -0,0 +1,12 @@ +--- +'@objectstack/rest': patch +--- + +fix(rest): the cached `GET /meta/:type/:name` validator moves when the served translation moves + +Clause-②: no +Metadata-protocol: none + +The default by-name metadata read (the cached door, `metadata.enableCache: true`) computed its `ETag` from the stored document and the locale, and translated the item only after judging `If-None-Match` against it. A client revalidating after a translation edit was answered `304` and kept the old labels; a client that read the item during a translation fault was answered `304` after the fault cleared and kept the `translationWarning`. + +The door now translates the item on every request before it judges the request, and folds what the translation contributed (the translated item, and the `translationWarning` of a fault) into the validator. A translation edit, a fault that begins and a fault that clears each answer `200` under a new `ETag`; an unchanged translation still revalidates to `304`. A read whose translation changes nothing keeps the `ETag` it had before. The translated answer itself is not cached. diff --git a/packages/metadata-protocol/src/protocol-search-and-cache.ts b/packages/metadata-protocol/src/protocol-search-and-cache.ts index 26edfb2295d..9021233aadf 100644 --- a/packages/metadata-protocol/src/protocol-search-and-cache.ts +++ b/packages/metadata-protocol/src/protocol-search-and-cache.ts @@ -95,6 +95,15 @@ export class ProtocolSearchAndCacheFacet { // language until a hard refresh (issue #1319). Folding the resolved // locale into the hash gives each locale a distinct validator. // + // [#38288 · ADR-0156 D3] The locale is all of the translation this + // validator holds: a translation edit, or a translation fault + // beginning or clearing, moves none of these bytes. So a door that + // translates the item must not hand this read its `ifNoneMatch`: + // it translates first, folds what the translation contributed into + // this value and judges the conditional request itself (the REST + // cached door, `packages/rest`, does). The `304` below is right + // only for a caller that serves `item` untranslated. + // // [ADR-0131 D6] No organization is part of the validator: the // read is the environment's for every caller, so the document // hashed below is the whole scope. An org-less caller's validator diff --git a/packages/rest/src/meta-item-cached-translation-etag.test.ts b/packages/rest/src/meta-item-cached-translation-etag.test.ts new file mode 100644 index 00000000000..6ebee1c214a --- /dev/null +++ b/packages/rest/src/meta-item-cached-translation-etag.test.ts @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#38288] The default `GET /meta/:type/:name` (the CACHED door, +// `metadata.enableCache` defaults to `true`) issues a validator that moves when +// the served TRANSLATION moves. +// +// The defect: the protocol's validator (`getMetaItemCached`) hashes the stored +// document and the locale, and the REST door translated the item only after +// that validator was judged. A client revalidating with `If-None-Match` after a +// translation edit was answered `304` and kept the old labels; a client that +// read the item during a translation fault was answered `304` after the fault +// cleared and kept the `translationWarning`. +// +// ADR-0156 D3: the translation and the `ETag` are computed on every request, +// over the cached part. So the door translates first and folds what the +// translation contributed into the validator before it judges the request. +// +// Everything is real but the i18n service: the REST route handlers over the +// real `ObjectStackProtocolImplementation` over a real `SchemaRegistry`. The +// i18n double holds mutable bundles, the way `loadTranslations` replaces a +// locale's bundle on a live service, and can be made to fail its read. +// +// Two arms of the cached door, both measured: +// - `object`: the door folds and judges the validator itself (its per-caller +// gate); before the fix it judged it before translating. +// - `report`: no per-caller step, so the protocol judged the validator; the +// door now judges it after translating, for every type. + +import { describe, it, expect, vi } from 'vitest'; +import { SchemaRegistry } from '@objectstack/objectql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { RestServer } from './rest-server.js'; +import { META_TRANSLATION_FAULT_WARNING } from './meta-item-read-gate.js'; + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const CUSTOMER = { + name: 'crm_customer', + label: 'Customer', + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, +}; +const PIPELINE = { name: 'crm_pipeline', label: 'Pipeline', objectName: 'crm_customer', type: 'tabular' }; + +/** A `de` bundle naming the object and the report with `label`. */ +function deBundle(label: string) { + return { + objects: { crm_customer: { label, fields: { title: { label: `${label} Titel` } } } }, + reports: { crm_pipeline: { label } }, + }; +} + +/** An `II18nService` double: bundles replaced in place, a read that can be made to fail. */ +function i18nDouble() { + const bundles: Record> = { en: {}, de: deBundle('Kunde') }; + const state = { fault: false }; + const svc = { + getLocales: () => Object.keys(bundles), + getTranslations: (locale: string) => { + if (state.fault) throw new Error('translation store unreachable'); + return bundles[locale] ?? {}; + }, + loadTranslations: (locale: string, data: Record) => { bundles[locale] = data; }, + getDefaultLocale: () => 'en', + getFallbackLocale: () => 'en', + t: (key: string) => key, + }; + return { svc, state }; +} + +function createMockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), + use: vi.fn(), + listen: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + }; +} + +function host() { + const registry = new SchemaRegistry(); + registry.registerObject(clone(CUSTOMER) as never, 'pkg_code', undefined, 'own'); + registry.registerItem('report', clone(PIPELINE) as never, 'name' as never, 'pkg_code'); + const engine = { registry, find: async () => [], count: async () => 0 }; + const protocol: any = new ObjectStackProtocolImplementation(engine as never, () => new Map()); + const cached = vi.spyOn(protocol, 'getMetaItemCached'); + const i18n = i18nDouble(); + const rest = new RestServer( + createMockServer() as never, protocol as never, { api: { requireAuth: false } } as never, + undefined, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, undefined, undefined, + // i18nServiceProvider — the 14th constructor argument. + async () => i18n.svc, + ); + (rest as unknown as { resolveExecCtx: () => Promise }).resolveExecCtx = + async () => ({ userId: 'test-user', systemPermissions: [] }); + rest.registerRoutes(); + return { rest, i18n, cached }; +} + +async function read(h: ReturnType, type: string, name: string, ifNoneMatch?: string) { + const route = (h.rest as any).getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/meta/:type/:name'); + if (!route) throw new Error('route not registered: GET /api/v1/meta/:type/:name'); + let status = 200; + let body: any; + const headers: Record = {}; + const res: any = { + status: (c: number) => { status = c; return res; }, + json: (b: unknown) => { body = b; return res; }, + send: (b: unknown) => { body = b; return res; }, + header: (k: string, v: string) => { headers[k] = v; return res; }, + setHeader: () => res, write: () => true, end: () => res, + }; + const requestHeaders: Record = { 'accept-language': 'de' }; + if (ifNoneMatch !== undefined) requestHeaders['if-none-match'] = ifNoneMatch; + await route.handler({ method: 'GET', params: { type, name }, query: {}, headers: requestHeaders, body: {} }, res); + return { status, body, etag: headers.ETag }; +} + +const CASES = [ + { type: 'object', name: CUSTOMER.name }, + { type: 'report', name: PIPELINE.name }, +] as const; + +for (const { type, name } of CASES) { + describe(`[#38288] the cached GET /meta/${type}/:name revalidates across a translation change`, () => { + it('a translation edit moves the ETag: the earlier ETag is answered 200 with the new label', async () => { + const h = host(); + const first = await read(h, type, name); + expect(first.status).toBe(200); + expect(first.body.item.label).toBe('Kunde'); + expect(typeof first.etag).toBe('string'); + // The cached door, measured — not the uncached read. + expect(h.cached).toHaveBeenCalled(); + + h.i18n.svc.loadTranslations('de', deBundle('Kundin')); + const again = await read(h, type, name, first.etag); + expect(again.status).toBe(200); + expect(again.body.item.label).toBe('Kundin'); + expect(again.etag).not.toBe(first.etag); + + // …and the new ETag revalidates to 304 while nothing moves. + const settled = await read(h, type, name, again.etag); + expect(settled.status).toBe(304); + expect(settled.body).toBeUndefined(); + }); + + it('control: an unchanged translation revalidates to 304 under the ETag it issued', async () => { + const h = host(); + const first = await read(h, type, name); + expect(first.status).toBe(200); + const again = await read(h, type, name, first.etag); + expect(again.status).toBe(304); + expect(again.body).toBeUndefined(); + }); + + it('a read served during a translation fault is answered 200, without the warning, once the fault clears', async () => { + const h = host(); + h.i18n.state.fault = true; + const faulted = await read(h, type, name); + expect(faulted.status).toBe(200); + expect(faulted.body.translationWarning).toBe(META_TRANSLATION_FAULT_WARNING); + expect(faulted.body.item.label).toBe(type === 'object' ? CUSTOMER.label : PIPELINE.label); + + h.i18n.state.fault = false; + const healed = await read(h, type, name, faulted.etag); + expect(healed.status).toBe(200); + expect(healed.body).not.toHaveProperty('translationWarning'); + expect(healed.body.item.label).toBe('Kunde'); + expect(healed.etag).not.toBe(faulted.etag); + }); + + it('a fault that begins after a healthy read is answered 200 with the warning', async () => { + const h = host(); + const healthy = await read(h, type, name); + expect(healthy.status).toBe(200); + expect(healthy.body).not.toHaveProperty('translationWarning'); + + h.i18n.state.fault = true; + const faulted = await read(h, type, name, healthy.etag); + expect(faulted.status).toBe(200); + expect(faulted.body.translationWarning).toBe(META_TRANSLATION_FAULT_WARNING); + expect(faulted.etag).not.toBe(healthy.etag); + }); + }); +} diff --git a/packages/rest/src/meta-item-read-routes.ts b/packages/rest/src/meta-item-read-routes.ts index 57ea70a5866..a99ce64c624 100644 --- a/packages/rest/src/meta-item-read-routes.ts +++ b/packages/rest/src/meta-item-read-routes.ts @@ -756,7 +756,6 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // but the `sortability` beside it follows that // caller's own field permission, which the // protocol's validator does not hash either. - const maskApplies = maskPosture.kind !== 'passthrough' || maskPosture.runtime !== undefined; // [#21476] Same move for a `view`: its body can carry // the public-form intake reason, which derives from // the posture and the bound object, and the @@ -783,8 +782,19 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // before the projection below has judged it. The // validator is judged after it, unchanged. const actionProjects = metaType === 'action'; + // [#38288 · ADR-0156 D3] …and for EVERY type, the + // translation: the body is translated below + // (`translateMetaEnvelope`), and the protocol's + // validator hashes the stored document and the locale, + // not what the translation step contributes. A `304` + // decided there pinned a client to its old labels + // after a translation edit, and to a + // `translationWarning` after the fault cleared. So the + // protocol never judges the conditional request on + // this door: the comparison is made below, after the + // translation is folded into the validator. const cacheRequest = { - ifNoneMatch: (maskApplies || intakeFolds || audienceFolds || actionProjects) ? undefined : (req.headers['if-none-match'] as string), + ifNoneMatch: undefined, ifModifiedSince: req.headers['if-modified-since'] as string, }; @@ -863,10 +873,6 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M cachedCascadeDeleteObjects.cascadeDeleteObjects, ); - if (result.notModified) { - res.status(304).send(); - return; - } // [ADR-0106 D1/D3] fetch → mask → send. The shared // cache still stores ONE full schema per (type, @@ -912,7 +918,8 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // withheld action is answered {@link sendMetaItemAbsent}, // the answer this arm gives a name with nothing behind // it; a served one keeps the protocol's validator, and - // its `304` is judged here as the protocol judges it. + // its `304` is judged below with every other type's, + // after the translation (#38288). let actionUndetermined = false; if (actionProjects) { const projected = await metaReadGate.projectMetaActionItem( @@ -928,11 +935,6 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M return; } actionUndetermined = projected.cacheControl !== undefined; - if (!actionUndetermined && result.etag - && normalizeIfNoneMatch(req.headers['if-none-match']) === result.etag.value) { - res.status(304).send(); - return; - } } // [#21476] The administrator's read names why an open // public form is not offered on this posture. @@ -965,6 +967,49 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M return; } + // [#5563] `getMetaItemCached` hands back the metadata + // document with the envelope already stripped + // (`result.data`; it does `const item = result?.item` + // internally). This branch is the DEFAULT — `enableCache` + // defaults to `true` — so leaving it unwrapped made the + // one shape `packages/spec` declares for this route the + // one a default deployment could never obtain. Rebuild + // the declared envelope here, in the REST layer that + // owns the response contract. + // + // `type` is folded to the canonical singular exactly as + // `metadata-protocol` folds it (#4432), so `/meta/objects/x` + // and `/meta/object/x` cannot answer two different `type` + // values across a configuration switch. The cached read + // carries no `lock` — it is the fast published-value path + // and never consulted the lock resolver; a caller that + // needs the ADR-0008 OCC carriers reads the uncached path. + // [#22114] That includes `version`, the read's token. Its + // ETag below stays the CACHE validator and is not the token: + // the validator varies by locale (#1319), by the caller's + // field visibility (ADR-0106 D3), by the translation + // (#38288) and by the served bytes + // (`getMetaItemCached`, #16525), none of which moves the + // stored row's version, and an item with no stored row has + // a validator but no version at all. + const cachedEnvelope = { + type: metaType, + name: req.params.name, + ...cachedBeside, + }; + // [#38288 · ADR-0156 D3] Translated BEFORE the validator is + // judged, on every request, over the cached part: what the + // translation contributed (the translated item, the + // `translationWarning` of a fault) is folded into the + // validator below, so a translation edit, a fault that + // begins and a fault that clears each move the ETag. The + // translated answer itself is never cached. + const cachedBody = await this.translateMetaEnvelope( + req, req.params.type, environmentId, cachedEnvelope, cachedDocument, cacheI18n, + runtimeView.document, + ); + const translationFingerprint = cachedTranslationFingerprint(cachedDocument, cachedBody); + // Set cache headers if (result.etag) { // [ADR-0106 D3] Fold the caller's field-visibility @@ -986,28 +1031,32 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M // answered a `304` for the list it replaced. // [#28001] …and so does the cascade list served // beside an object: a cascading object registered - // or removed is never answered a `304`. - const value = foldVisibilityFingerprintIntoEtag( - foldVisibilityFingerprintIntoEtag( - foldVisibilityFingerprintIntoEtag( - foldVisibilityFingerprintIntoEtag( - foldVisibilityFingerprintIntoEtag( - foldVisibilityFingerprintIntoEtag(result.etag.value, visibilityFingerprint), - runtimeView.fingerprint, - ), - intakeFingerprint, - ), - audienceFingerprint, - ), - disabledActionsFingerprint, - ), + // or removed is never answered a `304`. [#38288] + // …and so does what the translation contributed: + // a client is never answered a `304` for labels a + // translation edit replaced, nor for a fault's + // `translationWarning` once the fault cleared. A + // translation that changes nothing folds nothing. + // Folded in this order, each empty one a no-op. + const value = [ + visibilityFingerprint, + runtimeView.fingerprint, + intakeFingerprint, + audienceFingerprint, + disabledActionsFingerprint, cascadeDeleteObjectsFingerprint, + translationFingerprint, + ].reduce( + (folded: string, fingerprint: string) => foldVisibilityFingerprintIntoEtag(folded, fingerprint), + result.etag.value, ); const etagValue = result.etag.weak ? `W/"${value}"` : `"${value}"`; res.header('ETag', etagValue); - if ((maskApplies || intakeFolds || audienceFolds) && !besideJudged + // [#38288] Judged here for every type, never by + // the protocol (`cacheRequest` above says why). + if (!besideJudged && normalizeIfNoneMatch(req.headers['if-none-match']) === value) { res.status(304).send(); return; @@ -1031,39 +1080,7 @@ export function registerMetaItemReadRoutes(this: MetaItemReadRouteHost, scope: M } res.header('Vary', 'Accept-Language'); - // [#5563] `getMetaItemCached` hands back the metadata - // document with the envelope already stripped - // (`result.data`; it does `const item = result?.item` - // internally). This branch is the DEFAULT — `enableCache` - // defaults to `true` — so leaving it unwrapped made the - // one shape `packages/spec` declares for this route the - // one a default deployment could never obtain. Rebuild - // the declared envelope here, in the REST layer that - // owns the response contract. - // - // `type` is folded to the canonical singular exactly as - // `metadata-protocol` folds it (#4432), so `/meta/objects/x` - // and `/meta/object/x` cannot answer two different `type` - // values across a configuration switch. The cached read - // carries no `lock` — it is the fast published-value path - // and never consulted the lock resolver; a caller that - // needs the ADR-0008 OCC carriers reads the uncached path. - // [#22114] That includes `version`, the read's token. Its - // ETag above stays the CACHE validator and is not the token: - // the validator varies by locale (#1319), by the caller's - // field visibility (ADR-0106 D3) and by the served bytes - // (`getMetaItemCached`, #16525), none of which moves the - // stored row's version, and an item with no stored row has - // a validator but no version at all. - const cachedEnvelope = { - type: metaType, - name: req.params.name, - ...cachedBeside, - }; - res.json(await this.translateMetaEnvelope( - req, req.params.type, environmentId, cachedEnvelope, cachedDocument, cacheI18n, - runtimeView.document, - )); + res.json(cachedBody); } else { // Non-cached version // [#22128] The save door's reading of `?package=` @@ -1404,3 +1421,33 @@ function anonymousFormIntakeFingerprint(warnings: ReadonlyArray<{ path: string; function cachedDisabledActionsFingerprint(disabledActions: readonly string[] | undefined): string { return disabledActions === undefined ? '' : objectFieldVisibilityFingerprint([JSON.stringify(disabledActions)]); } + +/** + * [#38288 · ADR-0156 D3] What the translation step contributed to a cached + * by-name answer, as a fingerprint the door folds into the protocol's + * validator: the protocol hashes the stored document and the locale, and the + * body is translated after it, so without this fold a translation edit (or a + * translation fault beginning or clearing) moved no byte of the validator and + * a revalidating client was answered `304` for the labels, or the + * `translationWarning`, it was served before. + * + * `document` is what the door handed the translation, `served` the envelope it + * answered. Empty when the translation changed nothing and reported no fault — + * an untranslatable type, a locale that is the authored one, a bundle with no + * entry for the item — so such a read keeps the validator it had before the + * fold. Otherwise the served item itself is hashed (⛔ never a version marker + * of the bundle: the translation reads the bundle, the packaged base, the + * pair's and the patching packages' translations, and only its output says + * what all of them produced), together with the warning a fault reported. + */ +function cachedTranslationFingerprint(document: unknown, served: Readonly>): string { + const item = served.item; + const warning = typeof served.translationWarning === 'string' ? served.translationWarning : undefined; + if (warning === undefined && item === document) return ''; + const translated = item === document ? undefined : JSON.stringify(item); + if (warning === undefined && translated === JSON.stringify(document)) return ''; + return objectFieldVisibilityFingerprint([ + `item\u0000${translated ?? ''}`, + `warning\u0000${warning ?? ''}`, + ]); +} From 1b516cf9193356c5b42382bb41d2f8d644d67e4a Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:43:24 +0000 Subject: [PATCH 043/178] perf(plugin-view, app-shell): an object list loads the form package only when a form opens (#38486) 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_01AXsQkLFKRdQCqQ3RTr6JaoLA64Pdo43CcX7aDR1Nooow)_ Part of #37444. This is the second cut, after #38429: the object list page stops loading the form package before its first screen. What this PR build measured (Verification below, 20 vs 20 against main `4d07ddbf`): the list fetches about 45 KB gzip less form code before its first screen (225 → 224 scripts), and its LCP moved −46.5 ms at p 0.22, not a significant change and still above 2500 ms. So the card stays open after this PR, for candidate B. Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户打开对象列表页时,首屏前少下载约 45 KB 的表单代码;这次构建测得列表页首屏时间没有显著变化(−46.5 毫秒,p 0.22),仍未进 2.5 秒。页面上看到和保存的内容都不变。 - 属于「控制台首屏 2.5 秒内打开」专题,这是列表页的第二刀。 - 出错时,列表页上第一次点「新建」或编辑记录会多等一下,或者表单打不开;撤回这个 PR 即可恢复。 - 无。 ## What changes An object list fetched the whole of `@object-ui/plugin-form` (45.6 KB gzip, measured on `1afd9c13`) before its first screen, though it draws a form only when someone creates or edits a record. Two things did this: 1. `plugin-view`'s `ObjectView` imported `ObjectForm` statically. The form is drawn only inside the drawer or modal, whose content mounts when it opens. 2. The console's `AppContent` drew a closed `LazyModalForm` on every object page: `formObjectDef` is set whenever an object is open, and a lazy component that is drawn fetches its chunk even closed. Making only the first import lazy left the chunk on the list route (seen in a probe; it was still fetched at about 2.0 s). Now: - `plugin-view/src/ObjectView.tsx`: `ObjectForm` is `React.lazy`, and both form sites (drawer and modal) sit in a `Suspense` with a `null` fallback. - `app-shell/src/console/AppContent.tsx`: the record-form modal mounts the first render its open state is true (`useOpenedOnce(recordFormShown)`), and stays mounted after that, so it closes the way it did before. It is never drawn closed first. - `useOpenedOnce` moves from `app-shell/src/views/ObjectView.tsx` (where #38429 added it) to `app-shell/src/hooks/useOpenedOnce.ts`, package-internal, shared by both files. It is not exported from the package. No exported shape, prop or option changes; no spec or metadata change. ## Tests - New `plugin-view/src/__tests__/ObjectView.formLoadsOnOpen-37444.test.tsx`: a counted `vi.mock` factory for `@object-ui/plugin-form`. Importing and drawing a drawer-layout list evaluates no form module; clicking New loads it once and draws the form in `create` mode. - New `app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx`: an object page with no form open loads no form module and draws no modal; `?form=new` loads it once and its first render is open. - `ObjectView.tableEditable-10976`, `ObjectView.namedViewInlineEdit-10885` and `ObjectView.test.tsx` (navigation drawer default) read the form on the click's tick; they now wait for it, since it loads on first open.
Pin ablation Committed first, then `scripts/ablation-replace.mjs`, one half at a time: 1. `AppContent.tsx`: the anchor `{formObjectDef && recordFormMounted && (` replaced with `{formObjectDef && (`. Both AppContent cases red: case 1 drew a modal and `loads.form` was 1 (expected 0); case 2 failed on its starting count. Restored: blob equals HEAD. 2. `plugin-view/src/ObjectView.tsx`: the lazy `ObjectForm` const replaced with the static `import { ObjectForm } from '@object-ui/plugin-form';`. The plugin-view case red (`expected 1 to be +0`). Restored: blob equals HEAD, `git diff HEAD` empty.
## Acceptance notes - Read first: `AppContent.tsx` (the `recordFormMounted` gate next to `useRecordFormOpensOverDrawers`), then `plugin-view/src/ObjectView.tsx` (the lazy const and the two `Suspense` sites). - Two-minute check: on a list page, open the network panel and load the list: no `plugin-form` chunk. Click New: the form opens after one chunk fetch. Close it and open it again: no new fetch. - A user sees a short wait the first time a create or edit form opens on a page. ## Verification LCP reading on this PR's build (report on #37444, comment 7251766050), Lighthouse 13.6.0 desktop, 20 vs 20 per page against main at the merge base `4d07ddbf`: | page | main | PR | delta | p | |:--|--:|--:|--:|--:| | home | 2160 | 2184.5 | +24.5 | 0.41 | | object list | 2631 | 2584.5 | −46.5 | 0.22 | | record | 2533.5 | 2457 | −76.5 | 0.0007 | The list fetches no `plugin-form` chunk: 225 → 224 scripts, −45.4 KB gzip. It does not clear 2500 on this reading, so the card stays open. A same-session control read main `1afd9c13` at 2681.5. The same build read 2521.5 in the second-cut reading, so the box level moved about 160 ms between sessions. The record delta is unexplained: bytes, script count and the `plugin-form` request time match on both builds.
Gates Derived gates (`dispatch-gates.mjs --ran`): 38 derived, 38 run, 38 exit 0, 0 NOT-MEASURED, on `6a6dc4b9`. Two needed a fix first, on the new AppContent pin: `check:test-source-alias` (a module-top `import '@objectstack/lint'`) and `check-vi-mock-inherit` (both counted `plugin-form` factories now spread `importOriginal`); the pins and both ablations were re-run after it. `vitest run scripts/`: 172 files passed. Affected suite under the verify lock: 251 files / 2286 tests passed. eslint on the changed files: 0 errors. Overlap check against `origin/main` `430bbbf1`: merges cleanly. Changed lines: +290/−21 (311).
## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint on the changed files: 0 errors. - [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: n/a. - [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 with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibxzGFPvShbd2qnkdEv Co-authored-by: Claude --- .changeset/37444-list-route-defers-form.md | 14 ++ .../app-shell/src/console/AppContent.tsx | 7 +- ...tent.recordFormMountsOnOpen-37444.test.tsx | 146 ++++++++++++++++++ .../app-shell/src/hooks/useOpenedOnce.ts | 19 +++ .../app-shell/src/views/ObjectView.tsx | 14 +- ui/packages/plugin-view/src/ObjectView.tsx | 20 ++- .../ObjectView.formLoadsOnOpen-37444.test.tsx | 76 +++++++++ ...ectView.namedViewInlineEdit-10885.test.tsx | 5 +- .../ObjectView.tableEditable-10976.test.tsx | 5 +- .../src/__tests__/ObjectView.test.tsx | 5 +- 10 files changed, 290 insertions(+), 21 deletions(-) create mode 100644 .changeset/37444-list-route-defers-form.md create mode 100644 ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx create mode 100644 ui/packages/app-shell/src/hooks/useOpenedOnce.ts create mode 100644 ui/packages/plugin-view/src/__tests__/ObjectView.formLoadsOnOpen-37444.test.tsx diff --git a/.changeset/37444-list-route-defers-form.md b/.changeset/37444-list-route-defers-form.md new file mode 100644 index 00000000000..a538c7e75dc --- /dev/null +++ b/.changeset/37444-list-route-defers-form.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-view': patch +'@object-ui/app-shell': patch +'@objectstack/console': patch +--- + +perf(plugin-view, app-shell): an object list stops loading the form package before its first screen + +Clause-②: no +Metadata-protocol: none + +An object list page fetched the whole form package (about 46 KB gzip) before its first screen, though it draws a form only when someone creates or edits a record. Two things did this. The object view imported its create and edit form statically, and the console drew a closed record-form dialog on every object page. Now the object view loads its form the first time one opens, and the console mounts the record-form dialog the first time it opens and keeps it mounted after that, so closing it works as before. + +Nothing a user sees or saves changes, apart from a short wait the first time a form opens on a page. Nothing to migrate. diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 804b2bbf59d..f31819acb4b 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -32,6 +32,7 @@ import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js'; import { useHomePath } from '../hooks/useHomePath.js'; import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { useLauncherApps } from '../hooks/useLauncherApps.js'; +import { useOpenedOnce } from '../hooks/useOpenedOnce.js'; import { recordFormFieldNames } from '../utils/recordFormFields.js'; import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveRecordFormChrome, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js'; import { deriveRecordSurface, deriveRecordFlowSurface } from '@object-ui/plugin-view/core'; @@ -1056,6 +1057,10 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = isDialogOpen && !!formObjectDef && routeReadsSettled && routeSlotShown, recordDrawersOpening, ); + // objectstack#37444: the record form mounts the first time it opens, not with + // every object page. Closed, it drew nothing, yet its lazy chunk (the whole of + // `@object-ui/plugin-form`) was fetched before a list's first screen. + const recordFormMounted = useOpenedOnce(recordFormShown); // objectstack#27138 — the record the overlay edits may be held by a pending // approval that locks it. The record's field projection leaves that lock out @@ -1763,7 +1768,7 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = - {formObjectDef && ( + {formObjectDef && recordFormMounted && ( // objectstack#35403 — an edit draws the record's owner read-only, // with Change Owner beside it where the caller may transfer it. diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx new file mode 100644 index 00000000000..d936414365f --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.recordFormMountsOnOpen-37444.test.tsx @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — an object page mounts the record-form modal the first + * time it opens, so a list's first screen loads no form code. + * + * `AppContent` drew a closed `LazyModalForm` on every object page (the route's + * object is always the form's default object), and a lazy component that is + * drawn loads its chunk even closed: the whole of `@object-ui/plugin-form` was + * fetched before every list's first screen. The bundle half is measured on the + * built console and recorded on the PR; this file pins that the form module is + * not evaluated until the form opens, and that it opens as before. + * + * The instrument: a counted `vi.mock` factory, which runs the first time the + * module is imported. The module registry is per FILE, so the case that needs + * it unloaded runs first, and the later case asserts the count it starts from. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach, afterAll } from 'vitest'; +import React from 'react'; +import { render, cleanup, waitFor, screen } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { createI18n, I18nProvider } from '@object-ui/i18n'; +// The console layout's draft bar reaches a dynamic `@objectstack/lint` import; +// its first load is paid here, during collection, not inside a case's clock. +import '@objectstack/lint'; + +const { loads, modalOpen } = vi.hoisted(() => ({ loads: { form: 0 }, modalOpen: [] as boolean[] })); + +vi.mock('@object-ui/plugin-form', async (importOriginal) => { + loads.form += 1; + return { + ...(await importOriginal>()), + ModalForm: ({ schema }: { schema: { open?: boolean; objectName?: string } }) => { + modalOpen.push(!!schema.open); + return
; + }, + ObjectForm: () => null, + }; +}); + +vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ + ...(await importOriginal()), + CreateAppPage: () =>
, + EditAppPage: () =>
, + DashboardDesignPage: () =>
, +})); + +vi.mock('../../layout/ConsoleLayout', () => ({ + ConsoleLayout: ({ children }: { children?: React.ReactNode }) => ( +
{children}
+ ), +})); +vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null })); +vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null })); +vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null })); +vi.mock('../../views/ObjectView', () => ({ ObjectView: () =>
})); +vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () =>
})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ + user: { id: 'u1', name: 'Ada', email: 'ada@example.com', role: 'user' }, + getAuthConfig: async () => ({ features: {} }), + activeOrganization: null, + }), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +const dataSourceStub = { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', +}; +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => dataSourceStub, +})); + +const METADATA = { + apps: [{ name: 'crm', label: 'CRM', isDefault: true, navigation: [] }], + objects: [{ name: 'showcase_task', label: 'Task', fields: { subject: { type: 'text', label: 'Subject' } } }], + loading: false, + ensureType: undefined, + error: null, + refresh: async () => {}, +}; +vi.mock('../../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => METADATA, +})); + +const ACTION_RUNNER = { execute: vi.fn(), runner: { registerHandler: () => {}, getContext: () => ({}) } }; +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useActionRunner: () => ACTION_RUNNER, + useGlobalUndo: () => {}, + useMutationInvalidationBridge: () => {}, +})); + +// An edit dialog reads the approvals of the record it edits; none runs here. +vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, +}))); +afterAll(() => vi.unstubAllGlobals()); + +import { AppContent } from '../AppContent'; + +function mountAt(url: string) { + const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + render( + + + + } /> + + + , + ); +} + +afterEach(() => cleanup()); + +describe('objectstack#37444 — an object page mounts the record form when it opens', () => { + it('a list with no form open loads no form module and draws no modal', async () => { + expect(loads.form).toBe(0); + mountAt('/apps/crm/showcase_task'); + await screen.findByTestId('console-layout'); + // Long enough for a drawn lazy modal to have asked for its chunk and drawn. + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(screen.queryByTestId('modal-form')).toBeNull(); + expect(loads.form).toBe(0); + }); + + it('opening the create form loads it and draws it open', async () => { + expect(loads.form).toBe(0); + mountAt('/apps/crm/showcase_task?form=new'); + const modal = await screen.findByTestId('modal-form'); + expect(modal).toHaveAttribute('data-object', 'showcase_task'); + await waitFor(() => expect(modal).toHaveAttribute('data-open', 'true')); + expect(loads.form).toBe(1); + // It is never drawn closed first: the opening render is the first one. + expect(modalOpen[0]).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useOpenedOnce.ts b/ui/packages/app-shell/src/hooks/useOpenedOnce.ts new file mode 100644 index 00000000000..04f9e2007c5 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/useOpenedOnce.ts @@ -0,0 +1,19 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { useState } from 'react'; + +/** + * objectstack#37444 — `true` from the first render `open` is, and from then on. + * A lazy panel or dialog behind it loads only when someone opens it (closed, it + * draws nothing, so mounting it with every page only fetched its chunk before + * the page's first screen), and stays mounted after, so closing it animates and + * keeps its state as before. The state is adjusted during render, React's way of + * deriving state from a prop, so the opening render already mounts it. + * + * Package-internal: not exported from `./index.ts` or the package entry. + */ +export function useOpenedOnce(open: boolean): boolean { + const [opened, setOpened] = useState(open); + if (open && !opened) setOpened(true); + return opened || open; +} diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 35cd99e333b..b8c2f1f58e5 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -59,19 +59,7 @@ const CreateViewDialog = lazy(() => import('./CreateViewDialog.js').then((m) => ({ default: m.CreateViewDialog })), ); -/** - * objectstack#37444 — `true` from the first render `open` is, and from then on. - * A lazy panel or dialog behind it loads only when someone opens it (closed, it - * draws nothing, so mounting it with every list only fetched its chunk before - * the list's first screen), and stays mounted after, so closing it animates and - * keeps its state as before. The state is adjusted during render, React's way of - * deriving state from a prop, so the opening render already mounts it. - */ -function useOpenedOnce(open: boolean): boolean { - const [opened, setOpened] = useState(open); - if (open && !opened) setOpened(true); - return opened || open; -} +import { useOpenedOnce } from '../hooks/useOpenedOnce.js'; import { usePreviewDrafts, } from '../preview/PreviewModeContext.js'; diff --git a/ui/packages/plugin-view/src/ObjectView.tsx b/ui/packages/plugin-view/src/ObjectView.tsx index 8a4dc718ea3..1cad8b89daa 100644 --- a/ui/packages/plugin-view/src/ObjectView.tsx +++ b/ui/packages/plugin-view/src/ObjectView.tsx @@ -36,7 +36,6 @@ import type { TreeViewConfig, } from '@object-ui/types'; import { ObjectGrid } from '@object-ui/plugin-grid'; -import { ObjectForm } from '@object-ui/plugin-form'; import { cn, Dialog, @@ -99,6 +98,17 @@ import { usePermissions } from '@object-ui/permissions'; import { ViewSwitcher } from './ViewSwitcher'; import { useStableIdentity, isStructurallyEqual } from './stableIdentity'; +/** + * The create / edit form, loaded the first time one opens (objectstack#37444). + * + * A static import put the whole of `@object-ui/plugin-form` on every list's + * first screen, though the form is drawn only inside the drawer or modal below, + * whose content mounts when it opens. Its chunk now loads on that first open. + */ +const ObjectForm = React.lazy(() => + import('@object-ui/plugin-form').then((m) => ({ default: m.ObjectForm })), +); + /** * SchemaRenderer from @object-ui/react, used to render sub-view schemas. */ @@ -2934,7 +2944,9 @@ export const ObjectView: React.FC = ({ const renderDrawerForm = () => { const form = (
- + + +
); if (isMobile) { @@ -2981,7 +2993,9 @@ export const ObjectView: React.FC = ({ {formDescriptionText} )} - + + + ); diff --git a/ui/packages/plugin-view/src/__tests__/ObjectView.formLoadsOnOpen-37444.test.tsx b/ui/packages/plugin-view/src/__tests__/ObjectView.formLoadsOnOpen-37444.test.tsx new file mode 100644 index 00000000000..a984aa614c5 --- /dev/null +++ b/ui/packages/plugin-view/src/__tests__/ObjectView.formLoadsOnOpen-37444.test.tsx @@ -0,0 +1,76 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37444 — an object view loads `@object-ui/plugin-form` the first + * time its create / edit form opens, not with the list. + * + * `ObjectView` imported `ObjectForm` statically, so every list's first screen + * fetched the whole form package, though the form is drawn only inside the + * drawer or modal that mounts its content when it opens. The bundle half (which + * chunks a list load fetches) is measured on the built console and recorded on + * the PR. What a unit test can pin is that the form module is not evaluated + * until a form opens. + * + * The instrument: `vi.mock(path, factory)` runs `factory` the first time the + * module is imported, and not before. A STATIC import of the form package in + * `ObjectView`'s graph runs it while this file imports `ObjectView`, before any + * case starts, and the first case reds. The module registry is per FILE, so the + * case that needs it unloaded runs first, and the later case asserts the count + * it starts from. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, waitFor, act, fireEvent } from '@testing-library/react'; +import type { DataSource, ObjectViewSchema } from '@object-ui/types'; + +const loads = vi.hoisted(() => ({ form: 0 })); + +vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({ + ...(await importOriginal>()), + ObjectGrid: () =>
, +})); +vi.mock('@object-ui/plugin-form', async (importOriginal) => { + loads.form += 1; + return { + ...(await importOriginal>()), + ObjectForm: ({ schema }: { schema: { mode?: string } }) =>
, + }; +}); + +import { ObjectView } from '../ObjectView'; + +function makeDataSource() { + const state = { settled: false }; + const ds = { + find: vi.fn().mockResolvedValue({ data: [], total: 0 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => { + state.settled = true; + return { name: 'task', label: 'Tasks', fields: { name: { type: 'text' } } }; + }), + }; + return { ds: ds as unknown as DataSource, state }; +} + +describe('objectstack#37444 — the object view loads the form package when a form opens', () => { + it('importing and drawing the list evaluates no form module', async () => { + expect(loads.form).toBe(0); + const { ds, state } = makeDataSource(); + const schema = { type: 'object-view', objectName: 'task', layout: 'drawer' } as unknown as ObjectViewSchema; + render(); + await screen.findByTestId('object-grid'); + await waitFor(() => expect(state.settled, 'the object schema was never read').toBe(true)); + await act(async () => {}); + expect(screen.queryByTestId('object-form')).toBeNull(); + expect(loads.form).toBe(0); + + // Opening the create form loads it, and the form is drawn for that verb. + fireEvent.click(screen.getByRole('button', { name: 'New' })); + const form = await screen.findByTestId('object-form'); + expect(form.getAttribute('data-mode')).toBe('create'); + expect(loads.form).toBe(1); + }); +}); diff --git a/ui/packages/plugin-view/src/__tests__/ObjectView.namedViewInlineEdit-10885.test.tsx b/ui/packages/plugin-view/src/__tests__/ObjectView.namedViewInlineEdit-10885.test.tsx index c062b72f89c..54c8588484d 100644 --- a/ui/packages/plugin-view/src/__tests__/ObjectView.namedViewInlineEdit-10885.test.tsx +++ b/ui/packages/plugin-view/src/__tests__/ObjectView.namedViewInlineEdit-10885.test.tsx @@ -108,9 +108,12 @@ async function clickCell(named: Record, userActions?: Record setTimeout(r, 50)); + // objectstack#37444: the record form loads on its first opening, so its + // presence is waited for rather than read on this tick. + const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false); return { editor: document.querySelector('td[data-editing-cell] input') != null, - recordForm: screen.queryByTestId('object-form') != null, + recordForm, }; } diff --git a/ui/packages/plugin-view/src/__tests__/ObjectView.tableEditable-10976.test.tsx b/ui/packages/plugin-view/src/__tests__/ObjectView.tableEditable-10976.test.tsx index 245bc3f741b..e4635073497 100644 --- a/ui/packages/plugin-view/src/__tests__/ObjectView.tableEditable-10976.test.tsx +++ b/ui/packages/plugin-view/src/__tests__/ObjectView.tableEditable-10976.test.tsx @@ -100,9 +100,12 @@ async function clickCell(table: NonNullable, userActi // One tick lets React flush the editor, so `false` means "never opened", // not "not opened yet". await new Promise((r) => setTimeout(r, 50)); + // objectstack#37444: the record form loads on its first opening, so its + // presence is waited for rather than read on this tick. + const recordForm = await screen.findByTestId('object-form', {}, { timeout: 500 }).then(() => true, () => false); return { editor: document.querySelector('td[data-editing-cell] input') != null, - recordForm: screen.queryByTestId('object-form') != null, + recordForm, }; } diff --git a/ui/packages/plugin-view/src/__tests__/ObjectView.test.tsx b/ui/packages/plugin-view/src/__tests__/ObjectView.test.tsx index e778ef9ff4f..d220758a240 100644 --- a/ui/packages/plugin-view/src/__tests__/ObjectView.test.tsx +++ b/ui/packages/plugin-view/src/__tests__/ObjectView.test.tsx @@ -306,7 +306,7 @@ describe('ObjectView', () => { expect(onNavigate).toHaveBeenCalledWith('1', 'view'); }); - it('a navigation block without `mode` takes the spec\'s `drawer` default: a row click opens the record form in the drawer (objectstack#26677)', () => { + it('a navigation block without `mode` takes the spec\'s `drawer` default: a row click opens the record form in the drawer (objectstack#26677)', async () => { // Until objectstack#26677 a mode-less block fell through to the default // row behaviour; it now takes the spec's `drawer` default, like // `{ mode: 'drawer' }`. `split` and `popover`, which this suite also @@ -323,7 +323,8 @@ describe('ObjectView', () => { fireEvent.click(screen.getByTestId('grid-row')); - expect(screen.getByTestId('object-form')).toBeDefined(); + // objectstack#37444: the form loads on its first opening. + expect(await screen.findByTestId('object-form')).toBeDefined(); expect(screen.getByRole('dialog')).toBeDefined(); expect(onNavigate).not.toHaveBeenCalled(); }); From 6c5a31769833f01439c38f86e438ce5aedd8dfd0 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:07 +0000 Subject: [PATCH 044/178] fix(rest): a /data write or query refusal carrying a userMessage says it varies by Accept-Language (#38491) 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_01TenzsRopZj4jMbvjX8uz1X68WP728cZY7vcYa437QZ2u)_ Fixes #38316 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:多语言部署里,数据接口的新建、修改、删除和查询被业务规则拒绝时,回应现在会注明"内容随语言不同",状态码、错误码和提示文字都不变。 - 为什么做:读取接口和运行时的另一条路早已这样做,只有这几条写入路径漏了;漏掉时,前面若有共享缓存,可能把一种语言的拒绝提示给到用另一种语言的人。 - 出错会怎样:只多一个响应头,不改任何拒绝本身;若有问题可直接撤回本次改动。 - 要你做什么:无。 ## What changes - `packages/rest/src/crud-routes.ts`: every `/data` catch now answers through one exit, `sendRefusal` (renamed from `sendReadRefusal`). Before this PR only the two `GET` catches used it; the create (`POST /data/:object`), update (`PATCH /data/:object/:id`), delete (`DELETE /data/:object/:id`) and query (`POST /data/:object/query`) catches sent `mapped.body` with no `Vary`. The exit adds `Vary: Accept-Language` when the body carries a `userMessage` (`answerVariesByLanguage`, `@objectstack/types`), in the multi-value form the hosts append. Status, code and body are untouched. - The query catch is not named by the card; it is the same file, the same defect and the same one-line fix, declared in the claim's file surface (comment 7251018246). - `packages/types/src/localized-answer-vary.ts`: the "who asks" note named only the `/data` read routes' catch; it now names the `/data` CRUD and query routes' catch (`crud-routes.ts`). Comment only, but it ships in the `.d.ts`, so the changeset carries `@objectstack/types: patch` too. - New test `packages/rest/src/data-write-refusal-vary-38316.test.ts`; changeset `.changeset/38316-rest-write-refusal-vary.md` (`@objectstack/rest` patch). Read first: the four `sendRefusal(res, mapped)` lines in `crud-routes.ts` (create ~:337, query ~:410, update ~:525, delete ~:587), then the test. ## Tests - New file, 8 cases on the real routes and the real mapper: for each of create, update, delete and query, a refusal thrown with a declared status, code and `userMessage` answers `409 RESOURCE_CONFLICT` with that `userMessage` and exactly one `Vary` header whose value is the multi-value list holding `Accept-Language`; a CONTROL with no `userMessage` gets no `Vary`. Each case also checks the refusal came from the protocol call, not from a gate in front of it. - Ablation: with `crud-routes.ts` restored to the base (`d89d3e23`) and the test unchanged, the 4 positive cases fail and the 4 controls pass; with the fix, 8/8 pass. ## Acceptance notes - Five other catches in `@objectstack/rest` still send a `mapDataError` body with no `Vary`: `data-action-routes.ts` (field-access), `record-page-routes.ts` (record page), `search-routes.ts`, `form-routes.ts` (public form submit) and the API-key credential refusal in `rest-server.ts`. Same defect class, not touched here; carried by #38507 (filed by the area, each site measured before it changes). ## Verification Two-minute check: `pnpm --filter @objectstack/rest exec vitest run src/data-write-refusal-vary-38316.test.ts` shows 8 passed.
Local runs (heads 335445f1, ff070628 and 7c35f3ec) - `pnpm --filter '@objectstack/rest^...' build`: VERDICT command-exit 0. - `pnpm --filter @objectstack/rest test`: Test Files 438 passed (438); Tests 9025 passed, 351 skipped. - `pnpm --filter @objectstack/rest typecheck` and `pnpm --filter @objectstack/types typecheck`: exit 0. - New test plus the read twin (`data-record-read-malformed-query-door.test.ts`): 2 files, 25 tests passed. - Ablation: 4 failed, 4 passed (8) on the base `crud-routes.ts`. - ff070628 adds only a module-top `import '@objectstack/objectql'` to the new test (`check:test-source-alias` asked for it); on ff070628 the new test is 8/8 and `pnpm check:test-source-alias` exits 0. - 7c35f3ec (L1-b round 1, comment 7251789446) narrows the `types` note and adds `@objectstack/types: patch` to the changeset; on it `pnpm --filter @objectstack/types typecheck`, `pnpm check:doc-authoring`, `check-empty-changeset`, `check-changeset-no-major` and `check-drift-comment` exit 0. `pnpm check:query-options-erasure` and `pnpm check:type-check-debt` exit 0 uncapped on ff070628. - Derived gate families (`dispatch-gates.mjs --commands`, 66, all run, reconciled with `--ran`): 61 exit 0. NOT MEASURED locally, CI runs them: `node scripts/check-plugin-teardown-shape.mjs --self-test` (exit 3, shallow clone) and `pnpm check:dual-build-cjs-loads` (exit 3, needs a full `pnpm build`). `pnpm check:query-options-erasure` and `pnpm check:type-check-debt` hit the local 300 s cap (exit 124) and are re-running without it. `pnpm check:test-source-alias`: exit 1 on 335445f1, exit 0 on ff070628.
--- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5npfcRkNnuKynM3tpb)_ --------- Co-authored-by: Claude --- .changeset/38316-rest-write-refusal-vary.md | 9 ++ packages/rest/src/crud-routes.ts | 21 ++-- .../src/data-write-refusal-vary-38316.test.ts | 103 ++++++++++++++++++ packages/types/src/localized-answer-vary.ts | 2 +- 4 files changed, 126 insertions(+), 9 deletions(-) create mode 100644 .changeset/38316-rest-write-refusal-vary.md create mode 100644 packages/rest/src/data-write-refusal-vary-38316.test.ts diff --git a/.changeset/38316-rest-write-refusal-vary.md b/.changeset/38316-rest-write-refusal-vary.md new file mode 100644 index 00000000000..1325f85077d --- /dev/null +++ b/.changeset/38316-rest-write-refusal-vary.md @@ -0,0 +1,9 @@ +--- +"@objectstack/rest": patch +"@objectstack/types": patch +--- + +Clause-②: no +Metadata-protocol: none + +A `/data` create, update, delete or query refusal that carries a `userMessage` now sends `Vary: Accept-Language`, as the `/data` reads and the runtime dispatcher already did. A shared cache in front of those routes can no longer hand one caller's refusal sentence, in its language, to a caller asking in another. Status, code and body are unchanged. In `@objectstack/types`, the `answerVariesByLanguage` module note now names the `/data` CRUD and query routes as asking it (comment only). diff --git a/packages/rest/src/crud-routes.ts b/packages/rest/src/crud-routes.ts index fdda827e18e..2d2a135bc73 100644 --- a/packages/rest/src/crud-routes.ts +++ b/packages/rest/src/crud-routes.ts @@ -100,14 +100,19 @@ export interface CrudRouteHost { } /** - * [#37828] Answer a `/data` READ route's mapped refusal, saying it varies by + * [#37828] Answer a `/data` route's mapped refusal, saying it varies by * `Accept-Language` when its body carries a `userMessage` (the by-id read's * `404 RECORD_NOT_FOUND` is the one a cache stores by default). The token goes * on in the contract's multi-value form, which the hosts APPEND, so a `Vary` * another layer adds keeps its tokens. The rule and its reasons are * `answerVariesByLanguage`'s (`@objectstack/types`). + * + * [#38316] Every `/data` catch here answers through this one exit — the two + * reads, the query, and the create, update and delete — so a hook refusal + * with its own `userMessage` on a write says it varies as the read does, and + * as the runtime dispatcher's answer to the same refusal does. */ -function sendReadRefusal(res: any, mapped: { status: number; body: unknown }): void { +function sendRefusal(res: any, mapped: { status: number; body: unknown }): void { if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); res.status(mapped.status).json(mapped.body); } @@ -180,7 +185,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo } catch (error: any) { const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - sendReadRefusal(res, mapped); + sendRefusal(res, mapped); } }, metadata: { @@ -252,7 +257,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo // for any id (`data-record-read-malformed-query-door.test.ts`). const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - sendReadRefusal(res, mapped); + sendRefusal(res, mapped); } }, metadata: { @@ -329,7 +334,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo // in the caller's locale; this door relabels nothing. const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - res.status(mapped.status).json(mapped.body); + sendRefusal(res, mapped); } }, metadata: { @@ -402,7 +407,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo } catch (error: any) { const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - res.status(mapped.status).json(mapped.body); + sendRefusal(res, mapped); } }, metadata: { @@ -517,7 +522,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo // [#24768] As on the create: the engine named the field. const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - res.status(mapped.status).json(mapped.body); + sendRefusal(res, mapped); } }, metadata: { @@ -579,7 +584,7 @@ export function registerCrudEndpoints(this: CrudRouteHost, basePath: string): vo } const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); - res.status(mapped.status).json(mapped.body); + sendRefusal(res, mapped); } }, metadata: { diff --git a/packages/rest/src/data-write-refusal-vary-38316.test.ts b/packages/rest/src/data-write-refusal-vary-38316.test.ts new file mode 100644 index 00000000000..42f192d4031 --- /dev/null +++ b/packages/rest/src/data-write-refusal-vary-38316.test.ts @@ -0,0 +1,103 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38316] A `/data` write refusal that carries a `userMessage` says it varies + * by `Accept-Language`, as the `/data` reads already did (#37828) and as the + * runtime dispatcher's answer to the same refusal does. + * + * Read on the base (`d89d3e23`): the create, update and delete catches in + * `crud-routes.ts`, and the `POST /data/:object/query` catch beside them, sent + * the mapped body with no `Vary`; only the two `GET` catches added it. A shared + * cache in front of those routes could then hand one caller's sentence, in its + * language, to a caller asking in another. + * + * The door is the real route and the real mapper. The protocol is the one line + * that matters: the write throws what a hook refusal with its own `userMessage` + * throws (a declared status and code, and the sentence on `userMessage`, which + * `declaredUserMessage` in `@objectstack/types` carries onto the body), so each + * case reads the route's exit and nothing else. The rule is + * `answerVariesByLanguage`'s, also in `@objectstack/types`. + */ + +import { describe, it, expect } from 'vitest'; +import { LOCALIZED_ANSWER_VARY } from '@objectstack/types'; +import { RestServer } from './rest-server'; +// Paid at collection, not inside a case's window: `rest-server.ts` reaches it +// through a dynamic import (`pnpm check:test-source-alias`). +import '@objectstack/objectql'; + +const OBJECT = 'booking_38316'; +const ID = 'r_38316'; +const CTX = { userId: 'usr_38316_member', positions: [], permissions: [], posture: 'MEMBER', locale: 'fr-FR' }; +const SENTENCE = 'Ce créneau est déjà réservé.'; + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeHeaderRes() { + const res: any = { + _headers: [] as Array<[string, string | string[]]>, + write: () => true, end: () => {}, + header: (name: string, value: string | string[]) => { res._headers.push([name, value]); return res; }, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +const varyHeaders = (res: any) => res._headers.filter(([name]: [string]) => name.toLowerCase() === 'vary'); + +/** What a hook refusal declaring its own sentence throws. */ +const refusalWithSentence = () => + Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT', userMessage: SENTENCE }); +/** The same refusal with no sentence for the end user. */ +const refusalWithoutSentence = () => + Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT' }); + +/** route label · method · path · the protocol call it makes · the request. */ +const ROUTES = [ + ['create', 'POST', '/api/v1/data/:object', 'createData', { params: { object: OBJECT }, query: {}, headers: {}, body: { title: 'x' } }], + ['update', 'PATCH', '/api/v1/data/:object/:id', 'updateData', { params: { object: OBJECT, id: ID }, query: {}, headers: {}, body: { title: 'y' } }], + ['delete', 'DELETE', '/api/v1/data/:object/:id', 'deleteData', { params: { object: OBJECT, id: ID }, query: {}, headers: {} }], + ['query', 'POST', '/api/v1/data/:object/query', 'findData', { params: { object: OBJECT }, query: {}, headers: {}, body: {} }], +] as const; + +async function answer(method: string, path: string, call: string, req: unknown, thrown: () => Error) { + const calls: string[] = []; + const protocol = { [call]: async () => { calls.push(call); throw thrown(); } }; + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => CTX; + (rest as any).enforceApiAccess = async () => false; + rest.registerRoutes(); + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path); + expect(route, `${method} ${path}`).toBeDefined(); + const res = makeHeaderRes(); + await route!.handler(req as any, res); + // The refusal came from the protocol call, not from a gate in front of it. + expect(calls).toEqual([call]); + return res; +} + +describe('[#38316] /data write and query refusals say they vary by Accept-Language', () => { + it.each(ROUTES)( + '%s: the refusal keeps its status, code and userMessage, and Vary names Accept-Language in the append form', + async (_label, method, path, call, req) => { + const res = await answer(method, path, call, req, refusalWithSentence); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.code).toBe('RESOURCE_CONFLICT'); + expect(res._json.userMessage).toBe(SENTENCE); + // The multi-value form the hosts append, never a set that would drop CORS's `Origin`. + expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]); + }, + ); + + it.each(ROUTES)('CONTROL %s: a refusal with no userMessage gets no Vary from this door', async (_label, method, path, call, req) => { + const res = await answer(method, path, call, req, refusalWithoutSentence); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.code).toBe('RESOURCE_CONFLICT'); + expect(res._json.userMessage).toBeUndefined(); + expect(varyHeaders(res)).toEqual([]); + }); +}); diff --git a/packages/types/src/localized-answer-vary.ts b/packages/types/src/localized-answer-vary.ts index 25e70273a9b..9448613b626 100644 --- a/packages/types/src/localized-answer-vary.ts +++ b/packages/types/src/localized-answer-vary.ts @@ -34,7 +34,7 @@ * userMessage } }`, the Hono catch-all and the dispatcher's exit) are asked one * question: * - * - `@objectstack/rest`: the `/data` read routes' catch (`crud-routes.ts`); + * - `@objectstack/rest`: the `/data` CRUD and query routes' catch (`crud-routes.ts`); * - `@objectstack/hono`: `thrownJson`, both of `createHonoApp`'s catch arms; * - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`. * From ec087c2e347f6991b458b913cc78be02d9bbe139 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:12 +0000 Subject: [PATCH 045/178] fix(kanban): a list view board laned by a text field draws its Uncategorized lane past the first page and loads the rest of a lane's cards (#38500) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit repo:objectstack#5 · os-project-manager · session_01FEkQ5pH8MaBBP5T2dVcTHL Fixes #38120 Clause-②: no Metadata-protocol: none ## 维护者速读 - 列表视图里按文本字段分道的看板,空值记录全在第一页之后时,以前没有「未分类」这一道;现在这一道画在最后,带整道计数和「未加载的卡片」提示,各道(含未分类)都能点「加载更多」补齐卡片。按选项分道的看板本来就逐道分页,行为不变。 - 接在「看板按查找字段分道时补画未分类道、逐道加载更多」那两轮之后,替用文本字段分组看板的用户找回这部分记录的入口。 - 只多画一道、多给一个按钮,不改任何数据和配置;数据源不支持分组读、或分组读被拒绝或截断时,照旧只画第一页,可以直接撤回。 - 无。文本字段里某个值的记录全在第一页之后时为它补画一道,已另立 #38506。 ## What changes - `ui/packages/plugin-kanban/src/ObjectKanban.tsx`: the past-page gate (`pastPageLanes`, which drives `keepUncolumned` and the host lane paging `hostLanePagingOn`) now opens over a text lane field (`laneIsText`) as well as over a lookup (`laneTargetObject`). The rest of the gate is unchanged: a host-handed page with a lane read (`hostLaneRead`), flat lanes, lanes from the data, and the null-count rule — a partial (`hasMore`), refused or absent grouped read answers no counts, so nothing is drawn or offered from it. - On a text lane the "Uncategorized" lane's "Load more" reads records whose value is null OR blank (`''`), because the page buckets both into that lane and the lane read counts both under it; a lookup lane keeps `emptyLaneQueryFilter` (null only). - `extraLaneIds` (a lane whose records all sit past the page) is NOT widened: a text value past the page still draws no lane of its own. That is a visible-behaviour choice outside the card's asks; the seat ruled it and filed #38506 for it. - Option lanes: no code change. Measured: under a list view, a board laned by a field with options takes the per-lane paging path (`kanbanLanesPaged` in `ListView.tsx`, objectui#12619), which queries the "Uncategorized" lane on its own (`uncolumnedQueryFilter`: not in the lanes, or null). It already draws that lane with its cards and count when every such record sits past the list's first page. The host-handed path only carries option lanes on a swimlane board, which the flat-lane gate excludes. A pin for this is added (below). - `patch` changeset for `@object-ui/plugin-kanban`. Read first (by risk): `pastPageLanes` / `laneIsText` in `ObjectKanban.tsx`; the `emptyIsBlank` filter branch in `loadMoreHostLane`; the new `objectstack#38120` pins in `listKanbanEveryRecord-12619.test.tsx`. ## Tests All in `ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx` (the shared ListView + ObjectKanban rig the #37516 / #37517 pins live in; a new pin for a component with a shared harness goes into that file, ruling record 6583487846): - text lane (`tier`; deals 60–64 null, 65–69 blank, all past page one of 25): "Uncategorized" drawn last, badge `10`, zero cards, `Cards not loaded: 10`; - its "Load more" loads all 10 (null and blank), filter `["or",["tier","is_null"],["tier","=",""]]`, `$skip: 0`, `$top: 50`, `$count: true`; - a text lane on the page (`gold`, 13 of 30) loads the other 17 from `$skip: 13`, none twice, filter `"tier","=","gold"`; - CONTROL ×3: no grouped door, a refused read, a cut read (`hasMore`) draw no "Uncategorized" and offer no "Load more" (`gold` reads `13+`); - option lane (`stage` select; 6 null-stage and 4 unknown-stage records past the list's first 25): "Uncategorized" drawn with its 10 cards, badge `10`; rig self-check that the list's 25-row window holds none of them. This pins existing behaviour (premise reading); it passes before and after this change, so it carries no ablation. - Replaced: `CONTROL: a board laned by a text field offers no "Load more"`, which pinned exactly the branch this PR changes. Kept: `a board laned by a text field counts each whole lane but draws no lane past the page`.
Readings (head 311312f6, base origin/main 7e1b2229) - Rig file: `Test Files 1 passed (1)`, `Tests 44 passed (44)`. - `pnpm --filter @object-ui/plugin-kanban type-check` exit 0; `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-kanban/`: `Test Files 91 passed (91)`, `Tests 623 passed (623)`. - `pnpm --filter @object-ui/app-shell type-check` exit 0 (its `tsconfig.test.json` includes `src/**/*.test.tsx`). - Ablation 1 through `scripts/ablation-replace.mjs`: `(!!laneTargetObject || laneIsText)` to `(!!laneTargetObject /* ABLATED */)`: `Tests 3 failed | 41 passed (44)` — the three text-lane pins (Uncategorized drawn, its load, the `gold` load); every control green. Restored: blob == HEAD, `git diff HEAD` empty. - Ablation 2: `: held.emptyIsBlank` to `: false /* ABLATED */`: `Tests 1 failed | 43 passed (44)` — the Uncategorized load pin (the blank records are not read). Restored: blob == HEAD. - (The first ablation 1 attempt was refused by the tool before running: the replacement text already sat inside the anchor, so its count could not rise; re-run with a distinct replacement.) - Derived local gates (`dispatch-gates.mjs --ran`): 38 derived, 38 run, 0 NOT-MEASURED. 37 exit 0; `pnpm --dir ui exec vitest run scripts/` was SIGKILLed by the shared box's memory limit (exit 1, no test verdict), re-run as `pnpm --dir ui exec vitest run --maxWorkers=2 scripts/`: `Test Files 172 passed | 2 skipped (174)`, exit 0. `pnpm check:new-line-citations`: 0 new citations.
## Acceptance notes - Acceptance "a text-field kanban and an option kanban both show Uncategorized with its count" holds: the text half by this change, the option half by the per-lane paging path already on main (pinned here). - Not drawn by this PR: a text value whose records all sit past page one (in the rig, `bronze`). Filed #38506. - No browser walk: NOT MEASURED in a running app. The rig mounts the real `ListView` over the real `ObjectKanban` with a `ValueDataSource` that evaluates `$filter` / `$skip` / `$top` and a grouped-aggregate door. - No docs page describes the lookup-lane past-page behaviour this extends, so no docs change. ## Verification Two minutes: `pnpm --dir ui exec vitest run packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx -t "text-laned"` — expect 5 passed (the Uncategorized draw, its load, and the three controls), 0 failed. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pH8MaBBP5T2dVcTHL)_ Co-authored-by: Claude --- .../38120-kanban-text-lane-past-page.md | 10 ++ .../listKanbanEveryRecord-12619.test.tsx | 111 +++++++++++++++++- .../plugin-kanban/src/ObjectKanban.tsx | 28 ++++- 3 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 .changeset/38120-kanban-text-lane-past-page.md diff --git a/.changeset/38120-kanban-text-lane-past-page.md b/.changeset/38120-kanban-text-lane-past-page.md new file mode 100644 index 00000000000..dece093780f --- /dev/null +++ b/.changeset/38120-kanban-text-lane-past-page.md @@ -0,0 +1,10 @@ +--- +'@object-ui/plugin-kanban': patch +--- + +fix(kanban): a list view board laned by a text field draws its "Uncategorized" lane when every record with no value sits past the first page, and loads the rest of a lane's cards with "Load more" + +Clause-②: no +Metadata-protocol: none + +A list view hands its kanban one page of the view's query, and on a board laned by a text field the grouped lane read already counts each whole lane. The trailing "Uncategorized" lane was drawn only by the cards it held, so when every record with no value, or an empty one, sat past the first page those records had no lane on the board; and a lane that counted 30 records while drawing the page's 13 offered no way to load the rest. Both now behave as on a board laned by a lookup: "Uncategorized" is drawn last from the read's count with the "Cards not loaded" line, and a lane that draws fewer cards than it counts offers "Load more", reading its next records under the view's filter, order and search ("Uncategorized" reads the records whose value is empty or blank). A source with no grouped door, or a read that is refused or cut, draws the page's cards as before. A text value whose records all sit past the page still draws no lane of its own. Boards laned by a field's options already page each lane under a list view and are unchanged. Nothing to migrate. diff --git a/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx b/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx index 94d1c3806e6..270c76df144 100644 --- a/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx +++ b/ui/packages/app-shell/src/__tests__/listKanbanEveryRecord-12619.test.tsx @@ -89,8 +89,8 @@ const ROWS: Row[] = STAGES.flatMap(([stage, , count]) => })), ); -function makeDataSource() { - const store = new ValueDataSource({ items: ROWS }); +function makeDataSource(rows: Row[] = ROWS) { + const store = new ValueDataSource({ items: rows }); return { find: vi.fn(async (object: string, params: any) => store.find(object, params)), findOne: vi.fn(), @@ -165,6 +165,37 @@ describe('a kanban under a list view draws every record of the view in its colum expect(within(card).queryByText('Probability')).not.toBeInTheDocument(); expect(within(card).queryByText('Close Date')).not.toBeInTheDocument(); }); + + /** + * objectstack#38120 — a board laned by the options of a select field draws + * its "Uncategorized" lane with its count when every record with no stage, or + * a stage no option names, sits past the list's first page: that lane is a + * query of its own on this board, as each option's lane is. + */ + it('records with no stage or an unknown one, all past the first page, draw "Uncategorized" with their 10 cards and count', async () => { + const strays: Row[] = Array.from({ length: 10 }, (_, i) => ({ + id: `stray-${i}`, + name: `stray deal ${i}`, + account: `Account stray ${i}`, + stage: i < 6 ? null : 'archived', + amount: 1, + probability: 40, + close_date: '2026-11-01', + })); + const ds = makeDataSource([...ROWS, ...strays]); + mountBoard(ds); + + await waitFor(() => expect(cards()).toHaveLength(55)); + expect(within(lane('Uncategorized')).getAllByRole('listitem')).toHaveLength(10); + expect((within(lane('Uncategorized')).getByRole('heading').parentElement!.querySelector('span')!.textContent ?? '').trim()).toBe('10'); + // RIG SELF-CHECK: the list's own window, its first 25 rows, holds none of them. + const at = ds.find.mock.calls.findIndex((call: any[]) => call[1]?.$top === 25); + expect(at).toBeGreaterThanOrEqual(0); + const answer = (await ds.find.mock.results[at].value) as any; + const page: Row[] = Array.isArray(answer) ? answer : answer.data ?? answer.records ?? []; + expect(page).toHaveLength(25); + expect(page.some((row) => String(row.id).startsWith('stray'))).toBe(false); + }); }); /** @@ -847,12 +878,80 @@ describe('a lookup-laned board under a list view counts and totals each whole la expect(laneReads(ds)).toHaveLength(0); }); - it('CONTROL: a board laned by a text field offers no "Load more"', async () => { - mountBoard(dealSource(), { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'tier' } }); - + /** + * objectstack#38120 — a board laned by a text field draws its "Uncategorized" + * lane from the lane read's count, and offers "Load more" on a lane that + * draws fewer cards than it counts, as a lookup-laned board does. Deals + * 60–64 have no tier and 65–69 an empty one, all past the first page. + */ + const TIER_VIEW = { ...BOARD_VIEW, kanban: { ...BOARD_VIEW.kanban, groupByField: 'tier' } }; + const NO_TIER_PAST_PAGE: Row[] = DEALS.map((d, i) => (i >= 65 ? { ...d, tier: '' } : i >= 60 ? { ...d, tier: null } : d)); + async function tierPageDrawn() { await waitFor(() => expect(cards()).toHaveLength(25)); - await waitFor(() => expect(laneBadge('gold')).toBe('30')); + expect(within(lane('gold')).getAllByRole('listitem')).toHaveLength(13); + expect(within(lane('silver')).getAllByRole('listitem')).toHaveLength(12); + } + + it('a text-laned board draws "Uncategorized" last, counting its 10 records with no tier, all past the page', async () => { + mountBoard(dealSource(true, NO_TIER_PAST_PAGE), TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(screen.getByRole('group', { name: 'Uncategorized' })).toBeInTheDocument()); + expect(laneBadge('Uncategorized')).toBe('10'); + expect(within(lane('Uncategorized')).queryAllByRole('listitem')).toHaveLength(0); + expect(within(lane('Uncategorized')).getByText('Cards not loaded: 10')).toBeInTheDocument(); + expect(laneNames().slice(-3)).toEqual(['gold', 'silver', 'Uncategorized']); + }); + + it('the text-laned "Uncategorized" lane loads its 10 records, those with no tier and those with an empty one', async () => { + const ds = dealSource(true, NO_TIER_PAST_PAGE); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(loadMore('Uncategorized')).not.toBeNull()); + fireEvent.click(loadMore('Uncategorized')!); + + await waitFor(() => expect(within(lane('Uncategorized')).getAllByRole('listitem')).toHaveLength(10)); + expect(loadMore('Uncategorized')).toBeNull(); + expect(laneBadge('Uncategorized')).toBe('10'); + const read = laneReads(ds)[0]; + expect(read).toMatchObject({ $skip: 0, $top: 50, $count: true }); + expect(JSON.stringify(read.$filter)).toContain('["or",["tier","is_null"],["tier","=",""]]'); + }); + + it('a text lane on the page with 13 of its 30 cards loads the other 17 from its 14th record', async () => { + const ds = dealSource(); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + await waitFor(() => expect(loadMore('gold')).not.toBeNull()); + expect(loadMore('silver')).not.toBeNull(); + fireEvent.click(loadMore('gold')!); + + await waitFor(() => expect(within(lane('gold')).getAllByRole('listitem')).toHaveLength(30)); + expect(new Set(cardNames('gold')).size).toBe(30); + expect(loadMore('gold')).toBeNull(); + expect(laneBadge('gold')).toBe('30'); + const reads = laneReads(ds); + expect(reads).toHaveLength(1); + expect(reads[0]).toMatchObject({ $skip: 13, $top: 50 }); + expect(JSON.stringify(reads[0].$filter)).toContain('"tier","=","gold"'); + }); + + it.each([ + ['has no grouped door', false], + ['refuses the read', 'refuse'], + ['cuts the read (hasMore)', 'cut'], + ] as const)('CONTROL: when the source %s, a text-laned board draws no "Uncategorized" lane and offers no "Load more"', async (_, door) => { + const ds = dealSource(door, NO_TIER_PAST_PAGE); + mountBoard(ds, TIER_VIEW); + + await tierPageDrawn(); + if (door !== false) await waitFor(() => expect(ds.queryGroupHeaders).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(laneBadge('gold')).toBe('13+')); + expect(screen.queryByRole('group', { name: 'Uncategorized' })).toBeNull(); expect(screen.queryAllByRole('button', { name: 'Load more' })).toHaveLength(0); + expect(laneReads(ds)).toHaveLength(0); }); it('a board laned by a text field counts each whole lane but draws no lane past the page', async () => { diff --git a/ui/packages/plugin-kanban/src/ObjectKanban.tsx b/ui/packages/plugin-kanban/src/ObjectKanban.tsx index e6e309d4d32..2ccd34d1ebd 100644 --- a/ui/packages/plugin-kanban/src/ObjectKanban.tsx +++ b/ui/packages/plugin-kanban/src/ObjectKanban.tsx @@ -50,6 +50,7 @@ import { resolveNameField, resolveAffordance, isDeadlineSettled, + mergeFilterNodes, referencedRecordTitle, stateMachineNextValues, type SchemaLike, @@ -1980,8 +1981,9 @@ export const ObjectKanban: React.FC = ({ * record (one read of those records on the lane field's target object) and * by its key until then. The empty group is not one of them: it is the * trailing "Uncategorized" lane, drawn by the cards it holds and, over the - * same lane fields, by the read's count of it when none of those cards is - * on the page (`keepUncolumned` below, objectstack#37516). + * same lane fields and text ones, by the read's count of it when none of + * those cards is on the page (`keepUncolumned` below, objectstack#37516, + * objectstack#38120). * * Only over a lane field that names the object it references * (`laneTargetObject`): a reference's group key is its foreign key, the @@ -2005,8 +2007,16 @@ export const ObjectKanban: React.FC = ({ * draws the lane, so the board draws it from that count, under the gate the * lanes past the page take. A partial or refused read answers no counts * (`hostLaneCounts` null), and no lane is drawn from it. + * + * objectstack#38120 — the same over a text lane field (`laneIsText`), with + * "Load more" below: a text value is its own lane key, so `field = key` + * reads a lane's records as a find row spells them. A lane whose records all + * sit past the page is still not drawn there (`extraLaneIds`). A board laned + * by a field's options pages each lane itself under a list view + * (`lanePaging`), its "Uncategorized" lane included. */ - const pastPageLanes = hostLaneRead && flatLanes && lanesFromData && !!laneTargetObject; + const laneIsText = laneFieldDef?.type === 'text'; + const pastPageLanes = hostLaneRead && flatLanes && lanesFromData && (!!laneTargetObject || laneIsText); const keepUncolumned = pastPageLanes && (hostLaneCounts?.[KANBAN_UNCOLUMNED_ID] ?? 0) > 0; /** * objectstack#37517 — "Load more" on a lane of the board handed one page: @@ -2044,6 +2054,7 @@ export const ObjectKanban: React.FC = ({ pages: Record | null; objectName: string; groupBy: string; + emptyIsBlank: boolean; filter: unknown; params: Record; } | null>(null); @@ -2061,6 +2072,7 @@ export const ObjectKanban: React.FC = ({ pages: hostLanePages, objectName: schema.objectName, groupBy: schema.groupBy, + emptyIsBlank: laneIsText, filter: queryFilter, params: { $orderby: convertSortToQueryParams(schema.sort), @@ -2087,9 +2099,13 @@ export const ObjectKanban: React.FC = ({ return loading; }; mark((prev) => ({ ...prev, loading: { ...prev.loading, [laneId]: true } })); - const filter = laneId === KANBAN_UNCOLUMNED_ID - ? emptyLaneQueryFilter(held.filter, held.groupBy) - : laneQueryFilter(held.filter, held.groupBy, laneId); + // A text lane's empty value is `''` as well as none: both draw the + // trailing lane (`laneKeyOf`) and the lane read counts both under it. + const filter = laneId !== KANBAN_UNCOLUMNED_ID + ? laneQueryFilter(held.filter, held.groupBy, laneId) + : held.emptyIsBlank + ? mergeFilterNodes(held.filter, ['or', [held.groupBy, 'is_null'], [held.groupBy, '=', '']]) + : emptyLaneQueryFilter(held.filter, held.groupBy); dataSource .find(held.objectName, { ...held.params, $filter: filter, $skip: page.loaded, $top: KANBAN_LANE_PAGE_SIZE } as any) .then((result) => { From fa345c46214b5a56d9bb3ea0851f07a81c4e5162 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:59:09 +0000 Subject: [PATCH 046/178] fix(console): a parent's whole-record hand lock locks its inline master-detail lines in the edit form (#38388) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #38249 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:对象上写了「整单人手锁定」条件的单据(如已确认的订单),在控制台编辑对话框里,明细行也一并锁住:不能加行、复制行、删行、拖动排序或改单元格;明细字段自己写了「始终可改」的那一列仍可编辑;整单与明细都没有可改之处时,记录页的「编辑」按钮置灰并说明原因。 - 为什么做:对象级整单锁定上线后,表头字段锁住了,明细行却还能手改,与「整单人手锁定」的承诺不符,维护者裁定按字面先落地、再立此跟进卡补上明细这一半。 - 出错会怎样:漏锁时用户仍能手改明细行,服务端校验照常兜底;误锁时只影响手工编辑,按钮、接口、导入、流程照常写入;去掉对象上的锁定条件即可撤回。 - 要你做什么:无。 ## What changes Governing ruling: the maintainer on PR #38169 (the object-level hand lock), 「本 PR 按字面落地+立跟进卡」; this card is that follow-up. The opt-out reads the existing override rule of the two-tier lock model (ruling on #36806, Q1 = B on #37402): a field that declares a hand lock of its own — `uiReadonly: true` or a `uiReadonlyWhen` — is judged by it instead of any object-level default, and `uiReadonly: false` is not such a declaration. No key, value or schema property is added. **`@object-ui/plugin-form`** - `MasterDetailForm.tsx` (the edit dialog's line grids): the header record feed also lands the parent object's `uiReadonlyWhen` with its field names. On an EDIT form the lines judge it over the live header record (every header field seeded `null`, the stored row as `previous`, the host's predicate scope) through the one hand-lock verdict (`fieldReadOnlyByHand` of a field that declares nothing, i.e. the object lock itself, failing closed). While it holds: no Add, Duplicate, Remove or drag-reorder, no per-row editor, and every line column whose child field owns no hand lock is locked on every row. A create is not judged. - `deriveMasterDetail.ts`: derived and hydrated line columns carry an in-memory mark when their child field owns a hand lock (`childFieldOwnsHandLock`, which asks `effectiveUiReadonlyWhen` itself rather than restating the rule). `lockColumnsByParentHandLock` locks every unmarked column. `childLinesOpenUnderParentHandLock` answers whether some child field owns a non-static hand lock (exported from the root and from `/core`). **`@object-ui/app-shell`** - `editFormLockedByState.ts`: an object that places an inline child collection no longer keeps Edit live unconditionally. It greys Edit when the object's own `uiReadonlyWhen` holds over the record, every drawn header field is read-only, and no placed child object has a field that could open a line cell. That needs the child definitions, through a new optional `childObjectDef` argument; without it, or for a child it cannot answer, Edit stays live (fail open, as before). - `RecordDetailView.tsx`: passes the served object list as that resolver. Declared writes (REST, import, actions, flows) are untouched: nothing on the server reads either key (ruling on #36806). Published surface, both additive (a non-protocol widening, so `patch`): `@object-ui/plugin-form` exports `childLinesOpenUnderParentHandLock` from its `.` and `./core` entries, and the exported `editFormLockedByState` of `@object-ui/app-shell` takes an optional fourth argument, `childObjectDef`; a caller that omits it behaves as before. ## Why PR #38169's acceptance notes recorded that a parent's object lock did not reach its line rows, and its contract review (record 7236877945) escalated it. The maintainer summary of #37402 promises 「整单人手锁定」 for a confirmed order, while a person could still edit its lines. ## Tests - New `MasterDetailForm.parentHandLock-38249.test.tsx` (real `MasterDetailForm` and `GridField`): a locked parent offers no add / duplicate / remove / reorder and locks a line cell; a child field with its own `uiReadonlyWhen: 'false'` stays editable while its sibling is locked; `uiReadonly: true` stays locked; a fully configured entry (no child schema read) locks every cell; CONTROL draft parent edits as before; CONTROL a create is not judged. - `__tests__/dialogHandLock-36806.test.ts`, new top-level describe: `childFieldOwnsHandLock` over each spelling (`uiReadonly: false` and a server lock are not ownership); derived and authored (typed and untyped) columns; an unmarked column fails closed; `childLinesOpenUnderParentHandLock`. - `editFormLockedByState.test.ts`, new describe: true when the lock holds and no child field can open; false with a `'false'` child override; true with only a static child lock; false when the predicate does not hold; false when the header is locked field by field only; fail-open without child definitions. - `RecordDetailView.editLockedByState-32756.test.tsx`, new top-level describe: Edit disabled with the state reason on a locked document with lines; CONTROL a `'false'` child override and a draft record keep it live. ## Acceptance notes - Measured on `main` first: the new rendered pin against the unfixed code, 4 failed / 2 passed (a confirmed parent's line cell was editable; both controls green). - Precedence, as the existing override rule gives it: a child field with its own conditional `uiReadonlyWhen` (say over the line's own columns) is judged by that predicate, so the parent's lock does not reach that cell. Its default (no declaration) is now the child object's lock OR the parent's. - A row-level opt-out for adding or removing lines does not exist: under a locked parent no line is added, duplicated, removed or reordered, whatever the child fields declare. A field-level declaration opens only that field's cell on stored lines. - The per-row editor is not offered under a locked parent, because it edits every child field. So in a form-factor collection (`inlineEdit: 'form'`, lines shown as a list) a child field's own opt-out has no surface while the parent is locked: that collection reads fully locked. - A fully configured entry (typed columns and the relationship field) reads no child schema, so its columns carry no ownership mark and all lock under the parent lock (the hand lock fails closed). - Before the header record lands, the parent predicate is judged over `null`-seeded header fields; a predicate such as `record.status == 'confirmed'` then reads open until the record lands. This is the same window as the grid's own object-definition read noted on PR #38169. - Scope: the console edit form and the record page's Edit state. The record page's own line-items panel (`LineItemsPanel` / the record body table editor) is not changed here; whether it should follow the parent's lock is for its own card. - The four commits' `Claude-Session:` trailers name the dispatching seat's session (`session_017xRBcSAaBEfQpU2yJexSJ8`) instead of this dev session (`session_017xRBcSPkRxFWubkD5XfiDh`), a transcription slip; the history is left as pushed. - File surface beyond the two claimed files, each `check-handover.mjs --inflight` clear: `MasterDetailForm.tsx` (the line grid), `RecordDetailView.tsx` (the Edit state's caller), `core.ts` and `index.tsx` (one export each). ## Verification Patch round (seat claim amendment 7247687945, head `1933251b`): `Clause-②` corrected to `yes (widening)` here and in both changesets (still `patch`, `Metadata-protocol: none`); `origin/main` merged twice (`212babcf`, `1933251b`), no incoming commit touching this diff's files. On `1933251b`: the four pin files 4/4 files, 42/42 tests; `dispatch-gates.mjs --commands` 38 families, all run, all exit 0 (the ui `scripts/` suite 172 files passed, 2 skipped / 5,159 tests); `--ran`: "38 run, 0 NOT-MEASURED"; `overlap-check.mjs` VERDICT clean exit 0; `check:nul-bytes` OK. The readings below are the first round's. Two-minute check: `cd ui && pnpm exec vitest run packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx` — expect 6 passed. First files to read (by risk): `ui/packages/plugin-form/src/MasterDetailForm.tsx` (the `parentHandLocked` verdict and the three grid props it gates); `ui/packages/plugin-form/src/deriveMasterDetail.ts` (`childFieldOwnsHandLock` and the mark); `ui/packages/app-shell/src/utils/editFormLockedByState.ts` (the subform branch). Readings on `objectstack-ai/objectstack`, head `9166fa40` (the gate union on `81f9ef2c`; the one later commit adds only the record-page test describe, and the derived list on `9166fa40` is byte-identical).
Tests - `@object-ui/plugin-form` full suite: 249 files / 2,816 passed, 1 skipped. - `@object-ui/plugin-form` and `@object-ui/app-shell` `type-check` (both `tsc --noEmit` and the test tsconfig): exit 0. - app-shell targeted: `RecordDetailView.editLockedByState-32756.test.tsx` + `editFormLockedByState.test.ts` 27/27. The app-shell full suite is not run locally (CI `Test UI` runs it). - New and extended pins together (plugin-form + app-shell utils): 35/35.
Shown red without the fix (scripts/ablation-replace.mjs, restored to HEAD each time, blob equal and git diff HEAD empty) - `MasterDetailForm.tsx` parent verdict forced `false`: rendered pin 4 failed / 2 passed (controls green). - `editFormLockedByState.ts` back to returning false for any subform: 2 failed / 18 passed (the two "is true" cases). - `deriveMasterDetail.ts` ownership mark removed: 3 failed (derived and authored column cases, and the rendered `'false'` override case). - `RecordDetailView.tsx` resolver dropped: 1 failed / 6 passed (the Edit-disabled case).
Gates - `node scripts/pm/dispatch-gates.mjs --commands`: 38 families, all run on `81f9ef2c`; 37 exit 0. `pnpm --dir ui exec vitest run scripts/` exit 1: SIGKILLed by the container's memory limit while the plugin-form suite ran beside it, so not measured on that run. Rerun alone under the verify lock with `--maxWorkers=2`: 172 files passed, 2 skipped / 5,159 tests, exit 0. - `dispatch-gates.mjs --ran`: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED" over the raw record (the exit 1 above as recorded). - `overlap-check.mjs` before every push: VERDICT clean exit 0. - `pnpm check:nul-bytes`: OK. - Full dogfood battery: n/a (no `!`, no `(narrowing)` arm).
## 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. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [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: 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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcSPkRxFWubkD5XfiDh --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcSPkRxFWubkD5XfiDh)_ --------- Co-authored-by: Claude --- ...38249-inline-lines-hand-lock-edit-state.md | 12 ++ .../38249-inline-lines-hand-lock-form.md | 12 ++ .../src/utils/editFormLockedByState.test.ts | 51 ++++++ .../src/utils/editFormLockedByState.ts | 34 +++- ...etailView.editLockedByState-32756.test.tsx | 49 +++++- .../app-shell/src/views/RecordDetailView.tsx | 12 +- ...erDetailForm.parentHandLock-38249.test.tsx | 151 ++++++++++++++++++ .../plugin-form/src/MasterDetailForm.tsx | 59 +++++-- .../__tests__/dialogHandLock-36806.test.ts | 74 ++++++++- ui/packages/plugin-form/src/core.ts | 2 +- .../plugin-form/src/deriveMasterDetail.ts | 82 +++++++++- ui/packages/plugin-form/src/index.tsx | 2 +- 12 files changed, 518 insertions(+), 22 deletions(-) create mode 100644 .changeset/38249-inline-lines-hand-lock-edit-state.md create mode 100644 .changeset/38249-inline-lines-hand-lock-form.md create mode 100644 ui/packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx diff --git a/.changeset/38249-inline-lines-hand-lock-edit-state.md b/.changeset/38249-inline-lines-hand-lock-edit-state.md new file mode 100644 index 00000000000..701b2421593 --- /dev/null +++ b/.changeset/38249-inline-lines-hand-lock-edit-state.md @@ -0,0 +1,12 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the record page greys Edit on a hand-locked document whose inline lines are locked too + +Clause-②: yes (widening) +Metadata-protocol: none + +The record page's Edit was always live on an object whose field groups place an inline child collection, because the edit form still edited its lines. Now that a parent's whole-record hand lock (`uiReadonlyWhen`) locks those lines as well, Edit goes off with the state-lock reason when the lock holds over the record, every header field the form draws is read-only, and no field of any placed child object owns a hand lock that could open a line cell. Without a child object's definition, or when a child field declares a `uiReadonlyWhen` of its own, Edit stays live as before. + +Additive: the exported `editFormLockedByState` takes an optional fourth argument, `childObjectDef` (a child object name to its served definition); callers that omit it behave as before. diff --git a/.changeset/38249-inline-lines-hand-lock-form.md b/.changeset/38249-inline-lines-hand-lock-form.md new file mode 100644 index 00000000000..54bbab75f31 --- /dev/null +++ b/.changeset/38249-inline-lines-hand-lock-form.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-form': patch +--- + +fix(plugin-form): a parent's whole-record hand lock locks its inline master-detail lines in the edit form + +Clause-②: yes (widening) +Metadata-protocol: none + +The master-detail edit form now reads the parent object's `uiReadonlyWhen` (the whole-record hand lock) over its lines too. While it holds over the parent record, a person adds, duplicates, removes or reorders no line, the per-row editor is not offered, and every line cell is locked unless its child field declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`), which then judges that cell instead — the same override the object level already reads. So a child field whose own `uiReadonlyWhen` is the constant `false` keeps that one cell editable on a confirmed order; `uiReadonly: false` is not such a declaration. A create is not judged. A fully configured entry (typed columns and the relationship field, so no child schema is read) has every line cell locked while the parent lock holds. REST, import, action and flow writes are unchanged: nothing on the server reads either key. + +New export `childLinesOpenUnderParentHandLock`, from the package root and from `@object-ui/plugin-form/core`: whether a child object's lines can still be edited under a locked parent (some child field owns a hand lock that is not static). diff --git a/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts b/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts index 844fa387267..c3f5f3a5a29 100644 --- a/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts +++ b/ui/packages/app-shell/src/utils/editFormLockedByState.test.ts @@ -118,3 +118,54 @@ describe('editFormLockedByState reads the object-level uiReadonlyWhen (#37402)', expect(editFormLockedByState(order({}), { ...CONFIRMED, status: 'draft' })).toBe(false); }); }); + +/** + * #38249 — an object's whole-record hand lock locks its inline lines too, so + * an object that places a child collection greys Edit when the lock holds and + * no field of the child can open a line cell. Without the child's definition, + * or when a child field owns a lock that could open, Edit stays live. + */ +describe('editFormLockedByState with inline lines under the object-level uiReadonlyWhen (#38249)', () => { + const CONFIRMED = { id: 'o1', status: 'confirmed', amount: 1 }; + const order = { + name: 'order', + uiReadonlyWhen: "record.status == 'confirmed'", + fields: { status: { type: 'text' }, amount: { type: 'number' } }, + groupSubforms: [{ childObject: 'order_line', relationshipField: 'order' }], + }; + const line = (qty: Record = {}) => ({ + name: 'order_line', + fields: { order: { type: 'master_detail', reference: 'order' }, qty: { type: 'number', ...qty } }, + }); + const defs = (child: unknown) => (name: string) => (name === 'order_line' ? (child as any) : undefined); + + it('is true when the object lock holds and no child field can open a line cell', () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line()))).toBe(true); + }); + + it("is false when a child field keeps its cell editable with its own uiReadonlyWhen 'false'", () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonlyWhen: 'false' })))).toBe(false); + }); + + it('is true when the child field owns only a static lock', () => { + expect(editFormLockedByState(order, CONFIRMED, undefined, defs(line({ uiReadonly: true })))).toBe(true); + }); + + it('is false while the object predicate does not hold', () => { + expect(editFormLockedByState(order, { ...CONFIRMED, status: 'draft' }, undefined, defs(line()))).toBe(false); + }); + + it('is false when the header is locked only field by field: that leaves the lines open', () => { + const { uiReadonlyWhen: _drop, ...plain } = order; + const byField = { + ...plain, + fields: { status: { type: 'text', readonlyWhen: "record.status == 'confirmed'" }, amount: { type: 'number', readonlyWhen: "record.status == 'confirmed'" } }, + }; + expect(editFormLockedByState(byField, CONFIRMED, undefined, defs(line()))).toBe(false); + }); + + it("fails open without the child object's definition", () => { + expect(editFormLockedByState(order, CONFIRMED)).toBe(false); + expect(editFormLockedByState(order, CONFIRMED, undefined, () => undefined)).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/utils/editFormLockedByState.ts b/ui/packages/app-shell/src/utils/editFormLockedByState.ts index e1de5822dff..2928a3063a8 100644 --- a/ui/packages/app-shell/src/utils/editFormLockedByState.ts +++ b/ui/packages/app-shell/src/utils/editFormLockedByState.ts @@ -29,14 +29,20 @@ * so a writable field anywhere keeps Edit live; * - the object's field groups place no inline child collection * (`recordFormSubforms`, objectstack-ai/objectstack#36425), whose rows the - * form still edits whatever the header fields say. + * form still edits whatever the header fields say — unless the object's + * whole-record hand lock (`uiReadonlyWhen`) holds over the record, which + * locks those rows too (objectstack#38249), and no field of any placed + * child object owns a hand lock that could open a line cell + * (`childLinesOpenUnderParentHandLock`). That needs each child object's + * definition, from `childObjectDef`; without it, or for a child it cannot + * answer, Edit stays live. * * A predicate that faults resolves to its fail-open verdict (writable), as in * the form, so a broken rule never greys Edit. */ -import { effectiveUiReadonlyWhen, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core'; -import { filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core'; +import { effectiveUiReadonlyWhen, fieldReadOnlyByHand, isExpressionComputedField, resolveFieldRuleState, type ObjectHandLockDef } from '@object-ui/core'; +import { childLinesOpenUnderParentHandLock, filterSystemFields, isAutoGeneratedFieldType } from '@object-ui/plugin-form/core'; import type { FormField } from '@object-ui/types'; import { recordFormSubforms, type ObjectDefinitionForRecordForm } from './recordFormNavigation.js'; @@ -66,9 +72,11 @@ export function editFormLockedByState( objectDef: EditFormLockObject | null | undefined, record: Record | null | undefined, scope?: Record, + childObjectDef?: (name: string) => { fields?: Record } | null | undefined, ): boolean { if (!objectDef || !record) return false; - if (recordFormSubforms(objectDef)) return false; + const subforms = recordFormSubforms(objectDef); + if (subforms && !childObjectDef) return false; const declared = fieldEntries(objectDef.fields); // The fields the form draws: the form's own system-field pass drops the @@ -87,6 +95,24 @@ export function editFormLockedByState( for (const { name } of declared) ruleRecord[name] = null; for (const [k, v] of Object.entries(record)) if (v !== undefined) ruleRecord[k] = v; + if (subforms) { + // objectstack#38249 — the lines are locked only by the object's own + // whole-record hand lock (a field-level lock on the header leaves them + // open), judged by the one hand-lock verdict over the stored row. + const objectLockHolds = fieldReadOnlyByHand({}, ruleRecord, { + object: objectDef, + previous: ruleRecord, + scope, + fieldContext: 'object uiReadonlyWhen', + }); + if (!objectLockHolds) return false; + for (const subform of subforms) { + const childObject = typeof subform?.childObject === 'string' ? subform.childObject : undefined; + const child = childObject ? childObjectDef?.(childObject) : undefined; + if (!child || childLinesOpenUnderParentHandLock(child)) return false; + } + } + let shown = 0; let lockedByRule = 0; for (const { name, def } of entries) { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx index c6c113fd3ee..d93c37781cf 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.editLockedByState-32756.test.tsx @@ -133,8 +133,8 @@ function stateLockBadge(): HTMLElement | null { } /** Mount the console record page and wait for the record read and the header. */ -async function mountRecordPage(record: Record, fields: Record) { - const objects = [objectDef(fields)]; +async function mountRecordPage(record: Record, fields: Record, served?: any[]) { + const objects = served ?? [objectDef(fields)]; const dataSource = makeDataSource(record); render( @@ -245,3 +245,48 @@ describe('console record header — a record whose state locks every edit-form f expect(stateLockBadge()).toBeNull(); }); }); + +/** + * objectstack#38249 — an object whose whole-record hand lock (`uiReadonlyWhen`) + * holds locks its inline lines in the edit form too, so the record page greys + * Edit even though its field groups place a child collection — unless a child + * field owns a hand lock that could open a line cell. + */ +describe('console record header — a hand-locked document with inline lines (objectstack#38249)', () => { + const LINE_OBJECT = 'ebqu_claim_line'; + const parent = { + ...objectDef({ + id: { type: 'text', label: 'Id' }, + name: { type: 'text', label: 'Title' }, + status: { type: 'text', label: 'Status' }, + }), + uiReadonlyWhen: "record.status == 'approved'", + groupSubforms: [{ childObject: LINE_OBJECT, relationshipField: 'claim' }], + }; + const line = (amount: Record = {}) => ({ + name: LINE_OBJECT, + label: 'Claim line', + fields: { + claim: { type: 'master_detail', label: 'Claim', reference: OBJECT_NAME }, + amount: { type: 'currency', label: 'Amount', ...amount }, + }, + }); + + it('draws Edit disabled when the object lock holds and no line cell can open', async () => { + await mountRecordPage(APPROVED, {}, [parent, line()]); + await waitFor(() => expect(headerEditButton()).toBeDisabled()); + expect(stateLockBadge()).toBeInTheDocument(); + }); + + it("CONTROL: a child field whose own uiReadonlyWhen is 'false' keeps Edit enabled", async () => { + await mountRecordPage(APPROVED, {}, [parent, line({ uiReadonlyWhen: 'false' })]); + expect(headerEditButton()).not.toBeDisabled(); + expect(stateLockBadge()).toBeNull(); + }); + + it('CONTROL: a state the object lock does not hold keeps Edit enabled', async () => { + await mountRecordPage(DRAFT, {}, [parent, line()]); + expect(headerEditButton()).not.toBeDisabled(); + expect(stateLockBadge()).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 4abea6292ce..8f271c606b1 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -3108,8 +3108,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // goes off exactly when the form would open with no control. const predicateScope = usePredicateScope(); const editLockedByState = useMemo( - () => editFormLockedByState(objectDef as any, pageRecord as Record | null | undefined, predicateScope), - [objectDef, pageRecord, predicateScope], + () => editFormLockedByState( + objectDef as any, + pageRecord as Record | null | undefined, + predicateScope, + // The placed child objects' definitions: a parent's whole-record hand + // lock locks its inline lines too, unless a child field owns a lock + // that could open one (objectstack#38249). + (name) => objects.find((o: any) => o?.name === name), + ), + [objectDef, pageRecord, predicateScope, objects], ); // ── Audit history fetch ──────────────────────────────────────────── diff --git a/ui/packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx new file mode 100644 index 00000000000..6c7788cc57b --- /dev/null +++ b/ui/packages/plugin-form/src/MasterDetailForm.parentHandLock-38249.test.tsx @@ -0,0 +1,151 @@ +/** + * 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#38249 — a parent's whole-record hand lock (object-level + * `uiReadonlyWhen`) covers its inline master-detail lines in the edit form. + * + * While the predicate holds over the parent record, a person adds, + * duplicates, removes, reorders and edits no line by hand. A child field that + * declares a hand lock of its own (`uiReadonly: true` or a `uiReadonlyWhen`) + * is judged by that declaration instead, the same override the object level + * reads (`effectiveUiReadonlyWhen`): `uiReadonlyWhen: 'false'` keeps that one + * cell editable on a locked document. A create is not judged. + * + * Measured through the REAL `MasterDetailForm` and `GridField`. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import React from 'react'; + +import { registerAllFields } from '@object-ui/fields'; +import { MasterDetailForm } from './MasterDetailForm'; + +registerAllFields(); +afterEach(cleanup); + +const PARENT = 'sales_order'; +const CHILD = 'sales_order_line'; +const LINE = { id: 'L1', order: 'SO1', qty: 3, note: 'gift wrap' }; + +const PARENT_SCHEMA = { + name: PARENT, + uiReadonlyWhen: "record.status == 'confirmed'", + fields: { ref: { type: 'text', label: 'Ref' }, status: { type: 'text', label: 'Status' } }, +}; + +const childSchema = (note: Record) => ({ + name: CHILD, + fields: { + order: { type: 'master_detail', reference: PARENT, label: 'Order' }, + qty: { type: 'number', label: 'Qty' }, + note: { type: 'text', label: 'Note', ...note }, + }, +}); + +function makeDS(status: string, note: Record = {}) { + return { + getObjectSchema: vi.fn(async (obj: string) => + obj === PARENT ? PARENT_SCHEMA : obj === CHILD ? childSchema(note) : null, + ), + findOne: vi.fn().mockResolvedValue({ id: 'SO1', ref: 'SO-1', status }), + find: vi.fn().mockResolvedValue({ data: [LINE] }), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + batchTransaction: vi.fn().mockResolvedValue({ results: [] }), + }; +} + +/** Untyped authored columns: the child schema is read and each column hydrated from its field. */ +const DERIVED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty' }, { name: 'note', label: 'Note' }] }]; +/** A fully configured entry: typed columns and the FK, so no child schema is read. */ +const CONFIGURED = [{ childObject: CHILD, relationshipField: 'order', columns: [{ name: 'qty', label: 'Qty', type: 'number' }] }]; + +function mount(ds: ReturnType, details = DERIVED, mode: 'edit' | 'create' = 'edit') { + return render( + , + ); +} + +const offered = () => ({ + add: screen.queryByTestId('line-items-add') !== null, + duplicate: screen.queryAllByRole('button', { name: 'Duplicate row' }).length > 0, + remove: screen.queryAllByRole('button', { name: 'Remove row' }).length > 0, + reorder: screen.queryByTestId('line-items-drag-0') !== null, +}); + +/** Wait until the stored line is drawn and the header record has landed. */ +async function lineLoaded(ds: ReturnType) { + await waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy()); + await waitFor(() => expect(ds.findOne).toHaveBeenCalled()); + // A locked header field draws its read face, an open one its input. + await waitFor(() => expect(screen.queryByDisplayValue('SO-1') ?? screen.queryByText('SO-1')).toBeTruthy()); +} + +const qtyCell = () => screen.getByDisplayValue('3') as HTMLInputElement; +const noteCell = () => screen.getByDisplayValue('gift wrap') as HTMLInputElement; + +describe('MasterDetailForm: the parent object\'s uiReadonlyWhen hand-locks its inline lines (objectstack#38249)', () => { + it('a locked parent offers no add, duplicate, remove or reorder of a line, and locks a line cell that declares no hand lock of its own', async () => { + const ds = makeDS('confirmed'); + mount(ds); + await lineLoaded(ds); + await waitFor(() => expect(qtyCell().disabled).toBe(true)); + expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false }); + }); + + it("a child field whose own uiReadonlyWhen is 'false' stays editable on a locked parent; its siblings stay locked", async () => { + const ds = makeDS('confirmed', { uiReadonlyWhen: 'false' }); + mount(ds); + await lineLoaded(ds); + await waitFor(() => expect(qtyCell().disabled).toBe(true)); + expect(noteCell().disabled).toBe(false); + expect(offered().add).toBe(false); + }); + + it('a child field with uiReadonly: true stays locked on a locked parent (its own declaration locks it)', async () => { + const ds = makeDS('confirmed', { uiReadonly: true }); + mount(ds); + await lineLoaded(ds); + await waitFor(() => expect(qtyCell().disabled).toBe(true)); + expect(noteCell().disabled).toBe(true); + }); + + it('a fully configured entry (no child schema read) locks every line cell on a locked parent', async () => { + const ds = makeDS('confirmed'); + mount(ds, CONFIGURED); + await lineLoaded(ds); + await waitFor(() => expect(qtyCell().disabled).toBe(true)); + expect(offered()).toEqual({ add: false, duplicate: false, remove: false, reorder: false }); + }); + + it('CONTROL: while the parent predicate does not hold, the lines are edited as before', async () => { + const ds = makeDS('draft'); + mount(ds); + await lineLoaded(ds); + expect(qtyCell().disabled).toBe(false); + expect(noteCell().disabled).toBe(false); + expect(offered()).toEqual({ add: true, duplicate: true, remove: true, reorder: true }); + }); + + it('CONTROL: a create form is not judged — lines are added on an object that carries the lock', async () => { + const ds = makeDS('confirmed'); + mount(ds, DERIVED, 'create'); + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); + }); +}); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 94027885ddc..91e74bda150 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -33,7 +33,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { createPortal } from 'react-dom'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; -import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; +import { fieldReadOnlyByHand, resolveAffordance, runBatchTransaction } from '@object-ui/core'; import { isUntouchedNewRow, LineItemsField, preloadGridField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { @@ -45,7 +45,7 @@ import { useObjectTranslation, } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; -import { dataChangeMatches, extractFieldErrors, subscribeDataChanges } from '@object-ui/react'; +import { dataChangeMatches, extractFieldErrors, subscribeDataChanges, usePredicateScope } from '@object-ui/react'; import { ObjectForm } from './ObjectForm'; import { applyColumnPermissions } from './fieldWriteGate'; import { useUploadGate, UploadGateProvider, UploadInFlightNotice } from './uploadGate'; @@ -65,7 +65,7 @@ import { import { isSameStoredValue } from './sanitize'; import { resolveInitialRecord } from './initialRecord'; import { sectionEntryName } from './sectionFields'; -import { deriveDetail } from './deriveMasterDetail'; +import { deriveDetail, lockColumnsByParentHandLock } from './deriveMasterDetail'; import { schemaDefaultValues } from './schemaDefaults'; import { currencyFieldDefsOf, parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; // objectui#11428 — the per-row form's offer test is the spec's rule. @@ -681,13 +681,19 @@ interface HeaderRecordFeed { record: Record; /** The header object's field names, once its schema read has answered. */ objectFields: readonly string[] | null; + /** + * The header object's whole-record hand lock (`ObjectSchema.uiReadonlyWhen`), + * landed with its field names (objectstack#38249); `undefined` until then or + * when the object declares none. + */ + objectHandLock: unknown; /** Bumped per header record read started, so only the newest answer lands. */ seq: number; listeners: Set<(landed: 'record' | 'objectFields') => void>; } function createHeaderRecordFeed(opening: Record): HeaderRecordFeed { - return { record: opening, objectFields: null, seq: 0, listeners: new Set() }; + return { record: opening, objectFields: null, objectHandLock: undefined, seq: 0, listeners: new Set() }; } /** @@ -743,8 +749,10 @@ function observeHeaderReads( const answer = call(args); if (args[0] === objectName) { observe(answer, (objectSchema) => { - const fields = (objectSchema as { fields?: Record } | null)?.fields; + const served = objectSchema as { fields?: Record; uiReadonlyWhen?: unknown } | null; + const fields = served?.fields; feed.objectFields = fields ? Object.keys(fields) : []; + feed.objectHandLock = served?.uiReadonlyWhen ?? undefined; feed.listeners.forEach((listener) => listener('objectFields')); }); } @@ -1053,6 +1061,7 @@ const MasterDetailLines: React.FC = ({ // it, so a header that answers late still locks a paid invoice's lines. const [loadedRecord, setLoadedRecord] = useState>(headerRecord.record); const [objectFields, setObjectFields] = useState(headerRecord.objectFields); + const [parentHandLock, setParentHandLock] = useState(headerRecord.objectHandLock); // The user's edits, scraped from the host on its input/change events; null // until the first one. A landing record replaces the form's values, so it // drops them. @@ -1063,6 +1072,7 @@ const MasterDetailLines: React.FC = ({ const land = (landed: 'record' | 'objectFields') => { if (landed === 'objectFields') { setObjectFields(headerRecord.objectFields); + setParentHandLock(headerRecord.objectHandLock); return; } editedKeyRef.current = ''; @@ -1115,6 +1125,29 @@ const MasterDetailLines: React.FC = ({ [loadedRecord, editedRecord], ); + // objectstack#38249 — the PARENT's whole-record hand lock covers its lines. + // Judged as the header's own fields judge it: over the live header record + // (every header field seeded `null`, as the form seeds it), the stored one + // as `previous`, in the host's predicate scope, through the one hand-lock + // verdict (`fieldReadOnlyByHand` of a field that declares nothing, i.e. the + // object's lock itself, failing closed on a fault). A create is not judged. + // While it holds, no line is added, duplicated, removed, reordered or opened + // in the row editor, and every cell whose child field owns no hand lock is + // locked (`lockColumnsByParentHandLock`). + const predicateScope = usePredicateScope(); + const parentHandLocked = useMemo(() => { + if (formMode !== 'edit' || parentHandLock == null) return false; + const ruleRecord: Record = {}; + for (const name of objectFields ?? []) ruleRecord[name] = null; + for (const [k, v] of Object.entries(parentRecord)) if (v !== undefined) ruleRecord[k] = v; + return fieldReadOnlyByHand({}, ruleRecord, { + object: { uiReadonlyWhen: parentHandLock }, + previous: loadedRecord, + scope: predicateScope, + fieldContext: `object '${parentObjectName}' uiReadonlyWhen`, + }); + }, [formMode, parentHandLock, objectFields, parentRecord, loadedRecord, predicateScope, parentObjectName]); + // Document totals: Subtotal (Σ line amounts) → Tax (header rate %) → Total. // Shown only when the header carries the tax-rate field AND a detail has an // amount column; otherwise each grid keeps its own footer total. @@ -1284,7 +1317,9 @@ const MasterDetailLines: React.FC = ({ // redundant expand button. The test is `@objectstack/spec`'s // `isInlineRowFormOffered` (objectui#11428), asked with the // collection's RESOLVED form factor and lists, authored or derived. - {...(isInlineRowFormOffered({ inlineMode: d.inlineMode, formFields: d.formFields, columns: d.columns }) + // No row editor under the parent's hand lock (objectstack#38249): + // it edits every child field, owned lock or not. + {...(!parentHandLocked && isInlineRowFormOffered({ inlineMode: d.inlineMode, formFields: d.formFields, columns: d.columns }) ? { onRowExpand: (rowIdx: number) => onRowExpand(entry.id, rowIdx) } : {})} displayMode={d.inlineMode === 'form' ? 'list' : 'grid'} @@ -1295,7 +1330,10 @@ const MasterDetailLines: React.FC = ({ // the record-form containers share: a child column the caller // may not read is omitted, and one they may read but not edit // renders its cells locked (objectui#10163). - columns: applyColumnPermissions(d.columns, { perms, objectName: d.childObject, mode: formMode }), + columns: applyColumnPermissions( + parentHandLocked ? lockColumnsByParentHandLock(d.columns) : d.columns, + { perms, objectName: d.childObject, mode: formMode }, + ), // Show the per-grid running total whenever an amount column is // set — unless the document totals stack below subsumes it. // The grid's `totalField` names the CHILD column summed (this @@ -1307,8 +1345,11 @@ const MasterDetailLines: React.FC = ({ maxRows: d.maxRows, // The map rows above: the grid's Add and Duplicate follow // `allowAdd`, its per-row Remove `allowDelete`. - allowAdd: lineAddGranted, - allowDelete: lineRemoveGranted, + // The parent's hand lock withholds all three, and reorder + // (objectstack#38249). + allowAdd: lineAddGranted && !parentHandLocked, + allowDelete: lineRemoveGranted && !parentHandLocked, + ...(parentHandLocked ? { allowReorder: false } : {}), addLabel: d.inlineMode === 'form' ? (d.addLabel || t('detail.add')) : d.addLabel, // Checked against the grid's published type (objectui#11610), so // a key the grid does not declare, or one of its retired diff --git a/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts b/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts index c67c5639bc9..b669e7eb6e8 100644 --- a/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts +++ b/ui/packages/plugin-form/src/__tests__/dialogHandLock-36806.test.ts @@ -17,7 +17,13 @@ import { describe, it, expect } from 'vitest'; import { filterCreateModeFields, filterSystemFields } from '../autoLayout'; import { sanitizeFormData } from '../sanitize'; import { fromObjectSchema, type SectionFieldsContext } from '../sectionFields'; -import { deriveColumns, hydrateColumns } from '../deriveMasterDetail'; +import { + childFieldOwnsHandLock, + childLinesOpenUnderParentHandLock, + deriveColumns, + hydrateColumns, + lockColumnsByParentHandLock, +} from '../deriveMasterDetail'; import type { FormField } from '@object-ui/types'; const objectSchema = { @@ -88,3 +94,69 @@ describe('the dialog and line-item fields carry the object-level hand lock (#374 expect((authored[0] as any).uiReadonlyWhen).toBe(LOCK); }); }); + +/** + * #38249 — a parent's whole-record hand lock reaches its inline lines: every + * line column whose child field owns no hand lock is locked; a child field + * that declares one (`uiReadonly: true` or a `uiReadonlyWhen`) keeps its own + * verdict, the same override the object level reads. `uiReadonly: false` is + * not such a declaration. + */ +describe("a parent's whole-record hand lock over its line columns (#38249)", () => { + const line = { + name: 'order_line', + fields: { + parent: { type: 'master_detail', reference: 'order' }, + qty: { type: 'number' }, + notes: { type: 'text', uiReadonlyWhen: 'false' }, + sku: { type: 'text', uiReadonly: false }, + tag: { type: 'text', uiReadonlyWhen: "record.qty > 5" }, + }, + }; + const label = { booleanLabel: (v: boolean) => String(v) } as never; + const byName = (cols: any[], n: string) => cols.find((c) => c.name === n); + + it('childFieldOwnsHandLock reads the one override rule', () => { + expect(childFieldOwnsHandLock({ uiReadonlyWhen: 'false' })).toBe(true); + expect(childFieldOwnsHandLock({ uiReadonlyWhen: "record.qty > 5" })).toBe(true); + expect(childFieldOwnsHandLock({ uiReadonly: true })).toBe(true); + expect(childFieldOwnsHandLock({ uiReadonly: false })).toBe(false); + expect(childFieldOwnsHandLock({ readonly: true, readonlyWhen: 'true' })).toBe(false); + expect(childFieldOwnsHandLock({})).toBe(false); + expect(childFieldOwnsHandLock(undefined)).toBe(false); + }); + + it('derived columns: a field that owns no hand lock is locked; one that owns one keeps its own verdict', () => { + const locked = lockColumnsByParentHandLock(deriveColumns(line, { ...(label as object), relationshipField: 'parent' } as never)); + expect(byName(locked, 'qty')?.uiReadonly).toBe(true); + expect(byName(locked, 'sku')?.uiReadonly).toBe(true); + expect(byName(locked, 'notes')?.uiReadonly).toBeUndefined(); + expect(byName(locked, 'notes')?.uiReadonlyWhen).toBe('false'); + expect(byName(locked, 'tag')?.uiReadonly).toBeUndefined(); + }); + + it('authored columns: typed and untyped alike carry the mark from the child field', () => { + const cols = hydrateColumns( + [{ name: 'qty', type: 'number' }, { name: 'notes', type: 'text' }, { name: 'tag' }] as never, + line, + label, + ); + const locked = lockColumnsByParentHandLock(cols); + expect(byName(locked, 'qty')?.uiReadonly).toBe(true); + expect(byName(locked, 'notes')?.uiReadonly).toBeUndefined(); + expect(byName(locked, 'tag')?.uiReadonly).toBeUndefined(); + }); + + it('a column no child schema was read for carries no mark and is locked (fails closed)', () => { + const locked = lockColumnsByParentHandLock([{ name: 'notes', type: 'text' }] as never); + expect((locked[0] as any).uiReadonly).toBe(true); + }); + + it('childLinesOpenUnderParentHandLock: true only when some child field owns a lock that is not static', () => { + expect(childLinesOpenUnderParentHandLock(line)).toBe(true); + expect(childLinesOpenUnderParentHandLock({ fields: { qty: { type: 'number' }, sku: { type: 'text', uiReadonly: false } } })).toBe(false); + expect(childLinesOpenUnderParentHandLock({ fields: { qty: { type: 'number', uiReadonly: true } } })).toBe(false); + expect(childLinesOpenUnderParentHandLock({ fields: { qty: { type: 'number', readonly: true, uiReadonlyWhen: 'false' } } })).toBe(false); + expect(childLinesOpenUnderParentHandLock(undefined)).toBe(false); + }); +}); diff --git a/ui/packages/plugin-form/src/core.ts b/ui/packages/plugin-form/src/core.ts index f8cb42c3954..cc7cb659c96 100644 --- a/ui/packages/plugin-form/src/core.ts +++ b/ui/packages/plugin-form/src/core.ts @@ -31,7 +31,7 @@ export { sectionedGridLayout, } from './autoLayout'; export type { SectionedGridLayout } from './autoLayout'; -export { resolveInlineMode } from './deriveMasterDetail'; +export { childLinesOpenUnderParentHandLock, resolveInlineMode } from './deriveMasterDetail'; export type { InlineMode } from './deriveMasterDetail'; export { omitServerResolvedDefaults, optionListDefault } from './schemaDefaults'; export type { FieldDefaultsSchemaLike, OptionListFieldLike } from './schemaDefaults'; diff --git a/ui/packages/plugin-form/src/deriveMasterDetail.ts b/ui/packages/plugin-form/src/deriveMasterDetail.ts index 72aca4055a4..7cf189a457e 100644 --- a/ui/packages/plugin-form/src/deriveMasterDetail.ts +++ b/ui/packages/plugin-form/src/deriveMasterDetail.ts @@ -22,7 +22,7 @@ import { deriveInlineRowFormFields, } from '@objectstack/spec/data'; import { summaryDeclaresCurrency, type BooleanValueLabel, type GridColumn } from '@object-ui/fields'; -import { effectiveUiReadonlyWhen, isExpressionComputedField } from '@object-ui/core'; +import { effectiveUiReadonlyWhen, fieldStaticallyReadOnlyByHand, isExpressionComputedField } from '@object-ui/core'; /** * Minimal shape of a MASTER-DETAIL CHILD object's schema, as returned by @@ -322,6 +322,7 @@ function deriveColumn( // no hand lock of its own carries the child object's whole-record one. const handLockWhen = effectiveUiReadonlyWhen(d, childSchema); if (handLockWhen) (col as { uiReadonlyWhen?: unknown }).uiReadonlyWhen = handLockWhen; + markOwnHandLock(col, d); if (d?.requiredWhen) col.requiredWhen = d.requiredWhen; // A field carrying an arithmetic `expression` (e.g. amount = quantity * // unit_price) becomes a live read-only computed column. The expression may @@ -482,14 +483,91 @@ function withHandLock( // The EFFECTIVE predicate (objectstack#37402): the field's own, else the // child object's whole-record `uiReadonlyWhen`. const lockWhen = effectiveUiReadonlyWhen(d, childSchema); - if (!lockStatic && lockWhen == null) return col; + const ownsLock = childFieldOwnsHandLock(d); + if (!lockStatic && lockWhen == null && !ownsLock) return col; const next = { ...col } as GridColumn & { uiReadonly?: boolean; uiReadonlyWhen?: unknown }; if (lockStatic) next.uiReadonly = true; // The FIELD's predicate, never a column's own: the column may not open it. if (lockWhen != null) next.uiReadonlyWhen = lockWhen; + markOwnHandLock(next, d); return next; } +/** + * The PARENT's whole-record hand lock over its inline lines + * (objectstack#38249): while the parent object's `uiReadonlyWhen` holds over + * the parent record, a person adds, duplicates, removes, reorders and edits no + * line of it by hand. The lines are records of the CHILD object, whose own + * predicates cannot read the parent's columns, so the parent's lock reaches + * them here, as one more default under the same override the object level + * reads (`effectiveUiReadonlyWhen`, `@object-ui/core` `handLock.ts`): a child + * field that declares a hand lock of its own — `uiReadonly: true` or a + * `uiReadonlyWhen` — is judged by that declaration instead, so + * `uiReadonlyWhen: P\`false\`` keeps that one cell editable on a locked + * document; `uiReadonly: false` is not such a declaration. + * + * Declared writes (REST, import, actions, flows) are untouched: nothing on the + * server reads either key. + */ + +/** + * The in-memory mark a derived or hydrated column carries when its child field + * declares a hand lock of its own, so the parent's lock does not reach it. + * Never an authored `inlineColumns` key: an authored column with no child + * schema read carries no mark, and the parent's lock then locks it (the hand + * lock fails closed). + */ +const OWN_HAND_LOCK = 'uiReadonlyOwn'; + +/** Probe object for {@link childFieldOwnsHandLock}: its predicate is a value no field can declare. */ +const OBJECT_DEFAULT_PROBE = { uiReadonlyWhen: Object.freeze({}) }; + +/** + * True when a child field declares a hand lock of its own and is therefore + * judged by it rather than by any object-level default — the child object's or + * the parent's. Asked of `effectiveUiReadonlyWhen` itself, so this reads the + * one override rule rather than restating it. + */ +export function childFieldOwnsHandLock(def: Record | null | undefined): boolean { + if (!def) return false; + return effectiveUiReadonlyWhen(def, OBJECT_DEFAULT_PROBE) !== OBJECT_DEFAULT_PROBE.uiReadonlyWhen; +} + +function markOwnHandLock(col: GridColumn, d: Record | null | undefined): void { + if (childFieldOwnsHandLock(d)) (col as Record)[OWN_HAND_LOCK] = true; +} + +/** + * A collection's columns under its parent's whole-record hand lock: every + * column whose child field does not own a hand lock is locked on every row + * (`uiReadonly: true`, the in-memory carry `GridFieldWidget` judges first); a + * column whose field owns one keeps its own verdict. + */ +export function lockColumnsByParentHandLock(columns: readonly GridColumn[]): GridColumn[] { + return columns.map((col) => + (col as Record)[OWN_HAND_LOCK] === true + ? col + : ({ ...col, uiReadonly: true } as GridColumn), + ); +} + +/** + * Whether a line of this child object may still be edited by hand under its + * parent's whole-record hand lock: some child field owns a hand lock that is + * not static (`uiReadonly: true` / `readonly: true` still lock it), so its + * cell is judged by its own predicate. Read over the whole field map, not the + * drawn columns, so the answer fails open: a caller that greys a form's Edit on + * it keeps Edit live whenever any line cell might open. + */ +export function childLinesOpenUnderParentHandLock(childSchema: ChildObjectSchemaLike | null | undefined): boolean { + const fields = childSchema?.fields; + if (!fields || typeof fields !== 'object') return false; + return Object.values(fields).some( + (d) => !!d && typeof d === 'object' && childFieldOwnsHandLock(d as Record) + && !fieldStaticallyReadOnlyByHand(d as Record), + ); +} + /** * Field names for a child's full "row form" (the per-row expand editor) — the * form an inline master-detail collection opens when its author listed no diff --git a/ui/packages/plugin-form/src/index.tsx b/ui/packages/plugin-form/src/index.tsx index b48a9224bf3..5478a6fdc63 100644 --- a/ui/packages/plugin-form/src/index.tsx +++ b/ui/packages/plugin-form/src/index.tsx @@ -86,7 +86,7 @@ export type { BodyTableSnapshot, BodyTableRowError, } from './RecordBodyTableEditor'; -export { deriveDetail, deriveColumns, deriveFormFields, findRelationshipField, resolveInlineMode } from './deriveMasterDetail'; +export { childLinesOpenUnderParentHandLock, deriveDetail, deriveColumns, deriveFormFields, findRelationshipField, resolveInlineMode } from './deriveMasterDetail'; export type { DerivedDetail, InlineMode, ChildObjectSchemaLike } from './deriveMasterDetail'; /** From 5684ee878e14fb0e8038c3218f76371490f064e9 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:59:47 +0000 Subject: [PATCH 047/178] fix(app-shell): every door into a package's Studio opens its overview (#38501) 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_01TenzsRopZj4jMbvjX8uz1XK9aBD2HT65noa4cJe7UCLN)_ Fixes #38392 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到的变化:搭建者从 ⌘K、应用里的「在 Studio 中设计」、空菜单的「在应用搭建中打开」、设置 → 软件包这几个入口打开软件包时,以前先到对象列表,现在先到「概览」页。 - 为什么做:按你对「所有入口都先进概览页」的决定(App Studio 概览页这条线的收尾),让每个入口落在同一个页面。 - 出错会怎样:最坏是某个入口仍落在对象列表或概览页,不丢数据;对象列表的地址照常可用,可以直接撤回本改动。 - 要你做的:无。 ## What changes Every door that opens a package's Studio now builds `studioPackageOverviewPath` (`/studio/PKG/overview`) instead of `studioHomePath` (`/studio/PKG/data`, the object list). Ruling record 7247357556 on #37958 (maintainer 「OK」 to 「⌘K、应用里的「在 Studio 中设计」、空菜单和设置页这几个入口,现在打开的还是对象列表。要不要都改成先进概览页?」). Door census on main `d89d3e23` (every non-test caller of `studioHomePath` under `ui/packages/app-shell/src`, measured by grep and now held by the new census test): | Door | Where (symbol) | Before | After | |:---|:---|:---|:---| | 1. ⌘K package entries | `CommandPalette.tsx` `useStudioPaletteEntries` | `/studio/PKG/data` | `/studio/PKG/overview` | | 2. An app's Design in Studio | `appRoute.ts` `appStudioDesignPath`, also the bare-app / `system` / interface-list fallback of `appStudioRoutePath` (AppHeader, ShellPageActions, PageView) | `/studio/PKG/data` | `/studio/PKG/overview` | | 3. Empty menu "Open in App Studio" | `AppNoAccessEmptyState.tsx` (`app-empty-menu-open-studio`) | `/studio/PKG/data` | `/studio/PKG/overview` | | 4. Setup → Packages detail "Open in Studio" | `PackagesPage.tsx` (`pkg-detail-open-in-studio`) | `/studio/PKG/data` | `/studio/PKG/overview` | | 5. Setup → Packages landing after New Package | `PackagesPage.tsx` `CreatePackageDialog` `onCreated` | `/studio/PKG/data` | `/studio/PKG/overview` | | 6. Setup → Packages customizations "Customize in Studio" | `PackageCustomizationsPanel.tsx` (`pkg-detail-customize`) | `/studio/BASE/data` | `/studio/BASE/overview` | - `PackagesPage.tsx` loses its local `const studioPackagePath = (id) => studioHomePath(id)`, which shadowed the exported builder of the same name. - Docblocks that still said the object list (`appRoute.ts`, the palette's Studio entries, the empty state, the customizations panel, `studioHomePath` in `studioAddress.ts`) now say 概览. - `/studio/PKG/data` stays a working address for anyone who wants the object list; `studioHomePath` keeps its builder and route. - Not changed, deliberately: `setupMetadataRedirect.ts` (a retired Setup bookmark that lands on the objects it named, not a door); the pair's bare `/studio/BASE.custom`, which already lands on its base's 概览 since #38318; and the copilot / MCP review link `studioChangesReviewPath` (`/studio/PKG/data?changes=review`), see Acceptance notes. - Copy: the empty menu's description ("Create objects for this app in App Studio and they join its menu, or add entries in Design layout."), "Open in App Studio" and "Open this app in App Studio, where its items are customized" all stay true on 概览, so no string changes and no locale file is touched. ## ADR-0084 row owed (ask 3) Proposed text for the lander's ADR revisions row (#38438), to be added under ADR-0084's 2026-11-28 amendment, item (3): > *(Amended 2026-11-29, card #38392, ruling record [comment 7247357556](https://github.com/objectstack-ai/objectstack/issues/37958#issuecomment-7247357556), the maintainer's 「OK」 to 「⌘K、应用里的「在 Studio 中设计」、空菜单和设置页这几个入口,现在打开的还是对象列表。要不要都改成先进概览页?」: one landing for every door is ruled. Every door that opens a package's Studio lands on `/studio/PKG/overview`, not on the object list: the command palette's (⌘K) package entries, an app's design-in-Studio entry (`ui/packages/app-shell/src/utils/appRoute.ts#appStudioDesignPath`, also the bare-app fallback of `appStudioRoutePath`), the "Open in App Studio" of an app's empty menu, and Setup → Packages' "Open in Studio", its landing after New Package and its customizations section's "Customize in Studio". The pair's bare address `/studio/BASE.custom`, landed by #38318, lands on its base's 概览 and is covered by this ruling. `/studio/PKG/data` stays a working address for the object list.)* ## Tests - Re-pointed every pin of the old targets to `/overview`: `appRoute.test.ts` (door 2, five assertions), `CommandPalette.studioScope-11863.test.tsx` and `StudioPaletteGroups.surfaceScope-36900.test.tsx` (door 1), `AppNoAccessEmptyState.emptyMenu-36748.test.tsx` (door 3), `PackagesPage.installedAppsUpdates-34722.test.tsx` (doors 4, 5 and 6), `PackageCustomizationsPanel.test.tsx` (door 6), and the create harness in `PackageFormDialog.newAppStep-36748.test.tsx` (it mounts `CreatePackageDialog` as Setup → Packages does). - New `studioDoorsOverview-38392.test.ts`: (1) parses every non-test source of `@object-ui/app-shell` and refuses any `studioHomePath` reference outside the two files that mean the object list (an alias counts), with a control that the census sees those two; (2) one case per door (6) that finds the door's own `studioPackageOverviewPath(...)` call inside the element, function or handler that is the door.
Local readings at head 7be2d5f1 (worktree off main d89d3e23) - Build closure `pnpm turbo run build --filter='@object-ui/app-shell^...' --concurrency=2`: 72/72 tasks, lock VERDICT command-exit 0. - Door and pin files (12 files, incl. `studioAddress*.test.ts`, `SidebarItemMenu.designFollowsPackagePosture-12615`, `PageView.editInStudioOpensStudio-12540`): Test Files 12 passed (12), Tests 206 passed (206). - Narrowed `@object-ui/app-shell` run, every test file naming a touched door, component or builder (grep for `AppNoAccessEmptyState`, `PackagesPage`, `PackageCustomizationsPanel`, `appStudioDesignPath`, `appStudioRoutePath`, `studioHomePath`, `CommandPalette`, `StudioPaletteGroups` and the door test ids): Test Files 142 passed (142), Tests 1565 passed (1565). Declared narrowing: the whole package (2462 test files) is left to CI's Test UI; `vitest related` over the changed sources ran out of heap at 4096 MB building the import graph. - `pnpm --filter @object-ui/app-shell run type-check` (src and `tsconfig.test.json`): lock VERDICT command-exit 0. - Ablation 1 (palette door rewritten to the object list on disk, `scripts/ablation-replace.mjs`): the census door case and `CommandPalette.studioScope-11863` "opens a package on its 概览 Overview" both red (`expected '/studio/com.acme.hr/data' to be '/studio/com.acme.hr/overview'`); restored, blob equals HEAD. - Ablation 2 (a `studioHomePath` alias added to `PackagesPage.tsx`): census case 1 red, naming the two references; restored, blob equals HEAD. - Derived gate families (`dispatch-gates --commands`, 40): all exit 0; `--ran` reconciliation "40 derived, 40 run, 0 NOT-MEASURED, 0 UNRUN" (a derived zero, every exit recorded). Also `pnpm --dir ui run check:new-line-citations`: 0 new citations.
## Acceptance notes - Missed by the PM census, not changed here (out of this card's file surface, and a shared server contract): the copilot's "review changes" link `studioChangesReviewPath` builds `/studio/PKG/data?changes=review`, and the server prints the same address (`packages/types/src/studio-review-links.ts`, used by the MCP authoring tools and `os meta register --draft`). It opens the Changes drawer over the object list. Whether that link is a "door that opens a package's Studio" under the ruling is put to the seat in the report; 概览 has a Pending tab (`?tab=pending`) that could be its target. - Out of scope: `studioChangesReviewPath` (the review-changes deep link) is unchanged (seat reading, 2026-11-29T06:12Z: not a door under ruling 7247357556, no new card). - Overlap: `node scripts/pm/overlap-check.mjs` reports a textual conflict with #38389 in `PackagesPage.tsx`: #38389 inserts an import directly after the `studioHomePath` import line this PR replaces. One-line resolution for whichever lands second (keep both imports). - `SidebarAppMenu.tsx` reads `appStudioDesignPath` only to gate Design layout on the package's posture (`useStudioEntryGate` reads the package id off the path); it never navigates there, and `studioPathPackageId` parses the `/overview` path the same way (`SidebarItemMenu.designFollowsPackagePosture-12615.test.tsx` green). ## Verification Files to read first, by risk: 1. `ui/packages/app-shell/src/utils/appRoute.ts` — `appStudioDesignPath` is also the fallback of `appStudioRoutePath`, so the app header's bridge moves on the app root, `system` routes and interface lists. 2. `ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx` — the shadowing local const removed; both doors now call the builder directly. 3. `ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts` — the census and its allowlist. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts` — expect 8 passed. In the running console as a workspace admin: press ⌘K in Studio, pick a package; the address reads `/studio/PKG/overview` and 概览 is shown. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5orhB2g5mxU6E4fciu --------- Co-authored-by: Claude --- .changeset/38392-studio-doors-overview.md | 10 + .../CommandPalette.studioScope-11863.test.tsx | 4 +- .../app-shell/src/chrome/CommandPalette.tsx | 8 +- .../src/console/AppNoAccessEmptyState.tsx | 7 +- ...oAccessEmptyState.emptyMenu-36748.test.tsx | 2 +- .../src/utils/__tests__/appRoute.test.ts | 18 +- ui/packages/app-shell/src/utils/appRoute.ts | 17 +- ...ackageFormDialog.newAppStep-36748.test.tsx | 8 +- ...esPage.installedAppsUpdates-34722.test.tsx | 10 +- .../src/views/metadata-admin/PackagesPage.tsx | 16 +- .../PackageCustomizationsPanel.test.tsx | 2 +- .../PackageCustomizationsPanel.tsx | 7 +- ...oPaletteGroups.surfaceScope-36900.test.tsx | 2 +- .../src/views/studio-design/studioAddress.ts | 7 +- .../studioDoorsOverview-38392.test.ts | 200 ++++++++++++++++++ 15 files changed, 266 insertions(+), 52 deletions(-) create mode 100644 .changeset/38392-studio-doors-overview.md create mode 100644 ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts diff --git a/.changeset/38392-studio-doors-overview.md b/.changeset/38392-studio-doors-overview.md new file mode 100644 index 00000000000..02b599caec6 --- /dev/null +++ b/.changeset/38392-studio-doors-overview.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): every door into a package's Studio opens its 概览 Overview + +Clause-②: no +Metadata-protocol: none + +Opening a package's Studio now lands on its 概览 Overview page from every door, the way the bare package address and Studio's own entry already did. The doors that still opened the object list now open the Overview: the command palette's (⌘K) package entries, an app's Design in Studio (the app header's bridge where the page is the app's root, a system page or an interface list with none chosen), the "Open in App Studio" of an app whose menu is empty, and in Setup → Packages the detail sheet's "Open in Studio", the landing after New Package and the customizations section's "Customize in Studio". The object list keeps its address, `/studio//data`, for anyone who wants it. diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx index 9282aa0b4cf..47f5374bf95 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.studioScope-11863.test.tsx @@ -195,11 +195,11 @@ describe('the palette in the `studio` scope lists the Studio, not an app (object expect(shown('studio-flow')).toEqual(['Onboard AccountAcme CRM', 'Nightly Cleanup']); }); - it('opens a package on its Data pillar', async () => { + it('opens a package on its 概览 Overview (objectstack#38392)', async () => { mountStudio(); await studioListed(); pick('studio-package People '); - await waitFor(() => expect(locationNow()).toBe('/studio/com.acme.hr/data')); + await waitFor(() => expect(locationNow()).toBe('/studio/com.acme.hr/overview')); }); it("opens an object in its package's Data pillar, on that object", async () => { diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index f6ac95f3f48..e928315fac4 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -84,7 +84,8 @@ import { useAuth } from '@object-ui/auth'; import { matchesPaletteQuery } from './paletteMatch.js'; import { fetchPackages, type PkgEntry } from '../views/studio-design/packages-io.js'; import { isPackageLessItem, studioOrgScopePath } from '../views/studio-design/studioScope.js'; -import { studioHomePath, studioItemPath } from '../views/studio-design/studioAddress.js'; +import { studioItemPath } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; import { flattenNavigation, useAppReportEntries } from '../views/appReportIndex.js'; import { useServedApps } from '../hooks/useLauncherApps.js'; import { servedObjectLabel } from '../hooks/servedObjectLabel.js'; @@ -1093,7 +1094,8 @@ const NO_STUDIO_ENTRIES: StudioPaletteEntries = { packages: [], objects: [], flo * * - **Packages** come from `fetchPackages`, the list the Studio landing and its * package switcher read; kernel packages are already left out there. Each - * opens its Data pillar, as a landing card does. + * opens its 概览 Overview, where every door into a package lands + * (objectstack#38392). * - **Objects** come from the metadata cache (`useMetadata().objects`), each * listed under the package it declares (`_packageId`) and opened in that * package's Data pillar. One whose package is not in the list has no Studio @@ -1196,7 +1198,7 @@ function useStudioPaletteEntries(enabled: boolean, crossPackageItems = true): St key: pkg.id, label: pkg.name, name: pkg.id, - href: studioHomePath(pkg.id), + href: studioPackageOverviewPath(pkg.id), })), objects, flows, diff --git a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx index 8d7ac8ca7a6..44896354599 100644 --- a/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx +++ b/ui/packages/app-shell/src/console/AppNoAccessEmptyState.tsx @@ -38,7 +38,8 @@ * (the only one who can also fill the menu), the no-navigation answer first * reads the app's stored menu (`/layers`, the read the design mode's menu * editor makes); when it is empty too, the screen says the menu is empty and - * opens the app's package in Studio. Everyone else, and a stored menu that + * opens the app's package in Studio, on its 概览 Overview, where every door + * into a package lands (objectstack#38392). Everyone else, and a stored menu that * holds entries this caller is not shown, keep the access answer. */ @@ -54,7 +55,7 @@ import { Button, DataEmptyState } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; import { useServedAppLabel } from '../hooks/useServedAppLabel.js'; import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; -import { studioHomePath } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; import { createAuthenticatedFetch } from '@object-ui/auth'; /** The console's authenticated fetch: the stored bearer token beside the session cookie. */ @@ -154,7 +155,7 @@ export function AppNoAccessEmptyState({ app, setupPath, reason = 'no-navigation' })} action={ diff --git a/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx index 98ce4cc308b..3d2168eddae 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppNoAccessEmptyState.emptyMenu-36748.test.tsx @@ -66,7 +66,7 @@ describe('an empty stored menu is said as such, not as missing access (objectsta expect(status).toHaveAttribute('data-reason', 'empty-menu'); expect(status).toHaveTextContent('has nothing in its menu yet'); expect(status).not.toHaveTextContent(/grant access/i); - expect(screen.getByTestId('app-empty-menu-open-studio')).toHaveAttribute('href', `/studio/${PKG}/data`); + expect(screen.getByTestId('app-empty-menu-open-studio')).toHaveAttribute('href', `/studio/${PKG}/overview`); expect(screen.queryByTestId('app-no-access-open-setup')).toBeNull(); expect(String(fetchMock.mock.calls[0]?.[0])).toBe(`/api/v1/meta/app/visits/layers?package=${encodeURIComponent(PKG)}`); }); diff --git a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts index ccb2cbef718..5ba1f3054f0 100644 --- a/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/appRoute.test.ts @@ -259,12 +259,12 @@ describe('isApprovalsInboxLink (objectstack#35505)', () => { describe('appStudioDesignPath', () => { const crm = { name: 'crm', _packageId: 'com.acme.crm' }; - it('resolves an admin viewing a packaged app to its design surface', () => { - expect(appStudioDesignPath(crm, true)).toBe('/studio/com.acme.crm/data'); + it("resolves an admin viewing a packaged app to its package's 概览 Overview (objectstack#38392)", () => { + expect(appStudioDesignPath(crm, true)).toBe('/studio/com.acme.crm/overview'); }); it('URL-encodes the package id', () => { expect(appStudioDesignPath({ _packageId: 'com.acme/crm' }, true)).toBe( - '/studio/com.acme%2Fcrm/data', + '/studio/com.acme%2Fcrm/overview', ); }); it('returns null for non-admins', () => { @@ -377,16 +377,16 @@ describe('appStudioRoutePath', () => { ); }); - it('falls back to the plain Data tab for the app root and the system area', () => { - // No route type at all (bare /apps/:pkg) → Data tab. - expect(appStudioRoutePath(crm, true, { type: undefined, name: undefined })).toBe('/studio/com.acme.crm/data'); + it("falls back to the package's 概览 Overview for the app root and the system area (objectstack#38392)", () => { + // No route type at all (bare /apps/:pkg) → 概览. + expect(appStudioRoutePath(crm, true, { type: undefined, name: undefined })).toBe('/studio/com.acme.crm/overview'); // The system settings area is not an object. - expect(appStudioRoutePath(crm, true, { type: 'system', name: 'members' })).toBe('/studio/com.acme.crm/data'); + expect(appStudioRoutePath(crm, true, { type: 'system', name: 'members' })).toBe('/studio/com.acme.crm/overview'); }); - it('falls back to the Data tab for an interface list route (no surface name)', () => { + it("falls back to the package's 概览 Overview for an interface list route (no surface name)", () => { // e.g. /apps/:pkg/page with no specific page selected. - expect(appStudioRoutePath(crm, true, { type: 'page', name: undefined })).toBe('/studio/com.acme.crm/data'); + expect(appStudioRoutePath(crm, true, { type: 'page', name: undefined })).toBe('/studio/com.acme.crm/overview'); }); it('returns null for non-admins (bridge hidden), for both surface and Data targets', () => { diff --git a/ui/packages/app-shell/src/utils/appRoute.ts b/ui/packages/app-shell/src/utils/appRoute.ts index e69d601fae8..dc2d48a0e51 100644 --- a/ui/packages/app-shell/src/utils/appRoute.ts +++ b/ui/packages/app-shell/src/utils/appRoute.ts @@ -15,7 +15,8 @@ * framework-owned, app-independent page for this user (see below). */ -import { studioHomePath, studioItemPath, studioMetadataItemAddress } from '../views/studio-design/studioAddress.js'; +import { studioItemPath, studioMetadataItemAddress } from '../views/studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../views/studio-design/studioOverviewAddress.js'; /** * The minimal app shape THESE ROUTE HELPERS read. @@ -243,8 +244,8 @@ export function isApprovalsInboxLink(actionUrl: string | null | undefined): bool /** * App → Studio reverse bridge (ADR-0080). Resolves a running app to its owning - * package's design surface (`/studio/:packageId/data`), or `null` when there is - * nothing to open: + * package's 概览 Overview (`/studio/:packageId/overview`, where every door into + * a package lands, objectstack#38392), or `null` when there is nothing to open: * - the viewer is not a workspace admin (designing mutates shared package * metadata, so the entry point is admin-only — mirrors the runtime editors); * - the app has no owning package (runtime/DB apps), or its container is the @@ -262,7 +263,7 @@ export function appStudioDesignPath( if (!isWorkspaceAdmin) return null; const packageId = studioPackageId(app); if (!packageId) return null; - return studioHomePath(packageId); + return studioPackageOverviewPath(packageId); } /** @@ -322,8 +323,8 @@ const INTERFACE_SURFACE_ROUTE_TYPES = new Set(['dashboard', 'page', 'report']); * Console `/apps/:pkg/` route types that are NOT object records — the * interface surfaces (handled above) plus the `system` settings area. Any other * route type IS the object name (see `AppHeader`'s breadcrumb switch: the - * `else if (routeType)` branch treats it as an object), so it deep-links the - * Data pillar to that object. + * `else if (routeType)` branch treats it as an object), so it deep-links that + * object's designer ({@link appStudioObjectPath}). */ const NON_OBJECT_ROUTE_TYPES = new Set([...INTERFACE_SURFACE_ROUTE_TYPES, 'system']); @@ -333,9 +334,9 @@ const NON_OBJECT_ROUTE_TYPES = new Set([...INTERFACE_SURFACE_ROUTE_TYPES, 'syste * {@link INTERFACE_SURFACE_ROUTE_TYPES}), deep-link straight to THAT item in * Studio's "All metadata" area via {@link appStudioSurfacePath}. When it names an * object record page (the route type IS the object name), deep-link that object - * in the Data pillar via {@link appStudioObjectPath}. Otherwise (bare app root, + * in its designer via {@link appStudioObjectPath}. Otherwise (bare app root, * a `system` route, or an interface list route with no surface name) fall back - * to the package's generic Data tab via {@link appStudioDesignPath}. Returns + * to the package's 概览 Overview via {@link appStudioDesignPath}. Returns * null when the bridge should not render (non-admin / no owning package). * Centralizes the route-type → surface-type mapping so `AppHeader` stays * declarative and the decision is unit-tested here. diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx index 51872f0bdc9..bf9fa2e2d9c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx @@ -74,7 +74,7 @@ import { CreatePackageDialog } from './PackagesPage'; import { useMetadataClient } from './useMetadata'; import { t, useMetadataLocale } from './i18n'; import { newAppStep } from '../studio-design/newAppDoor'; -import { studioHomePath } from '../studio-design/studioAddress'; +import { studioPackageOverviewPath } from '../studio-design/studioOverviewAddress'; import { StudioDesignSurface } from '../studio-design/StudioDesignSurface'; import { StudioPillarRedirect } from '../studio-design/StudioPillarRedirect'; @@ -189,7 +189,7 @@ function NewAppHost() { open={open} onOpenChange={setOpen} newApp={step} - onSaved={(r) => navigate(studioHomePath(r.id))} + onSaved={(r) => navigate(studioPackageOverviewPath(r.id))} /> ); @@ -306,7 +306,7 @@ describe('PackageFormDialog with a new-app step: one confirm creates the package // (`CreatePackageDialog`) offers 「同时创建应用」, ticked by default. // --------------------------------------------------------------------------- -/** `CreatePackageDialog` as Setup → Packages mounts it: Studio on the new package after create. */ +/** `CreatePackageDialog` as Setup → Packages mounts it: Studio on the new package's 概览 Overview after create (objectstack#38392). */ function CreatePackageHost() { const navigate = useNavigate(); const [open, setOpen] = React.useState(false); @@ -315,7 +315,7 @@ function CreatePackageHost() { - navigate(studioHomePath(id))} /> + navigate(studioPackageOverviewPath(id))} /> ); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx index f770ea46cde..bc526f4cd16 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx @@ -675,7 +675,7 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = // are authoring: not on this face, though the package has a draft. expect(within(sheet).queryByText(row('engine.packages.detail.pendingChanges'))).toBeNull(); expect(within(sheet).queryByText(row('engine.packages.detail.browseMetadata'))).toBeNull(); - expect(within(sheet).getByTestId('pkg-detail-open-in-studio')).toHaveAttribute('href', '/studio/app.b2r4/data'); + expect(within(sheet).getByTestId('pkg-detail-open-in-studio')).toHaveAttribute('href', '/studio/app.b2r4/overview'); }); it('CONTROL: the same package on the development surface keeps every authoring action', async () => { @@ -737,7 +737,7 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = fireEvent.click(screen.getByRole('button', { name: row('engine.packages.new') })); fireEvent.click(await screen.findByTestId('stub-create-save')); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('CONTROL: New Package on the development surface stays on the list', async () => { @@ -786,7 +786,7 @@ describe('Setup → Packages: the new-package deep link (objectstack#36908)', () // The create lands in Studio on the new package, as New Package does. fireEvent.click(screen.getByTestId('stub-create-save')); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('CONTROL: the face without the param opens no dialog', async () => { @@ -821,7 +821,7 @@ describe('Setup → Packages: New Package offers 「同时创建应用」 (objec const save = await screen.findByTestId('stub-create-save'); expect(save).toHaveAttribute('data-new-app', 'step'); fireEvent.click(save); - expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/data'); + expect(await screen.findByTestId('where')).toHaveTextContent('/studio/app.fresh/overview'); }); it('the `?new=package` door opens the dialog with the app step', async () => { @@ -882,7 +882,7 @@ describe('Setup → Packages: a read-only base’s customizations in its detail await waitFor(() => expect(within(section).getByTestId('pkg-detail-customizations-summary')).toHaveTextContent('0 customized, 1 rearranged, 0 switched off'), ); - expect(within(section).getByTestId('pkg-detail-customize')).toHaveAttribute('href', '/studio/com.acme.code/data'); + expect(within(section).getByTestId('pkg-detail-customize')).toHaveAttribute('href', '/studio/com.acme.code/overview'); }); it('an authored package’s detail draws no customizations section: it is changed in place', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index 1eac052a20f..c402be9b60c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -138,7 +138,7 @@ import { useProtocolCheckSkippedText } from '../../console/marketplace/protocolC import { ProtocolCheckSkippedNote } from '../../console/marketplace/ProtocolCheckSkippedNote.js'; import type { InstalledPackageAtEitherStage } from '@objectstack/spec/api-assembled'; import type { PackagePublishResult } from '@objectstack/spec/system'; -import { studioHomePath } from '../studio-design/studioAddress.js'; +import { studioPackageOverviewPath } from '../studio-design/studioOverviewAddress.js'; import { LooseItemsBanner } from './LooseItemsBanner.js'; import { PackageCustomizationsPanel } from '../studio-design/PackageCustomizationsPanel.js'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; @@ -591,13 +591,6 @@ function InstalledAppUpdateCell({ rowId, read }: { rowId: string; read: UpdateRe ); } -/** - * A package's Studio address: the builder on the package's Data pillar. The - * administration face's create lands here, and its "Open in Studio" link - * points here (objectstack#36834). - */ -const studioPackagePath = (packageId: string) => studioHomePath(packageId); - /* -------------------------------------------------------------------------- */ /* Create-package dialog */ /* -------------------------------------------------------------------------- */ @@ -1175,7 +1168,7 @@ export function PackageDetailSheet({ <> onOpenChange(false)} data-testid="pkg-detail-open-in-studio" @@ -2372,12 +2365,13 @@ export function PackagesPage() { onOpenChange={setCreateOpen} onCreated={async (id) => { // objectstack#36834 — created from Setup, the empty package is - // designed next: straight into Studio on it, on its Data pillar. + // designed next: straight into Studio on it, on its 概览 Overview, + // where every door into a package lands (objectstack#38392). // The development surface stays // where it is and shows the new row. if (adminFace) { forgetPackageListReads(); - navigate(studioPackagePath(id)); + navigate(studioPackageOverviewPath(id)); return; } await load(); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.test.tsx index 87d2fea463d..c6f3798b4f1 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.test.tsx @@ -192,7 +192,7 @@ describe('Setup → Packages: an installed app’s customizations (objectstack#3 stubWire(200, served({ extensions: [{ object: 'account', kind: 'field', name: 'region' }] })); const { onNavigate } = renderPanel(); - expect(screen.getByTestId('pkg-detail-customize')).toHaveAttribute('href', `/studio/${APP}/data`); + expect(screen.getByTestId('pkg-detail-customize')).toHaveAttribute('href', `/studio/${APP}/overview`); await waitFor(() => expect(rows()).toHaveLength(1)); fireEvent.click(within(rows()[0]).getByRole('link')); expect(await screen.findByTestId('where')).toHaveTextContent(`/studio/${APP}/metadata/object/account`); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx index 2d78c7f86c1..2d0a3077d00 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageCustomizationsPanel.tsx @@ -23,7 +23,8 @@ * gives one), what kind of item it is and how it changed, and opens the item * in Studio. Tabs narrow by kind and a search by text; the first rows show, * the rest behind "Show all". A read that fails says so, never "0". - * "Customize in Studio" opens the app there, the home card's Customize door. + * "Customize in Studio" opens the app there, on its 概览 Overview, where every + * door into a package lands (objectstack#38392). */ import * as React from 'react'; @@ -39,7 +40,7 @@ import { loadCustomizationLabels, type CustomizationRow, } from './packageCustomizationRows.js'; -import { studioHomePath } from './studioAddress.js'; +import { studioPackageOverviewPath } from './studioOverviewAddress.js'; /** How many rows the section shows before "Show all". */ export const PACKAGE_CUSTOMIZATION_ROWS_SHOWN = 6; @@ -163,7 +164,7 @@ export function PackageCustomizationsPanel({

{t(`${K}.heading`, locale)}

{ diff --git a/ui/packages/app-shell/src/views/studio-design/studioAddress.ts b/ui/packages/app-shell/src/views/studio-design/studioAddress.ts index 266d0190d61..fcead365e32 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioAddress.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioAddress.ts @@ -220,7 +220,12 @@ export function studioPillarPath(segment: string, pillar: string, options: Studi return studioPath(segment, pillar, null, options); } -/** A package's old Data pillar address, `/studio//data`: the route lands it on the object list. */ +/** + * A package's old Data pillar address, `/studio//data`: the route lands + * it on the object list, and it stays a working address for anyone who wants + * that list. objectstack#38392 — the doors that open a package do not build + * it: they land on its 概览 Overview (`studioPackageOverviewPath`). + */ export function studioHomePath(packageId: string, options: StudioPathOptions = {}): string { return studioPillarPath(packageId, STUDIO_HOME_PILLAR, options); } diff --git a/ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts b/ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts new file mode 100644 index 00000000000..9400d7d6aaf --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/studioDoorsOverview-38392.test.ts @@ -0,0 +1,200 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38392 — every door that opens a package's Studio lands on its + * 概览 Overview, `/studio//overview` (ruling record 7247357556 on + * objectstack#37958), not on the object list, `/studio//data`. + * + * Each door's landing is pinned in its own component's test, where it is + * clicked or read off the rendered link. This file holds the census those + * pins cannot: it parses every non-test source of `@object-ui/app-shell` + * (comments are not code, so prose may still name the old address) and + * + * 1. refuses any reference to `studioHomePath`, the object list's builder, + * outside the files listed below with the reason each keeps it — so a new + * door that reaches for it goes red here, and a local alias of it (the + * shape Setup → Packages carried) is a reference too; + * 2. finds each named door's own `studioPackageOverviewPath(...)` call, inside + * the element, function or handler that is the door. + * + * `/studio//data` stays a working address for anyone who wants the + * object list (`studioAddress.test.ts` pins the builder and the route). + */ + +import { describe, expect, it } from 'vitest'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const SRC = resolve(HERE, '../..'); + +/** The files that may still build the object list address, and why. */ +const KEEPS_OBJECT_LIST: Readonly> = { + 'views/studio-design/studioAddress.ts': 'declares the builder, and the Changes drawer review link is spelled on it', + 'views/studio-design/setupMetadataRedirect.ts': 'a retired Setup bookmark, not a door: it lands on the objects it named', +}; + +const SKIP_DIRS = new Set(['node_modules', 'dist', '__tests__', '__mocks__']); +const SOURCE = /\.(?:ts|tsx)$/; +const NOT_SOURCE = /(?:\.test|\.spec|\.stories|\.d)\.(?:ts|tsx)$/; + +function sourcesUnder(dir: string): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) { + if (!SKIP_DIRS.has(entry)) out.push(...sourcesUnder(full)); + } else if (SOURCE.test(entry) && !NOT_SOURCE.test(entry)) { + out.push(full); + } + } + return out; +} + +function parse(rel: string): ts.SourceFile { + const file = resolve(SRC, rel); + return ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX); +} + +function walk(node: ts.Node, visit: (n: ts.Node) => void): void { + visit(node); + node.forEachChild((child) => walk(child, visit)); +} + +/** Every identifier in `sf` spelled `name`. */ +function identifiers(sf: ts.SourceFile, name: string): ts.Identifier[] { + const out: ts.Identifier[] = []; + walk(sf, (n) => { + if (ts.isIdentifier(n) && n.text === name) out.push(n); + }); + return out; +} + +/** Every call of `name(...)` in `sf`. */ +function callsOf(sf: ts.SourceFile, name: string): ts.CallExpression[] { + const out: ts.CallExpression[] = []; + walk(sf, (n) => { + if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === name) out.push(n); + }); + return out; +} + +function ancestors(node: ts.Node): ts.Node[] { + const out: ts.Node[] = []; + for (let at = node.parent; at; at = at.parent) out.push(at); + return out; +} + +/** A JSX element (or self-closing one) that carries `data-testid=""`. */ +function hasTestId(node: ts.Node, id: string): boolean { + const attrs = ts.isJsxElement(node) + ? node.openingElement.attributes + : ts.isJsxSelfClosingElement(node) + ? node.attributes + : null; + return !!attrs?.properties.some( + (p) => + ts.isJsxAttribute(p) && + p.name.getText() === 'data-testid' && + !!p.initializer && + ts.isStringLiteral(p.initializer) && + p.initializer.text === id, + ); +} + +function isFunctionNamed(node: ts.Node, name: string): boolean { + return ts.isFunctionDeclaration(node) && node.name?.text === name; +} + +/** The `onCreated={...}` attribute of a ``. */ +function isCreateDialogLanding(node: ts.Node): boolean { + if (!ts.isJsxAttribute(node) || node.name.getText() !== 'onCreated') return false; + const element = node.parent.parent; + return (ts.isJsxSelfClosingElement(element) || ts.isJsxOpeningElement(element)) && element.tagName.getText() === 'CreatePackageDialog'; +} + +/** The `href: ...` of a package entry: a property assignment inside the `packages` map. */ +function isPackageEntryHref(node: ts.Node): boolean { + if (!ts.isPropertyAssignment(node) || node.name.getText() !== 'href') return false; + return ancestors(node).some((a) => ts.isPropertyAssignment(a) && a.name.getText() === 'packages'); +} + +interface Door { + door: string; + file: string; + /** The node that is the door: the overview call sits inside it. */ + is: (node: ts.Node) => boolean; + /** When the door is a property, the call must be that property's whole value. */ + within?: (node: ts.Node) => boolean; +} + +const DOORS: readonly Door[] = [ + { + door: '⌘K: a package entry of the Studio scope', + file: 'chrome/CommandPalette.tsx', + is: (n) => isFunctionNamed(n, 'useStudioPaletteEntries'), + within: isPackageEntryHref, + }, + { + door: "an app's Design in Studio (and the bare-app fallback of appStudioRoutePath)", + file: 'utils/appRoute.ts', + is: (n) => isFunctionNamed(n, 'appStudioDesignPath'), + }, + { + door: 'the empty menu: Open in App Studio', + file: 'console/AppNoAccessEmptyState.tsx', + is: (n) => hasTestId(n, 'app-empty-menu-open-studio'), + }, + { + door: 'Setup → Packages: the detail sheet’s Open in Studio', + file: 'views/metadata-admin/PackagesPage.tsx', + is: (n) => hasTestId(n, 'pkg-detail-open-in-studio'), + }, + { + door: 'Setup → Packages: the landing after New Package', + file: 'views/metadata-admin/PackagesPage.tsx', + is: isCreateDialogLanding, + }, + { + door: 'Setup → Packages: the customizations section’s Customize in Studio', + file: 'views/studio-design/PackageCustomizationsPanel.tsx', + is: (n) => hasTestId(n, 'pkg-detail-customize'), + }, +]; + +describe('no door builds the object list address (objectstack#38392)', () => { + it('studioHomePath is referenced only where the object list is meant', () => { + const offenders: string[] = []; + for (const file of sourcesUnder(SRC)) { + const rel = relative(SRC, file).split('\\').join('/'); + if (rel in KEEPS_OBJECT_LIST) continue; + const sf = parse(rel); + for (const id of identifiers(sf, 'studioHomePath')) { + const { line } = sf.getLineAndCharacterOfPosition(id.getStart()); + offenders.push(`${rel}:${line + 1}`); + } + } + expect(offenders, 'a door into a package lands on studioPackageOverviewPath, not the object list').toEqual([]); + }); + + it('CONTROL: the census sees the files it spares', () => { + for (const rel of Object.keys(KEEPS_OBJECT_LIST)) { + expect(identifiers(parse(rel), 'studioHomePath').length, rel).toBeGreaterThan(0); + } + }); +}); + +describe('each door builds the package’s 概览 Overview (objectstack#38392)', () => { + it.each(DOORS.map((d) => [d.door, d] as const))('%s', (_name, door) => { + const calls = callsOf(parse(door.file), 'studioPackageOverviewPath').filter((call) => { + const up = ancestors(call); + if (!up.some(door.is)) return false; + if (!door.within) return true; + const holder = up.find(door.within); + return !!holder && ts.isPropertyAssignment(holder) && holder.initializer === call; + }); + expect(calls.length, `${door.file}: the door's own studioPackageOverviewPath call`).toBe(1); + }); +}); From 0af813f301204e45c89814bb5643dbfab7cc1059 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:04 +0000 Subject: [PATCH 048/178] docs(qa): checklist prose names action locations in protocol 19's words (#38512) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #38046 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:平台测试清单里描述动作按钮位置的文字,换成了 19 版的新位置词,按钮位置矩阵按现在的示例应用重新推导。 - 为什么做:动作位置改名之后的最后一块收尾,前一轮已改完送去保存和安装的样例,这一轮改描述文字。 - 出错会怎样:只改测试清单文本,不碰产品代码;有问题直接撤回即可。 - 要你做什么:无 ## What changes Acceptance item 3 of the card: after this PR, `git grep` over `docs/qa/platform-checklist/**` for `list_toolbar`, `list_item`, `record_header` and `record_more` finds them only in history rows and in prose that names them as retired (records-forms.json:137, :2246, access-security.json:3084). The vocabulary is protocol 19's `ACTION_LOCATIONS` (`packages/spec/src/ui/action.zod.ts`). Placement was read from code, not word-swapped: objectui's `actionRendersAt` (`ui/packages/types/src/ui-action.ts`) answers yes for a `record` action at both `record_page` and `record_row`, and a folded record-page action is `component: 'action:menu'`. | Item | Was | Now | |:--|:--|:--| | `records-forms.action-location-matrix` (rev 18 → 19) | variants matrix of the six page-part words | re-derived from the showcase fleet as it declares now: `list` (bulk_reassign), `record` (mark_done: row menu AND title bar), `record_page` (log_time, archive_task as buttons; open_docs, recalc_selection folded under ⋯), `record_row` (quick_view, reopen_task, bulk_reassign), `record_related`, `record_section` unchanged. Title, fixtures.requires[0], knownGaps[1], the probe variant and acceptance[0], [1], [2], [4] say the same | | `records-forms.script-action-hook-refusal-toast` (5 → 6) | reopen_task `list_item` only, "Task Detail renders no record_header bar" | `record_row` only; the Task Detail page now composes a `page:header` that lists its ids and leaves Reopen out | | `records-forms.record-open-path-and-header` (1 → 2) | "three record_header actions" | Mark Done at `record`, Log Time and Archive at `record_page`, two folded under ⋯ | | `i18n.surface-matrix` (17 → 18) | revoke_my_other_sessions "a list_toolbar action" | a `list` action (it declares `locations: ['list']` in `sys-session.object.ts`) | | `ux-conventions.disabled-control-reason` (7 → 8) | Archive "record_header (declares locations: ['record_header'] only)" | declares `['record_page']` only, one title-bar button | | `access-security.packaged-permission-set-lifecycle` (retired, 2 → 3) | `list_item + record_header` on a cited file | words marked as the pre-19 words; the cited object file is removed with the object (C3 stage 8). The item stays retired and reads as the record it is | Each touched item bumps `revision` with one history row. Re-read corrections found on the way, in the matrix item: `showcase_recalc_estimate` now declares a folded `record_page` beside `record_section` (the authored header's id list leaves it out, so the desktop Task Detail draws it in the bar only); `showcase_archive_task` joins the fleet list; `showcase_task` declares no `actionLayout`, so nothing rearranges the header. ## Tests Docs-only; no test reads this prose. `pnpm check:platform-checklist` validates the files (JSON shape, revision and history pairing, the matrix item's `enumSource` pin at 6).
Gates at d31b1049 `node scripts/pm/dispatch-gates.mjs --commands` derived 17 families; each ran with its exit code captured before any pipe: ``` node scripts/check-adr-links.mjs :: exit 0 node scripts/check-adr-links.mjs --self-test :: exit 0 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/ci/plan-test-core-shards.mjs --self-test :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:platform-checklist :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 (lint built under os-verify-lock, VERDICT command-exit 0) ``` `--ran`: `17 derived, 17 run, 0 NOT-MEASURED, 0 UNRUN` (a derived zero: all 17 carry an exit code). Control-byte self-scan of the four files: no hits. `overlap-check`: `VERDICT clean exit 0`.
## Acceptance notes - The scenario builds `docs/qa/scenarios/builds/order_to_cash.json` and `travel_expense.json` still carry the four words, as metadata values, not prose. The card's own text rules them out (they declare `engines.protocol: ^19` and the artifact door replays them); this PR does not touch them. - History rows (`approvals.json:1084`, `ux-conventions.json:311`, `records-forms.json` matrix history, `:7369`, `:7387`, `studio-authoring.json:5439`) record what was true and stay as written. - Line count is 60+ / 24- in four JSON files. ## Verification Read first: `records-forms.json` around the `records-forms.action-location-matrix` variants (the re-derived matrix), then its knownGaps[1]. Two-minute check: `git grep -nE "list_toolbar|list_item|record_header|record_more" -- 'docs/qa/platform-checklist/**'` lists only history rows plus three lines that say the words are retired. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5pH8MaBBP5T2dVcTHL Co-authored-by: Claude --- .../areas/access-security.json | 10 +++- docs/qa/platform-checklist/areas/i18n.json | 10 +++- .../areas/records-forms.json | 54 ++++++++++++------- .../areas/ux-conventions.json | 10 +++- 4 files changed, 60 insertions(+), 24 deletions(-) diff --git a/docs/qa/platform-checklist/areas/access-security.json b/docs/qa/platform-checklist/areas/access-security.json index 92bbb3e7e29..ea182c942c9 100644 --- a/docs/qa/platform-checklist/areas/access-security.json +++ b/docs/qa/platform-checklist/areas/access-security.json @@ -3070,7 +3070,7 @@ "since": "v16", "status": "retired", "retiredReason": "C3 stage 8 (ADR-0131 D3) retired the sys_permission_set row object: its data door, its Activate / Deactivate / Clone row actions and its `active` column are gone. A packaged set's base stays locked at the metadata door, a copy is made with POST /api/v1/security/permission-sets/:name/clone, and a set is switched off in the activation ledger (sys_metadata_activation).", - "revision": 2, + "revision": 3, "priority": "P2", "surface": "mixed", "personas": [ @@ -3081,7 +3081,7 @@ "app": "showcase", "requires": [ "a package-declared permission set: showcase_contributor (declared by com.example.showcase in examples/app-showcase/src/security/permission-sets.ts, projected to a sys_permission_set row at boot) — the SchemaRegistry, not the row's managed_by column, is what the lock reads (packaged-permission-set-lock.ts)", - "the Setup permission-sets surface rendering the object's own actions (Activate / Deactivate / Clone on locations list_item + record_header — packages/plugins/plugin-security/src/objects/sys-permission-set.object.ts)", + "the Setup permission-sets surface rendering the object's own actions (Activate / Deactivate / Clone on locations list_item + record_header, the page-part words protocol 19 later retired — packages/plugins/plugin-security/src/objects/sys-permission-set.object.ts, removed with the object by C3 stage 8; this item is retired and records the surface as it was)", "member M granted showcase_contributor, with a showcase_contributor-only verb to probe (e.g. a project PATCH the everyone baseline does not grant — compute the baseline union per access-security.crud-permission-matrix's knownGaps before picking it)" ], "knownGaps": [ @@ -3171,6 +3171,12 @@ "date": "2026-10-12", "change": "retired — the sys_permission_set row object, its data door and its row actions are retired with C3 stage 8 (ADR-0131 D3)", "ref": "#15204" + }, + { + "revision": 3, + "date": "2026-11-29", + "change": "fixtures.requires[1] marks its location words (list_item, record_header) as the pre-19 words protocol 19 retired (#36495) and its cited object file as removed with the object, so the retired item reads as the record it is. Nothing else changed; the item stays retired", + "ref": "#38046" } ] }, diff --git a/docs/qa/platform-checklist/areas/i18n.json b/docs/qa/platform-checklist/areas/i18n.json index 9694702d065..af023c2fba6 100644 --- a/docs/qa/platform-checklist/areas/i18n.json +++ b/docs/qa/platform-checklist/areas/i18n.json @@ -185,7 +185,7 @@ "title": "Every translatable surface localizes on a zh-CN session — one pass over the full translation-group vocabulary, plus the runtime i18n routes it resolves through", "since": "v15", "status": "active", - "revision": 17, + "revision": 18, "priority": "P1", "surface": "browser", "personas": ["admin on a zh-CN session"], @@ -199,7 +199,7 @@ "the showcase's declared surface carries FROZEN untranslated debt, ratcheted by scripts/check-i18n-coverage.mjs + i18n-coverage-baseline.json — expect some declared strings to legitimately fall back to en; the per-surface check is 'translated keys render translated, untranslated keys render the SOURCE label (never a raw dotted key)', not 100% coverage", "objects._views..emptyState WAS unafforded and no longer is: the #7714 specimen has landed. examples/app-showcase/src/ui/views/task.view.ts authors an emptyState on the `urgent` view (its comment block cites #7714) and src/system/translations/index.ts carries the zh-CN half under objects.showcase_task._views.urgent.emptyState.{title,message}. The variant is runnable; the only setup it needs is an empty `urgent` view (demote the two urgent seed rows)", "objects._sections is addressable ONLY on sections that declare a `name` (packages/spec/src/ui/component.zod.ts: a nameless section renders its authored label in every locale; packages/lint's translation-section-name-missing rule nudges authors toward the name). On the stock showcase every surface this item reads declares one: showcase_task's DEFAULT form (the New/Edit form, section `task`), the task record page — examples/app-showcase/src/ui/pages/task-detail.page.ts's record:details block names its sections overview / schedule / details since #22036, reusing objects.showcase_task._sections — and showcase_contact's create and edit forms, whose sections are its four fieldGroups (#36553). QA run #23163 read all three in zh under zh-CN, so the old reading (the record page renders EN in every locale) is stale. ⚠ The named formViews tabbed / wizard / split are reachable from NO console door: `…/showcase_task/view/tabbed` is a LIST-view route and renders the grid (records-forms.form-view-gallery says why), so do not read _sections there", - "acceptance[5]'s CONFIRM half HAS a stock specimen, so it is no longer pin-only (the old reading, QA run #21782's blocked(fixture) 'no zh confirmText', parked on #22017 row 8, is stale): sys_session's revoke_my_other_sessions, a list_toolbar action on the sys_session list (packages/platform-objects/src/identity/sys-session.object.ts; confirmText 'Sign out of every other device where you're currently logged in? Your current session will remain active.'), whose zh-CN entry in platform-objects' bundle (packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts) reads 要退出你当前已登录的其他所有设备吗?当前会话将保持活跃。 with successMessage 其他所有会话已撤销. Read from source at base f68b47ca and since driven live (QA run #33853: as the zh-CN admin with a second session open, the 退出其他设备 toolbar action on /_console/apps/setup/sys_session showed the zh confirm and the zh toast): drive it the same way, capture the confirm and the toast, and record it. No showcase action declares a `confirmText` still, so the showcase's live row is the toast half (e.g. showcase_recalc_estimate's zh successMessage); the unit pins `automated` names stay the copy's pin" + "acceptance[5]'s CONFIRM half HAS a stock specimen, so it is no longer pin-only (the old reading, QA run #21782's blocked(fixture) 'no zh confirmText', parked on #22017 row 8, is stale): sys_session's revoke_my_other_sessions, a list action (the list toolbar) on the sys_session list (packages/platform-objects/src/identity/sys-session.object.ts; confirmText 'Sign out of every other device where you're currently logged in? Your current session will remain active.'), whose zh-CN entry in platform-objects' bundle (packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts) reads 要退出你当前已登录的其他所有设备吗?当前会话将保持活跃。 with successMessage 其他所有会话已撤销. Read from source at base f68b47ca and since driven live (QA run #33853: as the zh-CN admin with a second session open, the 退出其他设备 toolbar action on /_console/apps/setup/sys_session showed the zh confirm and the zh toast): drive it the same way, capture the confirm and the toast, and record it. No showcase action declares a `confirmText` still, so the showcase's live row is the toast half (e.g. showcase_recalc_estimate's zh successMessage); the unit pins `automated` names stay the copy's pin" ] }, "steps": [ @@ -380,6 +380,12 @@ "date": "2026-11-27", "change": "steps[7] and fixtures.knownGaps[2] re-anchored on the contact's field groups. They read the contact's four section headings off ui/views/contact.view.ts's default form and its one create heading (who_is_this, 这是谁) off formViews.create. The internal-form retirement (#36425) stopped the Console loading both, and #36553 deletes them: the contact's create and edit forms are laid out by the object's four fieldGroups (contact / work / status / notes), the create leaving out the fields marked showOnCreate false, and the bundle no longer carries _sections.who_is_this. Revision 13's text stays as the record of what was true at its base. No clause's assertion changed", "ref": "#36553" + }, + { + "revision": 18, + "date": "2026-11-29", + "change": "fixtures.knownGaps (acceptance[5]'s confirm specimen) names revoke_my_other_sessions' location as list, the protocol-19 word it declares in packages/platform-objects/src/identity/sys-session.object.ts (it said list_toolbar, which protocol 19 retired, #36495). The action still draws on the sys_session list toolbar. No clause changed", + "ref": "#38046" } ] }, diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index f05f041ea67..7d7bab56c92 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -2222,10 +2222,10 @@ }, { "id": "records-forms.action-location-matrix", - "title": "Action buttons surface at exactly their declared locations — list toolbar, list row, record header/more/related/section — and each dispatches for real", + "title": "Action buttons surface at exactly their declared locations — list, record (page and row), record_page (button or ⋯), record_row, record_related, record_section — and each dispatches for real", "since": "v15", "status": "active", - "revision": 18, + "revision": 19, "priority": "P1", "surface": "browser", "personas": [ @@ -2234,7 +2234,7 @@ "fixtures": { "app": "showcase", "requires": [ - "the per-location action fleet on showcase_task (examples/app-showcase/src/ui/actions/index.ts): showcase_bulk_reassign (list_item+list_toolbar, flow), showcase_quick_view (list_item, modal), showcase_mark_done (list_item+record_header, a declarative write on the default script route — operation 'update', patch {done: true, progress: 100} — visible 'has(record.done) && record.done != true'), showcase_log_time (record_header+record_related, form), showcase_open_docs (record_more, url), showcase_recalc_estimate (record_section only, api — the Task Detail quick-actions bar's action), showcase_recalc_selection (record_more, api — declares record_more ONLY, which is what keeps it off the toolbar; objectui#3142), showcase_new_task (locations: [] — the fleet's headless specimen, read by the empty-locations probe), showcase_reopen_task (list_item only, operation 'update' patch {done: false}, visible 'has(record.done) && record.done == true' — Mark Done's mirror, so a done task's row menu offers Reopen where a not-done one offers Mark Done; a click on it is refused by the showcase_guard_task_reopen hook by design, which records-forms.script-action-hook-refusal-toast drives)", + "the per-location action fleet on showcase_task (examples/app-showcase/src/ui/actions/index.ts): showcase_bulk_reassign (record_row+list, flow), showcase_quick_view (record_row, modal), showcase_mark_done (record — the record page AND each list row, one word for both; a declarative write on the default script route — operation 'update', patch {done: true, progress: 100} — visible 'has(record.done) && record.done != true'), showcase_log_time (record_page+record_related, form), showcase_archive_task (record_page, script, disabled until the task is done), showcase_open_docs (record_page folded with component 'action:menu', url), showcase_recalc_estimate (record_section, api — the Task Detail quick-actions bar's action; it also declares a folded record_page, for the standard page a phone or the side drawer shows, which the authored Task Detail header leaves out), showcase_recalc_selection (record_page folded with component 'action:menu', api — that single-record placement ONLY, which is what keeps it off the list toolbar; objectui#3142), showcase_new_task (locations: [] — the fleet's headless specimen, read by the empty-locations probe), showcase_reopen_task (record_row only, operation 'update' patch {done: false}, visible 'has(record.done) && record.done == true' — Mark Done's mirror, so a done task's row menu offers Reopen where a not-done one offers Mark Done; a click on it is refused by the showcase_guard_task_reopen hook by design, which records-forms.script-action-hook-refusal-toast drives)", "seeded tasks in both done and not-done states for the CEL visibility both-sides check" ], "provisioning": { @@ -2243,18 +2243,18 @@ }, "knownGaps": [ "NO PIN COVERS A FULL CLAUSE — `automated` was dropped at revision 13, so this P1 item is hand-driven (Tier 2). The two objectui live specs it cited are adjacent: e2e/live/list-row-action-cel.spec.ts opens the first task row's menu and asserts only that at most one Mark Done renders (not both sides of acceptance[3], nor its fail-closed half), and e2e/live/action-modal.spec.ts only that the host's row Edit opens and closes a modal (one dispatch kind of acceptance[2], on no declared action). Tier 1 run #24598 scored every clause not-run on them. Re-add `automated` only with a pin that asserts a full clause.", - "[CLOSED by #22030 (PR #22036, 60ccda5a24), lifted by #22039 — the gap text is rewritten to say where each location now lives] a stock showcase boot hosts all six locations on showcase_task, including the three this gap used to block. record_header and record_more: Task Detail (showcase_task_detail, the record page the console opens for any task), whose first node is a page:header. That header renders the action ids it lists, each placed by its own locations, followed by the host's Edit / Share / Delete. Inline (record_header) on a desktop viewport, where the header's default inline budget is 3 (1 on mobile; a record_header action past the budget folds into ⋯): showcase_mark_done (script, shown only while the task is not done), showcase_log_time (form) and showcase_archive_task (script, disabled until the task is done). Under the ⋯ overflow (record_more without record_header): showcase_open_docs (url) and showcase_recalc_selection (api). The Task Detail quick-actions bar (record_section) names the task's record_section set, showcase_recalc_estimate (api), in examples/app-showcase/src/ui/pages/task-detail.page.ts; no action the header draws is also in the bar, so each action renders once on the page (#27520 row 9). record_related: Project Detail (showcase_project_detail, the record page for any project) → the Related tab (?tab=related), which holds the Tasks related list, a record:related_list for showcase_task through its project FK; open a project that has tasks. It is an authored node, not the synthesizer's strip: the page's tabs override still replaces that strip, and this tab puts the list back with no actions key, so its rows carry showcase_log_time beside the task's list_item actions, and its header renders the list_toolbar action (Reassign…), as in 18.1 (run #25817): that list's own toolbar placement, not an extra one. The Tasks tab beside it is the record:line_items grid, which hosts no record_related action. An expected action missing from one of these hosts is a missing placement, never blocked(fixture). The hosts were read from objectui source at pin a58626c88dc8 and from the served metadata, not from a browser render, so the first run against them is their first browser evidence", + "[CLOSED by #22030 (PR #22036, 60ccda5a24), lifted by #22039 — the gap text is rewritten to say where each location now lives] a stock showcase boot hosts all six locations on showcase_task, including the three this gap used to block (the record header, its ⋯ overflow and the related list). record_page, as buttons and folded: Task Detail (showcase_task_detail, the record page the console opens for any task), whose first node is a page:header. That header renders the action ids it lists, each placed by its own locations and component (showcase_task declares no actionLayout, so no pin or more list rearranges them), followed by the host's Edit / Share / Delete. As buttons (record_page or record, with no component 'action:menu') on a desktop viewport, where the header's default inline budget is 3 (1 on mobile; a button past the budget folds into ⋯): showcase_mark_done (record; shown only while the task is not done), showcase_log_time (form) and showcase_archive_task (script, disabled until the task is done). Under the ⋯ overflow (record_page folded with component 'action:menu', the fold the retired word record_more carried until protocol 19): showcase_open_docs (url) and showcase_recalc_selection (api). showcase_recalc_estimate declares that fold too, but the header's id list leaves it out (examples/app-showcase/test/record-action-location-hosts.test.ts holds the list equal to the task's record / record_page set less the bar's actions), so on the desktop Task Detail it draws only in the bar. The Task Detail quick-actions bar (record_section) names the task's record_section set, showcase_recalc_estimate (api), in examples/app-showcase/src/ui/pages/task-detail.page.ts; no action the header draws is also in the bar, so each action renders once on the page (#27520 row 9). record_related: Project Detail (showcase_project_detail, the record page for any project) → the Related tab (?tab=related), which holds the Tasks related list, a record:related_list for showcase_task through its project FK; open a project that has tasks. It is an authored node, not the synthesizer's strip: the page's tabs override still replaces that strip, and this tab puts the list back with no actions key, so its rows carry showcase_log_time beside the task's row actions (record_row, and record, which covers record_row: Mark Done), and its header renders the task's list action (Reassign…), as in 18.1 (run #25817): that list's own toolbar placement, not an extra one. The Tasks tab beside it is the record:line_items grid, which hosts no record_related action. An expected action missing from one of these hosts is a missing placement, never blocked(fixture). The hosts were read from objectui source at pin a58626c88dc8 and from the served metadata, not from a browser render, so the first run against them is their first browser evidence", "CLOSED by the qaact-placement-specimen recipe (#26625) for acceptance[4] half (a) and acceptance[3]'s fail-closed half. A runtime-authored action is still not joined into the served object's actions[] (QA run #23163 A4: its positive control, the same probe with a location, rendered nowhere), and authoring refuses a throwing `visible` (QA run #26456), so ⛔ do not author either probe at runtime. The recipe installs both specimens through the package loader, whose actions the served object does carry. Score half (a) on qaact_no_locations and the fail-closed half on qaact_visible_throws, each only on a surface where the recipe's qaact_control renders: the list row menu and the Project Detail Related-tab row menus. Task Detail's header, ⋯ overflow and quick-actions bar list their action ids, so the control is absent there and they are no evidence for either half (the recipe's knownGaps[0]). Half (b) stays on showcase_new_task as before." ] }, "variants": [ - "list_toolbar — showcase_bulk_reassign on the task list header", - "list_item — showcase_quick_view / showcase_mark_done in the row menu", - "record_header — showcase_mark_done / showcase_log_time in the detail title bar", - "record_more — showcase_open_docs / showcase_recalc_selection under the ⋯ overflow", + "list — showcase_bulk_reassign on the task list header", + "record — showcase_mark_done on BOTH surfaces the word covers: the row menu and the Task Detail title bar", + "record_page — showcase_log_time / showcase_archive_task as buttons in the Task Detail title bar, and showcase_open_docs / showcase_recalc_selection (component 'action:menu') under its ⋯ overflow, never as buttons", + "record_row — showcase_quick_view / showcase_reopen_task / showcase_bulk_reassign in the row menu, and on no record page", "record_related — showcase_log_time on each row of the related-list section inside a record (the Tasks related list on a showcase_project record), and on no row of the showcase_task list view", "record_section — showcase_recalc_estimate in the Task Detail quick-actions bar (record:quick_actions resolves through the location filter)", - "empty-locations semantics probe — an action with NO locations key renders on NO surface, and `locations: []` likewise (objectui#3142 collapsed the renderers onto one membership predicate, `actionRendersAt`; placement is a declaration, which is why recalc_selection has to name record_more)" + "empty-locations semantics probe — an action with NO locations key renders on NO surface, and `locations: []` likewise (objectui#3142 collapsed the renderers onto one membership predicate, `actionRendersAt`; placement is a declaration, which is why recalc_selection has to name record_page)" ], "steps": [ "boot the showcase on its own port and DB; sign in as admin; open the showcase_task list view", @@ -2267,19 +2267,19 @@ ], "acceptance": [ { - "clause": "Per variant, every location the fixture actually HOSTS renders ≥1 action declared for it; record_header/record_more require a showcase_task page that composes a record header and record_related a parent record page that renders the Tasks related list (fixture must provide both).", + "clause": "Per variant, every location the fixture actually HOSTS renders ≥1 action declared for it; record_page (buttons and ⋯) requires a showcase_task page that composes a record header and record_related a parent record page that renders the Tasks related list (fixture must provide both).", "oracle": "dom", - "verify": "after each hosted surface's screenshot confirms render, the DOM read lists the expected action names in that slot; matrix compiled per variant. The stock fixture hosts all six (fixtures.knownGaps names the page and tab for record_header, record_more and record_related): an expected action absent from its host is a missing placement, never blocked(fixture)", + "verify": "after each hosted surface's screenshot confirms render, the DOM read lists the expected action names in that slot; matrix compiled per variant. The stock fixture hosts all six (fixtures.knownGaps names the page and tab for record_page and record_related): an expected action absent from its host is a missing placement, never blocked(fixture)", "evidence": "per-location screenshots + the placement matrix" }, { - "clause": "placement is EXCLUSIVE, not additive: the matrix has zero extra placements — record_more-only actions (open_docs, recalc_selection) never render in record_header or list_toolbar; the engine location-filters even explicitly-named actions (the record:quick_actions bar note in the fixture source)", + "clause": "placement is EXCLUSIVE, not additive: the matrix has zero extra placements — the folded record_page-only actions (open_docs, recalc_selection; component 'action:menu') never render as title-bar buttons or on the list toolbar, and the record_row-only ones (quick_view, reopen_task) never render on the Task Detail page; the engine location-filters even explicitly-named actions (the record:quick_actions bar note in the fixture source)", "oracle": "dom", "verify": "the placement matrix's extra-placement cells are all empty, checked against every captured surface", "evidence": "the same matrix, extra-placement columns" }, { - "clause": "each HOSTED location's sampled action DISPATCHES for real — flow wizard opens and resumes, modal opens, script executes, form opens the declared edit form view, url navigates, api POSTs — and state-changing ones round-trip server-side (mark_done flips done; recalc updates the estimate). The url (open_docs) and api (recalc_selection) legs live on record_more, under the ⋯ overflow of the Task Detail title bar", + "clause": "each HOSTED location's sampled action DISPATCHES for real — flow wizard opens and resumes, modal opens, script executes, form opens the declared edit form view, url navigates, api POSTs — and state-changing ones round-trip server-side (mark_done flips done; recalc updates the estimate). The url (open_docs) and api (recalc_selection) legs live on the folded record_page (component 'action:menu'), under the ⋯ overflow of the Task Detail title bar", "oracle": "network", "verify": "one captured dispatch per location + API re-reads for the two state changes", "evidence": "the six traces + the two re-reads" @@ -2291,7 +2291,7 @@ "evidence": "the four reads + screenshots" }, { - "clause": "empty/missing locations means NO location — the probe action with no `locations` key renders on none of the six surfaces, and the headless `locations: []` declaration (showcase_new_task) renders on none either. Placement is a declaration, not a default: objectui#3142 collapsed four disagreeing renderers onto the single `actionRendersAt` predicate, a plain membership test, so an undeclared or empty list matches nothing. recalc_selection names record_more for that reason — an explicit single-record placement that also keeps it off the toolbar, where a dispatch would carry no selection and the endpoint would reject it — NOT to opt out of an everywhere-default", + "clause": "empty/missing locations means NO location — the probe action with no `locations` key renders on none of the six surfaces, and the headless `locations: []` declaration (showcase_new_task) renders on none either. Placement is a declaration, not a default: objectui#3142 collapsed four disagreeing renderers onto the single `actionRendersAt` predicate, a plain membership test, so an undeclared or empty list matches nothing. recalc_selection names record_page (folded with component 'action:menu') for that reason — an explicit single-record placement that also keeps it off the toolbar, where a dispatch would carry no selection and the endpoint would reject it — NOT to opt out of an everywhere-default", "oracle": "dom", "verify": "both six-surface DOM sweeps (the qaact-placement-specimen recipe's packaged locations-less qaact_no_locations, and showcase_new_task) come back with an empty placement list, half (a) counted only on the surfaces where the recipe's qaact_control renders; recalc_selection is present under ⋯ and absent from the toolbar. Without the recipe half (a) scores blocked(fixture) (knownGaps) and the clause is judged on half (b) plus the recalc_selection read; a runtime-authored probe's empty sweep is never evidence for half (a)", "evidence": "the two empty placement lists + the toolbar DOM read" @@ -2422,6 +2422,12 @@ "date": "2026-11-01", "change": "The Task Detail page draws each task action once (#27520 row 9: the walkthrough saw Mark Done, Log Time and Archive both in the header and as a button row in the body). The quick-actions bar now carries the task's record_section set alone, showcase_recalc_estimate, which declares record_section only, and Mark Done, Log Time and Archive drop record_section. fixtures.requires[0], the record_section variant and knownGaps[1] re-pointed: record_section is still hosted on showcase_task, by Recalculate Estimate in the bar, and the ⋯ overflow keeps open_docs (url) and recalc_selection (api). Read from the examples source at this branch, not a browser run; no clause changed", "ref": "#27520" + }, + { + "revision": 19, + "date": "2026-11-29", + "change": "Re-derived for protocol 19's location words (#36495; ACTION_LOCATIONS in packages/spec/src/ui/action.zod.ts), read off the showcase fleet as it now declares them and off objectui's placement predicate (ui/packages/types/src/ui-action.ts actionRendersAt: record answers both record_page and record_row; a folded action is component 'action:menu'). The variants matrix is the six new words: list (bulk_reassign), record (mark_done, on the row menu and the title bar), record_page (log_time and archive_task as buttons; open_docs and recalc_selection folded under ⋯), record_row (quick_view, reopen_task, bulk_reassign), record_related and record_section unchanged. The title, fixtures.requires[0], knownGaps[1], the probe variant and acceptance[0], [1], [2], [4] say the same. Corrections the re-read found: showcase_recalc_estimate declares a folded record_page beside record_section (the authored header's id list leaves it out, so the desktop page draws it in the bar only); archive_task joins the fleet list; showcase_task declares no actionLayout. Until 19 the words were list_toolbar, list_item, record_header and record_more. No clause's assertion changed beyond the vocabulary", + "ref": "#38046" } ], "enumSource": { @@ -6321,7 +6327,7 @@ "title": "A script action whose server-side hook refuses the write with a user-facing sentence answers a 4xx, the console shows exactly one error toast carrying that sentence, and the record is left unchanged", "since": "v17.5", "status": "active", - "revision": 5, + "revision": 6, "priority": "P2", "surface": "browser", "personas": [ @@ -6330,7 +6336,7 @@ "fixtures": { "app": "showcase", "requires": [ - "the refusal pair on showcase_task: the hook showcase_guard_task_reopen (examples/app-showcase/src/data/hooks/index.ts — beforeUpdate, condition previous.done == true && record.done != true, sandboxed body throws new Error(TASK_REOPEN_REFUSAL), onError:'abort') and the action showcase_reopen_task (examples/app-showcase/src/ui/actions/index.ts — a declared record write: operation 'update' with patch { done: false } and no body, which the action route performs as the caller, execution perRecord, visible 'has(record.done) && record.done == true', locations list_item only — the Task Detail page is kind:'full' and renders no record_header bar)", + "the refusal pair on showcase_task: the hook showcase_guard_task_reopen (examples/app-showcase/src/data/hooks/index.ts — beforeUpdate, condition previous.done == true && record.done != true, sandboxed body throws new Error(TASK_REOPEN_REFUSAL), onError:'abort') and the action showcase_reopen_task (examples/app-showcase/src/ui/actions/index.ts — a declared record write: operation 'update' with patch { done: false } and no body, which the action route performs as the caller, execution perRecord, visible 'has(record.done) && record.done == true', locations record_row only — so the task list's row menu offers it, and the Task Detail title bar, whose page:header lists its action ids and leaves this one out, does not)", "the refusal sentence, verbatim: 'A finished task cannot be reopened. Create a follow-up task instead.' (TASK_REOPEN_REFUSAL in the hooks file — re-read it there before the run, never from this line)", "a seeded FINISHED task (done: true) — 'Audit current IA' or 'App wireframes' (examples/app-showcase/src/data/seed/index.ts) — which is the only kind of record the action is offered on", "a console built from this checkout's ui/ tree (pnpm console:build, which copies ui/apps/console's build into packages/console/dist), served by the same boot the run drives", @@ -6429,6 +6435,12 @@ "date": "2026-10-26", "change": "fixtures.knownGaps[0] said the console-half pin lives in the objectui repo and is not runnable from this checkout; it is at ui/packages/app-shell/src/utils/__tests__/consoleServerAction.errorToast.test.ts and runs from ui/ with that package's vitest, so the note says where it is and how it runs, and still says it stubs fetch and the toast sink and is not this item's evidence (devx seat 2 REVISE on #26125). Re-read on main cc378e93. No clause changed", "ref": "#25846" + }, + { + "revision": 6, + "date": "2026-11-29", + "change": "fixtures.requires[0] names showcase_reopen_task's protocol-19 location, record_row (it said list_item, a word protocol 19 retired, #36495), and drops the stale reason beside it: the Task Detail page (kind 'full') does compose a page:header now, which lists its action ids and leaves Reopen out (examples/app-showcase/src/ui/pages/task-detail.page.ts), so the row menu is still the one place it is offered. No clause changed", + "ref": "#38046" } ] }, @@ -7671,7 +7683,7 @@ "title": "An object's list opens a record one way — the name opens the full page, the hover icon beside it the side drawer — and the record's header is two rows: the way through the list (↑ ↓, 「第 N 条,共 M 条 · 视图名」, ✕) over the record (its name, chips and up to three actions), with the tabs right under it", "since": "v18.7", "status": "active", - "revision": 1, + "revision": 2, "priority": "P1", "surface": "browser", "personas": [ @@ -7681,7 +7693,7 @@ "app": "showcase", "requires": [ "a fresh boot of the showcase (the live lane's `ui/e2e/live/ci/start-backend.sh`, or `pnpm dev -- --fresh --seed-admin`)", - "the showcase_account list (14 seeded accounts, a synthesized record page with a tab row) and the showcase_task list (its showcase_task_detail page authors three record_header actions: Mark Done, Log Time, Archive)" + "the showcase_account list (14 seeded accounts, a synthesized record page with a tab row) and the showcase_task list (its showcase_task_detail page's header draws three record-page buttons: Mark Done at record, Log Time and Archive at record_page; Open Docs and Recalculate Selection are folded under ⋯)" ] }, "steps": [ @@ -7773,6 +7785,12 @@ "date": "2026-11-20", "change": "initial — the one open path (#35854, maintainer ruling 「废弃」 on the open preference and navigation.mode) and the two-row record header (#35853, with the gap above the tabs of #35745), read from the PR branch and driven live against the showcase", "ref": "#35854" + }, + { + "revision": 2, + "date": "2026-11-29", + "change": "fixtures.requires[1] names the task page's header actions in protocol 19's words (#36495): Mark Done is placed at record, Log Time and Archive at record_page, and the two folded record_page actions sit under ⋯ (it said three record_header actions, a retired word). Read from examples/app-showcase/src/ui/pages/task-detail.page.ts and src/ui/actions/index.ts. No clause changed", + "ref": "#38046" } ] } diff --git a/docs/qa/platform-checklist/areas/ux-conventions.json b/docs/qa/platform-checklist/areas/ux-conventions.json index 1d351029d3c..ce3936ad804 100644 --- a/docs/qa/platform-checklist/areas/ux-conventions.json +++ b/docs/qa/platform-checklist/areas/ux-conventions.json @@ -216,7 +216,7 @@ "title": "Every disabled control explains itself — the reason shows on hover and on keyboard focus, and is exposed as an accessible description", "since": "v17.7", "status": "active", - "revision": 7, + "revision": 8, "priority": "P1", "surface": "browser", "personas": [ @@ -230,7 +230,7 @@ "the read-only showcase package in Studio (stock)" ], "knownGaps": [ - "FIXED, now the calibration reference (objectui#11811): the task record's Archive button (examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction, disabled while has(record.done) && record.done != true) carries its reason as a tooltip AND an aria-describedby on a focusable wrapper, in its one placement, record_header (it declares locations: ['record_header'] only; objectui DeclaredActionsBar.tsx; pin DeclaredActionsBar.disabledReason-11811.test.tsx). It declares its own reason, disabledReason: 'Mark the task done first.' (the action spec's disabledReason, #26619), so the text is the author's, not the generic platform fallback — record it as specific under clause 3. Check this control first to calibrate both the hover and the keyboard oracle", + "FIXED, now the calibration reference (objectui#11811): the task record's Archive button (examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction, disabled while has(record.done) && record.done != true) carries its reason as a tooltip AND an aria-describedby on a focusable wrapper, in its one placement, a button in the Task Detail title bar (it declares locations: ['record_page'] only; objectui DeclaredActionsBar.tsx; pin DeclaredActionsBar.disabledReason-11811.test.tsx). It declares its own reason, disabledReason: 'Mark the task done first.' (the action spec's disabledReason, #26619), so the text is the author's, not the generic platform fallback — record it as specific under clause 3. Check this control first to calibrate both the hover and the keyboard oracle", "Studio's Publish button on the read-only showcase package and the import wizard's disabled Next are FIXED for the keyboard (QA run #23953 at objectui daeb77fc84dd): each carries its reason on a focusable wrapper with an aria-describedby, so both now calibrate hover AND keyboard, expected PASS; the field inspector's Remove passes the same way (the automation Enabled switch is not a row: it stays enabled on a read-only package, variants[2]). Regression rows, expected PASS since QA run #24570 (objectui 4016370a, two fresh loads each): the field inspector's read-only Label / API name / Type / Required / Move up-down sit in a focusable panel wrapper described by the read-only reason, with the tooltip on focus (objectstack-ai/objectui#12303, closed by objectui PR #12324, b64fda3f — the rail body described by fieldRailReasonId, StudioDesignSurface.tsx); and the Studio validation editor's body on a read-only package is a role=group tab stop described by the reason, with the tooltip on hover and focus (objectstack-ai/objectui#12691, closed by objectui PR #12833, d0a00d79, ObjectValidationsPanel.tsx). Both fixes are in the console pin 4016370a and on objectui main" ] }, @@ -322,6 +322,12 @@ "date": "2026-11-15", "change": "variants[5]: 'Reassign…' renders disabled for the admin and is not rendered for a plain member, so the member leg records it not offered (QA run #33861, comment 6894395705; ledger 6896511848 of #33761 row 180). The clauses are unchanged. Read at base 895783a1", "ref": "#33981" + }, + { + "revision": 8, + "date": "2026-11-29", + "change": "fixtures.knownGaps (the Archive calibration control) names Archive's protocol-19 location, record_page, which examples/app-showcase/src/ui/actions/index.ts#ArchiveTaskAction declares (it said record_header, which protocol 19 retired, #36495). It is still drawn once, as a title-bar button. No clause changed", + "ref": "#38046" } ] }, From be1cc0617fc6a1d745021a9091e6bcdfb98df8ad Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:28:23 +0000 Subject: [PATCH 049/178] docs(adr): ADR-0161 dated note, a knowledge source declares how its hits are ordered for the caller and what a hit brings (#38511) 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 #38502 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`, 25 lines added and none removed against `main`, in three places: - **Header.** A fourth `**Amended**` line, dated 2026-11-29, in the shape of the three before it. It quotes the maintainer's choice 「A 精简:排序加带出」 and names ruling record `7251603512` on the decision card #38412. - **K1, under "What follows from the two lists".** The dated note. It amends by name the sentence "The service does not choose a model, compute a vector, score a candidate, rerank or parse a file" and gives its new reading: the service still computes no score, and may re-order the hits it is about to answer by an ordering their source declares against a platform-resolved fact about the caller, by position alone. The sentence itself, both K1 tables, the K8 table and every earlier note are left as written. - **K4.** One cross-reference line in the block that is there, saying the two source keys are declared by the K1 note and land with their readers. What the note fixes, executing the ruling record's conditions as written: no `filter` mode; the caller fact is a closed list the platform resolves and never a value a client or a model supplies; several `affinity` entries add and a source declares at most one `nearest`; the re-order applies to the unit returned (passage, record or group) inside the existing refill bound and reports no count; the tool gains no opt-out argument; `recency` is not in this note. Choices the note makes past the ruling's words, each marked ◆ in the text for the approver to accept or strike: 1. **The keys sit on the object arm**: `source.affinity` (entries `{ field, caller, mode, places? }`) and `source.expand` (`{ window?, follow? }`), with no wrapper key. 2. **The caller facts are a closed list of two**: `user` and `business_unit` (the primary unit and its parents), both read from the one resolver the caller-identity card #38363 builds. 3. **A boost combines by position, never by score** (the first point the ruling left open). Per source, `nearest` parts that source's units into tiers by distance in the caller's unit chain; inside a tier a `boost` moves a matching unit up by `places`. A hit keeps the score its adapter answered. 4. **Neighbouring passages are cut again from the record; no adapter member is added** (the second point the ruling left open). K8's closed list stays closed. - Review finding S1, rule chosen: neighbours are attached only when the passage cut at the hit's id is the hit's own `snippet`, character for character. Chosen over "only when `indexStatus` answers the expected fingerprint" because it judges the text the service holds, not a report from an optional member, so it is one rule for an adapter with `indexStatus` and one without, and it fails closed on an adapter whose snippet is not the passage. - Review nits N1 to N3 are taken in the note: `expand.window` is marked ◆ and names the heading-bounded mode it leaves out; `places` has no bound until #38503 sets one; a `follow` whose target the record tools serve to no caller is among the refusals. 5. **`expand.follow`** brings the related record's object, id and title, one hop, read as the caller. 6. **An expansion rides on the tool's hit** (`neighbours`, `related`) as a result of the service, so the hit an adapter answers gains no key. The note names the slice cards that build it: #38504 (`expand.window`), #38503 (`affinity`, after the caller-identity card #38363, with the ruling's three-arm measurement as its acceptance), #38505 (`expand.follow`). No code, no schema, no contract member, no changeset: the record declares and implements nothing. `skip-changeset` is declared on this pull: `docs/adr/**` publishes from no released package. ### Read first, by risk 1. The bullet "◆ By position, never by score". Two things to weigh: the re-order is per source (a source's units move only among the places that source's units hold, so another source's hit never moves), and `nearest` is a strict tiering inside the candidates the search already read, not a bounded lift. 2. The bullet "◆ Neighbouring passages are cut again from the record; no adapter member is added". It rests on three readings taken at `545a4fa278`: a passage carries no offset and is not a slice of the document's text; the splitter is pure and the fingerprint covers the applied split; the service already makes the same read and hash comparison in two places. 3. The bullet "◆ `expand.follow`". It reads the slice card's "declared fields" as the hop's object, id and title, and sends a list of fields to bring back to a later dated note. ## Tests None. The diff is one Markdown file under `docs/adr/`; no tested behaviour changes, so nothing is ablated. ## Acceptance notes - **Measured facts the two open points rest on**, all read on `main` at `545a4fa278`: - `knowledge-pgvector` and `knowledge-turso` answer a reciprocal rank fusion (`RRF_K` 60 in both) divided by the score of a passage first in both legs: ranks 1 to 10 in both legs score 1 down to 61/70, and a passage only one leg ranks scores at most 0.5. `knowledge-memory` answers the raw cosine similarity. `KnowledgeHitSchema` says the meaning of `score` is each adapter's. - The service orders merged hits by that score and nothing else (`kept.sort((a, b) => b.score - a.score)` in `searchByKey`, and the same comparison in `answerByRecord`). - `KnowledgeChunkSchema` carries `id`, `documentId`, `index`, `content`, `headingPath?`; no offset. Under `markdown` a passage begins with its heading path and a table cut between rows repeats its header row. - `IKnowledgeAdapter` has no method that reads a passage by document and index. All three in-tree adapters declare `capabilities.chunks` and store the passage ids the service sets. - `splitDocument` is pure; the fingerprint covers the resolved split and the split algorithm version; `checkFreshness` and `dropUnverifiedHits` already read a hit's record, assemble it and compare `docHash`. - **The caller-identity card #38363 is a draft, not merged** (branch `claude/issue-38363-mcp-asker-identity` at `0cea24a56c`, no pull request open on it when this was read). Its resolver answers the user, the active organization, and the primary business unit with its parents, each read as the caller. The note names the two facts it takes, not the resolver's code. - Noted, not filed (carrier in brackets): - That resolver lives in `packages/runtime/src/domains/mcp.ts` on its branch, a package `service-knowledge` does not depend on. The note leaves where it lives to the `affinity` slice and the caller-identity card. [carrier: #38503] - The `expand.window` slice card asks for work in "both stores"; under this note no store changes, because neighbours are cut again from the record. [carrier: #38504, the seat's to reword] - The `expand.follow` slice card's acceptance says "declared fields"; the note reads that as object, id and title. [carrier: #38505, the seat's to reword] - The 维护者速读 carries two sub-lines under its fourth line: the order asks for the two open points in one line each, and the agent file caps the section at four lines. ## Verification Two-minute check: `git diff --stat origin/main...HEAD` prints one file, 25 insertions and no deletion; then `pnpm check:adr-symbol-anchors` exits 0 with its ✅ line, which shows every `path#symbol` the note cites resolves.
Local gates at head ec46fbc986 (21 derived, 21 run, each exit 0) Derived with `node scripts/pm/dispatch-gates.mjs --commands` (no path passed; 1 changed path, +25 / -0 against merge base `545a4fa27`) and reconciled with `--ran`: "21 derived famil(ies) accounted for — 21 run, 0 NOT-MEASURED (a DERIVED zero — all 21 recorded an exit code and none of them is 3)". - `node scripts/check-adr-links.mjs` and its `--self-test` :: exit 0 ("1281 relative link destination(s) under docs/adr/ resolve") - `pnpm check:adr-anchors` :: exit 0 - `pnpm check:adr-index` :: exit 0 ("docs/adr/README.md is current, every record parsed") - `pnpm check:adr-symbol-anchors` :: exit 0 ("4561 anchors across 165 records resolve ... 0 line anchors survive") - `pnpm check:doc-authoring` :: exit 0 - `pnpm --filter @objectstack/lint run check:doc-formula-expressions` :: exit 0 (after building `@objectstack/formula` and `@objectstack/lint` under the verify lock, VERDICT command-exit 0) - `node scripts/check-closing-keyword-parity.mjs` and its `--self-test` :: exit 0 - `node scripts/check-comment-mask-corpus.mjs` :: exit 0 ("24362 files, 0 disagree, 0 unparseable") - `node scripts/ci/plan-test-core-shards.mjs --self-test` :: exit 0 - `pnpm check:ci-filter-parity`, `check:closed-ceremony-text`, `check:cross-package-test-inputs`, `check:driver-memory-census`, `check:gitlink-declared`, `check:nul-bytes`, `check:pm-governed-merges`, `check:pm-prior-rulings`, `check:refd-timer-probe`, `check:watch-hint-literal` :: exit 0 each The whole list was run again at `ec46fbc986`, after the rework commit, with `node scripts/pm/overlap-check.mjs` before the push (VERDICT clean, exit 0). At the first head, seven of these exited 3 on the first pass (PREREQUISITE NOT MET: the worktree had no `node_modules`, then two unbuilt packages); each was run again after `pnpm install` and the build and exited 0. The repo-wide scans and the full check farm are left to CI.
🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ...urn-knowledge-source-is-a-governed-type.md | 25 +++++++++++++++++++ 1 file changed, 25 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 a4b140313ec..e8612d48a02 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 @@ -19,6 +19,7 @@ - **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. +- **Amended** (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)): a fourth dated note, under "What follows from the two lists" in [K1](#k1--the-boundary), amends that list's sentence "The service does not choose a model, compute a vector, score a candidate, rerank or parse a file": the service may re-order the hits it is about to answer by an ordering their source declares against a fact about the caller, by position and never by score, and a source may declare what a hit brings with it (`source.affinity`, `source.expand`). It is written on the maintainer's ruling of that day, his choice of the decision card's option 「A 精简:排序加带出」 (record [`7251603512`](https://github.com/objectstack-ai/objectstack/issues/38412#issuecomment-7251603512) on #38412). It adds no contract member. A cross-reference stands under [K4](#k4--knowledge_source-is-admitted-as-a-metadata-type). The status line above is left as it is. --- @@ -112,6 +113,28 @@ Ruling D1, as two lists. The left one is the knowledge service's work, done once - The split strategies and their rules belong to the splitter's card, #37098 (`whole`, `recursive`, `markdown`, aware of Chinese text). This record fixes who owns the split and where its key lives (K8, item 10). - **Why the purge and the grouping run in the service, not in SQL** (Prime Directive #5). The index sits behind the adapter contract and may live in another store than the records, so the anti-join that finds stale documents and the grouping of hits by record cannot be pushed down in general. An adapter that shares a database with the records may do either in SQL later; that is K8's item 13, and it comes back with its reader. +> **Note (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)) — the second sentence of the list above: the service may re-order what it answers by an ordering the source declares against a fact about the caller, by position and never by score; and a source may declare what a hit brings with it.** The maintainer's words of 2026-11-29, verbatim and untranslated, as the filing gate of #38412 records them: 「检索按提问人单位加权,每种知识的要求不同吧,你的评估不能只考虑当前的规章制度,要考虑客户可能开发的各种元数据应用」. He ruled that day by choosing the decision card's option 「A 精简:排序加带出」, whose line on the card reads 「平台按提问人排序(加权、本单位就近优先),命中带出相邻或关联内容;不做硬筛选,按时间衰减等有应用要再加。一份架构记录加约三个 PR。」 (ruling record [`7251603512`](https://github.com/objectstack-ai/objectstack/issues/38412#issuecomment-7251603512) on #38412; the analysis is comment `7251063339` there). That record leaves three things to this note: the key names and shapes, how a boost combines with the stores' scores, and how neighbouring passages are read. A ◆ marks what this note decides past the ruling's words, for the approver to accept with it or strike. The conditions the ruling record carries are written below as given and are not marked. +> +> - **The sentence, amended.** The list above says: "The service does not choose a model, compute a vector, score a candidate, rerank or parse a file." From the merge of this note it reads: "The service does not choose a model, compute a vector, compute a score for a candidate, rerank or parse a file. It may re-order the hits it is about to answer by the ordering their source declares against a fact about the caller that the platform resolves, by position alone, and it changes the order the adapters answered in no other way." This is not rerank, which stays the adapter's in the table above: the service reads no passage text and calls no model to do it. It falls on the platform's side by K1's own test ("facts only the platform has"): who the caller is and where they sit in the organization is such a fact. The two tables, "Why the line is here" and the other sentences of the list are unchanged. +> - **◆ The keys, on the object arm.** `source.affinity?` and `source.expand?`, beside `metadataFields` and `split`, for item 10's reason: both name fields of the indexed object, so a later arm brings its own. A source that declares neither is answered exactly as before this note. No wrapper key holds the two: it would be a level kept for a third member this note does not admit, and no key is reserved (K4). +> - **`affinity`.** A list of entries `{ field, caller, mode, places? }`. `field` is a member of the source's `metadataFields`. `caller` names one fact from the closed list below. `mode` is `boost` or `nearest`, and nothing else: there is no `filter` mode, because narrowing is the search scope (item 17) and visibility is sharing. `boost` takes `places`, a positive integer; this note fixes no upper bound, and #38503 sets one and states it on the key. `nearest` takes none, reads a hierarchy, and a source declares at most one. Several entries add. +> - **◆ The caller facts are a closed list of two.** `user`: the caller's user id; `field` is then a field whose reference target (`packages/spec/src/data/field-value.zod.ts#referenceTargetOf`) is `sys_user`, and an entry matches a hit whose value is that id. `business_unit`: the caller's primary business unit, then each parent up to the root; `field` is then a field whose target is `sys_business_unit`, a `boost` entry matches a hit whose value is any unit of that chain, and `nearest` reads the chain in order. A list value (a lookup declared `multiple: true`) matches when an element does, and `nearest` takes its nearest element. Values are compared as a scope term compares them. Both are facts the resolver of [#38363](https://github.com/objectstack-ai/objectstack/issues/38363) answers, and the ordering reads that one resolver's answer, as the caller may read it about themselves, so a unit the caller may not read ends the chain below it. The resolver's third fact, the active organization, is left out: the organization filter of item 9 already decides which organizations' documents are ranked, and no application asks to order by it. The platform resolves a fact from the execution context the search already carries, at most once per search and only when a searched source declares an entry that reads it. It is never an argument of the tool, an option of `search`, or a value a client or a model supplies. The system identity is no caller in this sense, and a caller with no primary unit has no chain: an entry that finds no fact matches nothing. The active organization, positions, teams and non-primary memberships are not in the list; each joins it by a dated note here, with its resolver and its first reader. +> - **What is re-ordered.** The search runs as it does today up to its answer: the rounds, the scope check, the permission re-check, the per-hit record check, and the grouping under record granularity. What that leaves is the units that could be answered, best first by the adapters' scores: passages, or records, or `groupBy` groups, each standing as one hit. Today the first `topK` of them are answered. The re-order works on that list, before the cut to `topK`, and on nothing else. It asks no adapter again and changes neither the size of a round nor the condition of the refill, so a search still reads at most `topK × SEARCH_REFILL_FACTOR` passages per source (`packages/services/service-knowledge/src/knowledge-service.ts#SEARCH_REFILL_FACTOR`). A caller the re-check applies to is already asked `topK × SEARCH_FIRST_ROUND_FACTOR` per source in the first round, so there are units below `topK` to bring up. Under record granularity the freshness check then checks the hits about to be answered, as today. Nothing in the answer says that a hit moved or how far, and no count is returned (K9 rule 6, K10 rule 4); the moves go to the `debug` log. +> - **◆ By position, never by score.** (1) Per source: the units of one source are re-ordered among the places that source's units hold in the list, and a unit of another source is never moved. A declaration is one source's, and `nearest` means nothing for another source's hit. How units of different sources stand against each other stays what it is today. (2) A unit is judged on the hit that stands for it: that hit's source, and that hit's `metadata[field]`. (3) `nearest` parts the source's units into tiers: the caller's own unit first, then each parent in order, then every other unit together, a hit with no value among them. (4) Inside a tier, with its units numbered from 1 in their order, a unit's key is its number minus the sum of `places` of the `boost` entries it matches. The tier is ordered by key; a tie goes to the larger sum, then to the earlier number. So a unit that matches one entry with `places: 3` passes at most three units of its tier that match nothing, and a source without `nearest` is one tier. (5) A hit keeps the `score` its adapter answered. The service writes no score of its own, so an answer may no longer be in descending `score`. +> - **◆ Why position.** Read at `545a4fa278`: `knowledge-pgvector` and `knowledge-turso` answer a reciprocal rank fusion of two legs (`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts#RRF_K`, `packages/plugins/knowledge-turso/src/turso-adapter.ts#RRF_K`, both 60), divided by the score of a passage first in both legs. The passages ranked first to tenth in both legs score from 1 down to about 0.87, and a passage only one leg ranks scores at most 0.5. `knowledge-memory` answers the cosine similarity itself, and the hit's schema says the meaning of `score` is each adapter's (`packages/spec/src/ai/knowledge-document.zod.ts#KnowledgeHitSchema`). So a number added to a score, or multiplied into it, orders one source differently on each store: `+0.1` lifts a hit ranked ninth in both legs to second on the two SQL stores, and on the memory store past however many hits lie within 0.1 of it. A source is written once and builds on every store (K4), and a search over several sources may read several stores. Every adapter answers its hits best first, whatever its numbers mean, so position is the one thing the service can read alike from all of them. It also keeps what the amended sentence still forbids: the service computes no score. The other answers: adding to or multiplying the score, for the reason above. A rank fusion with the declaration as one more leg, which reads positions too: with the stores' constant, a weight near 1 puts every match above every non-match in a first round of 25 passages (the tool's default `topK` of 5), and a smaller weight has no unit an author can check. Matches first with no number, which is what `nearest` is: for a `boost` it would put a weak match above the best passage every time, and the ruling names both. +> - **Judged on the index copy; never an access decision.** An entry is judged on the values assembly stored with the document, as a scope term is, fresh as of the last sync. A document indexed before its source listed the field carries no value and matches nothing until a rebuild writes it again. The order tells a caller nothing they could not work out themselves: source admission already requires every `metadataFields` member to be queryable by the caller before the source is searched for them, and the facts are the caller's own. The re-order moves hits that passed the re-check; it removes none and admits none. +> - **◆ `expand.window`.** A positive integer: the passages on each side of the hit's passage, in the same document, that the hit brings with it, counted across headings. The heading-bounded mode of the decision card (`siblingsBy`) is not taken: it returns by a dated note here with a consumer. They are not hits: they are not counted in `topK`, they are not ordered, and no passage is answered twice in one answer, so a neighbour that is itself answered as a hit, or that an earlier hit already brought, is left out. Under record granularity the neighbours are those of the passage that stands for the record or the group. #38504 bounds the key and states the bound on it; this note fixes no number. +> - **◆ Neighbouring passages are cut again from the record; no adapter member is added.** Read at `545a4fa278`. A passage carries `id`, `documentId`, `index`, `content` and `headingPath?` (`packages/spec/src/ai/knowledge-document.zod.ts#KnowledgeChunkSchema`) and no position in the document's text. Its text is not a slice of that text either: under `markdown` a passage begins with its heading path, and a table cut between rows repeats its header row in each piece. So a neighbour is a passage, not a range, and there are two ways to have it. No method of the adapter contract reads a passage by document and index (`packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`); adding one reopens the list rule 5 of K8 closes. The other way needs no member. The splitter is pure (`packages/services/service-knowledge/src/split/splitter.ts#splitDocument`), the fingerprint covers the applied split and its algorithm version, and a search is served only under the fingerprint the service expects (K7 rule 5), so a document whose hash is the hit's `docHash` cuts again into the passages the index holds, index for index. The service already reads a hit's record, assembles it and compares that hash in two places: the freshness check of a record-level search, and the per-hit record check (`checkFreshness` and `dropUnverifiedHits` of `packages/services/service-knowledge/src/knowledge-service.ts#KnowledgeService`). **So the service does that for the hits it is about to answer, at most `topK`, cuts each matching document again, and takes the passages around the one whose `id` is the hit's `chunkId`.** ◆ One more check stands on that passage, because the fingerprint is an optional member (rule 2 of K8; K7 has a row for an adapter with no `indexStatus`) and `docHash` does not cover the split: an adapter that does not hold a search to the fingerprint may still answer passages cut under an earlier split. So neighbours are attached only when the `content` of the passage cut at that `id` is the hit's `snippet`, character for character, which is what a passage's `content` is defined as. The service judges the text it holds and nothing an adapter reports, so the rule is the same for an adapter with `indexStatus` and one without. It costs one read per source, of those records only, projected to the fields assembly reads, and a split in memory; no adapter is called and nothing is embedded. Why this one: every adapter that takes chunks gets it with no change, where an optional member would bring nothing on an adapter that lacks it (rule 2); and a neighbour is text of the record as it reads now, where a member would answer the index copy, which K10 rule 3 keeps for ranking and snippets. The price: a long document is read whole to bring a few passages. A member that reads passages by position returns by a dated note here, with a store as its reader, when that cost is measured on a real source. +> - **When a hit brings no neighbours.** Its adapter does not declare `capabilities.chunks`, so its passages are its own (the service says so once in its log, naming the adapter; rule 2). The hit carries no `docHash` or no record id. The record's hash is not the hit's, so the index is behind the record: the hit is answered as it is today, and its document is repaired as the freshness check repairs one. The cut holds no passage with the hit's `chunkId`, or that passage's `content` is not the hit's `snippet`: the store's passages were cut under another split, or its snippet is not the passage. The read fails. In each case the hit is answered without neighbours and nothing in the answer says why. A neighbour is attached only for a row that passed the caller's re-check in this search, and it is cut from fields the source admission already requires that caller to be able to query. +> - **◆ `expand.follow`.** A list of field names: `lookup` or `master_detail` fields of the indexed object that the source lists in `metadataFields`, one hop each. A hit brings, for each, the record the field points at: its object, its id and its title, the title being that object's display field as a hit's title is (K5). The id is read from the hit's record as it reads now, and the related record is read as the caller, under every gate a read of that object through the record tools passes. Nothing of it is stored in an index. A related record the caller may not read, one that no longer exists and an empty lookup all bring nothing, with no marker and no count; the answer then says no more than the row itself says to a caller who may query the field. The hop brings the name, not the content: an answer reads content as the asking user through the record tools (K10 rule 3), and a model that wants the related record's own passages searches with `scope` (item 17). So #38505's "declared fields" are this hop's three. A list of fields to bring, a second hop, and a `user` field as a hop each return by a dated note here with a consumer. A `multiple` lookup brings each record it names up to a bound #38505 states. +> - **◆ How an expansion rides.** On the hit of the one `search_knowledge` definition (K9 rule 1): `neighbours`, a list in document order of `{ offset, snippet, headingPath? }`, where `offset` is the signed distance from the hit's passage; and `related`, a list of `{ field, object, id, title? }`. An expansion is a result of the service, not a member ("What counts as a member" in K8): no adapter stores, reads or returns it, so the `KnowledgeHit` an adapter answers gains no key and the list stays closed. `IKnowledgeService.search` keeps its signature and its return type, and its hits come back in the declared order. The expansions ride beside the hits on the report the tool already reads for refused sources, and the slice that builds each writes that carrier. The tool gains no argument (K9 rule 2): there is no opt-out until a consumer asks. +> - **Refused when it is written**, by the schema or by the lint and `os validate` checks of row 4, each with a sentence that names the fix: a `field` or a `follow` member that is not in `metadataFields`; a `field` whose target is not the one its `caller` names; a `mode` outside the two, and a `filter` there is answered that narrowing is the search scope and visibility is sharing; a second `nearest`; `nearest` with a `caller` other than `business_unit`; `places` missing on a `boost`, present on a `nearest`, or not a positive integer; `expand.window` on a source whose split is `whole`, where a document is one passage and the key could do nothing (ADR-0078); a `follow` member that is not a `lookup` or `master_detail` field, or whose target is an object the record tools serve to no caller (a system object without `enable.aiReadable`), where the hop could bring nothing (ADR-0078). A source registered in code parses the same schema (point 3). +> - **No index is rebuilt for either key.** Neither enters the fingerprint or the recipe hash (K7): both are read when a search is answered and change nothing a store holds. Listing a field in `metadataFields` so that an entry can read it changes the recipe hash, as it always did. +> - **Not in this note.** A `filter` mode. A decay by date (`recency`): it returns by a dated note here with its first consumer. An opt-out argument on the tool. Any change to how hits of different sources are merged. +> - **The slices that build it**, each after this note merges, each key with its reader and its refusals in one PR (K10 rule 1). [#38504](https://github.com/objectstack-ai/objectstack/issues/38504): `expand.window`, which needs no identity. [#38503](https://github.com/objectstack-ai/objectstack/issues/38503): `affinity`, after #38363; it also settles with #38363 where the resolver lives so that the knowledge service can call it. Its acceptance is the ruling record's: on one question set, three arms (no identity, the model told who asks, the model told plus a declared `nearest`), at least three runs each, and if the third does not beat the second beyond the run-to-run range that result returns to the maintainer before `expand.follow` is built. [#38505](https://github.com/objectstack-ai/objectstack/issues/38505): `expand.follow`, after that. Each slice rewrites the docs sentences its code makes untrue, never ahead of it (K2). +> +> This note adds no contract member, no tool argument and no settings key: the list stays closed (rules 3 and 5 of K8). It declares, and the three slices build it. Until they land, `main` orders hits by the adapters' scores alone and a hit brings nothing with it. The code this note cites was read on `main` at `545a4fa278`; #38363 is a draft on its branch at `0cea24a56c`, not merged, and this note names the two facts its resolver answers, not its code. The tables of K1, the K8 table and every earlier note are left as written; read the list's second sentence with this note. + **The push door.** `indexDocument(sourceId, doc)` and `deleteDocument(sourceId, documentId)` hand a caller-built document to the adapter. On an object source that contradicts the first row above and K5: a pushed document is not built by assembly, so neither the content list nor the egress rule binds it, and the purge of #37096 removes it at the next complete rebuild, because no record answers for it. So **both calls are refused on an object source**, with a coded refusal (ADR-0112), from row 3 at the latest; an earlier card that touches the door may land the refusal sooner. They remain the write door of a source that is not an object source. Whether v1 has such a source is point 1 (K4): if that point stands, the two methods leave `IKnowledgeService` with the `file` and `http` arms. ### K2 — The texts this record revises @@ -223,6 +246,8 @@ The package whose README and tests carry the `http` shape, `knowledge-ragflow`, > **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. +> +> **Cross-reference (2026-11-29, [#38502](https://github.com/objectstack-ai/objectstack/issues/38502)).** Two source keys are declared by the dated note of 2026-11-29 under "What follows from the two lists" in [K1](#k1--the-boundary): `source.affinity` and `source.expand`, on the object arm. The table above lists the v1 keys as they stood and is left as written. Each of the two lands with its first reader (#38503 for `affinity`; #38504 and #38505 for `expand`), as "A key added later lands with its first reader" asks, and neither is reserved before that. No sentence of K4 is changed. ### K5 — A source lists its content fields; embedding is egress From 63acc6cde5fec499ea2077896b62fa9b3fdd2cdc Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:28:39 +0000 Subject: [PATCH 050/178] docs(pm-dispatch): a decision analysis opens with its Served-tier line, read before presenting (#38480) 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 #38391 Clause-②: no Metadata-protocol: none Rule-change: yes ## 维护者速读 - 用户能看到什么变化:用户无感;以后每份决策分析开头写明是哪一档做的、由哪个会话执笔,席位呈给你之前先核对这一行。 - 为什么做:你指出分诊会话写的四轴分析无法确认档位,这条规则让来路不明的分析不再直接落到你面前。 - 出错会怎样:最坏是同一个问题多跑一轮高档分析;决策箱里现有的每张卡,下次呈给你之前都会先补跑一轮;规则文本可随时撤回,不影响任何产品功能。 - 要你做什么:本 PR 改的是车队规则(席位自判为新规则,不是照抄裁决),并为腾出篇幅删掉了决策分析写法里唯一的速读示例,需要你批准后才能落地。 ## What changes Parts 1 and 2 of the card, rule text only. The full rule lives in one file, `decision-analysis.md`; `area-lease.md` points to it. **`.claude/skills/pm-dispatch/references/decision-analysis.md` 〈落卡分析模板〉, two lines added** (the file spells the two placeholders in angle brackets; written here as `TIER` and `SESSION` because this body cannot carry them): - Before: (none) - After: 「英文段首两行 `Served-tier: TIER`(`CONTRACT_REVIEW_TIER | TIER_DEFAULT`)、`Analysed-by: SESSION`(执笔会话或子代理),⛔ 不写模型 id;标 `CONTRACT_REVIEW_TIER` 须执笔转录过 `verify-review-tier.mjs`(`--tier-evidence=` 只判 L2 记录)。」 - Before: (none) - After: 「呈维护者前读该行:缺或未达档 ⇒ 达档重跑,贴带两行的 delta 评论(逐棱同异)再呈;⛔ 永不呈读不出档的分析。」 **Same section, deleted to pay for the two lines:** the worked 速读 example (「例(新应用的菜单名被存成译文)」 and its four sub-bullets, 414 bytes). It is an illustration, not a rule; the four-line shape it shows stays stated on the lines above it. **`.claude/skills/pm-dispatch/references/area-lease.md` 〈区内规则〉:** - Before: 「仅呈维护者选项组过独立评审,多卡一批;…」 - After: 「仅呈维护者选项组过独立评审(档位照 `decision-analysis.md`),多卡一批;…」 - Paid by two deletions in the same file, both restatements: - Before: 「所落 PR 欠的红检查读日志(`readings-ci.md`)派子代理读,一读兼守本条与该文。」 After: 「所落 PR 欠的红检查日志派子代理读(`readings-ci.md`)。」 - Before: 「挂前先查 PR 上已有落地评论,有即 ⛔ 不再挂。」 After: 「挂前先查已有落地评论,有即 ⛔ 不再挂。」 **`scripts/pm/check-skill-line-ratchet.mjs`:** the two rows lowered to the landed bytes, no raise: `decision-analysis.md` 5589 → 5580, `area-lease.md` 6990 → 6986. The declared cross-file move into `decision-analysis.md` still holds (+557 against a 568-byte source decrease). **One deviation from the card's wording, on purpose.** The card asks that an at-tier analysis be posted with `--tier-evidence=` as L2 records are. Read on main: `post-stamped.mjs` checks `--tier-evidence` only when the body is a `## Contract review` record (`recordTierEvidenceRefusal` returns early for any other comment), and `issue-create.mjs` takes no such option, while an analysis lives on the card body or in a delta comment. Writing "post it with `--tier-evidence=`" would name a check that does not run. The rule therefore names the check that does run on any transcript, `verify-review-tier.mjs`, and says plainly that the writer's flag judges L2 records only. **`.claude/skills/pm-dispatch/references/triage-duties.md`** (round 2): its pointer to the deleted example is dropped. - Before: 「决策卡速读居四棱块之上、同题,至多四行业务话;写法与例见 `decision-analysis.md`。」 - After: 「决策卡速读居四棱块之上、同题,至多四行业务话;写法见 `decision-analysis.md`。」 - Its ratchet row is lowered 13709 → 13692, the landed bytes. No row rises. **Deferred, not in this PR:** part 3 (a `record-recognisers.mjs` reader for the line on `needs-user-decision` cards) and the writer gap below (`post-stamped.mjs --tier-evidence` does not judge an analysis that names `Served-tier: CONTRACT_REVIEW_TIER`). Both are carried by follow-up card #38492 (Blocked-by #38472, which edits `record-recognisers.mjs`), with the contract review's nits N1-N4. **Why the rule-change line reads yes.** The maintainer's words on the card (「卡上现有的四轴分析是分诊会话写的,无法确认它用的是不是 fable。立卡更新skills」) order a skills update but do not cover this exact text, the example deletion or the two area-lease trims, so this is not declared `ruled`. ## Tests Rule text only; no code path changes, so nothing to ablate. ## Acceptance notes - The worked 速读 example was the only content in `decision-analysis.md` that could pay 361 bytes without deleting or rewording ruled lines. If the seat prefers to keep it, the alternative is a raise under a ruling of record, which this dev does not hold. - `post-stamped.mjs --tier-evidence` is accepted on every comment but judged only on `## Contract review` records. A reader that also judges an analysis carrying `Served-tier: CONTRACT_REVIEW_TIER` is carried by #38492. ## Round 2 Round 2 at head bb0562cca7: S1 (contract review: `triage-duties.md` pointed at the deleted example; fixed in the diff, its row lowered) and M1 (L1: part 3 and the writer gap had no carrier; now #38492), plus the L1 nit (the 速读 names the example deletion) and the contract review's N4 (the 速读's worst case names the one re-run per card already in the decision box). Round 3 at head 158d375b82: origin/main merged in (no rebase), bringing #38488 and #38472. The one conflict, in `scripts/pm/check-skill-line-ratchet.mjs`, is resolved by keeping both PRs' rows as each wrote them: `cross-repo-coordination.md` 4920 and `lanes/hotcrm.md` 181 from #38488, and `triage-duties.md` 13692 from this PR (main's 13709 would pass the gate but leave 17 bytes of headroom that this PR's deletion freed). ## Verification Two-minute check: `wc -c .claude/skills/pm-dispatch/references/decision-analysis.md .claude/skills/pm-dispatch/references/area-lease.md`, expected 5580 and 6986, then `node scripts/pm/check-skill-line-ratchet.mjs`, expected exit 0. Files to read first, by risk: `decision-analysis.md` lines 22-23 (the new rule); `area-lease.md` line 58 (the pointer); `triage-duties.md` line 49 and the three ratchet rows.
Local gates at head 158d375b82 (round 3): 41 of 42 derived families exit 0, 1 NOT MEASURED - `node scripts/pm/dispatch-gates.mjs --commands` on the final diff derived 42 commands for the 4 changed paths; all 42 ran in one batch under `scripts/pm/os-verify-lock.sh` (lock verdict: command-exit 0). - 41 exited 0, among them `pnpm check:pm-skill-ratchet`, `pnpm check:pm-skill-id-lint`, `pnpm check:pm-record-recognisers`, `pnpm check:pm-governed-merges`, `pnpm check:pm-dispatch-gates`, `pnpm check:pm-half-states`, `pnpm check:skill-frame-sync`, `pnpm check:doc-authoring`, `pnpm check:nul-bytes`. - NOT MEASURED: `pnpm --filter @objectstack/lint run check:doc-formula-expressions`, exit 3. Its prerequisite (the formula and lint builds) is not built in this worktree, so the gate ran no check; CI runs it. - `dispatch-gates --ran` with exit codes: "42 derived famil(ies) accounted for, 41 run, 1 NOT-MEASURED". - `node scripts/pm/check-skill-line-ratchet.mjs` exit 0 after the merge: `decision-analysis.md` 5580, `area-lease.md` 6986 and `triage-duties.md` 13692, each equal to its ceiling. - `node scripts/pm/overlap-check.mjs`: VERDICT clean against origin/main, with no open PR sharing a path. #38488 merged to main and was merged in this round; its `check-skill-line-ratchet.mjs` rows are kept as it wrote them. - Rounds 1 and 2 (c4302a74a5, bb0562cca7): the same one NOT MEASURED, every other derived family exit 0. - Families CI runs outside the derived list are read from this PR's check-runs, not re-run here.
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_ --------- Co-authored-by: Claude --- .claude/skills/pm-dispatch/references/area-lease.md | 6 +++--- .../skills/pm-dispatch/references/decision-analysis.md | 8 ++------ .claude/skills/pm-dispatch/references/triage-duties.md | 2 +- scripts/pm/check-skill-line-ratchet.mjs | 6 +++--- 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/.claude/skills/pm-dispatch/references/area-lease.md b/.claude/skills/pm-dispatch/references/area-lease.md index 7f377f135e3..e98470de580 100644 --- a/.claude/skills/pm-dispatch/references/area-lease.md +++ b/.claude/skills/pm-dispatch/references/area-lease.md @@ -40,7 +40,7 @@ - 认领前照 `dispatch-runbook.md` 派发前置核前提;开线程请求交席位攒批(`coordinator.md` 三)。 - 写码与开发期读码全经 `os-dev` 等子代理(一卡或一组耦合卡,文件面不相交)。 - 同系列卡可从前卡分支起步(AGENTS.md §2 主干形,⛔ 不叠 PR);新测试建按卡命名的新文件,AGENTS.md 共享 harness 规则适用时除外,由重叠检查定排队。 -- 席线程只协调,⛔ 不读 diff 与日志;ACCEPT 欠的自读(`contract-review.md`、〈路径分叉〉)除外。所落 PR 欠的红检查读日志(`readings-ci.md`)派子代理读,一读兼守本条与该文。 +- 席线程只协调,⛔ 不读 diff 与日志;ACCEPT 欠的自读(`contract-review.md`、〈路径分叉〉)除外。所落 PR 欠的红检查日志派子代理读(`readings-ci.md`)。 - 每区 dev 位空即补;逐位上张 PR 入合并队列才领下张,此前跑修复轮;Tier H 或待裁 PR 让位。 - 席每轮逐区查,核认领 Container & model 行;取卡照点名范围次序,p0/p1 插队;p3 留收口或搭同文件 PR 成批(每 PR ≤5 卡)。 - 认领必答:同区卡过 `execution-duties.md` 折叠五门即默认合一 PR,否则串行;额度墙亦照该文。 @@ -48,14 +48,14 @@ - 送审:≤50 行、只改文本或测试、`Clause-②: no` 且无他契约面 PR 由区照 `l1-review-checklist.md` 自审落地,ACCEPT 点名自审;余者由 L1 线程 ACCEPT 读,先于 `contract-review.md` 不起第二个 agent。 - 契约记录只欠 `contract-review.md` 四面,head 移动照其例外;同 patch-id 干净合 main 只保 ACCEPT。 - 落地:区先读 `check-governed-merges.mjs --pr N`;非受管 PR 照 `landing-operations.md` 自落,受拒报原文。 -- PASS 且全绿的非受管 PR 10 分钟内落地;挂前先查 PR 上已有落地评论,有即 ⛔ 不再挂。 +- PASS 且全绿的非受管 PR 10 分钟内落地;挂前先查已有落地评论,有即 ⛔ 不再挂。 - 受管面与过线卡的 PR 区 ⛔ 不落,交席位;席位照 SKILL.md〈路径分叉〉①–④ 一笔交棒。 - 席位每轮照 `execution-duties.md` 四件套行复查全部已 PASS 受管 PR,各区转来的一并在内。 - 性能卡与 PR 的提速数字只引已过 L1 的 bench PR 读数;⛔ 不引估算或未过 L1 的本地测量。 - 席只裁路由(拆并延、归区;区边界扩、缩、并、释放,重写租约表为记);改可见行为或解读 ADR 照 SKILL.md〈升级与决策〉呈维护者。 - 卡碰租约外文件 ⇒ 区交席位,⛔ 不留卡等维护者;席三选一:扩区;该区只认领此卡(文件级 `File surface:`,`check-handover.mjs --inflight` 复查);转他席。⛔ 不呈维护者、不起评审,只留否决窗口。 - 租约外是共享热文件(如 `packages/core`)⇒ 默认逐卡认领、租约路径不动:租约罩热文件即挡他席。 -- 仅呈维护者选项组过独立评审,多卡一批;席自裁 ⛔ 不起评审,自读码。均带 `Prior rulings read:` 行,开工前呈 ⛔ 不在施工中途。 +- 仅呈维护者选项组过独立评审(档位照 `decision-analysis.md`),多卡一批;席自裁 ⛔ 不起评审,自读码。均带 `Prior rulings read:` 行,开工前呈 ⛔ 不在施工中途。 - 席信箱只收:待裁、待落地受管 PR、跨区冲突、阻塞、交接完成;安全照 `security-findings.md`。 - 线程约 150k 即在干净点轮换,⛔ 不在 L1/L2 中途;交接写 `/mnt/project-files/<席>/handover-<区>.md`。 - 省耗:跨线程只传指针;⛔ 不减 dev。 diff --git a/.claude/skills/pm-dispatch/references/decision-analysis.md b/.claude/skills/pm-dispatch/references/decision-analysis.md index 295dab0276a..b43eae04a99 100644 --- a/.claude/skills/pm-dispatch/references/decision-analysis.md +++ b/.claude/skills/pm-dispatch/references/decision-analysis.md @@ -19,12 +19,8 @@ - 问题写客户看到的症状、谁碰到、多频繁;选项句写选了客户看到什么、约几个 PR。 - ⛔ 速读不写代码名、文件路径、命令、裁决字母、裸卡号;点到的卡配一句中文说明。 - 四轴、四棱块、自检行、置信缺口、工作量先例归英文分析段,⛔ 不删。 -- 例(新应用的菜单名被存成译文): - - 问题:在中文界面下新建或编辑应用,菜单里自动生成的名字被存成中文;换成英文界面, - 菜单还是中文。 - - 选项:A 存原文,切换语言时菜单名跟着变,一个小 PR;B 维持现状。 - - 推荐 A:应用要给不同语言的人用。 - - 不定会怎样:中文用户建的应用,在其他语言下菜单一直是中文。 +- 英文段首两行 `Served-tier: `、`Analysed-by: `(执笔会话或子代理),⛔ 不写模型 id;标 `CONTRACT_REVIEW_TIER` 须执笔转录过 `verify-review-tier.mjs`(`--tier-evidence=` 只判 L2 记录)。 +- 呈维护者前读该行:缺或未达档 ⇒ 达档重跑,贴带两行的 delta 评论(逐棱同异)再呈;⛔ 永不呈读不出档的分析。 分析段骨架:背景 / Governing text(引文 + grep,或 none found + 检索式)/ 协议声明、是否改协议 / 带 re-check 命令的前提 / 具体问题 / 选项 / 推荐 / 相关单与 PR。正文六项: diff --git a/.claude/skills/pm-dispatch/references/triage-duties.md b/.claude/skills/pm-dispatch/references/triage-duties.md index d6ad96e3d33..302b78d715f 100644 --- a/.claude/skills/pm-dispatch/references/triage-duties.md +++ b/.claude/skills/pm-dispatch/references/triage-duties.md @@ -46,7 +46,7 @@ - `needs-user-decision` = 设计卡、契约形状提案、需要 appetite 的多周程序;只挂 issue。 - 先例已定新键/值/导出名非契约形状提案;分诊审计 ⛔ 不自加门,唯语义/形状真分歧呈人。 - 碰迁移形状或删已发布能力也进决策箱;说明书脱节不进:有裁定出处才是 (b),否则改文档。 -- 决策卡速读居四棱块之上、同题,至多四行业务话;写法与例见 `decision-analysis.md`。 +- 决策卡速读居四棱块之上、同题,至多四行业务话;写法见 `decision-analysis.md`。 - 首行写立卡门类别 ①–④;四类定义、⛔ 清单、四答、理由判据与配额见 `filing-gate.md`。 - `finding` = 三类内待定级:(a) 可复现缺陷(复现或失败探针);(b) 违背已声明契约(引契约文); - (c) AI 写元数据会被运行时拒收或静默丢弃的陷阱;其余进 PR `## Acceptance notes`,⛔ 不立卡。 diff --git a/scripts/pm/check-skill-line-ratchet.mjs b/scripts/pm/check-skill-line-ratchet.mjs index d3fa0e80c53..97aac7c9cad 100644 --- a/scripts/pm/check-skill-line-ratchet.mjs +++ b/scripts/pm/check-skill-line-ratchet.mjs @@ -85,7 +85,7 @@ export const CEILINGS = new Map([ ['.claude/skills/pm-dispatch/references/dispatch-runbook.md', 20483], // raised 20070 → 20354 (+284) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): a card thread confirms Actions started after each push; the seat reads pr-state of every in-flight card PR; lowered 20354 → 20344 by the PR that moved the tier and effort values to the one home; raised 20344 → 20483 (+139) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」): the thread's first report carries the served tier and the seat writes it into the claim ['.claude/skills/pm-dispatch/references/state-machine.md', 4189], ['.claude/skills/pm-dispatch/references/contract-review.md', 6419], - ['.claude/skills/pm-dispatch/references/decision-analysis.md', 5589], // raised 5023 → 5589 (+566) by the declared cross-file move from SKILL.md (CROSS_FILE_MOVES below); before that: raised 4892 → 5023 (+131) by ruling record 7076338827, the addendum to 7076315104 (a simple question goes to the maintainer in chat after the at-tier analysis: 「不一定要写成文件吧?简单的问题是不是直接和我沟通就可以」) + ['.claude/skills/pm-dispatch/references/decision-analysis.md', 5580], // lowered 5589 → 5580 by the decision-analysis tier-line PR (its worked 速读 example deleted to pay for the `Served-tier:` / `Analysed-by:` lines); before that: raised 5023 → 5589 (+566) by the declared cross-file move from SKILL.md (CROSS_FILE_MOVES below); before that: raised 4892 → 5023 (+131) by ruling record 7076338827, the addendum to 7076315104 (a simple question goes to the maintainer in chat after the at-tier analysis: 「不一定要写成文件吧?简单的问题是不是直接和我沟通就可以」) ['.claude/skills/pm-dispatch/references/platform-readings.md', 1082], ['.claude/skills/pm-dispatch/references/readings-queue.md', 9074], ['.claude/skills/pm-dispatch/references/readings-channels.md', 7138], @@ -105,14 +105,14 @@ export const CEILINGS = new Map([ ['.claude/skills/pm-dispatch/references/true-green.md', 2068], ['.claude/skills/pm-dispatch/references/compile-surfaces.md', 2488], ['.claude/skills/pm-dispatch/references/seat-lifecycle.md', 9070], // raised 9070 → 9076 (+6) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): card-pick --why every patrol round; lowered 9076 → 9070 by the PR that moved the tier and effort values to the one home - ['.claude/skills/pm-dispatch/references/area-lease.md', 6990], // raised 6401 → 6586 by the ruled text (one seat per lane by default; a new `area:*` is a partition of that seat), ruling record 7030459053; raised 6586 → 6990 (+404, the landed bytes) by the ruled text (a zone boundary change is the seat's routing call, and a card outside the lease goes to the seat, which picks one of three routes), the maintainer's ruling quoted in the body of the rule card and recorded by triage record 7247665159 (「座位可以自己决定,立卡更新skills」) + ['.claude/skills/pm-dispatch/references/area-lease.md', 6986], // lowered 6990 → 6986 by the decision-analysis tier-line PR (its pointer paid by two deletions in the same file); before that: raised 6401 → 6586 by the ruled text (one seat per lane by default; a new `area:*` is a partition of that seat), ruling record 7030459053; raised 6586 → 6990 (+404, the landed bytes) by the ruled text (a zone boundary change is the seat's routing call, and a card outside the lease goes to the seat, which picks one of three routes), the maintainer's ruling quoted in the body of the rule card and recorded by triage record 7247665159 (「座位可以自己决定,立卡更新skills」) ['.claude/skills/pm-dispatch/references/coordinator.md', 4427], // raised 3781 → 4265 by the ruled text (one seat per lane by default; a new `area:*` is a partition of that seat), ruling record 7030459053; lowered 4265 → 4230 by the PR that moved the tier and effort values to the one home; raised 4230 → 4427 (+197) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」): the coordinator returns an underived ceiling order before a thread opens ['.claude/skills/pm-dispatch/references/untrusted-text.md', 3280], ['.claude/skills/pm-dispatch/references/security-findings.md', 3934], ['.claude/skills/pm-dispatch/references/external-contributions.md', 2006], ['.claude/skills/pm-dispatch/references/reading-discipline.md', 3822], ['.claude/skills/pm-dispatch/references/cross-repo-coordination.md', 4920], - ['.claude/skills/pm-dispatch/references/triage-duties.md', 13709], // edited byte-neutral by the re-basing PR (12399 → 12399); raised 12399 → 13559 (+1160, the landed bytes) by the rulings whose rows are written in it: ruling records 7031931263 (rows 2–5: 「adr接受你的建议」, 「只考虑合并没人认领的,没开始开发的,你负责处理」, 「影响评测的卡不能关,这个会影响到AI的开发效果」, 「adr和skills修改相对是重要的」), 7032145340 (row 6: 「同意」) and 7032418455 (row 7: 「你分诊的时候是不是应该同时评估大概的卡大小作为参考」); review record 7038100802 triggered the part of rows 2, 3 and 6 added in fix round 1 (one close reason, the sweep roll-over, the never-fold list of standing exclusions) and is a trigger, not a ruling; lowered 13559 → 13544 by the PR that moved the tier and effort values to the one home; raised 13544 → 13709 (+165, the landed bytes) by ruling record 7135874506 (items B4, B7 and C1: 「照推荐:采纳 5 条」) + ['.claude/skills/pm-dispatch/references/triage-duties.md', 13692], // lowered 13709 → 13692 by the decision-analysis tier-line PR (its pointer to the deleted worked 速读 example dropped); before that: edited byte-neutral by the re-basing PR (12399 → 12399); raised 12399 → 13559 (+1160, the landed bytes) by the rulings whose rows are written in it: ruling records 7031931263 (rows 2–5: 「adr接受你的建议」, 「只考虑合并没人认领的,没开始开发的,你负责处理」, 「影响评测的卡不能关,这个会影响到AI的开发效果」, 「adr和skills修改相对是重要的」), 7032145340 (row 6: 「同意」) and 7032418455 (row 7: 「你分诊的时候是不是应该同时评估大概的卡大小作为参考」); review record 7038100802 triggered the part of rows 2, 3 and 6 added in fix round 1 (one close reason, the sweep roll-over, the never-fold list of standing exclusions) and is a trigger, not a ruling; lowered 13559 → 13544 by the PR that moved the tier and effort values to the one home; raised 13544 → 13709 (+165, the landed bytes) by ruling record 7135874506 (items B4, B7 and C1: 「照推荐:采纳 5 条」) ['.claude/skills/pm-dispatch/references/execution-duties.md', 22249], // raised 19810 → 20148 (+338) by ruling records 7031931263 (row 2, the weekly ADR card: 「adr接受你的建议」) and 7032145340 (row 6, the lane seat claims the weekly sweep card: 「同意」); 20148 → 20154 (+6) by ruling record 7073679594 (the L2 review effort line moves to `high` on the review sweep's readings: 「C」, under ruling 7073045669 point 4); 20154 → 20277 (+123) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): a hold is Blocked-by + pm:blocked on the card, the probe covers card threads; 20277 → 22158 (+1881) by ruling record 7076315104 (the one home for tier and effort, the 定档 section: 「要把规则文字同统一整理一下,避免散落在各处,避免ai犯错」); raised 22158 → 22316 (+158) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」) (the coordinator session, the area thread and the director's effort); lowered 22316 → 22307 by the PR that drops the triage suggestion line (item C1 of ruling record 7135874506); lowered 22307 → 22249 to its landed size by the #35237 slice-12 pointer PR ['.claude/skills/pm-dispatch/references/filing-gate.md', 9124], // raised 9096 → 9101 (+5) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): same-epic order is the later card's Blocked-by; raised 8386 → 9096 (+710, the landed bytes) by the rulings whose rows are written in it: the rule card's body ruling (row 1, a dedupe hit on an open same-mechanism card ends in a comment: 「感觉你的第二种方案也很好啊」) and ruling record 7032145340 (row 6, the weekly sweep card entry rule and triage's move at first touch: 「同意」); review record 7038100802 triggered the quota line's pointer to row 1 (fix round 1) and is a trigger, not a ruling; lowered 9101 → 9089 by the PR that moved the tier and effort values to the one home; raised 9089 → 9124 (+35, the landed bytes) by ruling record 7135874506 (item A1: 「照推荐:采纳 5 条」) ['.claude/skills/pm-dispatch/references/project-forms.md', 4889], // raised 4669 → 4889 (+220 B, the two project-memory lines less 48 B of restatement cuts) by ruling record 7046610679 「同意,立卡派发」 under ruling record 6184799323, letter B From 430a3119d3cde3b0b0032acb7df26a4411097ea0 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:52:26 +0000 Subject: [PATCH 051/178] test(knowledge-pgvector): the live PostgreSQL pin reads the runtime-composed mark beside the deployment store (#38523) 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 #38514 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:主干上必过的"真实 PostgreSQL 时间一致性"检查从上一次知识服务改动起一直是红的,本单把它修回绿。 - 原因是上一单让运行时自动挂载的知识服务多带一个"由运行时组装"的标记(按知识库检索线的既定决定),而一条只在真实数据库任务里跑的测试还按旧的单一参数断言。 - 修法只改这一条测试的期望值并写明原因,产品代码不动;出错也只影响测试本身,可直接撤回。 - 没有跳过、删除或放宽任何用例;要你做的:无。 ## What changes `packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts`, one assertion: the knowledge service argument that `resolveCapabilityArgument('knowledge', …)` builds is now pinned as `{ deploymentAdapter: 'pgvector', runtimeComposed: { declared: false } }`, with a comment saying why the argument carries the runtime-composed mark (ADR-0161 K8, the dated note on item 12) and why `declared` is `false` (this stack writes no `requires: ['knowledge']`). No product code changes. Nothing in the package's shipped `files[]` changes, so this PR carries `skip-changeset` and no changeset (measured: after `pnpm --filter @objectstack/knowledge-pgvector build`, a test-only symbol has 0 hits across `dist`, `README.md` and `CHANGELOG.md`; the positive control `KnowledgePgvectorPlugin` hits 4 files in `dist`). ## The reading - The extra key is the intended mark, not a leak. `packages/core/src/capability-composition.ts` returns `runtimeComposed: { declared: stackDeclaredCapabilities(input.stack).includes('knowledge') }` beside `deploymentAdapter`, and its doc comment names it as the "enabled by configuration" mark of ADR-0161 K8. The service reads it: `KnowledgeServicePlugin` (`packages/services/service-knowledge/src/knowledge-service-plugin.ts`) declares `runtimeComposed?: { declared: boolean }` and uses it for the reap-guard switch, `enabledByConfiguration`, the `kernel:bootstrapped` hold and the boot-line level. The core unit test `packages/core/src/capability-composition.test.ts` already pins the two-key shape. - With the mark, the service serves only when an embedder and the deployment's store are present. This test registers a fake embedder and mounts the pgvector store, so the two later cases of the block (the source bound to the marked store; passages land in the pgvector tables and `search_knowledge` returns them) still hold at the new shape, and they now actually run instead of being skipped behind the failed `beforeAll`. - Other pins of the one-key argument: none. Every other test that names `resolveCapabilityArgument('knowledge', …)` is in `capability-composition.test.ts`, already at the new shape; the remaining `deploymentAdapter: '…'` hits in tests are constructor options, not pins of the resolver's answer. ## Tests
Live PostgreSQL (pgvector 0.6.0, a private cluster), whole live suite — 7 files / 91 tests passed `OS_TEST_POSTGRES_URL=… OS_EXPECT_LIVE_DIALECT_MATRIX=1 pnpm --filter @objectstack/knowledge-pgvector exec vitest run --maxWorkers=2 live-postgres` at 4055713e11: ``` Test Files 7 passed (7) Tests 91 passed (91) os-verify-lock: VERDICT command-exit 0 ```
The red, reproduced at the base, and green at the head — capability-mount file alone Head (4055713e11): `Test Files 1 passed (1)`, `Tests 4 passed (4)`. Base file restored (dccf836a86), same live database: ``` FAIL src/__tests__/capability-mount.live-postgres.test.ts > a knowledge_source with no adapter and no requires — mounted by the item, bound to the marked store AssertionError: expected { deploymentAdapter: 'pgvector', …(1) } to deeply equal { deploymentAdapter: 'pgvector' } Test Files 1 failed (1) Tests 2 passed | 2 skipped (4) ``` That is the exact signature on the failing `main` runs.
Non-live suite and typecheck `pnpm --filter @objectstack/knowledge-pgvector test`: `Test Files 4 passed | 7 skipped (11)`, `Tests 19 passed | 91 skipped (110)` (the skipped are the live files, no URL set). `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0, `check:test-typecheck: OK`.
## Verification Two-minute check: with a pgvector PostgreSQL at `OS_TEST_POSTGRES_URL`, run `pnpm --filter @objectstack/knowledge-pgvector exec vitest run capability-mount`; expect 4 passed. CI evidence line: the `Temporal Conformance (live PG + MySQL)` job is `never on pull_request` (its `if:` in `.github/workflows/ci.yml` excludes `pull_request`), so this PR's own checks publish it as skipped. It runs in the merge queue, because this path matches the `temporal_live` filter (`packages/plugins/knowledge-pgvector/**`), and on the `main` push after landing; the card closes on a green `main` push that runs the job. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb Co-authored-by: Claude --- .../src/__tests__/capability-mount.live-postgres.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts index a4b323ba14d..fea882cad4b 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts @@ -115,8 +115,13 @@ describe.skipIf(!PG_URL)('a knowledge_source with no adapter and no requires — const database = { driver: 'postgres', url: PG_URL as string }; const input = { stack, packageRoot: process.cwd(), env: {}, database }; // With what: the deployment's-store mark, and the store the rule mounts. + // The argument also carries the runtime-composed mark: the rule, not a + // host, mounted this service, so it is enabled by configuration (ADR-0161 + // K8, the dated note on item 12) and serves only with an embedder and the + // deployment's store — both present below, so it serves. `declared` is + // false because this stack writes no `requires: ['knowledge']`. const { argument: serviceArgument } = resolveCapabilityArgument('knowledge', input); - expect(serviceArgument).toEqual({ deploymentAdapter: 'pgvector' }); + expect(serviceArgument).toEqual({ deploymentAdapter: 'pgvector', runtimeComposed: { declared: false } }); const [extra] = resolveCapabilityExtras('knowledge', input); kernel = new LiteKernel({ logger: { level: 'silent' } } as never); From 2db5c6c619dba292efba215bc3e5f6fae5d05019 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:58:25 +0000 Subject: [PATCH 052/178] fix(metadata-protocol): name authored forms on the destructive-change refusal, and copy a form's name with its object (form type follow-ups) (#38386) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #37852. Five of the card's six boxes close here; the container-listing box stays open (see Acceptance notes). Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:删除对象字段被拦下时,提示里会列出仍在编辑这个字段的新式表单;把软件包复制成新命名空间时,表单名会跟着对象改名,表单按钮也指向复制后的表单。 - 为什么:表单独立成单独的元数据类型后留下的六项收尾,这里收掉五项(属于“表单独立成 form 元数据”专题)。 - 出错会怎样:只影响被拦下时的提示内容和复制出的表单名,不改变哪些保存会被拦下;可以直接撤回。 - 要你做什么:无。 ## What changes Each box was measured on `main` (81f2ff8b) first. A code change was made only where the measurement showed a defect. 1. **Destructive still-shown-by, `form` arm: defect, fixed** (`packages/metadata-protocol/src/destructive-still-shown-by.ts`). Measured with a probe on `main`: an object save removing `status` named the old-shape form view that edits it, but not an authored `form` item that edits it. The lint judge that reads form sections (`validateFormLayout`) walks `views[]` only. The served `form` listing is now read, its authored items only (a projected form, marked `_formDefinedIn`, is the `view` listing's item and is already named there). Each authored form goes before the judges in the stored form-view-item shape that judge already reads, and a finding on it is named `{ type: 'form', name, where }` at the form's own path. No position table is added; the judges stay the authority. The describes in `packages/spec/src/api/protocol.zod.ts` say the same, prose only, no shape change: `FieldStillShownBySchema.type` names `form` among the types (seat ruling 3 on the card); `DestructiveChangeIssueSchema.stillShownBy` names `form` among the `field_removed` item types and says an authored form is judged in the form view item shape (review S1); `where` gives `sections[0].fields[1]` as a `form` entry's path (review N1). The generated reference `packages/spec/docs/references/api/protocol.md` is regenerated from them. 2. **Unmanaged copy, form-name prefix: defect, fixed** (`packages/metadata-protocol/src/package-namespace-rename.ts`). Measured with a probe of `planNamespaceRename`: for an object whose name has no namespace prefix (`ticket` copied as `acme_ticket`), a `view` item `ticket.board` became `acme_ticket.board`, but a `form` item `ticket.entry` kept `ticket.entry` while its body's `object` became `acme_ticket`. `FormSchema` refuses that name, and a form action's `target` still opened the source's form. A prefixed object's form was already right. The `OBJECT.KEY` rule now covers `form` items as it covers `view` items. The engine is shared by the unmanaged install and `duplicatePackage`. 3. **Transaction ownership in the batch route: measured, stated and pinned** (`packages/rest/src/batch-routes.ts`). `ql.transaction(runOps, context, { require: true })`: with no unit open, the engine opens one and owns its commit and rollback. Inside a unit an outer caller opened, the engine joins it (ADR-0067 D2), and that caller decides, for the batch's writes too. The route opens its unit outside the metadata protocol's overlay-cache guard, and needs none: `sys_metadata` exposes `get`/`list` only, so a batch op writing it is refused `405 OBJECT_API_METHOD_NOT_ALLOWED` before the unit opens. A comment at the call states this; three pins hold it. 4. **`revertCommit` docblock: text corrected** (`packages/metadata-protocol/src/protocol-package-commits.ts`). The facet's docblock was a one-line pointer to `protocol.ts`, whose contract docblock states neither the walk order nor the form hold. It now states both where they run: newest first, every `form` item after every `view` row the commit edited, and a form held as published while one of those rows is not put back. `protocol.ts` sits exactly at its facade ceiling (11705 of 11705 lines) and is not on this claim, so it is untouched. 5. **Rollback pins for page and permission set: measured fine, pinned** (`protocol.revert-commit-honest-outcome.test.ts`). A commit holding a `view` row that cannot be put back, a `page`, a `permission` (permission set) and the `form` it created: the form is held and listed in `failed[]`, and the page and the permission set are restored all the same. CONTROL: with the view put back, all four revert, in the walk order `revertWalkOrder` gives. 6. **Container listing and withdrawn members: not done.** See Acceptance notes. ## Why Residuals of the `form` metadata type's landing, which its contract reviews recorded. None blocks a release. ## Tests Pins that encode a fix were shown red without it (at head 2b006ece4, before the main merge), through `scripts/ablation-replace.mjs`, on src the tests import directly (no build in the resolution path):
Box 1 ablation: delete the judged-forms line in removalSurfaces ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob 33af57a2158c -> 58b1b28fd577 × names the authored form, as a `form`, beside the old-shape form view Tests 1 failed | 15 passed (16) ablation-replace: ok restored: blob == HEAD (33af57a2158c) and `git diff HEAD` is empty ```
Box 2 ablation: the qualified-name rule back to view only ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob 0bd58b7141de -> b4c181514a2d × a bare object's form takes the object's copy name as its prefix, and the copy parses as a `form` × a form action's `target` naming the form follows it, as one naming a view item does Tests 2 failed | 20 passed (22) ablation-replace: ok restored: blob == HEAD (0bd58b7141de) and `git diff HEAD` is empty ```
Boxes 3 and 5 pin measured behaviour that this PR does not change, so they carry no ablation.
Package runs after merging main at d7645c3da, on the code of e9009fd9b (os-verify-lock) The head 450a0ae7c differs from e9009fd9b only in the changeset. ``` @objectstack/spec build && check:generated --fix: regenerated the 1 stale artifact (check:docs), then ✓ All 14 generated artifacts are up to date os-verify-lock: VERDICT command-exit 0 turbo build of the metadata-protocol and rest closures: Tasks 32 successful, 32 total @objectstack/spec, @objectstack/metadata-protocol and @objectstack/rest typecheck, then metadata-protocol vitest: Test Files 375 passed | 9 skipped (384) Tests 23657 passed | 45 skipped (23702) os-verify-lock: VERDICT command-exit 0 objectql protocol-duplicate-package battery (the rename engine through dist), then rest vitest: Test Files 4 passed (4) Tests 20 passed (20) Test Files 444 passed (444) Tests 9337 passed | 376 skipped (9713) os-verify-lock: VERDICT command-exit 0 ```
Derived gate families at head 450a0ae7c: 94 exit 0, 1 NOT MEASURED `node scripts/pm/dispatch-gates.mjs --commands` derived 95 families for this head. Each was run with its exit code captured before any pipe, then reconciled: ``` Run reconciliation — 95 derived, 94 run, 1 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 95 derived famil(ies) accounted for — 94 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3). ``` NOT MEASURED (exit 3, a prerequisite, not a red), left to CI: `node scripts/check-plugin-teardown-shape.mjs --self-test`. Its positive control is pinned to a commit this shallow clone cannot reach. `overlap-check.mjs` at 450a0ae7c, before its push, against origin/main a2205a85a: `VERDICT clean exit 0`. `test:repo` was not run locally: no diff path is in that project, and CI's `Test Core` runs it.
## Acceptance notes - **Box 6 is not done: its producer was not located.** The card's sentence ("decides membership from the member's own listing flag rather than the member's current published state") names no file, symbol or flag. The review records on the two landing PRs say the residual notes behind this card were delivered privately to the seat. Searched by reading: the served `view` listing's container expansion (`protocol-meta-list-reads.ts`), the effective `form` list (`protocol-form-reads.ts`), the old-shape withdrawal reader, and every listing flag spelled `listed`, `hidden` or `withdraw*` in `metadata-protocol`. None decides container membership by a member's own flag. No file was edited for it. Seat ruling 1 on the card splits box 6 off: after this PR merges, the card is re-scoped to box 6 alone. - **Box 3, measured beside the pins and not changed:** inside an outer unit that then COMMITS, a batch whose later op fails answers `404 RECORD_NOT_FOUND` and leaves the earlier op's row in place (probe at 2b006ece4: `alpha rows after outer commit [ 'a-1' ]`). The route catches the op's error to answer it, so the outer owner never sees a throw. No public door was found that runs the route inside an outer unit (an HTTP request opens none), so this is a reading, not a card (seat ruling 2: no change; a card is filed once a producer that runs the route inside a unit is named). - **#38381 (merged):** it moved the generated references from `content/docs/references/` to `packages/spec/docs/references/`. The merge of `main` took its deletion of `content/docs/references/api/protocol.mdx` (the old path is not restored), and the reference was regenerated at `packages/spec/docs/references/api/protocol.md`, where its diff is the rows of the three edited describes and nothing else. The PR's net diff touches no path under `content/docs/references/` and no hand-edited reference. `overlap-check.mjs` at 450a0ae7c: clean. - **Seen in passing, read in code only:** `validateFormLayout` (the `form-field-unknown` rule) walks `views[]` only, so an authored `forms:` item whose section names a field its object lacks gets no finding. Not measured at a public door. ## Verification Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/protocol.destructive-still-shown-by.test.ts src/package-namespace-rename.test.ts` shows 38 tests passing, among them the authored-form entry and the `acme_ticket.entry` copy name. Read first, by risk: 1. `packages/metadata-protocol/src/destructive-still-shown-by.ts`, `removalSurfaces` and `surfacesOf`: the judged form-view items and the mapping of their findings back to `form`. 2. `packages/metadata-protocol/src/package-namespace-rename.ts`, `isQualifiedViewName`: now true for `form` too, so `copyName` and the whole-value `target` rewrite both follow. 3. `packages/rest/src/rest-batch-no-rollback-driver.test.ts`, the new top-level describe. ## 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. - [x] 3. No formatter ran; `pnpm lint` passes (CI-owned). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset (`@objectstack/metadata-protocol` and `@objectstack/spec`, patch), and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: three describes in `protocol.zod.ts` (prose only), its generated reference `packages/spec/docs/references/api/protocol.md` regenerated (`check:generated` green). - [x] 7. No hand edits to a generated reference (`packages/spec/docs/references/`, formerly `content/docs/references/`), `packages/*/CHANGELOG.md` or `content/docs/releases/`; the one reference change is the generator's output. - [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_017xRBcRzyxrvN74VNo88Tx5)_ --------- Co-authored-by: Claude --- .changeset/37852-form-type-followups.md | 15 ++++ .../src/destructive-still-shown-by.ts | 51 ++++++++++-- .../src/package-namespace-rename.test.ts | 45 ++++++++++ .../src/package-namespace-rename.ts | 14 +++- .../src/protocol-package-commits.ts | 17 +++- ...rotocol.destructive-still-shown-by.test.ts | 65 +++++++++++++++ ...tocol.revert-commit-honest-outcome.test.ts | 82 +++++++++++++++++++ packages/rest/src/batch-routes.ts | 10 +++ .../src/rest-batch-no-rollback-driver.test.ts | 53 ++++++++++++ packages/spec/docs/references/api/protocol.md | 10 +-- packages/spec/src/api/protocol.zod.ts | 22 +++-- 11 files changed, 361 insertions(+), 23 deletions(-) create mode 100644 .changeset/37852-form-type-followups.md diff --git a/.changeset/37852-form-type-followups.md b/.changeset/37852-form-type-followups.md new file mode 100644 index 00000000000..e8e5f1f9225 --- /dev/null +++ b/.changeset/37852-form-type-followups.md @@ -0,0 +1,15 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol): the destructive-change refusal names the authored forms that still edit a removed field, and a copied form's name follows its object + +Clause-②: no +Metadata-protocol: none + +The `409 DESTRUCTIVE_CHANGE` refusal of an `object` save now names an authored `form` item that still edits a field the save removes, as `{ type: 'form', name, where }` in the finding's `stillShownBy` and in its message. Before, it named only the old-shape form views (`view` items) and passed over every `form` item. A form the `form` listing projects from an old-shape `view` row is still named once, as that view. + +A package copied under a namespace of its own (the unmanaged install's `targetNamespace`, and `duplicatePackage`) now gives each `form` item the copy name of its object as the prefix of its `OBJECT.KEY` name, as it already did for `view` items: `ticket.entry` of an object `ticket` copied as `acme_ticket` is written as `acme_ticket.entry`, and a form action's `target` naming it follows it. Before, a form of an object whose name carried no namespace prefix kept the source's name, which its own `object` no longer matched. + +`FieldStillShownBySchema.type` (`@objectstack/spec/api`) now names `form` among the types it reports: `view` is a list view or a form in an old-shape view, `form` an authored form item. `DestructiveChangeIssueSchema.stillShownBy` names `form` among the `field_removed` item types, and `where` gives a `form` entry's path. Prose only; no shape changes. diff --git a/packages/metadata-protocol/src/destructive-still-shown-by.ts b/packages/metadata-protocol/src/destructive-still-shown-by.ts index 8c28b3550d8..33af57a2158 100644 --- a/packages/metadata-protocol/src/destructive-still-shown-by.ts +++ b/packages/metadata-protocol/src/destructive-still-shown-by.ts @@ -41,6 +41,17 @@ * (`protocol-meta-list-reads.ts`, `isAggregatedViewContainer`). So the * type-change half reads `config` and the item's own root, and nothing else. * + * The `form` listing (ADR-0159) serves the authored `form` items and, marked + * by `PROJECTED_FORM_SOURCE_KEY`, the forms it projects out of old-shape + * `view` rows. A projected form is the `view` listing's item already, named + * there, so only the authored items are read. The form-layout judge walks + * `views[]` alone, so each authored form is put before the judges in the + * stored form view item shape that judge reads (`{ name, object, viewKind: + * 'form', config }`, the shape Studio saves through `PUT /meta/view`), and a + * finding on it is named as the `form` it is, at its own path. The form also + * stays in `forms[]`, so a judge that comes to read `forms[]` itself names the + * same positions, and the two are one entry. + * * ## How it reaches the judges * * The three judges live only on `@objectstack/lint`'s ROOT entry, and this @@ -55,7 +66,7 @@ import type { FieldStillShownBy } from '@objectstack/spec/api'; import { filterOperatorFieldTypeFit } from '@objectstack/spec/data'; -import { isViewFilterOrGroup } from '@objectstack/spec/ui'; +import { PROJECTED_FORM_SOURCE_KEY, isViewFilterOrGroup } from '@objectstack/spec/ui'; /** One destructive-change finding as `detectDestructiveObjectChanges` produces it. */ export interface DestructiveFinding { @@ -82,6 +93,7 @@ const COLLECTIONS = [ ['pages', 'page'], ['flows', 'flow'], ['reports', 'report'], + ['forms', 'form'], ] as const; type Collection = (typeof COLLECTIONS)[number][0]; @@ -114,8 +126,10 @@ export async function withStillShownBy( let stack: Stack; try { const lists = await Promise.all(wanted.map(([, type]) => listServed(type))); - stack = { objects: [], views: [], datasets: [], dashboards: [], pages: [], flows: [], reports: [] }; + stack = { objects: [], views: [], datasets: [], dashboards: [], pages: [], flows: [], reports: [], forms: [] }; wanted.forEach(([collection], i) => { stack[collection] = lists[i] ?? []; }); + // A projected form is the `view` listing's item, named there. + stack.forms = stack.forms.filter((form) => isRecord(form) && !(PROJECTED_FORM_SOURCE_KEY in form)); } catch (error) { // Not computed, said once: the refusal itself stands unchanged. console.warn( @@ -220,7 +234,23 @@ function removalSurfaces( const withAll: AnyRec = { ...nextBody, name: str(nextBody.name) ?? objectName, fields: restored }; const others = stack.objects.filter((o) => !(isRecord(o) && o.name === objectName)); - const at = (objectBody: AnyRec): Stack => ({ ...stack, objects: [...others, objectBody] }); + // Each authored form, as the form view item the form-layout judge reads, + // after the served views; `formOf` maps its position back to the form. + const formOf = new Map(); + const formViews: AnyRec[] = []; + for (const form of stack.forms) { + const name = isRecord(form) ? str(form.name) : undefined; + if (!isRecord(form) || !name) continue; + const { name: _name, object, ...config } = form; + const judged: AnyRec = { name, object, viewKind: 'form', config }; + formOf.set(judged, name); + formViews.push(judged); + } + const at = (objectBody: AnyRec): Stack => ({ + ...stack, + objects: [...others, objectBody], + views: [...stack.views, ...formViews], + }); const baselineStack = at(withAll); const baseline = judge(judges, baselineStack); if (!baseline) return answers; @@ -230,13 +260,17 @@ function removalSurfaces( const { [field]: _gone, ...rest } = restored; const findings = judge(judges, at({ ...withAll, fields: rest })); if (!findings) continue; - answers.set(field, surfacesOf(baselineStack, findings.filter((f) => !seen.has(findingKey(f))))); + answers.set(field, surfacesOf(baselineStack, findings.filter((f) => !seen.has(findingKey(f))), formOf)); } return answers; } -/** The added findings, grouped by the item they sit in, plus the widgets that show the field through a dataset. */ -function surfacesOf(stack: Stack, added: readonly Finding[]): FieldStillShownBy[] { +/** + * The added findings, grouped by the item they sit in, plus the widgets that + * show the field through a dataset. A finding on a form view item `formOf` + * names is the authored `form` it was made from, at the form's own path. + */ +function surfacesOf(stack: Stack, added: readonly Finding[], formOf: ReadonlyMap): FieldStillShownBy[] { const byItem = new Map(); const add = (type: string, name: string, where: string, via?: string): void => { const id = `${type}:${name}:${via ?? ''}`; @@ -251,6 +285,11 @@ function surfacesOf(stack: Stack, added: readonly Finding[]): FieldStillShownBy[ if (!match) continue; const [, collection, index, rest] = match; const item = stack[collection as Collection][Number(index)]; + const form = formOf.get(item); + if (form !== undefined) { + add('form', form, rest.replace(/^config\.?/, '').replace(/\.field$/, '') || '(root)'); + continue; + } const name = isRecord(item) ? str(item.name) : undefined; if (!isRecord(item) || !name) continue; add(TYPE_OF[collection], name, rest.replace(/\.field$/, '') || '(root)'); diff --git a/packages/metadata-protocol/src/package-namespace-rename.test.ts b/packages/metadata-protocol/src/package-namespace-rename.test.ts index dc651687e20..f57c27752d3 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.test.ts @@ -9,6 +9,7 @@ * reach: the engine does not trust its caller's judgement of the names. */ import { describe, expect, it } from 'vitest'; +import { FormSchema } from '@objectstack/spec/ui'; import { METADATA_ITEM_NAME_STORAGE_LIMIT, OBJECT_TABLE_IDENTIFIER_LIMIT, @@ -95,6 +96,50 @@ describe('planNamespaceRename — the one rename engine (#30794)', () => { }); }); +describe('planNamespaceRename — a `form` item\'s OBJECT.KEY name follows its object (ADR-0159 D3)', () => { + const ticketForm = { + name: 'ticket.entry', object: 'ticket', type: 'simple', sections: [{ fields: [{ field: 'title' }] }], + }; + const leadForm = { + name: 'crm_lead.entry', object: 'crm_lead', type: 'simple', sections: [{ fields: [{ field: 'title' }] }], + }; + const formItems: NamespaceRenameItem[] = [ + ...items, + { type: 'object', name: 'ticket', body: { name: 'ticket', fields: { title: { name: 'title', type: 'text' } } } }, + { type: 'form', name: 'ticket.entry', body: ticketForm }, + { type: 'form', name: 'crm_lead.entry', body: leadForm }, + { type: 'action', name: 'open_entry', body: { name: 'open_entry', type: 'form', target: 'ticket.entry' } }, + ]; + const plan = () => planNamespaceRename({ + sourcePackageId: 'com.example.crm', sourceNamespace: 'crm', targetNamespace: 'acme', items: formItems, retryVerb: 'install', + }); + + it('a bare object\'s form takes the object\'s copy name as its prefix, and the copy parses as a `form`', () => { + const rename = plan(); + expect(rename.copyName('form', 'ticket.entry')).toBe('acme_ticket.entry'); + expect(rename.copyName('forms', 'ticket.entry')).toBe('acme_ticket.entry'); + const out = rename.rewrite('form', 'ticket.entry', ticketForm) as { item: Record }; + expect(out.item).toMatchObject({ name: 'acme_ticket.entry', object: 'acme_ticket' }); + expect(FormSchema.safeParse(out.item).success).toBe(true); + }); + + it('a form action\'s `target` naming the form follows it, as one naming a view item does', () => { + const out = plan().rewrite('action', 'open_entry', formItems[6]!.body) as { item: Record }; + expect(out.item.target).toBe('acme_ticket.entry'); + }); + + it('CONTROL: a prefixed object\'s form takes the same name the prefix swap gives it', () => { + const rename = plan(); + expect(rename.copyName('form', 'crm_lead.entry')).toBe('acme_lead.entry'); + const out = rename.rewrite('form', 'crm_lead.entry', leadForm) as { item: Record }; + expect(FormSchema.safeParse(out.item).success).toBe(true); + }); + + it('CONTROL: a form of an object the copy does not rename keeps its name', () => { + expect(plan().copyName('form', 'other_case.entry')).toBe('other_case.entry'); + }); +}); + describe('planNamespaceRename — a copied capability, and every grant and requirement of it (#35157)', () => { // The shape an AI-built app writes: the package DECLARES its capability, // a set GRANTS it, an action and an object REQUIRE it (ADR-0066 D1). diff --git a/packages/metadata-protocol/src/package-namespace-rename.ts b/packages/metadata-protocol/src/package-namespace-rename.ts index 36bbd8e23b2..0bd58b7141d 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.ts @@ -161,9 +161,14 @@ const CAPABILITY_REFERENCE_KEYS: ReadonlySet = new Set(['systemPermissio */ const HAS_CAPABILITY_CALL = /(\bhasCapability\(\s*)(['"])([^'"\\]*)\2/g; -/** A `view` row whose name is qualified `.` (`ViewItemNameSchema`). */ +/** + * A row whose name is qualified by its object, `.`: a `view` item + * (`ViewItemNameSchema`) or a `form` item (ADR-0159 D3, `FormSchema`: "a form + * whose name is OBJECT.KEY", its prefix its `object`). + */ function isQualifiedViewName(type: string, name: unknown): name is string { - return isViewType(type) && typeof name === 'string' && name.includes('.'); + const singular = PLURAL_TO_SINGULAR[String(type)] ?? String(type); + return (singular === 'view' || singular === 'form') && typeof name === 'string' && name.includes('.'); } /** A body's `fields` record keys, when it has one. */ @@ -302,6 +307,11 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam // while its `object` stayed `iojn_ext`. An object this copy does not // rename keeps its items' names. // + // A `form` item's name is qualified the same way (ADR-0159 D3), so it + // follows its object by the same rule: `ticket.entry` copies as + // `iojn2_ticket.entry` beside the body's `object: 'iojn2_ticket'`, the + // only name `FormSchema` accepts for that object. + // // A value that IS such a name, whole, follows the item: a form action's // `target` (`.`) kept `ticket.entry`, so the copy's // button opened the SOURCE's form, on the source's object. Whole values diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index cee57dcab20..ac328bdbeb9 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -1247,7 +1247,22 @@ export class ProtocolPackageCommitsFacet { return row; } - /** The body of `ObjectStackProtocolImplementation#revertCommit`; the method's docblock there is its contract. */ + /** + * The body of `ObjectStackProtocolImplementation#revertCommit`; the + * method's docblock there is its contract, and two of its rules are + * stated here, where they run: + * + * - **The walk order** ({@link revertWalkOrder}): the plan's items newest + * first, so an item is taken back before an item it depends on (a view + * before the new object it binds), except that every `form` item is + * walked after every `view` row the commit edited (ADR-0159 D5). Each + * other item keeps its newest-first place. + * - **The hold** ({@link editedViewsNotPutBack}, ADR-0067 D3): a `form` + * item is taken back only once every `view` row the commit edited stands + * again. While one is in `failed[]`, the form goes into `failed[]` too, + * nothing written, and stays as published; the commit's other items, + * of every other type, are still reverted. + */ static async revertCommit(host: Pick, request: { commitId: string; /** diff --git a/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts index 7d274cf5eec..f8d1eaca3ba 100644 --- a/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts +++ b/packages/metadata-protocol/src/protocol.destructive-still-shown-by.test.ts @@ -302,6 +302,71 @@ describe('a refused field removal names the views and forms that still show the }); }); +/** + * An authored `form` item (ADR-0159) editing `status`, and a CONTROL on + * another object whose form edits a field of the same name. + */ +const leadQuickForm = row('form', 'crm_lead.quick_edit', { + name: 'crm_lead.quick_edit', + object: 'crm_lead', + type: 'simple', + sections: [{ label: 'Main', fields: [{ field: 'name' }, { field: 'status' }] }], +}); +const contactObject = row('object', 'crm_contact', { name: 'crm_contact', label: 'Contact', fields: FIELDS }); +const contactQuickForm = row('form', 'crm_contact.quick_edit', { + name: 'crm_contact.quick_edit', + object: 'crm_contact', + type: 'simple', + sections: [{ label: 'Main', fields: [{ field: 'status' }] }], +}); +/** An old-shape form item, which the served `form` listing also serves, projected and marked. */ +const leadEntryItem = row('view', 'crm_lead.entry', { + name: 'crm_lead.entry', + object: 'crm_lead', + viewKind: 'form', + config: { type: 'simple', sections: [{ label: 'Main', fields: ['name', 'status'] }] }, +}); + +describe('a refused field removal names the authored forms that still edit the field', () => { + it('names the authored form, as a `form`, beside the old-shape form view', async () => { + const err = await refusal([leadObject, leadForm, leadQuickForm], withoutStatus); + expect(err.code).toBe('DESTRUCTIVE_CHANGE'); + expect(err.status).toBe(409); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([ + { type: 'view', name: 'crm_lead_edit', where: ['sections[0].fields[1]'] }, + { type: 'form', name: 'crm_lead.quick_edit', where: ['sections[0].fields[1]'] }, + ]); + expect(removed.message).toContain('form "crm_lead.quick_edit"'); + }); + + it('CONTROL: a form of another object editing a field of the same name is not named', async () => { + const err = await refusal([leadObject, contactObject, contactQuickForm], withoutStatus); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([]); + }); + + it('CONTROL: a form the `form` listing projects from an old-shape view is named once, as the view', async () => { + const { protocol } = makeKernel([leadObject, leadEntryItem]); + // The premise: the served `form` listing does serve the projection. + const forms = await protocol.getMetaItems({ type: 'form' }); + expect(forms.items.map((i: any) => i.name)).toContain('crm_lead.entry'); + const err = await refusalOf(protocol, withoutStatus); + const removed = err.issues.find((i: any) => i.code === 'field_removed' && i.field === 'status'); + expect(removed.stillShownBy).toEqual([ + { type: 'view', name: 'crm_lead.entry', where: ['config.sections[0].fields[1]'] }, + ]); + }); + + it('produces a `form` entry the declared wire shape parses (DestructiveChangeIssueSchema)', async () => { + const err = await refusal([leadObject, leadQuickForm], withoutStatus); + for (const issue of err.issues) { + const parsed = DestructiveChangeIssueSchema.safeParse(issue); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + } + }); +}); + describe('a refused type change names the list-view filters whose operator no longer fits', () => { it('names the view filter whose text operator the new number type refuses', async () => { const err = await refusal([leadObject, leadList, leadForm], { diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index 605925e7f5e..858376ee1d1 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -752,3 +752,85 @@ describe('[#33851] revertCommit reports a removed item whose registry heal stops expect(storedLabelOf(rows, c)).toBe('Other'); }); }); + +// ═══════════════════════════════════════════════════════════════════════════ +// [ADR-0159 D5, ADR-0067 D3] The form's walk order and hold: a commit's +// `page` and `permission` (permission set) items keep theirs +// ═══════════════════════════════════════════════════════════════════════════ + +describe('[ADR-0159 D5, ADR-0067 D3] a commit\'s page and permission set revert beside a `form` the hold keeps', () => { + const pageBody = (label: string) => ({ name: 'ticket_home', label, type: 'app', regions: [] }); + const permissionBody = (label: string) => ({ name: 'ticket_agent', label, objects: {} }); + const formBody = { + name: 'ticket.entry', object: 'ticket', type: 'simple', sections: [{ fields: [{ field: 'title' }] }], + }; + const labelOf = (rows: Map, type: string, name: string): string | undefined => { + for (const r of rows.values()) { + if (r.type === type && r.name === name && r.state === 'active') return JSON.parse(r.metadata).label; + } + return undefined; + }; + const hasRow = (rows: Map, type: string, name: string): boolean => + [...rows.values()].some((r) => r.type === type && r.name === name && r.state === 'active'); + + /** + * The page and the permission set saved twice (v1 'Before', v2 'After'), + * a list view saved twice, and the form the commit created. `viewPutBack` + * false records the view as edited with no version to restore, so it + * lands in `failed[]` and the hold keeps the form. + */ + async function commitWithForm(viewPutBack: boolean) { + const rig = makeProtocol(); + const save = (type: string, name: string, item: unknown) => rig.protocol.saveMetaItem({ type, name, item, packageId: PKG }); + await save('object', 'ticket', objectBody('Ticket')); + await save('page', 'ticket_home', pageBody('Before')); + await save('page', 'ticket_home', pageBody('After')); + await save('permission', 'ticket_agent', permissionBody('Before')); + await save('permission', 'ticket_agent', permissionBody('After')); + const view = (label: string) => ({ name: 'ticket.board', object: 'ticket', label, viewKind: 'list', config: { type: 'grid', columns: ['title'] } }); + await save('view', 'ticket.board', view('Before')); + await save('view', 'ticket.board', view('After')); + await save('form', 'ticket.entry', formBody); + recordApply(rig.commits, 'c1', [ + { type: 'view', name: 'ticket.board', existedBefore: true, prevVersion: viewPutBack ? 1 : null }, + { type: 'page', name: 'ticket_home', existedBefore: true, prevVersion: 1 }, + { type: 'permission', name: 'ticket_agent', existedBefore: true, prevVersion: 1 }, + { type: 'form', name: 'ticket.entry', existedBefore: false, prevVersion: null }, + ]); + return rig; + } + + it('the view not put back holds the form as published, and the page and the permission set are restored all the same', async () => { + const { protocol, rows } = await commitWithForm(false); + expect(hasRow(rows, 'form', 'ticket.entry')).toBe(true); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.failed.map((f: { type: string; name: string }) => `${f.type}/${f.name}`)).toEqual(['view/ticket.board', 'form/ticket.entry']); + expect(res.reverted).toEqual(expect.arrayContaining([ + { type: 'page', name: 'ticket_home', action: 'restored' }, + { type: 'permission', name: 'ticket_agent', action: 'restored' }, + ])); + expect(labelOf(rows, 'page', 'ticket_home')).toBe('Before'); + expect(labelOf(rows, 'permission', 'ticket_agent')).toBe('Before'); + expect(hasRow(rows, 'form', 'ticket.entry')).toBe(true); + }); + + it('CONTROL: the view put back, the form is removed too, and the page and the permission set are restored', async () => { + const { protocol, rows } = await commitWithForm(true); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.failed).toEqual([]); + expect(res.reverted.map((r: { type: string; name: string; action: string }) => `${r.type}/${r.name}:${r.action}`)).toEqual([ + 'permission/ticket_agent:restored', + 'page/ticket_home:restored', + 'view/ticket.board:restored', + 'form/ticket.entry:removed', + ]); + expect(labelOf(rows, 'page', 'ticket_home')).toBe('Before'); + expect(labelOf(rows, 'permission', 'ticket_agent')).toBe('Before'); + expect(hasRow(rows, 'form', 'ticket.entry')).toBe(false); + }); +}); diff --git a/packages/rest/src/batch-routes.ts b/packages/rest/src/batch-routes.ts index f321bb114e1..16579f55605 100644 --- a/packages/rest/src/batch-routes.ts +++ b/packages/rest/src/batch-routes.ts @@ -562,6 +562,16 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string): return out; }; let results: any[]; + // Who owns this unit: with none open, the engine opens it and + // commits or rolls it back itself; inside a unit an outer + // caller opened, the engine JOINS it (ADR-0067 D2) and that + // caller decides commit or rollback, for these ops' writes too. + // It is opened here, not through the metadata protocol's + // overlay-cache guard, and needs none: no op can write a + // `sys_metadata` row (that object exposes `get` and `list` + // only, refused above before the unit opens), so its rollback + // never takes back a metadata write a cached read still serves. + // `rest-batch-no-rollback-driver.test.ts` pins both halves. try { results = await ql.transaction(runOps, context, { require: true }); } catch (error: unknown) { diff --git a/packages/rest/src/rest-batch-no-rollback-driver.test.ts b/packages/rest/src/rest-batch-no-rollback-driver.test.ts index d99cfa0692d..d913b41efbc 100644 --- a/packages/rest/src/rest-batch-no-rollback-driver.test.ts +++ b/packages/rest/src/rest-batch-no-rollback-driver.test.ts @@ -33,6 +33,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataObject } from '@objectstack/metadata-core'; import { RestServer } from './rest-server'; /** Inherits `beginTransaction`; the transport declares it cannot honour it. */ @@ -114,6 +115,7 @@ async function boot(canRollBack: boolean) { batch: (operations: unknown[]) => call(batchRoute, { operations }), discovery: () => call(discoveryRoute), rows: async (object: string) => (await engine.find(object, {})) as any[], + engine, }; } @@ -180,3 +182,54 @@ describe('[#32604] controls: POST /api/v1/batch on a driver that can roll back i expect(doc.body.capabilities.transactionalBatch.enabled).toBe(true); }); }); + +/** + * Which side owns the transaction `POST /api/v1/batch` runs in. The route + * calls `ql.transaction(runOps, context, { require: true })`: with no unit + * open, the engine opens one and owns its commit and rollback; inside a unit + * an outer caller opened, the engine JOINS it (ADR-0067 D2) and that caller + * decides commit or rollback, for the batch's writes too. And no op can write + * a `sys_metadata` row (the object exposes `get` and `list` only), so the + * unit, opened outside the metadata protocol's overlay-cache guard, never + * rolls back a metadata write. + */ +describe('POST /api/v1/batch: the transaction is the opener\'s', () => { + it('inside a unit an outer caller opened, the batch joins it: the outer rollback takes back the rows the batch answered 200 for', async () => { + const ctx = await boot(true); + const outer = new Error('the outer caller rolls back'); + let answer: { status: number; body: any } | undefined; + await expect(ctx.engine.transaction(async () => { + answer = await ctx.batch(GOOD_BATCH); + // Joined: the batch's rows are visible inside the outer unit, not yet committed. + expect((await ctx.engine.find('nrb_alpha', {})).map((r: any) => r.id)).toEqual(['a-1']); + throw outer; + })).rejects.toBe(outer); + expect(answer?.status).toBe(200); + expect(await ctx.rows('nrb_alpha')).toEqual([]); + expect(await ctx.rows('nrb_beta')).toEqual([]); + }); + + it('CONTROL: inside an outer unit that commits, the batch\'s rows land with it', async () => { + const ctx = await boot(true); + await ctx.engine.transaction(async () => { + expect((await ctx.batch(GOOD_BATCH)).status).toBe(200); + }); + expect((await ctx.rows('nrb_alpha')).map((r) => r.id)).toEqual(['a-1']); + expect((await ctx.rows('nrb_beta')).map((r) => r.id)).toEqual(['b-1']); + }); + + it('an op writing `sys_metadata` is refused 405 before the transaction opens, and nothing is written', async () => { + const ctx = await boot(true); + ctx.engine.registry.registerObject(SysMetadataObject as any); + await ctx.engine.syncSchemas(); + const before = await ctx.rows('sys_metadata'); + const answer = await ctx.batch([ + { object: 'nrb_alpha', action: 'create', data: { id: 'a-1', title: 'First op' } }, + { object: 'sys_metadata', action: 'create', data: { type: 'form', name: 'nrb_alpha.entry', metadata: '{}' } }, + ]); + expect(answer.status).toBe(405); + expect(answer.body.code).toBe('OBJECT_API_METHOD_NOT_ALLOWED'); + expect(await ctx.rows('nrb_alpha')).toEqual([]); + expect(await ctx.rows('sys_metadata')).toEqual(before); + }); +}); diff --git a/packages/spec/docs/references/api/protocol.md b/packages/spec/docs/references/api/protocol.md index 1675b7f0f0d..f432ce63ece 100644 --- a/packages/spec/docs/references/api/protocol.md +++ b/packages/spec/docs/references/api/protocol.md @@ -837,15 +837,15 @@ A write-path strip event: caller-supplied fields legally dropped from the payloa | **code** | `string` | ✅ | What the save loses: `field_removed`, `field_type_change`, `field_required_no_default`, `currency_mode_to_record`, `currency_field_repointed`, `unit_code_field_declared` or `unit_mode_to_record`. | | **field** | `string` | optional | The field the finding is about. | | **message** | `string` | ✅ | The finding in prose. When `stillShownBy` names items, the prose ends by naming them too. | -| **stillShownBy** | `{ type: string; name: string; where: string[]; via?: string; … }[]` | optional | The metadata items that still show the field, computed from the environment's served metadata (one served listing per type: what the code packages register, with this environment's stored active rows folded over them; drafts are not read, and no record is read). On `field_removed` and `field_type_change` findings only; absent on every other code, and absent when it could not be computed: a listing could not be read, a judge threw or could not be loaded, or the retyped field's new definition carries no readable `type` (absent is "not computed", `[]` is "computed, none"). On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow` and `report` items in which the platform's reference-integrity suite, form-layout check and widget-binding check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with the field and dangles without it, the saved body taken as the save would write it; plus each dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position those judges do not read is not seen, nor is an item of any other type (an app, an action, a permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a served `view` item bound to the saved object that names the field by its bare name and whose operator does not fit the new type, judged by `filterOperatorFieldTypeFit` (an operator is unfit only where a declared-type door refuses it; a filter another door refuses, such as any filter on a field retyped to `formula`, is not named). The rules read are a view item's `config.filter` (the canonical served shape), a flattened list overlay's own `filter`, and the `userFilters.tabs[].filter` of either, rules inside an any-of group included. Filters elsewhere (datasets, dashboards, reports, flows), dotted paths, and comparands are not judged there. The save does not edit any listed item. | +| **stillShownBy** | `{ type: string; name: string; where: string[]; via?: string; … }[]` | optional | The metadata items that still show the field, computed from the environment's served metadata (one served listing per type: what the code packages register, with this environment's stored active rows folded over them; drafts are not read, and no record is read). On `field_removed` and `field_type_change` findings only; absent on every other code, and absent when it could not be computed: a listing could not be read, a judge threw or could not be loaded, or the retyped field's new definition carries no readable `type` (absent is "not computed", `[]` is "computed, none"). On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow`, `report` and `form` items in which the platform's reference-integrity suite, form-layout check and widget-binding check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with the field and dangles without it, the saved body taken as the save would write it; an authored `form` item is judged in the form view item shape the form-layout check reads, and a form the served `form` listing projects from an old-shape `view` is named once, as that view; plus each dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position those judges do not read is not seen, nor is an item of any other type (an app, an action, a permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a served `view` item bound to the saved object that names the field by its bare name and whose operator does not fit the new type, judged by `filterOperatorFieldTypeFit` (an operator is unfit only where a declared-type door refuses it; a filter another door refuses, such as any filter on a field retyped to `formula`, is not named). The rules read are a view item's `config.filter` (the canonical served shape), a flattened list overlay's own `filter`, and the `userFilters.tabs[].filter` of either, rules inside an any-of group included. Filters elsewhere (datasets, dashboards, reports, flows), dotted paths, and comparands are not judged there. The save does not edit any listed item. | ### Nested Shape: `DestructiveChangeIssue.stillShownBy[number]` | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view, or a form in an old-shape view), `form` (an authored form item), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | | **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | -| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `sections[0].fields[1]` on a `form` item, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | | **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | | **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | @@ -1002,9 +1002,9 @@ Enable package response | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | +| **type** | `string` | ✅ | The metadata type of the item: `view` (a list view, or a form in an old-shape view), `form` (an authored form item), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another object, or the saved object's own body). | | **name** | `string` | ✅ | The item's name, as the served list names it. One item can appear in more than one entry: a dashboard once directly and once per `via` dataset, a view once per unfit `operator`. | -| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | +| **where** | `string[]` | ✅ | Each position inside the item that names the field, as a path relative to the item as the served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view item (the served listing never presents a `{ list, form, listViews }` container, only the view items it expands into), `columns[1]` on a flattened list overlay, `sections[0].fields[1]` on a `form` item, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on the item itself. | | **via** | `string` | optional | A dashboard widget shows the field through this dataset: it names a dimension or measure of the dataset, and that dimension or measure names the field. | | **operator** | `string` | optional | On a `field_type_change` entry only: the filter operator, as the view rule spells it, that no longer fits the new type (`filterOperatorFieldTypeFit` answers `unfit`). | diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 5b0bc42267e..dcd1de9e416 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -1457,8 +1457,9 @@ export const SaveMetaItemResponseSchema = lazySchema(() => z.object({ */ export const FieldStillShownBySchema = lazySchema(() => z.object({ type: z.string().describe( - 'The metadata type of the item: `view` (a list view or a form), `dataset`, `dashboard`, `page`, ' - + '`flow`, `report`, or `object` (another object, or the saved object\'s own body).', + 'The metadata type of the item: `view` (a list view, or a form in an old-shape view), `form` (an ' + + 'authored form item), `dataset`, `dashboard`, `page`, `flow`, `report`, or `object` (another ' + + 'object, or the saved object\'s own body).', ), name: z.string().describe( 'The item\'s name, as the served list names it. One item can appear in more than one entry: a ' @@ -1468,8 +1469,9 @@ export const FieldStillShownBySchema = lazySchema(() => z.object({ 'Each position inside the item that names the field, as a path relative to the item as the ' + 'served listing presents it: `config.columns[1]` or `config.sections[0].fields[2]` on a view ' + 'item (the served listing never presents a `{ list, form, listViews }` container, only the ' - + 'view items it expands into), `columns[1]` on a flattened list overlay, `widgets[3]` on a ' - + 'dashboard. The literal `(root)` when the finding sits on the item itself.', + + 'view items it expands into), `columns[1]` on a flattened list overlay, `sections[0].fields[1]` ' + + 'on a `form` item, `widgets[3]` on a dashboard. The literal `(root)` when the finding sits on ' + + 'the item itself.', ), via: z.string().optional().describe( 'A dashboard widget shows the field through this dataset: it names a dimension or measure of ' @@ -1505,11 +1507,13 @@ export const DestructiveChangeIssueSchema = lazySchema(() => z.object({ + 'absent when it could not be computed: a listing could not be read, a judge threw or could not ' + 'be loaded, or the retyped field\'s new definition carries no readable `type` (absent is "not ' + 'computed", `[]` is "computed, none"). ' - + 'On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow` and `report` ' - + 'items in which the platform\'s reference-integrity suite, form-layout check and widget-binding ' - + 'check (`@objectstack/lint`, the judges `os validate` runs) find a reference that resolves with ' - + 'the field and dangles without it, the saved body taken as the save would write it; plus each ' - + 'dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position ' + + 'On `field_removed`: the `object`, `view`, `dataset`, `dashboard`, `page`, `flow`, `report` and ' + + '`form` items in which the platform\'s reference-integrity suite, form-layout check and ' + + 'widget-binding check (`@objectstack/lint`, the judges `os validate` runs) find a reference that ' + + 'resolves with the field and dangles without it, the saved body taken as the save would write it; ' + + 'an authored `form` item is judged in the form view item shape the form-layout check reads, and ' + + 'a form the served `form` listing projects from an old-shape `view` is named once, as that view; ' + + 'plus each dashboard widget bound to a dataset dimension or measure that dangles (`via`). A position ' + 'those judges do not read is not seen, nor is an item of any other type (an app, an action, a ' + 'permission set), nor code outside the metadata. On `field_type_change`: each filter rule of a ' + 'served `view` item bound to the saved object that names the field by its bare name and whose ' From d1a06a3d83f97c4056ccca062a049715d205026b Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:03:27 +0000 Subject: [PATCH 053/178] fix(plugin-chatbot): one answer's body-less step turns render as one group with one source block (#38530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #38457 Clause-②: no Metadata-protocol: none ## 维护者速读 - 在 AI 问询页,同一次回答里连着的几段步骤现在挨在一起排,「计算方式」只出一次;不同轮问答之间的间距不变。 - 替用户解决「一个回答看起来像好几条不相干回复」的观感问题(AI 问询体验)。 - 只影响聊天里的排版,出错时最多是步骤显示成原来的分散样子,可直接撤回。 - 无 ## What changes The conversation store persists each step of one agent answer as its own assistant row, and app-shell's history hydration (`toUIMessages`, one row in, one message out) keeps that shape, so a reloaded multi-tool answer reaches `ChatbotEnhanced` as several assistant messages with no prose. Each was laid out as its own turn (the `ConversationContent` gap plus the outer `space-y-4`) and each drew its own 「计算方式」 block. The existing hydrated-step test for objectui#10899 documents the same persisted shape. In `ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx`: - `isBodylessStepTurn` names a finished assistant turn with no body: no showable prose (empty, whitespace or the `(called ...)` placeholder), no chart, no question, no record citations, no draft review. A streaming turn never counts, so nothing is regrouped (and remounted) mid-stream. - `segmentStepTurns` folds every run of two or more ADJACENT such turns into one segment. A user turn or an assistant turn with prose ends the run, so a group never crosses turns, and a lone step turn renders exactly as before. - The message loop body moved, unchanged apart from its source list, into a `renderMessage(message, answerSources)` closure. A step group renders as one `data-testid="assistant-step-group"` child of the conversation with `flex flex-col gap-2`, the spacing `MessageContent` uses inside a message. The turn gap now falls only around the group. - The group draws ONE `AnswerSourceBlock`, under its last step, with every step's sources concatenated in call order. `AnswerSourceBlock` already takes a list and separates entries with a rule, so merging drops nothing. Producer note: the split comes from the store's per-step persistence (served by the AI service outside this repository) and the one-row-per-message hydration in app-shell. I fixed it at render, as the card asks: the card limits grouping to body-less messages and keeps each step row, while merging rows at hydration would also join prose rows and collapse the step rows into one summary, which is a different visible result. ## Tests `ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.stepGroup-38457.test.tsx` (real `ChatbotEnhanced`, jsdom): - three body-less step turns render in one group, the group is the conversation's only assistant child, it carries the in-message spacing, and there is exactly one 「计算方式」 holding both steps' sources in call order; - CONTROL: two separate turns keep separate children (the turn gap) and their own blocks; - CONTROL: an assistant turn with prose ends the run.
Readings at 2a6f16a7 - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-chatbot/`: Test Files 83 passed (83), Tests 775 passed (775); `pnpm --filter @object-ui/plugin-chatbot type-check`: exit 0 (lock VERDICT command-exit 0). - Ablation 1, via `scripts/ablation-replace.mjs` (anchor hit 1 to 0, blob 01861fd0 to 22149602): `if (run.length > 1) segments.push` replaced by `if (false) segments.push`. Result: the group pin turns red, 1 failed and 2 passed. Restored blob = HEAD blob 01861fd0. - Ablation 2 (blob 01861fd0 to 59bc3ad7): the last step's merged sources replaced by each step's own. Result: the group pin turns red, 1 failed and 2 passed. Restored and checked by hash. - `pnpm --dir ui exec vitest run scripts/`: Test Files 172 passed and 2 skipped; Tests 5159 passed and 2 skipped. - `node scripts/pm/dispatch-gates.mjs --ran`: 38 derived, 38 run, each with its exit code (all 0), 0 NOT-MEASURED. `pnpm check:changeset-fixed`: exit 0. `pnpm check:new-line-citations` (ui): 0 new.
## Acceptance notes - Not verified in a browser. The AI chat page needs a live AI service and a model, and neither runs in this container. The layout is pinned in jsdom only. - Left as the card scopes it: the final prose answer that follows a step group stays a separate child, so the turn-sized gap still sits between the last step and the answer text. The card asks only for body-less messages to be grouped. - A hidden HITL continuation user turn also ends a run, so steps either side of an approval stay in separate groups. ## Verification Read first: the `segmentStepTurns` / `isBodylessStepTurn` helpers, then the step-group branch in the message loop. The `renderMessage` move is the large hunk and is the old loop body except for the `AnswerSourceBlock sources={answerSources}` line. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.stepGroup-38457.test.tsx` should report 3 passed. Account: os-project-manager 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5pH8MaBBP5T2dVcTHL --------- Co-authored-by: Claude --- .changeset/38457-chat-steps-one-group.md | 12 + .../plugin-chatbot/src/ChatbotEnhanced.tsx | 278 ++++++++++++------ .../ChatbotEnhanced.stepGroup-38457.test.tsx | 115 ++++++++ 3 files changed, 313 insertions(+), 92 deletions(-) create mode 100644 .changeset/38457-chat-steps-one-group.md create mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.stepGroup-38457.test.tsx diff --git a/.changeset/38457-chat-steps-one-group.md b/.changeset/38457-chat-steps-one-group.md new file mode 100644 index 00000000000..cfa97e1b10c --- /dev/null +++ b/.changeset/38457-chat-steps-one-group.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-chatbot': patch +--- + +fix(plugin-chatbot): the steps of one AI answer read as one answer, with one "How this was computed" block + +Clause-②: no +Metadata-protocol: none + +The conversation store keeps each step of an agent answer as its own assistant message, so a reloaded answer that called several tools showed several prose-less messages in a row: each only a step line, some with their own "How this was computed" block. Each was spaced like a separate reply. Adjacent assistant messages with no body (no prose, chart, question, record citations or draft review) are now drawn as one group: their step lines sit at the spacing used inside a message, and the group shows one "How this was computed" block holding every step's sources in call order. A user message or an assistant message with prose ends the group, so the gap between separate turns is unchanged, and a single prose-less message renders as before. + +Nothing to migrate. diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index f6e95feb240..01861fd05eb 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -73,7 +73,7 @@ import { Source, } from './elements/sources'; import { detectPackageRemovedResult } from './mapMessages'; -import { AnswerSourceBlock } from './AnswerSource'; +import { AnswerSourceBlock, type AnswerSourceBlockProps } from './AnswerSource'; import { RecordCitations } from './RecordCitations'; import { DraftReviewCard } from './chat/DraftReviewCard'; import type { @@ -138,6 +138,72 @@ function formatMessageProps(role: ChatbotEnhancedMessage['role']): MessageProps[ return role === 'user' ? 'user' : 'assistant'; } +/** + * objectstack#38457 — a finished assistant turn with no body: no showable + * prose (empty, whitespace or the persisted `(called …)` placeholder), no + * chart, no question, no record citations, no draft review. The conversation + * store persists each step of one answer as its own assistant row, so a + * reloaded answer arrives as several of these in a row — steps of ONE answer, + * not separate replies. A streaming turn never counts: it is still becoming + * its final shape, and regrouping it mid-stream would remount it. + */ +function isBodylessStepTurn( + message: ChatbotEnhancedMessage, + questionsByMessage: ReadonlyMap, +): boolean { + if (message.role !== 'assistant' || message.streaming) return false; + const text = message.content.trim(); + if (text.length > 0 && !isToolCallPlaceholder(message.content)) return false; + return ( + !message.charts?.length && + !questionsByMessage.has(message.id) && + !message.recordCitations && + !message.draftReview + ); +} + +type MessageSegment = + | { kind: 'message'; message: ChatbotEnhancedMessage } + | { kind: 'steps'; messages: ChatbotEnhancedMessage[] }; + +/** + * objectstack#38457 — the conversation in render order, with every run of two + * or more ADJACENT step turns folded into one `steps` segment. Any other + * message — a user turn, or an assistant turn with a body — ends the run, so a + * step group never reaches across turns. A lone step turn stays a plain + * message. + */ +function segmentStepTurns( + messages: readonly ChatbotEnhancedMessage[], + isStep: (message: ChatbotEnhancedMessage) => boolean, +): MessageSegment[] { + const segments: MessageSegment[] = []; + let run: ChatbotEnhancedMessage[] = []; + const flush = () => { + if (run.length > 1) segments.push({ kind: 'steps', messages: run }); + else if (run.length === 1) segments.push({ kind: 'message', message: run[0] }); + run = []; + }; + for (const message of messages) { + if (isStep(message)) { + run.push(message); + continue; + } + flush(); + segments.push({ kind: 'message', message }); + } + flush(); + return segments; +} + +/** A message's lifted answer sources, one per tool that answered one, in call order. */ +function answerSourcesOf(message: ChatbotEnhancedMessage): AnswerSourceBlockProps['sources'] { + if (message.role === 'user') return []; + return (message.toolInvocations ?? []).flatMap((tool) => + tool.answerSource ? [{ key: tool.toolCallId, source: tool.answerSource }] : [], + ); +} + const ChatbotEnhanced = React.forwardRef( ( { @@ -653,89 +719,14 @@ const ChatbotEnhanced = React.forwardRef( recordHandoffOpenLabel, }; - return ( -
- {onClear && !hideClearBar && messages.length > 0 && ( -
- -
- )} - - {headerSlot ? ( -
- {headerSlot} -
- ) : null} - - - - {messages.length === 0 && renderEmptyState ? ( -
{renderEmptyState(emptyStateActions)}
- ) : messages.length === 0 ? ( - -
- {assistantAvatarUrl ? ( - - ) : ( - - )} -
-
-

{L.emptyTitle}

-

- {L.emptyDescription} -

-
- {suggestions && suggestions.length > 0 ? ( -
- {suggestions.map((s) => ( - - ))} -
- ) : null} -
- ) : ( - messages.map((message) => { + // One message of the conversation. `answerSources` is what its + // 「计算方式」 block draws: its own sources, or — inside a step group + // (objectstack#38457) — none on the earlier steps and the whole group's on + // the last. + const renderMessage = ( + message: ChatbotEnhancedMessage, + answerSources: AnswerSourceBlockProps['sources'], + ) => { const isUser = message.role === 'user'; // objectstack#30223 — the follow-up turn `useHitlInChat` sends // the model after 确认 / 取消 is not the person's words, so it @@ -916,13 +907,7 @@ const ChatbotEnhanced = React.forwardRef( ) : null} {!isUser ? ( - - tool.answerSource - ? [{ key: tool.toolCallId, source: tool.answerSource }] - : [], - )} - /> + ) : null} {/* ADR-0160 D9 — the records the answer rests on. */} {!isUser && message.recordCitations ? ( @@ -1000,7 +985,116 @@ const ChatbotEnhanced = React.forwardRef(
); - }) + }; + const isStepTurn = (message: ChatbotEnhancedMessage) => + isBodylessStepTurn(message, questionsByMessage); + + return ( +
+ {onClear && !hideClearBar && messages.length > 0 && ( +
+ +
+ )} + + {headerSlot ? ( +
+ {headerSlot} +
+ ) : null} + + + + {messages.length === 0 && renderEmptyState ? ( +
{renderEmptyState(emptyStateActions)}
+ ) : messages.length === 0 ? ( + +
+ {assistantAvatarUrl ? ( + + ) : ( + + )} +
+
+

{L.emptyTitle}

+

+ {L.emptyDescription} +

+
+ {suggestions && suggestions.length > 0 ? ( +
+ {suggestions.map((s) => ( + + ))} +
+ ) : null} +
+ ) : ( + segmentStepTurns(messages, isStepTurn).map((segment) => + segment.kind === 'message' ? ( + renderMessage(segment.message, answerSourcesOf(segment.message)) + ) : ( + // objectstack#38457 — one answer's body-less step turns, drawn + // as ONE child of the conversation: the turn gap + // (`ConversationContent`'s gap and spacing) separates turns, + // and inside the group the steps sit at the in-message + // spacing. The group's 「计算方式」 is drawn once, under its + // last step, carrying every step's sources in call order. +
+ {segment.messages.map((message, i, group) => + renderMessage( + message, + i === group.length - 1 ? group.flatMap(answerSourcesOf) : [], + ), + )} +
+ ), + ) )} {isLoading && !messages.some((message) => message.streaming) ? ( ({ object, scope: 'visible_to_you' as const, line: 'Read the matching records' }); + +/** One persisted step row: the placeholder text and the step's completed tool. */ +function stepTurn(id: string, toolName: string, object?: string): ChatbotEnhancedMessage { + return { + id, + role: 'assistant', + content: `(called ${toolName})`, + toolInvocations: [ + { + toolCallId: `${id}-call`, + toolName, + state: 'output-available', + ...(object ? { answerSource: source(object) } : {}), + }, + ], + }; +} + +const question = (id: string, content: string): ChatbotEnhancedMessage => ({ id, role: 'user', content }); + +/** The conversation's own children: one per turn the turn gap separates. */ +const conversationChildren = (container: HTMLElement) => { + const first = container.querySelector('.is-user, .is-assistant, [data-testid="assistant-step-group"]'); + return Array.from(first!.parentElement!.children); +}; + +describe('step turns of one answer render as one group (objectstack#38457)', () => { + it('three body-less step turns sit in one group at in-message spacing, with one 计算方式 block', () => { + const { container } = render( + , + ); + + const groups = screen.getAllByTestId('assistant-step-group'); + expect(groups).toHaveLength(1); + const group = groups[0]; + // All three steps are inside the group, and the group — not each step — + // is the conversation's child, so the turn gap falls only around it. + expect(group.querySelectorAll('.is-assistant')).toHaveLength(3); + expect(conversationChildren(container)).toHaveLength(2); + // The in-message spacing (`MessageContent`'s own gap), not the turn gap. + expect(group).toHaveClass('gap-2'); + + // One 「计算方式」 for the whole answer, holding both steps' sources. + expect(screen.getAllByTestId('answer-source')).toHaveLength(1); + fireEvent.click(screen.getByRole('button', { name: 'How this was computed' })); + const block = screen.getByTestId('answer-source'); + const sections = within(block).getAllByTestId('answer-source-section'); + expect(sections.map((section) => section.getAttribute('data-object'))).toEqual(['crm_project', 'crm_form']); + }); + + it('CONTROL — two separate turns keep the turn gap and their own 计算方式 blocks', () => { + const { container } = render( + , + ); + expect(screen.queryByTestId('assistant-step-group')).toBeNull(); + expect(conversationChildren(container)).toHaveLength(4); + expect(screen.getAllByTestId('answer-source')).toHaveLength(2); + }); + + it('CONTROL — a turn with prose ends the run: no group reaches across it', () => { + render( + , + ); + expect(screen.queryByTestId('assistant-step-group')).toBeNull(); + expect(screen.getAllByTestId('answer-source')).toHaveLength(2); + }); +}); From 1dccbb1663b6e7cb061663c029fd856fbbe58957 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:29:54 +0000 Subject: [PATCH 054/178] fix(rest): four more refusal exits say they vary by Accept-Language when the body carries a userMessage (#38532) 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_01TenzsRopZj4jMbvjX8uz1XHtWFhuTj5hxNoYFb2Sn8Y5)_ Fixes #38507 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:多语言部署里,记录字段权限、记录页、全局搜索和公开表单提交这四个接口被拒绝时,回应现在会注明"内容随语言不同",状态码、错误码和提示文字都不变。 - 为什么做:上一张同类卡只修了数据增删改查接口,这四个接口漏了;漏掉时前面若有共享缓存,可能把一种语言的提示给到用另一种语言的人。 - 出错会怎样:只多一个响应头,不改任何拒绝本身;若有问题可直接撤回本次改动。 - 要你做什么:无。 ## What changes Per-site verdicts for the five catches the card lists (main `0af813f3`). Each sent `res.status(mapped.status).json(mapped.body)` after `mapDataError` with no `Vary`. | Site | Can its body carry a `userMessage`? | Verdict | |:---|:---|:---| | `data-action-routes.ts`, `GET /data/:object/:id/field-access` | Yes. The handler itself throws `recordNotFoundError` (`@objectstack/core`) when the row goes away after the read, and that factory sets a localized `userMessage` (`operationUserMessage('record_not_found', caller)`). Its `404` is cacheable by default. | Changed | | `record-page-routes.ts`, `POST /data/:object/:id/page` | Yes. The record read (`p.getData`) throws the same `recordNotFoundError`, and any hook refusal with its own `userMessage` reaches this catch. | Changed | | `search-routes.ts`, `GET /search` | Yes, measured. `searchAll` (`protocol-record-reads.ts`) rethrows every `engine.find` failure except a missing table, so a `beforeFind` hook's refusal with its own `userMessage` arrives here as thrown. The test drives this through a real ObjectQL engine and the real protocol. | Changed | | `form-routes.ts`, `POST /forms/:slug/submit` | Yes. A hook refusal on the create carries its own `userMessage` onto the body. | Changed | | `rest-server.ts`, API-key credential refusal (`enforceApiAccess`) | No. `apiKeyManagementCredentialRefusal` (`@objectstack/core`, `api-key-management-credential.ts`) builds its error with `code`, `status`, `statusCode` and `object` only, so `declaredUserMessage` answers `undefined` and the mapped body has no `userMessage`. The last test case pins that reading. | Unchanged | - Each changed catch adds `Vary: Accept-Language` when `answerVariesByLanguage(mapped.body)` is true, in the multi-value form the hosts append, exactly as `crud-routes.ts`'s `sendRefusal` does. Status, code and body are untouched. - `packages/types/src/localized-answer-vary.ts`: the "who asks" note named only `crud-routes.ts` for `@objectstack/rest`; it now names the four catches too. Comment only, but it ships in the `.d.ts`, so the changeset carries `@objectstack/types: patch`. - New test `packages/rest/src/rest-refusal-vary-38507.test.ts`; changeset `.changeset/38507-rest-refusal-vary-rest.md` (`@objectstack/rest` and `@objectstack/types`, patch). Read first: the four `answerVariesByLanguage` lines (`data-action-routes.ts` ~:615, `record-page-routes.ts` ~:527, `search-routes.ts` ~:136, `form-routes.ts` ~:993), then the search case in the test, which is the one site the card left unmeasured. ## Tests - New file, 9 cases on the real routes and the real mapper. For each changed site, a refusal the route can really answer carries a `userMessage` and exactly one `Vary` header whose value is the multi-value list holding `Accept-Language`; a CONTROL with no `userMessage` gets no `Vary`. Field access and record page use the real `recordNotFoundError` (localized `404 RECORD_NOT_FOUND`); search uses a real ObjectQL engine on SQLite under the real protocol with a `beforeFind` hook refusal; form submit uses a hook refusal on the create. Each case checks the refusal came from the call it targets, not a gate in front of it. The ninth case pins that the credential refusal's mapped body has no `userMessage`. - Ablation: with the four route files restored to the base (`0af813f3`) and the test unchanged, the 4 positive cases fail, each on the `Vary` assertion (expected one `Vary`, received none), and the 4 controls and the credential case pass; with the fix, 9/9 pass. ## Acceptance notes - Same family, not touched here: `handleRouteError` (`error-response.ts`) sends `resolveErrorResponse`'s body with no `Vary`, and that body carries a producer-declared `userMessage` through the same rule (`withDeclaredUserMessage`, `@objectstack/types`). It is the shared exit of 43 calls across 14 other `@objectstack/rest` route files (meta, batch, approvals, data actions and others). Carried by #38542, filed by this card thread at the seat's request; not run on a live host. - The other `mapDataError` calls in this package (`importUndoFailure`, the record page's `refusalOf`, the recycle-bin and security-routes authz-store arms) build a nested envelope from `code` and `message` only, so they answer no `userMessage` and owe no header. ## Verification Two-minute check: `pnpm --filter @objectstack/rest exec vitest run src/rest-refusal-vary-38507.test.ts` shows 9 passed.
Local runs (head b7398cda) and CI - New test file: 9/9 pass. Ablation (four route files restored to `0af813f3`, test unchanged): 4 failed, 5 passed; each failure is the `Vary` assertion (`expected [] to deeply equal [ [ 'Vary', [ 'Accept-Language' ] ] ]`). - `pnpm --filter @objectstack/rest test` under the verify lock: VERDICT command-exit 0, Test Files 440 passed (440), Tests 9042 passed, 351 skipped. - `pnpm --filter @objectstack/rest typecheck && pnpm --filter @objectstack/types typecheck`: VERDICT command-exit 0. - `node scripts/pm/dispatch-gates.mjs --commands` (69 families): 67 exit 0 on the first pass. `node scripts/check-plugin-teardown-shape.mjs --self-test` exited 3 (its pinned fixture commit was not in the shallow clone); after `git fetch --depth=1 origin 621a4876…` it exits 0 (48 cases). `pnpm check:dual-build-cjs-loads` exited 3, PREREQUISITE NOT MET (it reads every package's `dist/`, and only the rest closure was built here): NOT MEASURED locally, answered by CI's `Lint & Repo Gates` (success). `--ran` reconciliation: 69 derived, 69 run. - CI on b7398cda: 59 success, 11 skipped, 0 failed, including `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core` (12/12 shards), `Build Core`, `Check Changeset`, `Governed Surface Queue Guard` and `Dogfood Regression Gate`. `check-expected-skips --pr 38532`: OK, every skip in main's roster. - `check-governed-merges --pr 38532`: NOT governed; 305 changed lines (+301 / -4).
--- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kgSTHJ7Z9KoRm3XCy)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5kgSTHJ7Z9KoRm3XCy --------- Co-authored-by: Claude --- .changeset/38507-rest-refusal-vary-rest.md | 9 + packages/rest/src/data-action-routes.ts | 7 +- packages/rest/src/form-routes.ts | 6 +- packages/rest/src/record-page-routes.ts | 7 +- .../rest/src/rest-refusal-vary-38507.test.ts | 265 ++++++++++++++++++ packages/rest/src/search-routes.ts | 6 + packages/types/src/localized-answer-vary.ts | 5 +- 7 files changed, 301 insertions(+), 4 deletions(-) create mode 100644 .changeset/38507-rest-refusal-vary-rest.md create mode 100644 packages/rest/src/rest-refusal-vary-38507.test.ts diff --git a/.changeset/38507-rest-refusal-vary-rest.md b/.changeset/38507-rest-refusal-vary-rest.md new file mode 100644 index 00000000000..bbd0ba213bb --- /dev/null +++ b/.changeset/38507-rest-refusal-vary-rest.md @@ -0,0 +1,9 @@ +--- +'@objectstack/rest': patch +'@objectstack/types': patch +--- + +Clause-②: no +Metadata-protocol: none + +A refusal carrying a `userMessage` now says it varies by `Accept-Language` on four more REST routes: the record field projection (`GET /data/:object/:id/field-access`), the record page (`POST /data/:object/:id/page`), the global search (`GET /search`) and the public form submit (`POST /forms/:slug/submit`). The status, code and body are unchanged; the header is added in the multi-value form the hosts append, so a `Vary` another layer sets keeps its tokens. Before, a shared cache in front of these routes could serve one caller's localized sentence (the localized `404 RECORD_NOT_FOUND`, a hook refusal's own message) to a caller asking in another language. The API-key credential refusal on `sys_api_key` writes carries no `userMessage` and is unchanged. In `@objectstack/types`, the `answerVariesByLanguage` docblock now names these exits among the ones that ask it. diff --git a/packages/rest/src/data-action-routes.ts b/packages/rest/src/data-action-routes.ts index d4a59740fdf..d68649cbc8c 100644 --- a/packages/rest/src/data-action-routes.ts +++ b/packages/rest/src/data-action-routes.ts @@ -76,7 +76,7 @@ import { applyDroppedFieldsHeader, handleRouteError, logUnexpectedRouteError, ma // [#24348] The shared ADR-0112 nested envelope for the import doors' control // opt-out refusal — the flat sibling-`code` dialect the doors' older answers // use is ratcheted down by `check:route-envelope`. -import { resolveThrownHttpError, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; +import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, resolveThrownHttpError, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; // [#26594] The read path's ONE no-row answer, for a row that left the caller's // sight between the record read and the projection. import { recordNotFoundError } from '@objectstack/core'; @@ -608,6 +608,11 @@ export function registerDataActionEndpoints(this: DataActionRouteHost, basePath: } catch (error: any) { const mapped = mapDataError(error, req.params?.object); logUnexpectedRouteError(error, mapped); + // [#38507] The no-row answer is `recordNotFoundError`'s localized + // `404 RECORD_NOT_FOUND`, a status a cache stores by default: + // say it varies by `Accept-Language`, as the `/data` by-id read + // does (`answerVariesByLanguage`, `@objectstack/types`). + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); res.status(mapped.status).json(mapped.body); } }, diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index ca470f73809..c2268c420f6 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -86,7 +86,7 @@ import { type FormIntakeLayer, type UnreadableFormBody, } from '@objectstack/spec/ui'; -import { validationFailure } from '@objectstack/types'; +import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, validationFailure } from '@objectstack/types'; import { FILE_REFERENCE_TYPES, RUNTIME_OWNED_FIELD_TYPES } from '@objectstack/spec/data'; import type { ServerScopedDataRequest } from './data-action-routes.js'; import { isExpectedRouteError, mapDataError } from './error-response.js'; @@ -987,6 +987,10 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo if (!isExpectedRouteError(mapped.status, mapped.body)) { logError('[REST] Public form submit error:', error); } + // [#38507] A hook refusal's own `userMessage` reaches the visitor + // in their language, so the answer says it varies by + // `Accept-Language` (`answerVariesByLanguage`, `@objectstack/types`). + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); res.status(mapped.status).json(mapped.body); } }, diff --git a/packages/rest/src/record-page-routes.ts b/packages/rest/src/record-page-routes.ts index f91616543c2..3e386b79042 100644 --- a/packages/rest/src/record-page-routes.ts +++ b/packages/rest/src/record-page-routes.ts @@ -45,7 +45,7 @@ import { } from '@objectstack/spec/api'; import { isMultiValueField, parseFilterAST, referenceTargetOf } from '@objectstack/spec/data'; import { measureServerTiming } from '@objectstack/observability'; -import { sendError, sendOk } from '@objectstack/types'; +import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, sendError, sendOk } from '@objectstack/types'; import { recordNotFoundError } from '@objectstack/core'; import { refuseUnknownQueryParams } from './query-allowlist.js'; import { logUnexpectedRouteError, mapDataError, nestedRefusalEnvelope } from './error-response.js'; @@ -520,6 +520,11 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: } catch (error: any) { const mapped = mapDataError(error, object); logUnexpectedRouteError(error, mapped); + // [#38507] A refusal carrying a `userMessage` (the record read's + // localized `404 RECORD_NOT_FOUND`, a hook's own sentence) says it + // varies by `Accept-Language`, as the `/data` routes do + // (`answerVariesByLanguage`, `@objectstack/types`). + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); res.status(mapped.status).json(mapped.body); } }, diff --git a/packages/rest/src/rest-refusal-vary-38507.test.ts b/packages/rest/src/rest-refusal-vary-38507.test.ts new file mode 100644 index 00000000000..7035ca3b3e6 --- /dev/null +++ b/packages/rest/src/rest-refusal-vary-38507.test.ts @@ -0,0 +1,265 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38507] Four `@objectstack/rest` catches outside `crud-routes.ts` that answer + * a `mapDataError` body say it varies by `Accept-Language` when the body + * carries a `userMessage`, as the `/data` routes do (#37828, #38316). + * + * Read on the base (`0af813f3`): each sent `res.status(mapped.status).json( + * mapped.body)` with no `Vary`, so a shared cache in front of the route could + * hand one caller's sentence, in its language, to a caller asking in another. + * The rule is `answerVariesByLanguage`'s (`@objectstack/types`). + * + * Each case drives the real route through the real mapper, and the refusal is + * one the route can really answer: + * - `GET /data/:object/:id/field-access` and `POST /data/:object/:id/page`: + * the no-row answer, `recordNotFoundError` (`@objectstack/core`), whose + * `userMessage` is rendered in the caller's language; + * - `GET /search`: a `beforeFind` hook's refusal with its own `userMessage`, + * thrown by a real ObjectQL engine one call under the real protocol's + * `searchAll`, which relays it as thrown; + * - `POST /forms/:slug/submit`: a hook refusal with its own `userMessage` on + * the create. + * Each CONTROL is the same refusal with no `userMessage`, which gets no `Vary`. + * + * The fifth site the card names, the API-key credential refusal in + * `rest-server.ts`, is left unchanged: `apiKeyManagementCredentialRefusal` + * (`@objectstack/core`) sets no `userMessage`, so its body never carries one; + * the last case pins that reading. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { LOCALIZED_ANSWER_VARY, mapDataError } from '@objectstack/types'; +import { apiKeyManagementCredentialRefusal, recordNotFoundError } from '@objectstack/core'; +import { projectedFormsOf } from '@objectstack/spec/ui'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { RestServer } from './rest-server'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECT = 'ticket_38507'; +const ID = 'r_38507'; +const CTX = { userId: 'usr_38507_member', positions: [], permissions: [], posture: 'MEMBER', locale: 'fr-FR' }; +const SENTENCE = 'Ce créneau est déjà réservé.'; + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeHeaderRes() { + const res: any = { + _headers: [] as Array<[string, string | string[]]>, + write: () => true, end: () => {}, send: () => res, + header: (name: string, value: string | string[]) => { res._headers.push([name, value]); return res; }, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +const varyHeaders = (res: any) => res._headers.filter(([name]: [string]) => name.toLowerCase() === 'vary'); + +/** What a hook refusal declaring its own sentence throws. */ +const refusalWithSentence = () => + Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT', userMessage: SENTENCE }); +/** The same refusal with no sentence for the end user. */ +const refusalWithoutSentence = () => + Object.assign(new Error('The slot is already booked.'), { status: 409, code: 'RESOURCE_CONFLICT' }); + +function routeOf(rest: RestServer, method: string, path: string) { + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === path); + expect(route, `${method} ${path}`).toBeDefined(); + return route!; +} + +/** A server over a stub protocol, past the auth and exposure gates. */ +function stubServer(protocol: Record, extra: (rest: any) => void = () => {}) { + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => CTX; + (rest as any).enforceApiAccess = async () => false; + extra(rest); + rest.registerRoutes(); + return rest; +} + +describe('[#38507] GET /data/:object/:id/field-access', () => { + const PATH = '/api/v1/data/:object/:id/field-access'; + const req = { params: { object: OBJECT, id: ID }, query: {}, headers: {} }; + + it('the row gone after the read: the localized 404 RECORD_NOT_FOUND says Vary: Accept-Language', async () => { + const reads: string[] = []; + const rest = stubServer( + { getData: async () => { reads.push('getData'); return { object: OBJECT, id: ID, record: { id: ID } }; } }, + (r) => { r.resolveSecurityService = async () => ({ getRecordFieldAccess: async () => { reads.push('fieldAccess'); return null; } }); }, + ); + const res = makeHeaderRes(); + await routeOf(rest, 'GET', PATH).handler(req as any, res); + expect(reads).toEqual(['getData', 'fieldAccess']); + expect(res._status, JSON.stringify(res._json)).toBe(404); + expect(res._json.code).toBe('RECORD_NOT_FOUND'); + expect(res._json.userMessage).toEqual(expect.any(String)); + // The multi-value form the hosts append, never a set that would drop CORS's `Origin`. + expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]); + }); + + it('CONTROL: a read refusal with no userMessage gets no Vary from this door', async () => { + const rest = stubServer({ getData: async () => { throw refusalWithoutSentence(); } }); + const res = makeHeaderRes(); + await routeOf(rest, 'GET', PATH).handler(req as any, res); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.userMessage).toBeUndefined(); + expect(varyHeaders(res)).toEqual([]); + }); +}); + +describe('[#38507] POST /data/:object/:id/page', () => { + const PATH = '/api/v1/data/:object/:id/page'; + const req = { params: { object: OBJECT, id: ID }, query: {}, headers: {}, body: {} }; + + it('no such row: the localized 404 RECORD_NOT_FOUND says Vary: Accept-Language', async () => { + const reads: string[] = []; + const rest = stubServer({ getData: async () => { reads.push('getData'); throw recordNotFoundError(OBJECT, ID, CTX as any); } }); + const res = makeHeaderRes(); + await routeOf(rest, 'POST', PATH).handler(req as any, res); + expect(reads).toEqual(['getData']); + expect(res._status, JSON.stringify(res._json)).toBe(404); + expect(res._json.code).toBe('RECORD_NOT_FOUND'); + expect(res._json.userMessage).toEqual(expect.any(String)); + expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]); + }); + + it('CONTROL: a read refusal with no userMessage gets no Vary from this door', async () => { + const rest = stubServer({ getData: async () => { throw refusalWithoutSentence(); } }); + const res = makeHeaderRes(); + await routeOf(rest, 'POST', PATH).handler(req as any, res); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.userMessage).toBeUndefined(); + expect(varyHeaders(res)).toEqual([]); + }); +}); + +describe('[#38507] GET /search — a real engine under the real protocol', () => { + let engine: ObjectQL; + let thrown: () => Error = refusalWithSentence; + const hookCalls = { n: 0 }; + let search: () => Promise; + + beforeAll(async () => { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject({ + name: OBJECT, label: 'Ticket 38507', fields: { name: { name: 'name', type: 'text' } }, + } as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + await engine.insert(OBJECT, { id: ID, name: 'QQ38507 row' } as any); + // Registered after the seed, so only the search's read meets it. + engine.registerHook('beforeFind', () => { hookCalls.n += 1; throw thrown(); }, { object: OBJECT }); + + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => CTX; + rest.registerRoutes(); + const route = routeOf(rest, 'GET', '/api/v1/search'); + search = async () => { + const res = makeHeaderRes(); + await route.handler({ params: {}, query: { q: 'QQ38507', objects: OBJECT }, headers: {} } as any, res); + return res; + }; + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('a beforeFind refusal with its own userMessage is relayed with Vary: Accept-Language', async () => { + thrown = refusalWithSentence; + const before = hookCalls.n; + const res = await search(); + expect(hookCalls.n).toBeGreaterThan(before); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.code).toBe('RESOURCE_CONFLICT'); + expect(res._json.userMessage).toBe(SENTENCE); + expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]); + }); + + it('CONTROL: the same refusal with no userMessage gets no Vary from this door', async () => { + thrown = refusalWithoutSentence; + const res = await search(); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.userMessage).toBeUndefined(); + expect(varyHeaders(res)).toEqual([]); + }); +}); + +describe('[#38507] POST /forms/:slug/submit', () => { + const SLUG = 'contact-38507'; + const formView = { + name: 'contact', object: 'inquiry', viewKind: 'form', _diagnostics: { valid: true }, + config: { + data: { object: 'inquiry' }, + sections: [{ fields: ['name'] }], + sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` }, + }, + }; + const inquiry = { name: 'inquiry', label: 'Inquiry', fields: { name: { type: 'text', label: 'Name' } } }; + + async function submit(thrown: () => Error) { + const calls: string[] = []; + const protocol: any = { + getDiscovery: async () => ({ version: 'v0', routes: { data: '', metadata: '' } }), + getMetaTypes: async () => [], + getMetaItems: async (r: { type: string }) => { + if (r.type === 'view') return [formView]; + if (r.type === 'form') return projectedFormsOf([formView] as any); + if (r.type === 'object') return [inquiry]; + return []; + }, + getMetaItem: async ({ type, name }: any) => ({ type, name, item: formView }), + createData: async () => { calls.push('createData'); throw thrown(); }, + }; + const single = async () => ({ posture: 'single', requestedPosture: 'single', defaultOrgId: async () => 'org_38507' }); + const rest = new RestServer( + createMockServer() as any, protocol, { api: { requireAuth: false } } as any, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, + single as any, + ); + rest.registerRoutes(); + const res = makeHeaderRes(); + await routeOf(rest, 'POST', '/api/v1/forms/:slug/submit') + .handler({ params: { slug: SLUG }, query: {}, headers: {}, body: { name: 'x' } } as any, res); + // The refusal came from the create, not from a gate in front of it. + expect(calls).toEqual(['createData']); + return res; + } + + it('a hook refusal with its own userMessage says Vary: Accept-Language', async () => { + const res = await submit(refusalWithSentence); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.code).toBe('RESOURCE_CONFLICT'); + expect(res._json.userMessage).toBe(SENTENCE); + expect(varyHeaders(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]); + }); + + it('CONTROL: the same refusal with no userMessage gets no Vary from this door', async () => { + const res = await submit(refusalWithoutSentence); + expect(res._status, JSON.stringify(res._json)).toBe(409); + expect(res._json.userMessage).toBeUndefined(); + expect(varyHeaders(res)).toEqual([]); + }); +}); + +describe('[#38507] the API-key credential refusal cannot vary', () => { + it('its mapped body carries no userMessage, so the unchanged exit owes no Vary', () => { + const refusal = apiKeyManagementCredentialRefusal({ object: 'sys_api_key', operation: 'update', credential: 'api_key' }); + expect(refusal, 'the refusal this gate sends').toBeDefined(); + const mapped = mapDataError(refusal, 'sys_api_key'); + expect([mapped.status, mapped.body.code]).toEqual([403, 'PERMISSION_DENIED']); + expect(mapped.body.userMessage).toBeUndefined(); + }); +}); diff --git a/packages/rest/src/search-routes.ts b/packages/rest/src/search-routes.ts index 7161079aedd..0d044decf59 100644 --- a/packages/rest/src/search-routes.ts +++ b/packages/rest/src/search-routes.ts @@ -40,6 +40,7 @@ * export was added anywhere, so the published surface does not move. */ +import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY } from '@objectstack/types'; import { logUnexpectedRouteError, mapDataError } from './error-response.js'; import { refuseRepeatedQueryParams } from './query-multiplicity.js'; import { refuseUnknownQueryParams } from './query-allowlist.js'; @@ -128,6 +129,11 @@ export function registerSearchEndpoints(this: SearchRouteHost, basePath: string) } catch (error: any) { const mapped = mapDataError(error); logUnexpectedRouteError(error, mapped); + // [#38507] `searchAll` relays an object read's refusal as it was + // thrown, a `beforeFind` hook's own `userMessage` included, so + // the answer says it varies by `Accept-Language` when it carries + // one (`answerVariesByLanguage`, `@objectstack/types`). + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); res.status(mapped.status).json(mapped.body); } }, diff --git a/packages/types/src/localized-answer-vary.ts b/packages/types/src/localized-answer-vary.ts index 9448613b626..e82b4638776 100644 --- a/packages/types/src/localized-answer-vary.ts +++ b/packages/types/src/localized-answer-vary.ts @@ -34,7 +34,10 @@ * userMessage } }`, the Hono catch-all and the dispatcher's exit) are asked one * question: * - * - `@objectstack/rest`: the `/data` CRUD and query routes' catch (`crud-routes.ts`); + * - `@objectstack/rest`: the `/data` CRUD and query routes' catch (`crud-routes.ts`), + * and the record field-access, record page, search and public form submit + * catches (`data-action-routes.ts`, `record-page-routes.ts`, `search-routes.ts`, + * `form-routes.ts`); * - `@objectstack/hono`: `thrownJson`, both of `createHonoApp`'s catch arms; * - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`. * From 97fad97baf55ee8a014b6158ca90a70ca36a880f Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:32:13 +0000 Subject: [PATCH 055/178] test(cli): nightly e2e fixtures open their object from app navigation (#38534) 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 #38493 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:只改了三个夜间测试里的示例配置,产品行为没有任何变化。 - 为什么做:夜间测试自昨天起一直报红,原因是新加的「应用导航」发布检查让这些本该干净的示例配置多出了警告。 - 出错会怎样:只影响测试,不影响用户;若有问题,直接撤回此改动即可。 - 要你做什么:无。 ## What changes Test fixtures only, in the three nightly-tier CLI suites the card names. Each fixture that is meant to raise no advisory now declares an app whose `navigation` opens its object (`{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: ... }`) and gives that object a list view (`listViews: { all: { type: 'grid', columns: ['title'] } }`). No rule, assertion, test name or skip changed. - `packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts`: the clean control, the conversions minimal pair and the severity minimal pair (all three copy one object and app). - `packages/cli/test/validate-json-warning-parity.e2e.test.ts`: the clean control. - `packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts`: the `stack()` and `packageCarried()` builders. The html-page members already had a navigation entry, but it opened only the page, and an html page names no object, so the object was unreachable. Every member now carries the object entry, with the page entry beside it where there is a page. ## Why The publish-time app-shell rules that d57895211e (#38107) added in `packages/lint/src/validate-app-shell-reach.ts` warn on an app with no navigation entry (`app-navigation-empty`), on an object no entry opens (`object-unreachable-from-navigation`), and on an object opened as a list with no list view (`object-without-view`). The rules are intended behaviour. The fixtures predate them, and these suites are `*.e2e.test.*` files, which run only in the nightly tier (`OS_TEST_TIERS=nightly`), so #38107's own PR checks never ran them. So the "nothing to warn about" controls, `--strict` exit 0 and `lint` `passed: true / failing: 0` went red. The before log shows all three rules: 6 lines naming `app-navigation-empty`, 14 naming `object-unreachable-from-navigation` and 2 naming `object-without-view`. The third rule hit the `jsx-gate` member with no pages, whose navigation already opened the object but with no list view. That rule comes from the same commit and the same validator file. No failure had any other cause. Per test, nothing was out of scope: no failing test counts findings that these rules add on purpose. Every failing test asserts a zero-advisory baseline (exit 0 under `--strict`, an empty warning set, `failing: 0`, or exactly one finding of a named kind). In each one, the right fix was to make the baseline clean again, not to widen the count. ## Tests
Before / after, nightly tier, the three files (head 1af5b3eda0, origin/main merged) Command (run under `scripts/pm/os-verify-lock.sh`, after `pnpm turbo run build --filter='@objectstack/cli^...'`): ``` OS_TEST_TIERS=nightly pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 src/commands/validate-json-strict-exit.e2e.test.ts test/jsx-gate-manifest-notice.e2e.test.ts test/validate-json-warning-parity.e2e.test.ts ``` - Before (the three files restored to merge base 545a4fa278, everything else at the head): `Test Files 3 failed (3)`, `Tests 15 failed | 41 passed (56)`. That matches the 15 failures in run 46229659209. - After: `Test Files 3 passed (3)`, `Tests 56 passed (56)`. - `pnpm --filter @objectstack/cli typecheck`: exit 0. Both legs compile these files (`src/**` through `tsconfig.json`, `test/**` through `tsconfig.test.json`).
## Acceptance notes - Other `*.e2e.test.*` / `*.live.test.*` files that declare apps with no navigation (8 under `packages/cli/test/`: `artifact-pinned-boot`, three `i18n-extract-*`, `serve-app-anchored-optional-import`, `serve-cluster-driver-diagnosis`, `serve-runtime-assets-branding-warning`, `start-signal-forwarding`) run `serve`, `start` or `i18n`, never `validate`, `lint` or `build`. The rules do not run there, and none of these files is in the nightly's failing list. No finding. ## Verification
Gates - `node scripts/pm/dispatch-gates.mjs --commands` on head 1af5b3eda0: 55 commands. 51 exit 0. 4 exit 3 (PREREQUISITE NOT MET, the workspace `dist/` is not built): `check:dual-build-cjs-loads`, `check:i18n`, `check:i18n-coverage`, `check:i18n-walk-parity`. These are NOT MEASURED locally and left to CI: they read built output, which no file in this diff feeds. - `dispatch-gates --ran`: `55 derived famil(ies) accounted for — 51 run, 4 NOT-MEASURED (4 DERIVED from a recorded exit 3)`. - `check-governed-merges --test` on the three-dot file list: NOT governed. - `overlap-check`: `VERDICT clean exit 0`. - No changeset. Test files only, and neither package build ships them (`tsconfig.build.json` excludes `src/**/*.test.ts`, and `test/` is outside `files[]`), so this takes `skip-changeset`.
Two-minute check: run the command above. Expected: `Tests 56 passed (56)`. Read first: `packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts` `stack()` (the one fixture whose navigation shape changed rather than grew). --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_ Co-authored-by: Claude --- .../validate-json-strict-exit.e2e.test.ts | 31 ++++++++++++++++--- .../test/jsx-gate-manifest-notice.e2e.test.ts | 17 +++++----- .../validate-json-warning-parity.e2e.test.ts | 16 ++++++++-- 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts b/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts index ac70ddd63f7..c64bedb1ed2 100644 --- a/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts +++ b/packages/cli/src/commands/validate-json-strict-exit.e2e.test.ts @@ -170,7 +170,15 @@ export default defineStack({ }, { strict: false }); `; -/** The zero-warning control — pins the other end of the matrix. */ +/** + * The zero-warning control — pins the other end of the matrix. + * + * The app opens its object from navigation and the object declares a list + * view: without the entry the app-shell rules raise `app-navigation-empty` and + * `object-unreachable-from-navigation`, and with the entry but no view they + * raise `object-without-view`, each a warning `--strict` promotes. The fixtures + * below copy this object and app, for the same reason. + */ const CLEAN_SOURCE = ` import { defineStack } from '@objectstack/spec'; @@ -181,8 +189,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], }, { strict: false }); `; @@ -210,8 +223,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], flows: [{ name: 'strictexit_notify', label: 'Notify', @@ -249,8 +267,13 @@ export default defineStack({ label: 'Ticket', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } }, + listViews: { all: { type: 'grid', columns: ['title'] } }, + }], + apps: [{ + name: 'strictexit_app', + label: 'Strict Exit App', + navigation: [{ id: 'nav_ticket', type: 'object', label: 'Tickets', objectName: 'strictexit_ticket' }], }], - apps: [{ name: 'strictexit_app', label: 'Strict Exit App' }], ${finding === 'info' ? ` permissions: [{ name: 'strictexit_reader', label: 'Reader', objects: { strictexit_ticket: { allowRead: true } } }],` : ` tools: [{ diff --git a/packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts b/packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts index bce10f923db..9d02bcf3599 100644 --- a/packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts +++ b/packages/cli/test/jsx-gate-manifest-notice.e2e.test.ts @@ -125,17 +125,20 @@ function noticesIn(payload: Record): Array Date: Sun, 29 Nov 2026 08:38:36 +0000 Subject: [PATCH 056/178] =?UTF-8?q?fix(knowledge):=20the=20keyword=20leg?= =?UTF-8?q?=20keeps=20=E3=80=85,=20=E3=80=86=20and=20=E3=80=87=20inside=20?= =?UTF-8?q?an=20unspaced=20run=20(#38498)?= 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_01TenzsRopZj4jMbvjX8uz1XJFhX5XfWT8anspjCw9gfjz)_ Part of #38411. This PR is the follow-up to #38469: the separator marks found in its review. Still open on the card: the BrightRule model-graded eval and Ask 3. Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:中文、日文提问里的「々」「〆」「〇」不再把词切断,「人々」「二〇二四年」这类写法在知识检索的关键词一路能被匹配到;其他提问不变。 - 为什么做:知识平台专题,上一个中日韩关键词改动在审核中发现的遗漏。 - 出错会怎样:最坏情况是含这三个符号的提问关键词排序变差,向量一路照常作答;不改索引、不需重建,可直接撤回。 - 要你做什么:无。 ## What changes - `keywordTerms` in `knowledge-turso/src/sql.ts` and `knowledge-pgvector/src/sql.ts` (one rule, kept identical) split a query at the whole CJK symbols block (` -〿`). That block also holds three marks written inside a word: 々 (U+3005), 〆 (U+3006) and 〇 (U+3007). A mark split the run it sat in, and a run of one character is then dropped, so 「人々」 gave no term and 「二〇二四年」 lost its first pieces. The split class is now ` -〄〈-〿`, and the three marks are named in `UNSEGMENTED_RUN`, whatever their script: 々 and 〇 are Han, 〆 is Common. 「、」, 「。」 and the brackets still split. - pgvector's `UNSEGMENTED` (which keeps a term off the `tsvector`) gains the same three marks, so a piece made only of 〆 is matched as a substring, not as a word. - New changeset `.changeset/38411-cjk-separator-marks.md` (patch, both stores). The #38469 changeset is left as main has it. ## Tests
Pins, ablation, type check - New pin in both stores: 「人々」 gives `['人々']`; 「二〇二四年」 gives `['二〇二', '〇二四', '二四年', '二〇', '〇二', '二四', '四年']`; 「〆切日」 gives `['〆切日', '〆切', '切日']`; 「出差、住宿。审批」 gives `['出差', '住宿', '审批']`. pgvector also pins `isWordTerm('〆〆〆') === false`. - knowledge-turso: `Test Files 4 passed (4)`, `Tests 286 passed (286)`. knowledge-pgvector without a database: `Test Files 4 passed | 7 skipped (11)`, `Tests 20 passed | 91 skipped (111)`. Type check of both: green. One run under the verify lock: `VERDICT command-exit 0`. - Ablation: both `sql.ts` set to the merge base (blob hashes checked), the pins run, then both restored and their hashes checked again. turso: `Tests 2 failed` (the new pin, on `:memory:` and `file:`). pgvector: `Tests 2 failed | 4 passed (6)` (the new pin and the `〆〆〆` pin). - NOT MEASURED: the live pgvector suite, reason: no PostgreSQL in this container for this follow-up. CI covers it.
## Verification - Read first: `packages/plugins/knowledge-turso/src/sql.ts` (`UNSEGMENTED_RUN` and the split class in `keywordTerms`). - Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t 'keeps 々'` should show the pin passing twice.
Local gate subset at 86a724b0 (CI runs the full farm) - `node scripts/pm/dispatch-gates.mjs --commands` derived 66 families for the 5 changed files. Each was run with its exit code captured before any pipe: **62 exit 0**. `--ran` reconciliation: `66 derived, 62 run, 2 NOT-MEASURED, 2 UNRUN`. - NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test` and `check:dual-build-cjs-loads`, reason: exit 3, PREREQUISITE NOT MET (shallow clone; not every package has a `dist/`). - NOT MEASURED: `check:query-options-erasure` and `check:type-check-debt`, reason: repo-wide scans stopped by the 240 s per-gate limit (exit 124). CI's Lint & Repo Gates and TypeScript Type Check run them. - `overlap-check`: `VERDICT clean exit 0` against origin/main 430bbbf1 (no open PR shares a file). - Self-scan of the changed files for control bytes: no hits.
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm --------- Co-authored-by: Claude --- .changeset/38411-cjk-separator-marks.md | 11 +++++++++++ .../src/__tests__/keyword-terms.test.ts | 10 ++++++++++ packages/plugins/knowledge-pgvector/src/sql.ts | 15 +++++++++------ .../src/__tests__/acceptance.test.ts | 8 ++++++++ packages/plugins/knowledge-turso/src/sql.ts | 8 +++++--- 5 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 .changeset/38411-cjk-separator-marks.md diff --git a/.changeset/38411-cjk-separator-marks.md b/.changeset/38411-cjk-separator-marks.md new file mode 100644 index 00000000000..073029d4cf6 --- /dev/null +++ b/.changeset/38411-cjk-separator-marks.md @@ -0,0 +1,11 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge): the keyword leg keeps 々, 〆 and 〇 inside an unspaced run + +Clause-②: no +Metadata-protocol: none + +`keywordTerms` in `@objectstack/knowledge-turso` and `@objectstack/knowledge-pgvector` split a query at the whole CJK symbols block, so the iteration mark 々 (U+3005), the closing mark 〆 (U+3006) and the ideographic zero 〇 (U+3007) cut a run of Han text. With a run of one character dropped, 「人々」 gave no keyword term, and 「二〇二四年」 lost the pieces holding its first figure. The three marks now belong to an unspaced run: 「人々」 is one piece, 「二〇二四年」 gives 「二〇二」, 「〇二四」 and the rest. 「、」, 「。」 and the brackets still split terms. Matching is unchanged. On libSQL a piece is matched by the trigram index (three characters) or `LIKE` (two). On PostgreSQL a piece is matched as a substring, by `LIKE` when it holds no cased letter and by `ILIKE` otherwise. A piece made only of 〆 also counts as a substring term there, never as a `tsvector` word. No index or fingerprint change, no reindex. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts index e72fcb0db02..8d19ab7620d 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -40,10 +40,20 @@ describe('knowledge-pgvector keywordTerms', () => { expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); }); + it('keeps 々, 〆 and 〇 inside a run, and still splits at 、 and 。', () => { + // The three marks sit in the CJK symbols block, whose other characters are punctuation. + expect(keywordTerms('人々')).toEqual(['人々']); + expect(keywordTerms('二〇二四年')).toEqual(['二〇二', '〇二四', '二四年', '二〇', '〇二', '二四', '四年']); + expect(keywordTerms('〆切日')).toEqual(['〆切日', '〆切', '切日']); + expect(keywordTerms('出差、住宿。审批')).toEqual(['出差', '住宿', '审批']); + }); + it('matches a piece as a substring and a figure or a code of three characters or more on the tsvector', () => { expect(keywordTerms('住宿费2000元以下').map((t) => [t, isWordTerm(t)])).toEqual([ ['2000', true], ['住宿费', false], ['元以下', false], ['住宿', false], ['宿费', false], ['元以', false], ['以下', false], ]); + // A piece holding only 〆, which belongs to no script, is still a substring term, never a tsvector word. + expect(isWordTerm('〆〆〆')).toBe(false); }); it('matches a substring term without a cased letter by LIKE, and one holding a cased letter by ILIKE', () => { diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index 26c13bb1586..6c839790061 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -136,17 +136,20 @@ export const WORD_MIN_CHARS = 3; /** * A character the `simple` parser does not split a run of text at: Han, - * Hiragana, Katakana and Hangul. A run of them is one `tsvector` word, so a - * term holding one is matched as a substring ({@link containsOperator}), never as a word. + * Hiragana, Katakana and Hangul, and the marks 々, 〆 and 〇 a run holds. A run + * of them is one `tsvector` word, so a term holding one is matched as a + * substring ({@link containsOperator}), never as a word. */ -export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u; +export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007]/u; /** * A run of characters written without spaces between words: Han, Hiragana, * Katakana (with the prolonged sound mark, which belongs to no script) and - * Hangul. + * Hangul, and the three marks written inside a word in the CJK symbols block, + * 々 (U+3005), 〆 (U+3006) and 〇 (U+3007), named whatever their script, since + * the split below takes the rest of that block as punctuation. */ -const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u30fc\uff70]+/gu; +const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007\u30fc\uff70]+/gu; /** * The terms of a query for the keyword leg: split at white space and at @@ -174,7 +177,7 @@ export function keywordTerms(query: string): string[] { const stripped = text.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); if (stripped !== '') words.push(stripped); }; - for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { + for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { let at = 0; for (const run of term.matchAll(UNSEGMENTED_RUN)) { word(term.slice(at, run.index)); diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index c68a9c32200..f32bf215996 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1010,6 +1010,14 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); }); + it('keeps 々, 〆 and 〇 inside a run, and still splits at 、 and 。', () => { + // The three marks sit in the CJK symbols block, whose other characters are punctuation. + expect(keywordTerms('人々')).toEqual(['人々']); + expect(keywordTerms('二〇二四年')).toEqual(['二〇二', '〇二四', '二四年', '二〇', '〇二', '二四', '四年']); + expect(keywordTerms('〆切日')).toEqual(['〆切日', '〆切', '切日']); + expect(keywordTerms('出差、住宿。审批')).toEqual(['出差', '住宿', '审批']); + }); + it('the organization filter, the record scope and the metadata filter hold in the keyword leg too', async () => { const adapter = store.adapter(); const s = source('kw_scope'); diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index e3790a963c4..d95dd098928 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -394,9 +394,11 @@ export const TRIGRAM_MIN_CHARS = 3; /** * A run of characters written without spaces between words: Han, Hiragana, * Katakana (with the prolonged sound mark, which belongs to no script) and - * Hangul. + * Hangul, and the three marks written inside a word in the CJK symbols block, + * 々 (U+3005), 〆 (U+3006) and 〇 (U+3007), named whatever their script, since + * the split below takes the rest of that block as punctuation. */ -const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u30fc\uff70]+/gu; +const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007\u30fc\uff70]+/gu; /** * The terms of a query for the keyword leg: split at white space and at @@ -423,7 +425,7 @@ export function keywordTerms(query: string): string[] { const stripped = text.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); if (stripped !== '') words.push(stripped); }; - for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { + for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { let at = 0; for (const run of term.matchAll(UNSEGMENTED_RUN)) { word(term.slice(at, run.index)); From 0771cddc21eb8949720c8656352351f83727b131 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:39:42 +0000 Subject: [PATCH 057/178] feat(mcp): get_current_user tells an MCP client's model who is signed in (#38513) 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 #38363 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 通过 MCP 连接的 AI 助手现在能查到"当前登录的是谁":本人、所在组织、主业务单元及其上级单元;之前它只能反问用户。 - 属于知识专题:让 MCP 通道像问答页面一样知道提问人是谁,答"我们单位的制度"这类问题时不再反问。 - 只读取登录者本人有权看的信息,看不到的上级单元直接省略、不点名;出错时最多是助手拿不到单元信息,可直接撤回。 - 无。目前普通成员看不到自己的单元信息,助手只会说"单元不可读";你已定下让每位内部成员默认能读本组织的业务单元,那张卡做完后助手就能直接答出单元(本改动没有放宽任何权限)。 ## What changes - **A new read-only MCP tool, `get_current_user`** (`packages/mcp/src/mcp-http-tools.ts`). No argument, so it can answer about nobody else. It registers where the bridge carries the new optional `McpDataBridge.currentUser` member and the grant is the read family's (an API key, a session, or an OAuth token with `data:read`). It answers `user` (id, name), `organization` (the vetted active organization: id, name), `businessUnits` (the primary unit, then each parent up to the root: id, name, kind) and `businessUnitNote` (why the chain stops, or that no primary unit is recorded), so an absent unit never reads as "no unit". - **One resolver, `resolveCallerIdentity`** (`packages/runtime/src/domains/mcp.ts`), which the HTTP bridge's `currentUser` member calls, and which the declared retrieval-ranking card (Blocked-by this one) can call as is. It takes the caller's `ExecutionContext` and a reader that runs as that caller. Every read is a by-id `findData` through `callData` with the request's own context: permissions, row-level security and field masking apply, and nothing reads with a system context. The parent walk is here because `IBusinessUnitGraphService` walks descendants only. It is cycle-safe and capped at `CALLER_UNIT_CHAIN_MAX_DEPTH` (32) reads; no contract member was added. A link field masked off a row the caller can read (`primary_business_unit_id` on the user, `parent_business_unit_id` on a unit) is "not readable" and ends the chain with its note. A link that is present but empty means no unit or the top of the tree. A `401`/`403`/`404` read is "not readable" and the fact is left out. Any other failure, such as a driver fault, fails the call with its coded envelope, so it never reads as a permission limit. - **One fixed sentence in the open server's `initialize` text**, sent only where the tool registers (`ASKER_TOOL_LINE`, `packages/mcp/src/mcp-server-runtime.ts`). It names the tool and says when to call it. It carries no caller fact and reads nothing, so it is byte-identical for every caller. A host's own text (`instructions` / `dataOnlyInstructions`) and an operator-configured text are left whole, as before. - The stdio transport does not list the tool: its bridge has no `currentUser` member, and `packages/mcp/src/plugin.ts` is not touched. - `@objectstack/mcp` exports the answer's types, `McpCurrentUser` and `McpBusinessUnitFact`, from its index beside `McpDataBridge`, so an outside bridge implementer can name what `currentUser` returns. - **The tools/list weight pin measures the new tool** (`packages/mcp/src/tools-list-weight-34689.test.ts`). Its stub bridge gains `currentUser` and its sanity list names `get_current_user`. `TOOLS_LIST_BYTE_CEILING` goes from 38,000 to 39,000, and its header no longer promises room for one more tool. Table below. ## Deviation from the 7248187244 scope note The adoption note (comment 7248187244) asked for an asker paragraph in the `initialize` instructions with a read-only tool beside it as the fallback. This PR ships **the tool alone plus one fixed pointer sentence** in the open server's `initialize` text. The sentence carries no caller fact and is the same bytes for every caller. Reasons, measured on d89d3e2356: 1. `handleHttpRequest` builds a fresh server for **every** POST, and `instructions` is evaluated in that constructor for every method: `initialize`, `tools/list` and every `tools/call`. A per-user paragraph would read the caller's identity (3+N reads) on every MCP request, unless `initialize` got a method-specific path. The tool reads only when the model calls it. 2. Where a host injects its own text (`hostInstructions`: the authoring injection's `instructions` / `dataOnlyInstructions`) or the operator sets `instructions`, that text replaces the open text whole, and nothing is appended to it. A paragraph would be missing on exactly those hosts. The tool is served on all of them. 3. A client that drops or truncates `initialize` instructions gets nothing from a paragraph. A tool in `tools/list` reaches every client. The transport is stateless, so there was no server-side cache to leak across in either shape. What the tool route achieves for a model's answers is measured by #38503's arm 2 ("the model told who asks"). The probe below is written to be re-run there as is. What the tool costs in `tools/list`: one row. On the real `/mcp` route a session user goes from 21 to 22 tools (probe below). On the weight pin's API-key surface it goes from 17 to 18 tools and from **37,931 to 38,569 bytes**: | | tools | total bytes | descriptions | input schemas | |:--|--:|--:|--:|--:| | before (stub without `currentUser`) | 17 | 37,931 | 13,160 | 21,637 | | after (stub with `currentUser`) | 18 | 38,569 | 13,502 | 21,751 | | `get_current_user` row | | 456 | 342 | 114 | Before this change the old ceiling of 38,000 left 69 bytes of headroom. The new ceiling of 39,000 leaves 431 bytes, which is not enough for another tool.
Per-tool rows after (measured at 38fbe352b1, mcp closure rebuilt) ``` tools/list: 18 tools, 38569 bytes (descriptions 13502, input schemas 21751) | tool | description | input schema | both | | query_dataset | 826 | 4591 | 5417 | | aggregate_records | 1061 | 3943 | 5004 | | validate_expression | 633 | 3671 | 4304 | | list_datasets | 2567 | 490 | 3057 | | query_records | 1119 | 1853 | 2972 | | run_action | 1352 | 884 | 2236 | | delete_record | 783 | 894 | 1677 | | get_record | 431 | 1228 | 1659 | | delete_records | 763 | 888 | 1651 | | create_upload_link | 794 | 827 | 1621 | | resume_run | 716 | 488 | 1204 | | describe_object | 927 | 223 | 1150 | | read_file | 444 | 621 | 1065 | | list_actions | 483 | 114 | 597 | | update_record | 42 | 460 | 502 | | get_current_user | 342 | 114 | 456 | | create_record | 73 | 348 | 421 | | list_objects | 146 | 114 | 260 | ``` The before run, from the parent commit's version of the file, prints the same rows without `get_current_user`.
## Tests - `packages/mcp/src/mcp-asker-38363.test.ts` (JSON-RPC through `handleHttpRequest`): - the tool registers, read-only and with no argument, for a key or session and for a `data:read` token. It does not register for `data:write` / `actions:execute` / `metadata:write` grants, or on a bridge without the member. - Two callers get their own facts, unchanged. - An argument is refused before the member runs. - A member throw answers the coded envelope. - The `initialize` sentence appears exactly where the tool registers. It carries no caller fact, it is identical for two callers, and the member is not called. - Host and configured texts stay whole. - `packages/runtime/src/domains/mcp-asker-38363.test.ts`: - `resolveCallerIdentity`: two users get their own chains up to the root, and it reads only their own rows. - A hidden parent is absent and not named, and the chain ends below it with a note. A hidden primary unit leaves no unit. - A parent link masked off a readable unit ends the chain with the "next unit up is not readable" note, and the next unit is never read. The control is a present, empty link: that is the top, with no note. Ablated: with the fix hunk reverted on disk, this case fails (1 failed, 14 passed); with it restored, 15 passed. - A `403` throw leaves the fact out. A `500` throw or a status-less throw fails the answer. - A deployment with no business units answers the user and organization. - A masked primary-unit field and an empty one answer differently. - No active organization gives no organization key. - A loop stops, and the depth cap holds. No user means no read. - Through `buildMcpBridge`, every read is a by-id `findData` carrying the caller's own `ExecutionContext` (never `isSystem`), and a refused read leaves the fact out.
Local runs, review rework (final head 2d2b2bf4fb: origin/main merged in 206d1f0787, then the fix commit) ``` pnpm --filter '@objectstack/runtime^...' --filter '@objectstack/mcp^...' build BUILD_OK (under the lock) pnpm --filter @objectstack/mcp typecheck exit 0 pnpm --filter @objectstack/runtime typecheck exit 0 runtime src/domains/mcp-asker-38363.test.ts 15 passed (15) mcp src/mcp-asker-38363.test.ts 8 passed (8) lock VERDICT command-exit 0 ``` Derived gate list at 2d2b2bf4fb (`dispatch-gates --commands`, the same 69 commands): 68 exited 0. `check:dual-build-cjs-loads` exited 3 with PREREQUISITE NOT MET, because the fresh worktree had built only the closure. After a full `turbo run build` (123 tasks, VERDICT command-exit 0) it exits 0 ("126 published require entry point(s) across 74 package(s) load"). `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN".
Local runs, patch round (final head 38fbe352b1: origin/main merged in 165fe83467, then the weight-pin commit) ``` pnpm --filter '@objectstack/mcp^...' build BUILD_OK (under the lock) pnpm --filter @objectstack/mcp typecheck exit 0 pnpm --filter @objectstack/mcp test Test Files 89 passed (89) · Tests 1665 passed (1665) src/tools-list-weight-34689.test.ts 1 passed · 18 tools, 38569 bytes (ceiling 39,000) parent commit's version of the same file 1 passed · 17 tools, 37931 bytes (ceiling 38,000) ``` Derived gate list at 38fbe352b1 (`dispatch-gates --commands`, the same 69 commands as the first round): 68 exited 0. `check:dual-build-cjs-loads` exited 3 with PREREQUISITE NOT MET, because this fresh worktree had built only the mcp closure. After a full `turbo run build` (123 tasks, VERDICT command-exit 0) it reads "126 published require entry point(s) across 74 package(s) load" and exits 0. `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN". The runtime suite was not re-run in this round. The merge brought in main's runtime test changes; none of them is this PR's code.
Local runs, first round (head 0cea24a56c) ``` pnpm --filter '@objectstack/runtime^...' --filter '@objectstack/mcp^...' build VERDICT command-exit 0 pnpm --filter @objectstack/mcp typecheck exit 0 (re-run at 0cea24a56c) pnpm --filter @objectstack/runtime typecheck exit 0 (re-run at 0cea24a56c) pnpm --filter @objectstack/mcp test Test Files 89 passed (89) · Tests 1661 passed (1661) at b5881fa8f8 pnpm --filter @objectstack/runtime test Test Files 657 passed (657) · Tests 12507 passed | 25 skipped (12532) at b5881fa8f8 both asker files at 0cea24a56c runtime 14 passed (14) · mcp 8 passed (8) ``` The commits after b5881fa8f8 change only the changeset and add a module-top `import '@objectstack/metadata'` to the runtime asker test, which `check:test-source-alias` asked for. Derived gate list (`node scripts/pm/dispatch-gates.mjs --commands`, 69 commands) run at 0cea24a56c: all 69 exited 0. `--ran` gives "69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN". The first pass at b5881fa8f8 had four reds: - `check:test-source-alias` was a real red on the new runtime test, fixed in 0cea24a56c. - `check:query-options-erasure` read the uncommitted probe file mid-removal. - `check:dts-closure` and `check:dual-build-cjs-loads` hit PREREQUISITE NOT MET on packages outside the build closure. The re-run at the final head is the reading of record.
## Acceptance notes - **Plain members read no business unit by default.** On the showcase, a member with no permission set granting `sys_business_unit` read gets `user` and `organization` plus the note "Your primary business unit is not readable with your permissions." That is the fixed rule (only what the caller may read), and this PR widens no permission. Today a plain member gets that note unless an app grants `sys_business_unit` read. #38515 is ruled D: `member_default` gains one read-only line on business units, with no row policy, added by a separate build card. Once that build lands, every internal member gets their own chain with no app grant. This PR's code does not change for it, because the tool already reads the chain as the caller may, and this PR adds no permission line. - **`enable.aiReadable` is not consulted.** The record tools need that opt-in before they read a `sys_*` object. `get_current_user` instead reads a fixed projection of the caller's own facts: their `sys_user` row (`id`, `name`, `primary_business_unit_id`, all readable to a plain member), their active `sys_organization` (`id`, `name`), and the units on their own chain (`id`, `name`, `kind`, `parent_business_unit_id`). These are read under the caller's permissions, RLS and field masking. This is the same set of facts the ask route's asker block gets from the platform. It opens no general read of those objects. - **tools/list weight pin.** The pin's stub bridge now carries `currentUser`, so its surface matches the runtime bridge's. The ceiling moved from 38,000 to 39,000 beside the table above, as the test's header asks of a PR that adds weight. - The `initialize` answer's two construction sites named on the card: the long-lived server's site (`mcp-server-runtime.ts` ~2205, used by stdio) is unchanged, because stdio does not register the tool. - The filter-placeholder idea on the card thread (`{current_business_unit_ids}` and the like) is new filter vocabulary and a separate decision. It is not built here. ## Verification Live probe through the real `/api/v1/mcp` route. The showcase was booted `multiTenant: 'posture-only'` with `MCPServerPlugin` (a scratch dogfood file, not committed). Organization A ("Acme Group") has units `Acme Group HQ` (company) → `Field Operations` (division) → `West Coast` (office), and `Acme Group HQ` → `HQ Finance` (department). A unit `Seconded Desk` in A has its parent in organization B, behind the organization wall. Ada is primary in West Coast, Lin in HQ Finance, Max in Seconded Desk. All three are members of A, signed in by session.
Before (base d89d3e2356, mcp and runtime rebuilt from base) vs after - `tools/list`: 21 tools before, 22 after; the only added name is `get_current_user`. - `initialize`: identical text for Ada and Lin, both before and after. The only line added after is the fixed "Who is asking: call get_current_user …" sentence. No id or name of either caller appears in it. - `tools/call get_current_user`, before: `isError: true`, "MCP error -32602: Tool get_current_user not found". - After, no set grants `sys_business_unit` read: - every user gets `{ user: { id, name }, organization: { id, name: "Acme Group" }, businessUnitNote: "Your primary business unit is not readable with your permissions." }`, with no error. - After, each holds a set granting `sys_business_unit` read: - Ada: `businessUnits` = West Coast (office), Field Operations (division), Acme Group HQ (company). - Lin: `businessUnits` = HQ Finance (department), Acme Group HQ (company). - Max: `businessUnits` = Seconded Desk only, `businessUnitNote`: "The chain ends here: the next unit up is not readable with your permissions." The organization-B parent's id and name appear nowhere in the answer.
**Re-running the probe (for the next card's arm 2).** Nothing extra is committed. Save the script below as `packages/qa/dogfood/test/zz-probe-38363.dogfood.test.ts`, build `@objectstack/mcp` and `@objectstack/runtime` (and their closure), then run: ``` PROBE_OUT=/tmp/probe.json pnpm --filter @objectstack/dogfood exec vitest run --project isolated test/zz-probe-38363.dogfood.test.ts ``` Delete the file afterwards. For the "before" arm, write base `packages/mcp/src` and `packages/runtime/src` into the tree (`git restore --source=BASE_SHA -- packages/mcp/src packages/runtime/src`), rebuild those two, re-run the probe, then restore HEAD and rebuild. - Fixture: the showcase app (`bootShowcase`, `multiTenant: 'posture-only'`, `extraPlugins: [new MCPServerPlugin()]`). - Users: `p38363-ada`, `p38363-lin` and `p38363-max`, all members of organization "Acme Group" and signed in by session. - Units: those listed above. The BU-read grant is the showcase's `showcase_field_ops_delegate` permission set. - What the probe reads per user: `initialize` instructions, `tools/list` names, and `tools/call get_current_user`. It runs once before the grant and once after. - **No model was in the loop, so no question was asked.** The probe measures the text a model is handed, not a model's answer. "The model's answer changes with the asker" is NOT MEASURED here, per question or otherwise. What is measured is that the model-visible text differs between Ada, Lin and Max only by their own facts: the `get_current_user` answer differs, and `initialize` is byte-identical.
Probe script (no angle brackets, so it survives the body sanitizer) ```ts // Probe for get_current_user through the real /api/v1/mcp route (not committed). // Save as packages/qa/dogfood/test/zz-probe-38363.dogfood.test.ts, build mcp + runtime, then: // PROBE_OUT=/tmp/probe.json pnpm --filter @objectstack/dogfood exec vitest run --project isolated test/zz-probe-38363.dogfood.test.ts // Readings land in PROBE_OUT as JSON; delete the file afterwards. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { writeFileSync } from 'node:fs'; import { type VerifyStack } from '@objectstack/verify'; import { MCPServerPlugin } from '@objectstack/mcp'; import { bootShowcase } from './showcase-boot.js'; const SYS = { isSystem: true } as const; const OUT = process.env.PROBE_OUT ?? '/tmp/probe-38363.json'; const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? b?.data?.id ?? ''); describe('probe 38363', () => { let stack: VerifyStack; let ql: any; const tok: any = {}; const readings: any = {}; const mcp = async (token: string, method: string, params?: unknown) => { const res = await stack.api('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}` }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, ...(params !== undefined ? { params } : {}) }), }); return { status: res.status, body: (await res.json()) as any }; }; const userId = async (email: string) => String((await ql.findOne('sys_user', { where: { email }, context: SYS }))?.id ?? ''); const inOrg = (o: string) => ({ context: { ...SYS, tenantId: o } }); const organization = async (token: string, name: string, slug: string) => { const created = await stack.apiAs(token, 'POST', '/auth/organization/create', { name, slug }); expect(created.status, await created.clone().text()).toBe(200); const id = String(((await created.json()) as any).id); await stack.apiAs(token, 'POST', '/auth/organization/set-active', { organizationId: id }); return id; }; beforeAll(async () => { stack = await bootShowcase({ multiTenant: 'posture-only', extraPlugins: [new MCPServerPlugin()] }); ql = await stack.kernel.getServiceAsync('objectql'); const ownerA = await stack.signUp('p38363-owner-a@verify.test'); const orgA = await organization(ownerA, 'Acme Group', 'p38363-acme'); const ownerB = await stack.signUp('p38363-owner-b@verify.test'); const orgB = await organization(ownerB, 'Other Holding', 'p38363-other'); readings.orgs = { orgA, orgB }; const unit = async (o: string, name: string, code: string, kind: string, parent?: string) => idOf(await ql.insert('sys_business_unit', { name, code, kind, organization_id: o, ...(parent ? { parent_business_unit_id: parent } : {}) }, inOrg(o))); const group = await unit(orgA, 'Acme Group HQ', 'P-GRP', 'company'); const ops = await unit(orgA, 'Field Operations', 'P-OPS', 'division', group); const west = await unit(orgA, 'West Coast', 'P-WEST', 'office', ops); const fin = await unit(orgA, 'HQ Finance', 'P-FIN', 'department', group); const holding = await unit(orgB, 'Other Holding Parent', 'P-HOLD', 'company'); let seconded = ''; try { seconded = await unit(orgA, 'Seconded Desk', 'P-SEC', 'department', holding); } catch (e: any) { readings.secondedInsertError = String(e?.message ?? e); } readings.units = { group, ops, west, fin, holding, seconded }; const people: any[] = [['ada', 'p38363-ada@verify.test', west], ['lin', 'p38363-lin@verify.test', fin]]; if (seconded) people.push(['max', 'p38363-max@verify.test', seconded]); for (const [k, email, bu] of people) { tok[k] = await stack.signUp(email); const uid = await userId(email); await ql.insert('sys_member', { user_id: uid, organization_id: orgA, role: 'member' }, inOrg(orgA)); const act = await stack.apiAs(tok[k], 'POST', '/auth/organization/set-active', { organizationId: orgA }); expect(act.status).toBe(200); await ql.insert('sys_business_unit_member', { user_id: uid, business_unit_id: bu, is_primary: true, organization_id: orgA }, inOrg(orgA)); readings[`${k}_uid`] = uid; readings[`${k}_primary_at_rest`] = (await ql.findOne('sys_user', { where: { id: uid }, fields: ['primary_business_unit_id'], context: SYS }))?.primary_business_unit_id; } readings.grant = async () => { for (const [k] of people) { await ql.insert('sys_user_permission_set', { user_id: readings[`${k}_uid`], permission_set: 'showcase_field_ops_delegate', organization_id: orgA }, inOrg(orgA)); } }; }, 180_000); afterAll(async () => { const { grant, ...rest } = readings; writeFileSync(OUT, JSON.stringify(rest, null, 2)); await stack?.stop(); }); it('reads', async () => { for (const k of Object.keys(tok)) { const init = await mcp(tok[k], 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'probe', version: '0' } }); readings[`${k}_initialize`] = { status: init.status, instructions: init.body?.result?.instructions }; const list = await mcp(tok[k], 'tools/list'); const names = (list.body?.result?.tools ?? []).map((t: any) => t.name); readings[`${k}_tools`] = { count: names.length, hasGetCurrentUser: names.includes('get_current_user'), names }; } const callAll = async (phase: string) => { for (const k of Object.keys(tok)) { const r = await mcp(tok[k], 'tools/call', { name: 'get_current_user', arguments: {} }); const text = r.body?.result?.content?.[0]?.text; let parsed: unknown = text; try { parsed = JSON.parse(text); } catch { /* keep text */ } readings[`${phase}_${k}`] = { status: r.status, isError: r.body?.result?.isError ?? false, rpcError: r.body?.error, answer: parsed }; } }; await callAll('no_grant'); await readings.grant(); await callAll('with_bu_read'); }, 180_000); }); ```
**Read first (by risk):** 1. `packages/runtime/src/domains/mcp.ts`: `resolveCallerIdentity`, `readOrUndefined` (which throws count as a refusal) and the `currentUser` member (the reader runs as `ec`). 2. `packages/mcp/src/mcp-http-tools.ts`: `currentUserToolServed`, the one gate shared by registration and the `initialize` sentence. 3. `packages/mcp/src/mcp-server-runtime.ts`: `ASKER_TOOL_LINE`, the fixed text. **Two-minute check:** `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-asker-38363.test.ts`. Expect 8 tests passing, including "carries no caller fact and reads none: the same text for every caller". --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .changeset/38363-mcp-asker.md | 13 + packages/mcp/src/index.ts | 3 + packages/mcp/src/mcp-asker-38363.test.ts | 192 ++++++++++++ packages/mcp/src/mcp-http-tools.ts | 108 +++++++ packages/mcp/src/mcp-server-runtime.ts | 25 +- .../mcp/src/tools-list-weight-34689.test.ts | 22 +- .../src/domains/mcp-asker-38363.test.ts | 277 ++++++++++++++++++ packages/runtime/src/domains/mcp.ts | 178 +++++++++++ 8 files changed, 807 insertions(+), 11 deletions(-) create mode 100644 .changeset/38363-mcp-asker.md create mode 100644 packages/mcp/src/mcp-asker-38363.test.ts create mode 100644 packages/runtime/src/domains/mcp-asker-38363.test.ts diff --git a/.changeset/38363-mcp-asker.md b/.changeset/38363-mcp-asker.md new file mode 100644 index 00000000000..209fa805149 --- /dev/null +++ b/.changeset/38363-mcp-asker.md @@ -0,0 +1,13 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +--- + +feat(mcp): `get_current_user` tells an MCP client's model who is signed in + +Clause-②: yes (widening) +Metadata-protocol: none + +The `/mcp` route lists a new read-only tool, `get_current_user`, for an API key, a session and an OAuth token that grants `data:read`. It answers the caller's own facts: their user id and name, their active organization, and their primary business unit (`sys_user.primary_business_unit_id`) followed by each parent unit up to the top of the tree, each with its `name` and `kind`. Every read runs as the caller through the data API's permissions, row-level security and field masking, so a unit the caller may not read is left out (never named) and `businessUnitNote` says where the chain stops, or that no primary unit is recorded; a read that fails for any other reason fails the call with its coded error rather than reading as a permission limit. It takes no argument and answers nothing about any other user. A deployment with no business units answers the user and organization. + +Where the tool registers and neither the host nor the operator writes the `initialize` text, that text gains one sentence pointing the model to the tool; the sentence is the same for every caller. `@objectstack/mcp` exports the answer's types, `McpCurrentUser` and `McpBusinessUnitFact`, for a host that implements `McpDataBridge.currentUser`. The stdio transport does not list the tool. The identity is resolved by one runtime function that any later door needing the asker's identity can reuse. diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 2f6996290d6..4a1285e5e29 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -67,6 +67,9 @@ export type { McpActionUnavailable, RegisterActionToolsOptions, McpFederationBridge, + // [#38363] What `McpDataBridge.currentUser` answers, for an outside bridge implementer. + McpCurrentUser, + McpBusinessUnitFact, } from './mcp-http-tools.js'; // [#33712] Step 1 of the amended confirmation contract: the person asked in their client. export { diff --git a/packages/mcp/src/mcp-asker-38363.test.ts b/packages/mcp/src/mcp-asker-38363.test.ts new file mode 100644 index 00000000000..18b9182f7f8 --- /dev/null +++ b/packages/mcp/src/mcp-asker-38363.test.ts @@ -0,0 +1,192 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38363] `get_current_user`: an MCP client's model can learn who is signed + * in — the caller's user, active organization and primary business unit with + * its parents — through the real registration path (`handleHttpRequest`, a + * JSON-RPC round-trip), never a list of names. + * + * Pinned here: the tool registers exactly where the bridge resolves its + * caller (`currentUser`) and the grant is the read family's; it takes no + * argument; a call answers the bridge's facts unchanged, and a member throw + * answers the ADR-0112 envelope; the open server's `initialize` text points to + * the tool exactly where it registers, with the same sentence for every caller + * (no caller fact in it), and a host's own text is left whole. + * + * The resolver behind the member is pinned in + * `packages/runtime/src/domains/mcp-asker-38363.test.ts`. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { + MCP_OAUTH_SCOPE_ACTIONS, + MCP_OAUTH_SCOPE_DATA_READ, + MCP_OAUTH_SCOPE_DATA_WRITE, + MCP_OAUTH_SCOPE_METADATA_WRITE, +} from '@objectstack/spec/ai'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { GET_CURRENT_USER_TOOL_NAME, type McpCurrentUser, type McpDataBridge } from './mcp-http-tools.js'; +import type { McpAuthoringInjection } from './types.js'; + +const ADA: McpCurrentUser = { + user: { id: 'u_ada', name: 'Ada' }, + organization: { id: 'org_1', name: 'Acme Group' }, + businessUnits: [ + { id: 'bu_west', name: 'West Coast', kind: 'office' }, + { id: 'bu_group', name: 'Acme Group', kind: 'company' }, + ], +}; + +function makeBridge(currentUser?: () => Promise): McpDataBridge { + return { + async listObjects() { return []; }, + async describeObject() { return null; }, + async query() { return { records: [] }; }, + async get() { return null; }, + async create() { return {}; }, + async update() { return {}; }, + async remove() { return {}; }, + ...(currentUser ? { currentUser } : {}), + }; +} + +interface Opts { grantedScopes?: string[]; authoring?: Partial } + +async function rpc(runtime: MCPServerRuntime, bridge: McpDataBridge, body: unknown, o: Opts = {}) { + const res = await runtime.handleHttpRequest( + new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }), + { + bridge, + parsedBody: body, + ...(o.grantedScopes ? { toolOptions: { grantedScopes: o.grantedScopes } } : {}), + ...(o.authoring + ? { + authoring: { + registry: { getAll: () => [], execute: async () => ({}) as never }, + principal: { userId: 'u_ada', scopes: o.grantedScopes ?? [] }, + ...o.authoring, + } as McpAuthoringInjection, + } + : {}), + }, + ); + expect(res.status).toBe(200); + return (await res.json()) as any; +} + +async function listedTool(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}) { + const json = await rpc(runtime, bridge, { jsonrpc: '2.0', id: 1, method: 'tools/list' }, o); + return ((json.result?.tools ?? []) as any[]).find((t) => t.name === GET_CURRENT_USER_TOOL_NAME); +} + +async function instructionsOf(runtime: MCPServerRuntime, bridge: McpDataBridge, o: Opts = {}): Promise { + const json = await rpc(runtime, bridge, { + jsonrpc: '2.0', + id: 2, + method: 'initialize', + params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'pin', version: '0' } }, + }, o); + expect(json.error).toBeUndefined(); + return json.result.instructions; +} + +async function call(runtime: MCPServerRuntime, bridge: McpDataBridge, args: Record = {}) { + const json = await rpc(runtime, bridge, { + jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: GET_CURRENT_USER_TOOL_NAME, arguments: args }, + }); + return json.result as { content: Array<{ type: string; text: string }>; isError?: boolean }; +} + +describe('[#38363] get_current_user — registration', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); }); + + it('registers, read-only and with no argument, where the bridge resolves its caller: a key or session, a data:read token', async () => { + for (const o of [{}, { grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] }] as Opts[]) { + const tool = await listedTool(runtime, makeBridge(async () => ADA), o); + expect(tool).toBeDefined(); + expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + expect(Object.keys(tool.inputSchema.properties ?? {})).toEqual([]); + expect(tool.description).toContain('businessUnits'); + } + }); + + it('is not registered for a grant without data:read, nor on a bridge without the member', async () => { + for (const grantedScopes of [[MCP_OAUTH_SCOPE_DATA_WRITE], [MCP_OAUTH_SCOPE_ACTIONS], [MCP_OAUTH_SCOPE_METADATA_WRITE]]) { + expect(await listedTool(runtime, makeBridge(async () => ADA), { grantedScopes })).toBeUndefined(); + } + expect(await listedTool(runtime, makeBridge())).toBeUndefined(); + }); +}); + +describe('[#38363] get_current_user — the answer', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); }); + + it('answers the bridge\'s facts for this caller, unchanged; two callers get their own', async () => { + const lin: McpCurrentUser = { + user: { id: 'u_lin', name: 'Lin' }, + organization: { id: 'org_1', name: 'Acme Group' }, + businessUnits: [{ id: 'bu_fin', name: 'HQ Finance', kind: 'department' }, { id: 'bu_group', name: 'Acme Group', kind: 'company' }], + }; + const adaMember = vi.fn(async () => ADA); + const adaRes = await call(runtime, makeBridge(adaMember)); + const linRes = await call(runtime, makeBridge(async () => lin)); + expect(adaMember).toHaveBeenCalledTimes(1); + expect(adaRes.isError).toBeFalsy(); + expect(JSON.parse(adaRes.content[0].text)).toEqual(ADA); + expect(JSON.parse(linRes.content[0].text)).toEqual(lin); + }); + + it('refuses an argument rather than answer about someone else', async () => { + const member = vi.fn(async () => ADA); + const res = await call(runtime, makeBridge(member), { userId: 'u_lin' }); + expect(res.isError).toBe(true); + expect(member).not.toHaveBeenCalled(); + }); + + it('a member throw answers the coded envelope', async () => { + const res = await call(runtime, makeBridge(async () => { + throw Object.assign(new Error('Service unavailable'), { code: 'SERVICE_UNAVAILABLE', status: 503 }); + })); + expect(res.isError).toBe(true); + const envelope = JSON.parse(res.content[0].text); + expect(envelope.error ?? envelope).toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); + }); +}); + +describe('[#38363] initialize — the pointer to get_current_user', () => { + let runtime: MCPServerRuntime; + beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); }); + + it('the open server names the tool exactly where it registers', async () => { + const served = await instructionsOf(runtime, makeBridge(async () => ADA)); + expect(served.split(GET_CURRENT_USER_TOOL_NAME)).toHaveLength(2); + expect(await instructionsOf(runtime, makeBridge())).not.toContain(GET_CURRENT_USER_TOOL_NAME); + expect( + await instructionsOf(runtime, makeBridge(async () => ADA), { grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] }), + ).not.toContain(GET_CURRENT_USER_TOOL_NAME); + }); + + it('carries no caller fact and reads none: the same text for every caller', async () => { + const member = vi.fn(async () => ADA); + const text = await instructionsOf(runtime, makeBridge(member)); + expect(member).not.toHaveBeenCalled(); + for (const fact of ['u_ada', 'Ada', 'Acme', 'West Coast', 'org_1']) expect(text).not.toContain(fact); + expect(await instructionsOf(runtime, makeBridge(async () => ({ user: { id: 'u_lin', name: 'Lin' } })))).toBe(text); + }); + + it('a host\'s own initialize text and a configured one are left whole', async () => { + const hostText = 'Host text, owned by the host.'; + expect(await instructionsOf(runtime, makeBridge(async () => ADA), { + grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ], + authoring: { dataOnlyInstructions: hostText }, + })).toBe(hostText); + const configured = new MCPServerRuntime({ name: 't', version: '1.0.0', instructions: 'Configured.' }); + expect(await instructionsOf(configured, makeBridge(async () => ADA))).toBe('Configured.'); + }); +}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index e2c17046b59..09ef8699a31 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -498,6 +498,50 @@ export interface McpDataBridge { * `packages/mcp` holds no second copy. OPTIONAL — see {@link getRecordContext}. */ recordContextToolDefinitions?(): ReadonlyArray>; + /** + * [#38363] `get_current_user`: who is signed in on this connection, as the + * caller may read it about themselves ({@link McpCurrentUser}). Every read + * behind it runs AS the principal, under the same permissions, row-level + * security and field masking every other member runs under: a record the + * caller may not read is left out, never named. It answers nothing about + * any other user and writes nothing. + * + * OPTIONAL: a bridge that cannot resolve its principal's identity (the + * stdio API-key host) omits it, and the tool does not register. + */ + currentUser?(): Promise; +} + +/** + * [#38363] One business unit in {@link McpCurrentUser.businessUnits}: the + * fields of its `sys_business_unit` row the caller read. + */ +export interface McpBusinessUnitFact { + id: string; + name?: string; + /** The unit's `kind` (company, division, department, …), where it carries one. */ + kind?: string; +} + +/** + * [#38363] What `get_current_user` answers: the caller's own facts, each read + * with the caller's own permissions. A key is absent when its fact is not + * recorded or not readable; `businessUnitNote` says which, so an absent unit + * never reads as "no unit". + */ +export interface McpCurrentUser { + /** The signed-in user: their id, and their display name where readable. Absent for a connection with no user. */ + user?: { id: string; name?: string }; + /** The active organization: its id, and its name where readable. Absent when the session has none. */ + organization?: { id: string; name?: string }; + /** + * The primary business unit first, then each parent unit up to the top of + * the tree, as far as the caller may read them. Absent when no unit is + * readable or recorded. + */ + businessUnits?: McpBusinessUnitFact[]; + /** Why the business units end where they do, when they are not the whole chain up to the top. */ + businessUnitNote?: string; } /** [#35442] Where a manual page lives: its name, app, title, manual and the console address to cite. */ @@ -3382,6 +3426,9 @@ export function wireBridgeTools( // [ADR-0149 D2] `search_knowledge`, only where the bridge carries both // knowledge members and the grant admits `data:read`. registered.push(...registerKnowledgeTools(server, bridge, options)); + // [#38363] `get_current_user`, only where the bridge resolves its caller + // and the grant admits `data:read`. + registered.push(...registerCurrentUserTool(server, bridge, options)); return registered; } @@ -3783,6 +3830,67 @@ export function registerKnowledgeTools( return [SEARCH_KNOWLEDGE_TOOL_NAME]; } +/** [#38363] The tool that says who is signed in on this connection. */ +export const GET_CURRENT_USER_TOOL_NAME = 'get_current_user'; + +/** + * [#38363] Whether this bridge and grant register `get_current_user`: the + * bridge resolves its caller ({@link McpDataBridge.currentUser}) and the grant + * is the read family's (an undefined grant keeps it, a scope list without + * `data:read` does not). The one gate: {@link registerCurrentUserTool} + * registers from it, and `handleHttpRequest` reads it to decide whether the + * `initialize` instructions point to the tool. + */ +export function currentUserToolServed( + bridge: Partial | undefined, + options: RegisterObjectToolsOptions = {}, +): boolean { + if (!bridge || typeof bridge.currentUser !== 'function') return false; + const scopes = options.grantedScopes; + return !scopes || scopes.includes(MCP_OAUTH_SCOPE_DATA_READ); +} + +/** + * [#38363] Register `get_current_user` over {@link McpDataBridge.currentUser}. + * + * - **The caller's own facts, nothing else.** The member reads the caller's + * user row, active organization and primary business unit with its parents + * AS the caller; a unit the caller may not read is left out and the chain + * ends below it. It takes no argument, so it can answer about no one else. + * - **A tool, not an `initialize` paragraph.** It is served on every host + * whose bridge resolves the caller, including the ones whose host or + * operator writes the whole `initialize` text; it costs one row of + * `tools/list`, and no read runs until it is called. + */ +export function registerCurrentUserTool( + server: McpServer, + bridge: Partial, + options: RegisterObjectToolsOptions = {}, +): string[] { + if (!currentUserToolServed(bridge, options)) return []; + const resolve = bridge.currentUser!.bind(bridge); + server.registerTool( + GET_CURRENT_USER_TOOL_NAME, + { + description: + 'Who is signed in here: your user id and name, active organization, and primary business unit then each ' + + 'parent up to the top (businessUnits). Read with your own permissions: a unit you may not read is left ' + + 'out, and businessUnitNote says why the chain stops. Call it instead of asking the user who they are or ' + + 'which company or unit they are in.', + inputSchema: strictToolInput({ surface: `this ${GET_CURRENT_USER_TOOL_NAME} call` }, {}), + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + }, + async () => { + try { + return textResult(await resolve()); + } catch (err) { + return errorResultWithCode(err); + } + }, + ); + return [GET_CURRENT_USER_TOOL_NAME]; +} + /** * [#27745] Register the federation pair, `list_remote_tables` and * `import_object`, over {@link McpFederationBridge}. diff --git a/packages/mcp/src/mcp-server-runtime.ts b/packages/mcp/src/mcp-server-runtime.ts index 147b39a54c5..3c51b09fdac 100644 --- a/packages/mcp/src/mcp-server-runtime.ts +++ b/packages/mcp/src/mcp-server-runtime.ts @@ -24,7 +24,7 @@ import { type McpCallerExecutionContext, } from './tool-call-interceptor.js'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import { wireBridgeTools, datasetToolsServed, packageDocToolsServed, grantsAuthoringTools, thrownRefusalEnvelope, dataDoorAnswerOf, dataDoorRefusalEnvelope } from './mcp-http-tools.js'; +import { wireBridgeTools, datasetToolsServed, packageDocToolsServed, currentUserToolServed, grantsAuthoringTools, thrownRefusalEnvelope, dataDoorAnswerOf, dataDoorRefusalEnvelope } from './mcp-http-tools.js'; import { FLOW_RUNTIME_STATE_KEY, isServerFault, logServerFault } from '@objectstack/types'; import type { McpDataBridge, @@ -2035,13 +2035,28 @@ function definitionReaderServed( return definitionReaderOf(authoring!.registry.getAll().map((tool) => tool.name)); } +/** + * [#38363] Where the open server tells its client who is asking: the tool + * that reads the signed-in user's own facts, named in the few lines + * `initialize` carries because a client reads a tool's description only after + * it has chosen that tool (#34659 ruling D5 = A). The facts themselves are + * never in this text: it is the same sentence for every caller, so nothing + * about one user rides a text another connection could be handed. Sent only + * where the tool registers ({@link currentUserToolServed}). + */ +const ASKER_TOOL_LINE = + 'Who is asking: call get_current_user for the signed-in user, their organization and their business unit with ' + + 'its parent units before you answer a question that depends on who asks (whose company or unit, "my" ' + + 'records); do not ask the user for what it answers.'; + /** * [#34686] The open server's own `initialize` text for one HTTP request: the * default sentence, [#34774] the authoring contract line when it registers * authoring tools, the selection rule when this request's grant registers * both dataset tools, [#35442] the answer-order rule when it registers both - * doc tools, [#34766] the drafts line when it registers authoring tools, and - * the skills install line. Read only when neither the + * doc tools, [#38363] the asker line when it registers get_current_user, + * [#34766] the drafts line when it registers authoring tools, and the skills + * install line. Read only when neither the * host (`hostInstructions`) nor the runtime's configured `instructions` * answers: both are whole texts their author owns, and the configured one is * the same string for every grant, so nothing is appended to either. @@ -2050,12 +2065,14 @@ function openServerInstructions( datasetRule: boolean, authoringServed = false, docRule: { served: boolean; definitionReader?: string } = { served: false }, + askerServed = false, ): string { return [ DEFAULT_HTTP_INSTRUCTIONS, authoringServed ? AUTHORING_CONTRACT_LINE : undefined, datasetRule ? DATASET_SELECTION_RULE : undefined, docRule.served ? packageDocAnswerRule(docRule.definitionReader) : undefined, + askerServed ? ASKER_TOOL_LINE : undefined, authoringServed ? AUTHORING_DRAFTS_LINE : undefined, skillsInstallLine(PACKAGE_VERSION), ] @@ -3078,6 +3095,8 @@ export class MCPServerRuntime { served: packageDocToolsServed(opts.bridge, opts.toolOptions), definitionReader: definitionReaderServed(opts.authoring, opts.toolOptions?.grantedScopes), }, + // [#38363] The pointer to get_current_user, where it registers. + currentUserToolServed(opts.bridge, opts.toolOptions), ), }, ); diff --git a/packages/mcp/src/tools-list-weight-34689.test.ts b/packages/mcp/src/tools-list-weight-34689.test.ts index 7f06b4e68d0..d47e90a637f 100644 --- a/packages/mcp/src/tools-list-weight-34689.test.ts +++ b/packages/mcp/src/tools-list-weight-34689.test.ts @@ -5,9 +5,9 @@ * in the client's own tokens, before any work starts. * * The surface is the one a self-hosted app serves an API key (no scope list): - * object CRUD with `aggregate_records`, the action trio, the file pair and the + * object CRUD with `aggregate_records`, the action trio, the file pair, the * dataset pair — the dataset descriptions are the service-analytics - * definitions the runtime hands the bridge. It is read through the real + * definitions the runtime hands the bridge — and `get_current_user`. It is read through the real * registration path (a `tools/list` round-trip), never from a list of names. * * The run prints one row per tool (description bytes, input-schema bytes) and @@ -16,8 +16,9 @@ * * pnpm --filter @objectstack/mcp exec vitest run src/tools-list-weight-34689.test.ts * - * The ceiling is the slimmed total with headroom for one more tool's worth of - * text. Teaching prose belongs in the served SKILL.md (`skill-md.ts`), which a + * The ceiling is the measured total plus a small margin, not room for another + * tool: a PR that adds a tool or description text raises it beside its own + * before/after table. Teaching prose belongs in the served SKILL.md (`skill-md.ts`), which a * client reads when it needs it; a description carries what the call needs. */ @@ -57,6 +58,9 @@ function makeFullBridge(): McpDataBridge & McpActionBridge & McpFileBridge { async listDatasets() { return { datasets: [] }; }, async queryDataset() { throw new Error('not called'); }, datasetToolDefinitions() { return getDatasetToolDefinitions(); }, + // The runtime bridge resolves its caller on every key, session and data:read + // token, so `get_current_user` is on this surface too. + async currentUser() { return {}; }, }; } @@ -84,10 +88,12 @@ async function measureToolsList(): Promise<{ total: number; rows: ToolRow[] }> { } /** - * The slimmed total (36,481 bytes, from 47,712) plus room for one more tool. A PR - * that needs more raises it beside its own before/after table. + * The slimmed total (36,481 bytes, from 47,712), raised to 39,000 when + * `get_current_user` joined the surface (38,569 bytes measured). It leaves no + * room for another tool: a PR that needs more raises it beside its own + * before/after table. */ -const TOOLS_LIST_BYTE_CEILING = 38_000; +const TOOLS_LIST_BYTE_CEILING = 39_000; describe('[#34689] the open door tools/list weight', () => { it('prints the per-tool table and stays under the ceiling', async () => { @@ -97,7 +103,7 @@ describe('[#34689] the open door tools/list weight', () => { 'list_objects', 'describe_object', 'validate_expression', 'query_records', 'aggregate_records', 'get_record', 'create_record', 'update_record', 'delete_record', 'delete_records', 'list_actions', 'run_action', 'resume_run', 'read_file', 'create_upload_link', - 'list_datasets', 'query_dataset', + 'list_datasets', 'query_dataset', 'get_current_user', ])); const sorted = [...rows].sort((a, b) => (b.description + b.inputSchema) - (a.description + a.inputSchema)); diff --git a/packages/runtime/src/domains/mcp-asker-38363.test.ts b/packages/runtime/src/domains/mcp-asker-38363.test.ts new file mode 100644 index 00000000000..42dc8a07c0c --- /dev/null +++ b/packages/runtime/src/domains/mcp-asker-38363.test.ts @@ -0,0 +1,277 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38363] Who is signed in, as the HTTP MCP bridge resolves it for + * `get_current_user`. + * + * Pinned here: + * - {@link resolveCallerIdentity}, the one resolver: each caller gets their own + * user, organization and primary business unit chain up to the root; a unit + * the reader does not return (the caller may not read it) is absent, never + * named, and the chain ends below it with a note; a deployment with no + * business units answers the user and organization; a masked primary-unit + * field and an empty one answer differently; a looping or runaway parent + * chain is bounded; a connection with no user reads nothing. + * - The bridge member: every read is a `findData` by id through the caller's + * own `ExecutionContext` (never a system context), and a refused read is a + * fact left out, not a failed tool call. + * + * The real permission path (a member who may not read a parent unit) is + * measured through the live `/mcp` route in the PR's verification section; the + * tool layer on the MCP side is pinned in `packages/mcp/src/mcp-asker-38363.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import { + CALLER_UNIT_CHAIN_MAX_DEPTH, + buildMcpBridge, + resolveCallerIdentity, + type CallerRecordReader, +} from './mcp.js'; + +type Rows = Record>>; + +/** A tenant: two companies under one group, a sibling the second user cannot see. */ +const TREE: Rows = { + sys_user: { + u_ada: { id: 'u_ada', name: 'Ada', primary_business_unit_id: 'bu_west' }, + u_lin: { id: 'u_lin', name: 'Lin', primary_business_unit_id: 'bu_fin' }, + u_none: { id: 'u_none', name: 'Nobody', primary_business_unit_id: null }, + }, + sys_organization: { org_1: { id: 'org_1', name: 'Acme Group' } }, + sys_business_unit: { + bu_group: { id: 'bu_group', name: 'Acme Group', kind: 'company', parent_business_unit_id: null }, + bu_ops: { id: 'bu_ops', name: 'Field Operations', kind: 'division', parent_business_unit_id: 'bu_group' }, + bu_west: { id: 'bu_west', name: 'West Coast', kind: 'office', parent_business_unit_id: 'bu_ops' }, + bu_fin: { id: 'bu_fin', name: 'HQ Finance', kind: 'department', parent_business_unit_id: 'bu_group' }, + }, +}; + +/** A reader over `rows` that answers only the ids `hidden` does not name, recording each read. */ +function readerOver(rows: Rows, hidden: ReadonlySet = new Set()) { + const reads: Array<{ object: string; id: string; fields: readonly string[] }> = []; + const read: CallerRecordReader = async (object, id, fields) => { + reads.push({ object, id, fields }); + if (hidden.has(id)) return undefined; + const row = rows[object]?.[id]; + return row ? { ...row } : undefined; + }; + return { read, reads }; +} + +describe('[#38363] resolveCallerIdentity — the caller\'s own facts', () => { + it('two users in different units each get their own user, organization and unit chain up to the root', async () => { + const { read } = readerOver(TREE); + const ada = await resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read); + const lin = await resolveCallerIdentity({ userId: 'u_lin', tenantId: 'org_1' }, read); + + expect(ada).toEqual({ + user: { id: 'u_ada', name: 'Ada' }, + organization: { id: 'org_1', name: 'Acme Group' }, + businessUnits: [ + { id: 'bu_west', name: 'West Coast', kind: 'office' }, + { id: 'bu_ops', name: 'Field Operations', kind: 'division' }, + { id: 'bu_group', name: 'Acme Group', kind: 'company' }, + ], + }); + expect(lin).toEqual({ + user: { id: 'u_lin', name: 'Lin' }, + organization: { id: 'org_1', name: 'Acme Group' }, + businessUnits: [ + { id: 'bu_fin', name: 'HQ Finance', kind: 'department' }, + { id: 'bu_group', name: 'Acme Group', kind: 'company' }, + ], + }); + }); + + it('reads only the caller\'s own user row and the units on their own chain', async () => { + const { read, reads } = readerOver(TREE); + await resolveCallerIdentity({ userId: 'u_lin', tenantId: 'org_1' }, read); + expect(reads.map((r) => `${r.object}:${r.id}`)).toEqual([ + 'sys_user:u_lin', 'sys_organization:org_1', 'sys_business_unit:bu_fin', 'sys_business_unit:bu_group', + ]); + }); + + it('a parent unit the caller may not read is absent, not named, and the chain ends below it', async () => { + const { read } = readerOver(TREE, new Set(['bu_ops'])); + const ada = await resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read); + expect(ada.businessUnits).toEqual([{ id: 'bu_west', name: 'West Coast', kind: 'office' }]); + expect(ada.businessUnitNote).toBe('The chain ends here: the next unit up is not readable with your permissions.'); + const text = JSON.stringify(ada); + expect(text).not.toContain('bu_ops'); + expect(text).not.toContain('Field Operations'); + // The root above the hidden unit is not reached either: its link is on the hidden row. + expect(text).not.toContain('bu_group'); + }); + + it('a parent link masked off a readable unit is not readable, never the top of the tree', async () => { + const masked: Rows = { + ...TREE, + sys_business_unit: { + ...TREE.sys_business_unit, + bu_west: { id: 'bu_west', name: 'West Coast', kind: 'office' }, + }, + }; + const { read, reads } = readerOver(masked); + const ada = await resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read); + expect(ada.businessUnits).toEqual([{ id: 'bu_west', name: 'West Coast', kind: 'office' }]); + expect(ada.businessUnitNote).toBe('The chain ends here: the next unit up is not readable with your permissions.'); + expect(reads.filter((r) => r.object === 'sys_business_unit')).toHaveLength(1); + // The control: a present, empty link is the top, with no note. + const lin = await resolveCallerIdentity({ userId: 'u_lin', tenantId: 'org_1' }, read); + expect(lin.businessUnits?.map((u) => u.id)).toEqual(['bu_fin', 'bu_group']); + expect(lin.businessUnitNote).toBeUndefined(); + }); + + it('a primary unit the caller may not read leaves no unit and says so', async () => { + const { read } = readerOver(TREE, new Set(['bu_west'])); + const ada = await resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read); + expect(ada.businessUnits).toBeUndefined(); + expect(ada.businessUnitNote).toBe('Your primary business unit is not readable with your permissions.'); + expect(JSON.stringify(ada)).not.toContain('West Coast'); + }); + + it('a refusal that arrives as a throw is a fact left out, not a failed answer', async () => { + const read: CallerRecordReader = async (object, id) => { + if (object === 'sys_business_unit' && id === 'bu_ops') { + throw Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED', status: 403 }); + } + return TREE[object]?.[id]; + }; + const ada = await resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read); + expect(ada.businessUnits?.map((u) => u.id)).toEqual(['bu_west']); + expect(ada.businessUnitNote).toContain('not readable'); + }); + + it('a throw that is not a refusal (a driver fault) is not read as a permission limit: it fails the answer', async () => { + for (const fault of [ + Object.assign(new Error('connection reset'), { code: 'INTERNAL_ERROR', status: 500 }), + new Error('socket hang up'), + ]) { + const read: CallerRecordReader = async (object, id) => { + if (object === 'sys_business_unit' && id === 'bu_ops') throw fault; + return TREE[object]?.[id]; + }; + await expect(resolveCallerIdentity({ userId: 'u_ada', tenantId: 'org_1' }, read)).rejects.toBe(fault); + } + }); + + it('a deployment with no business units answers the user and the organization', async () => { + const noUnits: Rows = { + sys_user: { u1: { id: 'u1', name: 'Solo', primary_business_unit_id: null } }, + sys_organization: { org_1: { id: 'org_1', name: 'Solo Org' } }, + }; + const { read, reads } = readerOver(noUnits); + const out = await resolveCallerIdentity({ userId: 'u1', tenantId: 'org_1' }, read); + expect(out).toEqual({ + user: { id: 'u1', name: 'Solo' }, + organization: { id: 'org_1', name: 'Solo Org' }, + businessUnitNote: 'No primary business unit is recorded for you.', + }); + expect(reads.some((r) => r.object === 'sys_business_unit')).toBe(false); + }); + + it('a masked primary-unit field is not readable; an empty one is not recorded', async () => { + const masked: Rows = { sys_user: { u1: { id: 'u1', name: 'Masked' } } }; + const outMasked = await resolveCallerIdentity({ userId: 'u1' }, readerOver(masked).read); + expect(outMasked.businessUnitNote).toBe('Your primary business unit is not readable with your permissions.'); + const outEmpty = await resolveCallerIdentity({ userId: 'u_none' }, readerOver(TREE).read); + expect(outEmpty.businessUnitNote).toBe('No primary business unit is recorded for you.'); + }); + + it('no active organization: no organization key; an unreadable user row keeps the id alone', async () => { + const out = await resolveCallerIdentity({ userId: 'ghost' }, readerOver(TREE).read); + expect(out).toEqual({ + user: { id: 'ghost' }, + businessUnitNote: 'Your primary business unit is not readable with your permissions.', + }); + }); + + it('a parent chain that loops stops at the loop', async () => { + const loop: Rows = { + sys_user: { u1: { id: 'u1', primary_business_unit_id: 'a' } }, + sys_business_unit: { + a: { id: 'a', name: 'A', parent_business_unit_id: 'b' }, + b: { id: 'b', name: 'B', parent_business_unit_id: 'a' }, + }, + }; + const { read, reads } = readerOver(loop); + const out = await resolveCallerIdentity({ userId: 'u1' }, read); + expect(out.businessUnits?.map((u) => u.id)).toEqual(['a', 'b']); + expect(out.businessUnitNote).toContain('loop'); + expect(reads.filter((r) => r.object === 'sys_business_unit')).toHaveLength(2); + }); + + it('a chain deeper than the cap is cut at the cap', async () => { + const deep: Rows = { sys_user: { u1: { id: 'u1', primary_business_unit_id: 'n0' } }, sys_business_unit: {} }; + for (let i = 0; i < CALLER_UNIT_CHAIN_MAX_DEPTH + 10; i++) { + deep.sys_business_unit[`n${i}`] = { id: `n${i}`, parent_business_unit_id: `n${i + 1}` }; + } + const { read, reads } = readerOver(deep); + const out = await resolveCallerIdentity({ userId: 'u1' }, read); + expect(out.businessUnits).toHaveLength(CALLER_UNIT_CHAIN_MAX_DEPTH); + expect(out.businessUnitNote).toContain(`${CALLER_UNIT_CHAIN_MAX_DEPTH} units`); + expect(reads.filter((r) => r.object === 'sys_business_unit')).toHaveLength(CALLER_UNIT_CHAIN_MAX_DEPTH); + }); + + it('a connection with no user reads nothing', async () => { + const { read, reads } = readerOver(TREE); + const out = await resolveCallerIdentity({ tenantId: 'org_1' }, read); + expect(out.user).toBeUndefined(); + expect(out.businessUnitNote).toContain('not signed in as a user'); + expect(reads).toEqual([]); + }); +}); + +describe('[#38363] the HTTP bridge\'s currentUser member', () => { + function harness(ec: Record, findData: (req: any) => Promise) { + const protocol = { findData: vi.fn(findData) }; + const services: Record = { protocol }; + const kernel: any = { context: { getService: (n: string) => services[n] ?? null } }; + const ctx: any = { + request: { method: 'POST', url: '/api/v1/mcp', headers: { host: 'acme.test' } }, + environmentId: 'platform', + executionContext: ec, + }; + const deps = (new HttpDispatcher(kernel) as any).domainDeps; + return { bridge: buildMcpBridge(deps, ctx), protocol }; + } + + it('reads every fact by id through the caller\'s own ExecutionContext, never a system one', async () => { + const ec = { userId: 'u_ada', tenantId: 'org_1', positions: [], permissions: [] }; + const { bridge, protocol } = harness(ec, async (req) => { + const id = req.query?.where?.id; + const row = TREE[req.object]?.[id]; + return { object: req.object, records: row ? [row] : [] }; + }); + const out = await bridge.currentUser(); + expect(out.businessUnits.map((u: any) => u.id)).toEqual(['bu_west', 'bu_ops', 'bu_group']); + expect(protocol.findData).toHaveBeenCalledTimes(5); + for (const [req] of protocol.findData.mock.calls) { + expect(req.context).toBe(ec); + expect(req.context.isSystem).toBeUndefined(); + expect(req.query.limit).toBe(1); + expect(Object.keys(req.query.where)).toEqual(['id']); + } + }); + + it('a read the data door refuses leaves that fact out and the tool answers', async () => { + const ec = { userId: 'u_ada', tenantId: 'org_1', positions: [], permissions: [] }; + const { bridge } = harness(ec, async (req) => { + if (req.object === 'sys_business_unit') { + throw Object.assign(new Error('Permission denied'), { code: 'PERMISSION_DENIED', statusCode: 403 }); + } + const row = TREE[req.object]?.[req.query?.where?.id]; + return { object: req.object, records: row ? [row] : [] }; + }); + const out = await bridge.currentUser(); + expect(out).toEqual({ + user: { id: 'u_ada', name: 'Ada' }, + organization: { id: 'org_1', name: 'Acme Group' }, + businessUnitNote: 'Your primary business unit is not readable with your permissions.', + }); + }); +}); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 418ce9ca94a..180101f0a64 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1030,6 +1030,174 @@ function actionCallDoorWiring( }; } +/** + * [#38363] The most business units {@link resolveCallerIdentity} reads up a + * parent chain: the primary unit and at most this many minus one above it. A + * real org tree is far shallower; the cap bounds the reads a broken tree (a + * parent link that loops past the cycle check, or a runaway import) can cost. + */ +export const CALLER_UNIT_CHAIN_MAX_DEPTH = 32; + +/** [#38363] One business unit of {@link CallerIdentity}: the fields of its row the caller read. */ +export interface CallerBusinessUnit { + id: string; + name?: string; + kind?: string; +} + +/** + * [#38363] Who is signed in, as the caller may read it about themselves. The + * structural twin of `McpCurrentUser` (`@objectstack/mcp`), which the + * `get_current_user` tool renders. + */ +export interface CallerIdentity { + user?: { id: string; name?: string }; + organization?: { id: string; name?: string }; + businessUnits?: CallerBusinessUnit[]; + businessUnitNote?: string; +} + +/** + * [#38363] Read one record by id AS the caller: the row with the fields the + * caller may read, or `undefined` when there is none they may read. A refusal + * may also arrive as a throw: {@link resolveCallerIdentity} reads a `401`, + * `403` or `404` throw as "not readable" for the fact it was reading, and + * lets every other throw through. + */ +export type CallerRecordReader = ( + object: string, + id: string, + fields: readonly string[], +) => Promise | undefined>; + +/** A non-empty string value of `row[key]`, or `undefined`. */ +function textOf(row: Record | undefined, key: string): string | undefined { + const v = row?.[key]; + return typeof v === 'string' && v.trim() !== '' ? v : undefined; +} + +/** The statuses a read refuses with when the caller may not read the row or the object. */ +const CALLER_READ_REFUSAL_STATUSES: ReadonlySet = new Set([401, 403, 404]); + +/** + * {@link CallerRecordReader}, with a refusal read as "not readable". Only a + * refusal: a throw carrying any other status, or none (a driver fault, an + * outage), is rethrown, so the tool answers the coded failure instead of + * telling the model that its caller's permissions hide a unit they may well + * read. + */ +async function readOrUndefined( + read: CallerRecordReader, + object: string, + id: string, + fields: readonly string[], +): Promise | undefined> { + try { + return await read(object, id, fields); + } catch (err) { + const e = err as { status?: unknown; statusCode?: unknown } | null; + const status = typeof e?.status === 'number' ? e.status : e?.statusCode; + if (typeof status === 'number' && CALLER_READ_REFUSAL_STATUSES.has(status)) return undefined; + throw err; + } +} + +/** + * [#38363] The ONE resolver of the caller's own identity facts, for any door + * that tells a model who is asking (`get_current_user` on `/mcp` today; a + * retrieval ranking by the asker reads the same answer). It takes the + * caller's `ExecutionContext` and a reader that runs AS that caller, and + * never reads with a system or elevated context, so it can answer only what + * the caller could read for themselves through the data API: + * + * - **user** — `ec.userId`, and the `name` of their `sys_user` row; + * - **organization** — `ec.tenantId` (the session's active organization), and + * the `name` of its `sys_organization` row; + * - **businessUnits** — the unit their `sys_user.primary_business_unit_id` + * names (the projection of the `is_primary` membership plugin-sharing keeps, + * ADR-0057 addendum D12, which the sharing rules keyed on the primary unit + * read too), then each `parent_business_unit_id` up to the root. The + * `IBusinessUnitGraphService` contract walks descendants only, so the walk + * is here, one gated read per unit, cycle-safe and capped at + * {@link CALLER_UNIT_CHAIN_MAX_DEPTH}. + * + * A unit the caller may not read is left out, never named, and the chain ends + * below it; `businessUnitNote` says so, and says when no unit is recorded or + * the primary unit field is not readable, so a missing unit never reads as + * "no unit". A deployment with no business units answers the user and the + * organization, with the note that no unit is recorded. Nothing about any + * other user is read, and nothing is written. + */ +export async function resolveCallerIdentity( + ec: { userId?: unknown; tenantId?: unknown } | undefined, + read: CallerRecordReader, +): Promise { + const userId = typeof ec?.userId === 'string' && ec.userId !== '' ? ec.userId : undefined; + if (!userId) { + return { businessUnitNote: 'This connection is not signed in as a user, so it has no user or business unit.' }; + } + const out: CallerIdentity = {}; + + const userRow = await readOrUndefined(read, 'sys_user', userId, ['id', 'name', 'primary_business_unit_id']); + const userName = textOf(userRow, 'name'); + out.user = { id: userId, ...(userName ? { name: userName } : {}) }; + + const orgId = typeof ec?.tenantId === 'string' && ec.tenantId !== '' ? ec.tenantId : undefined; + if (orgId) { + const orgName = textOf(await readOrUndefined(read, 'sys_organization', orgId, ['id', 'name']), 'name'); + out.organization = { id: orgId, ...(orgName ? { name: orgName } : {}) }; + } + + // A field the caller may not read is masked off the row (absent), while + // one with no value is present and empty: the two answer differently. + if (!userRow || !Object.prototype.hasOwnProperty.call(userRow, 'primary_business_unit_id')) { + out.businessUnitNote = 'Your primary business unit is not readable with your permissions.'; + return out; + } + const primary = userRow.primary_business_unit_id; + let nextId = typeof primary === 'string' && primary !== '' ? primary : undefined; + if (!nextId) { + out.businessUnitNote = 'No primary business unit is recorded for you.'; + return out; + } + + const units: CallerBusinessUnit[] = []; + const seen = new Set(); + let note: string | undefined; + while (nextId) { + if (seen.has(nextId)) { + note = 'The parent units loop back on themselves, so the chain ends at the last unit before the loop.'; + break; + } + if (units.length >= CALLER_UNIT_CHAIN_MAX_DEPTH) { + note = `The chain is cut at ${CALLER_UNIT_CHAIN_MAX_DEPTH} units; the units above them are not listed.`; + break; + } + seen.add(nextId); + const row = await readOrUndefined(read, 'sys_business_unit', nextId, ['id', 'name', 'kind', 'parent_business_unit_id']); + if (!row) { + note = units.length === 0 + ? 'Your primary business unit is not readable with your permissions.' + : 'The chain ends here: the next unit up is not readable with your permissions.'; + break; + } + const name = textOf(row, 'name'); + const kind = textOf(row, 'kind'); + units.push({ id: nextId, ...(name ? { name } : {}), ...(kind ? { kind } : {}) }); + // As for the primary unit: a parent link masked off the row (absent) + // is not readable, while one present and empty is the top of the tree. + if (!Object.prototype.hasOwnProperty.call(row, 'parent_business_unit_id')) { + note = 'The chain ends here: the next unit up is not readable with your permissions.'; + break; + } + const parent = row.parent_business_unit_id; + nextId = typeof parent === 'string' && parent !== '' ? parent : undefined; + } + if (units.length > 0) out.businessUnits = units; + if (note) out.businessUnitNote = note; + return out; +} + /** * Build a principal-bound {@link McpDataBridge}: every method runs AS the * request's ExecutionContext through {@link callData} (RLS/permissions) and @@ -1449,6 +1617,16 @@ export function buildMcpBridge( // compose (`ifNotRecorded`): this request's, as the dataset tools' // `nextStep` reads it on this door (`userTextLocalesOf`). userTextLocales: async (): Promise => userTextLocalesOf(ec), + // [#38363] `get_current_user`: the caller's own identity facts, through + // the one resolver ({@link resolveCallerIdentity}), every read by id + // AS this request's caller through {@link callData} — the data API's + // permissions, row-level security and field masking. + currentUser: async (): Promise => resolveCallerIdentity(ec, async (object, id, fields) => { + const res: any = await callData('query', { object, query: { where: { id }, fields: [...fields], limit: 1 } }, driver, envId, ec); + const rows: unknown = Array.isArray(res) ? res : res?.records; + const row = Array.isArray(rows) ? rows[0] : undefined; + return row && typeof row === 'object' ? (row as Record) : undefined; + }), // ── Skill metadata → MCP prompts (#3905) ────────────────── // ADR-0063 §2 names skills the only third-party extension primitive, From 3b900a80713a77090f7f0560df4bd08efbf52565 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:40:03 +0000 Subject: [PATCH 058/178] feat(client): ai.savedQuestions and ai.answers for the AI answer follow-up routes (#38539) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _Requested by **Jianguo** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbXxoCGcWFTzHUA2xmDrNEuW)_ Fixes #32644 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用户无感;用开发包写程序的人现在能直接调用「收藏问题、把回答存成视图或报表、给回答打分」这几项能力,不必再手拼网址。 - 为什么做:这是控制台两项需求(收藏问题入口、回答打分)要用的开发包这一半,那两张卡在等它。 - 出错会怎样:只有调用这些新方法的人受影响,已有方法一行未改;出了问题可以直接撤回这次合并。 - 要你做什么:无。 ## What changes `ObjectStackClient.ai` gains two namespaces for the eight route and method pairs `packages/spec/src/api/ai-answer.zod.ts` declares. Every parameter and return type is a `@objectstack/spec/api` type from that file; there is no hand-written shape. | Method | Route | Resolves to | |:--|:--|:--| | `ai.savedQuestions.list()` | `GET /api/v1/ai/saved-questions` | `ListAiSavedQuestionsResponse` | | `ai.savedQuestions.create(request)` | `POST /api/v1/ai/saved-questions` | `CreateAiSavedQuestionResponse` | | `ai.savedQuestions.delete(id)` | `DELETE /api/v1/ai/saved-questions/:id` | `void` (204) | | `ai.savedQuestions.run(id)` | `POST /api/v1/ai/saved-questions/:id/run`, no body | `RunAiSavedQuestionResponse` | | `ai.answers.createArtifact(conversationId, turnId, request)` | `POST …/conversations/:id/turns/:turnId/artifact` | `CreateAiAnswerArtifactResponse` | | `ai.answers.getFeedback(conversationId, turnId)` | `GET …/turns/:turnId/feedback` | `GetAiAnswerFeedbackResponse` | | `ai.answers.setFeedback(conversationId, turnId, request)` | `POST …/turns/:turnId/feedback` | `SetAiAnswerFeedbackResponse` | | `ai.answers.deleteFeedback(conversationId, turnId)` | `DELETE …/turns/:turnId/feedback` | `void` (204) | Each method resolves to the route's `data` payload after `unwrapResponse` strips the envelope, the same reading the rest of `ai.*` uses. The payload is returned whole rather than plucked (`questions`, `feedback`), so no `?? []` fallback stands in for a missing member. A refusal throws the shared transport error, carrying the route's code on `err.code` and the status on `err.httpStatus`. The request and response types, plus `AiSavedQuestion`, `AiSavedQuestionErrorCode`, `AiAnswerArtifactKind`, `AiAnswerRating` and `AiAnswerFeedback`, are re-exported from the package root beside the other AI wire types. Files: `packages/client/src/index.ts`, `packages/client/src/ai-answer-follow-ups.test.ts`, `.changeset/32644-client-ai-answer-follow-ups.md`. ## Why #31889 and #31865 (console, `plugin-chatbot`) need these routes from the SDK. The card's ruling: "Type them from the spec shapes only; ⛔ no hand-written shapes." ## Tests `packages/client/src/ai-answer-follow-ups.test.ts`, 11 tests: - one test per method pinning verb, URL (ids percent-encoded), request body and the resolved payload; the two deletes resolve on a 204 that has no body; - a refusal pins `err.code` `RESOURCE_CONFLICT` and `err.httpStatus` 409 off an `AiSavedQuestionErrorSchema`-legal envelope; - every response fixture and request body parses against its spec schema; - `expectTypeOf` pins every request parameter and resolved type to the spec type, compiled by `check:test-typecheck`. Reverse checks, each restored afterwards: sending `PUT` from `setFeedback` and an unencoded id plus a `{}` body from `run` turned 2 of 11 red; typing `setFeedback`'s request as a hand-written `{ rating: string; note?: string | null }` turned `tsc -p tsconfig.test.json` red at the signature pin (TS2344). ## Acceptance notes - The producer is the cloud AI service, so nothing in this repo serves these routes. `client-url-conformance.test.ts` exempts `/api/v1/ai/` for that reason and stays green with the new methods enumerated and driven; the cloud repo's AI route ledger drives every `ai.*` method against its real table, so these URLs are checked there. - The dispatch suggested a `minor` changeset. `Metadata-protocol: none` takes `patch` (AGENTS.md Post-Task Checklist step 3, `check-changeset-no-major`), so it ships `patch`. - `packages/client/README.md` lists one example per `ai.*` namespace; it is outside this card's file surface, so the new namespaces are not added there. ## Verification All local readings at head `5b9ac603` (base `0af813f3`; `origin/main` has moved 3 commits since, none under `packages/client` or `packages/spec`).
Package tests and type-check - `pnpm --filter @objectstack/client run typecheck`: exit 0 (`tsc --noEmit`, then `check:test-typecheck`: 0 files / 0 errors held in the debt ledger). - `packages/client`: `vitest run --maxWorkers=2`: Test Files 60 passed (60), Tests 840 passed (840). - `eslint --no-inline-config` on the two touched source files: exit 0. - Closure built first under the verify lock: `turbo run build --filter '@objectstack/client...'`, 46 of 46 tasks, VERDICT command-exit 0.
Derived gate families (dispatch-gates --commands, 69) - 68 of 69 exit 0. `check-plugin-teardown-shape --self-test` and `spec check:skill-examples` first exited 3 on prerequisites (the shallow clone's pinned fixture commit; an unbuilt `@objectstack/client-react`); both were cleared and re-run green. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, reason: PREREQUISITE NOT MET (it needs every workspace package's `dist/`); CI's Lint and Repo Gates runs it. - `dispatch-gates --ran`: 69 derived families accounted for, 68 run, 1 NOT MEASURED, 0 unrun. - Dogfood battery: not owed (no `!` in the title, no `(narrowing)` arm).
**Read first:** `packages/client/src/index.ts` in the `ai = {` namespace, the `savedQuestions` and `answers` blocks (the two 204 deletes are the risk hunk: they must not parse a body); then `ai-answer-follow-ups.test.ts`. **Two-minute check:** `cd packages/client && pnpm exec vitest run src/ai-answer-follow-ups.test.ts` shows 11 passed. ## 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. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the touched files locally; CI runs the repository lint) - [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. (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 with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jREYTQb5JmJ3TewGpr --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jREYTQb5JmJ3TewGpr)_ --------- Co-authored-by: Claude --- .../32644-client-ai-answer-follow-ups.md | 16 ++ .../client/src/ai-answer-follow-ups.test.ts | 208 ++++++++++++++++++ packages/client/src/index.ts | 146 ++++++++++++ 3 files changed, 370 insertions(+) create mode 100644 .changeset/32644-client-ai-answer-follow-ups.md create mode 100644 packages/client/src/ai-answer-follow-ups.test.ts diff --git a/.changeset/32644-client-ai-answer-follow-ups.md b/.changeset/32644-client-ai-answer-follow-ups.md new file mode 100644 index 00000000000..78a75043150 --- /dev/null +++ b/.changeset/32644-client-ai-answer-follow-ups.md @@ -0,0 +1,16 @@ +--- +'@objectstack/client': patch +--- + +feat(client): `ai.savedQuestions` and `ai.answers`, the SDK methods for the AI answer follow-up routes + +Clause-②: yes +Metadata-protocol: none + +The client now calls the eight routes `@objectstack/spec/api` declares in `ai-answer.zod.ts`, typed from those spec shapes only: + +- `ai.savedQuestions.list()`, `create(request)`, `delete(id)` and `run(id)`: `GET`/`POST /api/v1/ai/saved-questions`, `DELETE /api/v1/ai/saved-questions/:id` and `POST /api/v1/ai/saved-questions/:id/run`. +- `ai.answers.createArtifact(conversationId, turnId, request)`: `POST /api/v1/ai/conversations/:id/turns/:turnId/artifact`, answering a list view, a report draft or a one-widget dashboard draft, discriminated by `kind`. +- `ai.answers.getFeedback`, `setFeedback` and `deleteFeedback(conversationId, turnId, …)`: `GET`/`POST`/`DELETE /api/v1/ai/conversations/:id/turns/:turnId/feedback`. + +Each method resolves to the route's `data` payload; the two deletes resolve `undefined` on the route's 204. A refusal throws the usual transport error, with the route's code on `err.code` and the status on `err.httpStatus`. The request and response types are re-exported from `@objectstack/client`. The routes are served by the AI service; check `discovery.services` first, as for the rest of `ai.*`. diff --git a/packages/client/src/ai-answer-follow-ups.test.ts b/packages/client/src/ai-answer-follow-ups.test.ts new file mode 100644 index 00000000000..2570e29156e --- /dev/null +++ b/packages/client/src/ai-answer-follow-ups.test.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `client.ai.savedQuestions.*` and `client.ai.answers.*` against the AI answer + * follow-up routes `ai-answer.zod.ts` declares. + * + * The producer is the cloud AI service, so nothing in this repo serves these + * routes: the URL conformance sweep exempts `/api/v1/ai/` and the cloud repo's + * route ledger drives this namespace against its real table. What this file + * pins is the half that lives here, per method: the verb, the URL, the request + * body, and the `data` payload the method resolves to once the envelope is + * stripped. Every fixture parses against its spec schema, and every signature + * is pinned to the spec type, so a shape changed in the spec reaches this file + * instead of drifting away from it. + */ + +import { describe, it, expect, expectTypeOf, vi } from 'vitest'; +import { + CreateAiAnswerArtifactRequestSchema, + CreateAiAnswerArtifactResponseSchema, + CreateAiSavedQuestionRequestSchema, + CreateAiSavedQuestionResponseSchema, + GetAiAnswerFeedbackResponseSchema, + ListAiSavedQuestionsResponseSchema, + RunAiSavedQuestionResponseSchema, + SetAiAnswerFeedbackRequestSchema, + SetAiAnswerFeedbackResponseSchema, + AiSavedQuestionErrorSchema, + type CreateAiAnswerArtifactRequest, + type CreateAiAnswerArtifactResponse, + type CreateAiSavedQuestionRequest, + type CreateAiSavedQuestionResponse, + type GetAiAnswerFeedbackResponse, + type ListAiSavedQuestionsResponse, + type RunAiSavedQuestionResponse, + type SetAiAnswerFeedbackRequest, + type SetAiAnswerFeedbackResponse, +} from '@objectstack/spec/api'; +import { ObjectStackClient } from './index'; + +const BASE = 'http://localhost:3000'; +const AI = `${BASE}/api/v1/ai`; + +interface Answer { status: number; body?: unknown } + +function clientAnswering(answer: Answer) { + const fetchMock = vi.fn().mockResolvedValue({ + ok: answer.status >= 200 && answer.status < 300, + status: answer.status, + statusText: String(answer.status), + headers: new Headers(), + json: async () => { + if (answer.body === undefined) throw new SyntaxError('Unexpected end of JSON input'); + return answer.body; + }, + }); + return { client: new ObjectStackClient({ baseUrl: BASE, fetch: fetchMock }), fetchMock }; +} + +const enveloped = (data: unknown): Answer => ({ status: 200, body: { success: true, data } }); + +/** The one request a method put on the wire: verb, URL, parsed body. */ +function sent(fetchMock: ReturnType) { + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit | undefined]; + return { + verb: (init?.method ?? 'GET').toUpperCase(), + url, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : init?.body, + }; +} + +const SAVED = { + id: 'sq_1', + question: 'How many open deals per stage?', + source: null, + agentId: 'ask', + conversationId: 'conv/1', + turnId: 'turn 1', + createdAt: '2026-11-29T07:00:00.000Z', +}; + +const FEEDBACK = { + conversationId: 'conv/1', + turnId: 'turn 1', + rating: 'down' as const, + note: 'Wrong quarter', + createdAt: '2026-11-29T07:00:00.000Z', + updatedAt: null, +}; + +describe('fixtures are spec-legal', () => { + it('every response payload and request body below parses against its spec schema', () => { + expect(ListAiSavedQuestionsResponseSchema.parse({ questions: [SAVED] })).toBeTruthy(); + expect(CreateAiSavedQuestionResponseSchema.parse({ question: SAVED })).toBeTruthy(); + expect(RunAiSavedQuestionResponseSchema.parse({ question: SAVED.question, toolName: 'aggregate_data', result: { rows: [] } })).toBeTruthy(); + expect(CreateAiAnswerArtifactResponseSchema.parse({ + kind: 'view', + view: { id: 'pv_1', object_name: 'deal', label: 'Open deals', config: {} }, + })).toBeTruthy(); + expect(GetAiAnswerFeedbackResponseSchema.parse({ feedback: FEEDBACK })).toBeTruthy(); + expect(SetAiAnswerFeedbackResponseSchema.parse({ feedback: FEEDBACK })).toBeTruthy(); + expect(CreateAiSavedQuestionRequestSchema.parse({ conversationId: 'conv/1', turnId: 'turn 1' })).toBeTruthy(); + expect(CreateAiAnswerArtifactRequestSchema.parse({ kind: 'report', label: 'Deals' })).toBeTruthy(); + expect(SetAiAnswerFeedbackRequestSchema.parse({ rating: 'down', note: 'Wrong quarter' })).toBeTruthy(); + }); +}); + +describe('client.ai.savedQuestions — verb, URL, body, payload', () => { + it('list: GET /saved-questions, no body, resolves to the `data` payload', async () => { + const data = { questions: [SAVED] }; + const { client, fetchMock } = clientAnswering(enveloped(data)); + await expect(client.ai.savedQuestions.list()).resolves.toEqual(data); + expect(sent(fetchMock)).toEqual({ verb: 'GET', url: `${AI}/saved-questions`, body: undefined }); + }); + + it('create: POST /saved-questions with the request as the body', async () => { + const request = { conversationId: 'conv/1', turnId: 'turn 1', toolCallId: 'call_2' }; + const data = { question: SAVED }; + const { client, fetchMock } = clientAnswering({ status: 201, body: { success: true, data } }); + await expect(client.ai.savedQuestions.create(request)).resolves.toEqual(data); + expect(sent(fetchMock)).toEqual({ verb: 'POST', url: `${AI}/saved-questions`, body: request }); + }); + + it('delete: DELETE /saved-questions/:id, encoded, and a 204 with no body resolves', async () => { + const { client, fetchMock } = clientAnswering({ status: 204 }); + await expect(client.ai.savedQuestions.delete('sq/1')).resolves.toBeUndefined(); + expect(sent(fetchMock)).toEqual({ verb: 'DELETE', url: `${AI}/saved-questions/sq%2F1`, body: undefined }); + }); + + it('run: POST /saved-questions/:id/run with no request body', async () => { + const data = { question: SAVED.question, toolName: 'query_records', result: { records: [] } }; + const { client, fetchMock } = clientAnswering(enveloped(data)); + await expect(client.ai.savedQuestions.run('sq_1')).resolves.toEqual(data); + expect(sent(fetchMock)).toEqual({ verb: 'POST', url: `${AI}/saved-questions/sq_1/run`, body: undefined }); + }); + + it('a refusal throws with the route error code and status', async () => { + const error = { + code: 'RESOURCE_CONFLICT', + message: 'This saved question has no query to run', + details: { reason: 'saved_question_has_no_query', question: SAVED.question }, + }; + expect(AiSavedQuestionErrorSchema.parse(error)).toBeTruthy(); + const { client } = clientAnswering({ status: 409, body: { success: false, error } }); + await expect(client.ai.savedQuestions.run('sq_1')).rejects.toMatchObject({ + code: 'RESOURCE_CONFLICT', + httpStatus: 409, + }); + }); +}); + +describe('client.ai.answers — verb, URL, body, payload', () => { + const TURN = `${AI}/conversations/conv%2F1/turns/turn%201`; + + it('createArtifact: POST …/turns/:turnId/artifact with the request as the body', async () => { + const request = { kind: 'widget' as const, toolCallId: 'call_2', label: 'Deals by stage' }; + const data = { + kind: 'widget', + published: false, + drafts: [{ type: 'dataset', name: 'deals_by_stage' }, { type: 'dashboard', name: 'deals_by_stage_dashboard' }], + dataset: { name: 'deals_by_stage' }, + dashboard: { name: 'deals_by_stage_dashboard' }, + }; + expect(CreateAiAnswerArtifactResponseSchema.parse(data)).toBeTruthy(); + const { client, fetchMock } = clientAnswering({ status: 201, body: { success: true, data } }); + await expect(client.ai.answers.createArtifact('conv/1', 'turn 1', request)).resolves.toEqual(data); + expect(sent(fetchMock)).toEqual({ verb: 'POST', url: `${TURN}/artifact`, body: request }); + }); + + it('getFeedback: GET …/turns/:turnId/feedback; an unrated answer resolves `feedback: null`', async () => { + const { client, fetchMock } = clientAnswering(enveloped({ feedback: null })); + await expect(client.ai.answers.getFeedback('conv/1', 'turn 1')).resolves.toEqual({ feedback: null }); + expect(sent(fetchMock)).toEqual({ verb: 'GET', url: `${TURN}/feedback`, body: undefined }); + }); + + it('setFeedback: POST …/turns/:turnId/feedback with the request as the body', async () => { + const request = { rating: 'down' as const, note: 'Wrong quarter' }; + const data = { feedback: FEEDBACK }; + const { client, fetchMock } = clientAnswering(enveloped(data)); + await expect(client.ai.answers.setFeedback('conv/1', 'turn 1', request)).resolves.toEqual(data); + expect(sent(fetchMock)).toEqual({ verb: 'POST', url: `${TURN}/feedback`, body: request }); + }); + + it('deleteFeedback: DELETE …/turns/:turnId/feedback, and a 204 with no body resolves', async () => { + const { client, fetchMock } = clientAnswering({ status: 204 }); + await expect(client.ai.answers.deleteFeedback('conv/1', 'turn 1')).resolves.toBeUndefined(); + expect(sent(fetchMock)).toEqual({ verb: 'DELETE', url: `${TURN}/feedback`, body: undefined }); + }); +}); + +describe('signatures are the spec types', () => { + it('every request parameter and resolved value is the `@objectstack/spec/api` type', () => { + const { client } = clientAnswering({ status: 204 }); + const { savedQuestions, answers } = client.ai; + expectTypeOf(savedQuestions.list).returns.resolves.toEqualTypeOf(); + expectTypeOf(savedQuestions.create).parameter(0).toEqualTypeOf(); + expectTypeOf(savedQuestions.create).returns.resolves.toEqualTypeOf(); + expectTypeOf(savedQuestions.delete).returns.resolves.toEqualTypeOf(); + expectTypeOf(savedQuestions.run).returns.resolves.toEqualTypeOf(); + expectTypeOf(answers.createArtifact).parameter(2).toEqualTypeOf(); + expectTypeOf(answers.createArtifact).returns.resolves.toEqualTypeOf(); + expectTypeOf(answers.getFeedback).returns.resolves.toEqualTypeOf(); + expectTypeOf(answers.setFeedback).parameter(2).toEqualTypeOf(); + expectTypeOf(answers.setFeedback).returns.resolves.toEqualTypeOf(); + expectTypeOf(answers.deleteFeedback).returns.resolves.toEqualTypeOf(); + }); +}); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 5af543c7be4..edfb3d11bbe 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -74,6 +74,17 @@ import { ListAiPendingActionsResponse, ApproveAiPendingActionResponse, RejectAiPendingActionResponse, + // The AI answer follow-up routes (`ai-answer.zod.ts`): saved questions, an + // answer turned into an artifact, an answer's rating. + ListAiSavedQuestionsResponse, + CreateAiSavedQuestionRequest, + CreateAiSavedQuestionResponse, + RunAiSavedQuestionResponse, + CreateAiAnswerArtifactRequest, + CreateAiAnswerArtifactResponse, + GetAiAnswerFeedbackResponse, + SetAiAnswerFeedbackRequest, + SetAiAnswerFeedbackResponse, GetLocalesResponse, GetTranslationsResponse, GetFieldLabelsResponse, @@ -8023,6 +8034,125 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, }, + + /** + * Saved questions: a question the caller keeps to run again later, typed + * in or saved from one of their answers. + * + * Every type here is a `@objectstack/spec/api` shape from `ai-answer.zod.ts`, + * and each method resolves to the route's `data` payload once + * `unwrapResponse` strips the `{ success: true, data }` envelope. A failure + * throws the shared transport error: `err.code` is the route's + * `AiSavedQuestionErrorCode`, `err.httpStatus` the status. + * + * Every route is the caller's own: a saved question that is not the + * caller's answers 404 RESOURCE_NOT_FOUND. + */ + savedQuestions: { + /** The caller's saved questions in the session's organization, newest first, at most 200. */ + list: async (): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch(`${this.baseUrl}${route}/saved-questions`); + return this.unwrapResponse(res); + }, + + /** + * Save a typed question (`question`), or one of the caller's answers + * (`conversationId` with `turnId`, and optionally `toolCallId`). Saved + * from an answer, the server reads the query off the stored turn. + */ + create: async (request: CreateAiSavedQuestionRequest): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch(`${this.baseUrl}${route}/saved-questions`, { + method: 'POST', + body: JSON.stringify(request), + }); + return this.unwrapResponse(res); + }, + + /** Delete a saved question. The route answers 204 with no body. */ + delete: async (id: string): Promise => { + const route = this.getRoute('ai'); + await this.fetch(`${this.baseUrl}${route}/saved-questions/${encodeURIComponent(id)}`, { + method: 'DELETE', + }); + }, + + /** + * Run a saved question's stored query again, as the caller and under + * their current permissions. Nothing is stored. A question saved without + * a query answers 409 RESOURCE_CONFLICT (`saved_question_has_no_query`). + */ + run: async (id: string): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch(`${this.baseUrl}${route}/saved-questions/${encodeURIComponent(id)}/run`, { + method: 'POST', + }); + return this.unwrapResponse(res); + }, + }, + + /** + * One answer of a conversation, addressed by the conversation id and the + * turn id: turn it into an artifact, or rate it. + * + * Typed from the same `ai-answer.zod.ts` shapes as {@link savedQuestions}, + * and resolving to the `data` payload the same way. A conversation that is + * not the caller's answers 403 PERMISSION_DENIED. + */ + answers: { + /** + * Turn an answer into a list view, a report draft or a one-widget + * dashboard draft. The server builds it from the stored turn's query, + * never from the request body; `report` and `widget` need the + * manage_metadata capability and publish nothing. Narrow the answer on + * its `kind`. + */ + createArtifact: async ( + conversationId: string, + turnId: string, + request: CreateAiAnswerArtifactRequest, + ): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch( + `${this.baseUrl}${route}/conversations/${encodeURIComponent(conversationId)}/turns/${encodeURIComponent(turnId)}/artifact`, + { method: 'POST', body: JSON.stringify(request) }, + ); + return this.unwrapResponse(res); + }, + + /** The caller's rating of an answer; `feedback` is null when unrated. */ + getFeedback: async (conversationId: string, turnId: string): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch( + `${this.baseUrl}${route}/conversations/${encodeURIComponent(conversationId)}/turns/${encodeURIComponent(turnId)}/feedback`, + ); + return this.unwrapResponse(res); + }, + + /** Rate an answer, or change its rating. */ + setFeedback: async ( + conversationId: string, + turnId: string, + request: SetAiAnswerFeedbackRequest, + ): Promise => { + const route = this.getRoute('ai'); + const res = await this.fetch( + `${this.baseUrl}${route}/conversations/${encodeURIComponent(conversationId)}/turns/${encodeURIComponent(turnId)}/feedback`, + { method: 'POST', body: JSON.stringify(request) }, + ); + return this.unwrapResponse(res); + }, + + /** Clear the caller's rating. The route answers 204 with no body, also when there was no rating. */ + deleteFeedback: async (conversationId: string, turnId: string): Promise => { + const route = this.getRoute('ai'); + await this.fetch( + `${this.baseUrl}${route}/conversations/${encodeURIComponent(conversationId)}/turns/${encodeURIComponent(turnId)}/feedback`, + { method: 'DELETE' }, + ); + }, + }, }; /** @@ -9569,6 +9699,22 @@ export type { ListAiPendingActionsResponse, ApproveAiPendingActionResponse, RejectAiPendingActionResponse, + // The AI answer follow-up routes (`ai-answer.zod.ts`): saved questions, an + // answer turned into an artifact, an answer's rating. + AiSavedQuestion, + ListAiSavedQuestionsResponse, + CreateAiSavedQuestionRequest, + CreateAiSavedQuestionResponse, + RunAiSavedQuestionResponse, + AiSavedQuestionErrorCode, + AiAnswerArtifactKind, + CreateAiAnswerArtifactRequest, + CreateAiAnswerArtifactResponse, + AiAnswerRating, + AiAnswerFeedback, + GetAiAnswerFeedbackResponse, + SetAiAnswerFeedbackRequest, + SetAiAnswerFeedbackResponse, GetLocalesResponse, GetTranslationsResponse, GetFieldLabelsResponse, From 4a43d6c33ab0528cabefdc42af7e81fdbb79daf4 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:40:41 +0000 Subject: [PATCH 059/178] perf(knowledge-pgvector): compute each keyword term's IDF once per search (#38533) 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 #38510 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用 PostgreSQL 存储知识库的部署,中文整句检索的关键词一路 p95 从约 3.9 秒降到约 1.6 秒,排名一致(六次实测,218 个问题全部相同)。 - 为什么做:属于 AI 知识库检索这条主线,解决中日韩问题拆成多达 16 个词后、每个词的权重在每一行候选上重复计算拖慢检索的问题。 - 出错会怎样:碰到的是用 PostgreSQL 知识库检索的用户,最坏是检索变慢或排序变化;只改了一条查询语句,可直接撤回。 - 要你做的:无。 ## What changes The pgvector keyword score evaluated `ln(1.0 + (n - d + 0.5) / (d + 0.5))` for every term on every candidate row. A new materialized `idf` CTE computes each term's weight once per search from the one-row `stats`, and the keyword leg scores a candidate as `h.hN * w.wN` summed over its terms. The arithmetic stays `numeric` (no `float8`), so every score is digit-for-digit the per-row one and every tie keeps its order. No extension, no index, no fingerprint change, no new export; `sql.ts` is untouched. Read first, by risk: 1. `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts`, the keyword-leg hunk in `search` (the `idf` CTE and the `kw` score): the only behaviour change. 2. `packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts`: takes the adapter's own statement and compares its score against an independently written per-row form on a live PostgreSQL. 3. `packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts`: the shape pin (one `ln()` per term, all inside `idf`, none in `kw`). ### Before / after (pgvector) Bench: PostgreSQL 16.15 + pgvector 0.6.0, 67,447 synthetic passages (10,368 docs; the piece 公司 is in 99.7% of passages), 218 unspaced zh questions, keyword leg alone (all-zero query vector), topK 10, 3 interleaved runs per side. Before = `origin/main` dccf836a86, after = this branch. Shared box, load average 4 to 7 during the runs, so read the ratio, not the absolutes. | run | p50 ms | p95 ms | max ms | rankings vs before1 | |:--|--:|--:|--:|:--| | before1 | 488 | 3,903 | 4,151 | (reference) | | after1 | 354 | 1,602 | 1,793 | 0 of 218 differ | | before2 | 490 | 3,840 | 4,054 | 0 of 218 differ | | after2 | 359 | 1,569 | 1,808 | 0 of 218 differ | | before3 | 596 | 3,910 | 4,318 | 0 of 218 differ | | after3 | 448 | 1,622 | 1,769 | 0 of 218 differ | By class, p95 before vs after: questions holding 公司 (33) 3,958-4,261 vs 1,747-1,784 ms; any 2-character piece (123) 3,931-3,975 vs 1,646-1,697 ms; only 3-character pieces (95) 514-658 vs 392-521 ms. ### Turso twin: measured, not changed `knowledge-turso` evaluates the same per-row expression in SQLite double arithmetic. Same corpus indexed through the real `TursoKnowledgeAdapter.upsert` into a local libSQL file, same 218 questions, 3 interleaved runs per side, with a scratch once-form (an `idf AS MATERIALIZED` CTE) against `origin/main`: | side | p50 ms | p95 ms | rankings | |:--|--:|--:|:--| | before (3 runs) | 405-422 | 1,026-1,066 | reference | | once-form (3 runs) | 411-419 | 973-999 | 0 of 218 differ in all 3 | About 5% on p95: a double `ln()` per row is cheap, and turso's time goes to the candidate scan of 2-character pieces (LIKE). Not worth a second adapter change in this PR, so `turso-adapter.ts` is untouched. ## Tests - New `idf-once.test.ts` (no database): for a 16-term unspaced question and a mixed word/substring question, the ranking statement holds exactly one `ln(` per term, all inside `idf AS MATERIALIZED (... FROM stats)`, none in `kw`, and `kw` scores `h.hN * w.wN ... FROM hits h CROSS JOIN idf w`; no `float8` anywhere. - New `idf-once.live-postgres.test.ts`: indexes a 7-passage fixture, records the statement the adapter sends, and re-runs its CTEs with a final SELECT comparing, as text, the adapter's own score expression against `hits x ln(1.0 + (n - d + 0.5) / (d + 0.5))` per row. Every candidate equal, the scores not all one value, `idf` exactly one row. - One-off ablations, not kept: the adapter restored to dccf836a86 turns all 4 new cases red; the weight mutated to `(d + 1.5)` turns both live cases red on the equality assertion, restored by blob hash.
Readings (head 623da38969) - `pnpm --filter @objectstack/knowledge-pgvector exec vitest run --maxWorkers=2` with `OS_TEST_POSTGRES_URL` and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`: `Test Files 1 failed | 12 passed (13)`, `Tests 112 passed | 2 skipped (114)`. The failed file is `capability-mount.live-postgres.test.ts` at its line 119: it expects `resolveCapabilityArgument('knowledge', ...)` to equal `{ deploymentAdapter: 'pgvector' }`, and `@objectstack/core` now also answers `runtimeComposed: { declared: false }`. It fails the same way with this diff reverted, so it was already red on main (see Acceptance notes). - `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0; the test-layer check compiles both new files (`--listFiles` counts them in `tsconfig.json` and `tsconfig.test.json`). - `dispatch-gates --commands`: 67 families derived and run locally, 66 exit 0. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, needs a full `pnpm build`): NOT MEASURED locally, CI runs it. `--ran`: 67 accounted, 66 run, 1 NOT MEASURED.
## Acceptance notes - Already red on main, outside this claim's file surface: `capability-mount.live-postgres.test.ts` pins the knowledge capability argument as `{ deploymentAdapter: 'pgvector' }`, and core's `resolveCapabilityArgument` added `runtimeComposed` (merge 91fc3980e4). CI runs the pgvector live files only when a PR touches `packages/plugins/knowledge-pgvector/**` (the `temporal_live` paths filter), so `Temporal Conformance (live PG + MySQL)` is expected to go red here on that file. Reported to the area seat; not fixed in this PR. - The class numbers come from a synthetic corpus, not a customer one. The ratio (about 2.4x on p95) is the reading to keep; the absolutes are from a loaded shared box. ## Verification Two minutes, against any PostgreSQL with pgvector: ``` OS_TEST_POSTGRES_URL=postgres://USER@HOST:PORT/DB pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/idf-once.live-postgres.test.ts src/__tests__/idf-once.test.ts ``` Expected: `Test Files 2 passed (2)`, `Tests 4 passed (4)`. To reproduce the bench: the scratch harness (a deterministic corpus generator, an `adapter.search` timer and a ranking diff) indexes the corpus through `PgvectorKnowledgeAdapter.upsert` with a dim-8 zero embedder, then times `adapter.search(q, { topK: 10 })` per question for the `origin/main` copy and the branch copy of `pgvector-adapter.ts` in alternation, and compares the rankings question by question. https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com> --- .changeset/38510-keyword-idf-once.md | 10 ++ .../__tests__/idf-once.live-postgres.test.ts | 117 ++++++++++++++++++ .../src/__tests__/idf-once.test.ts | 80 ++++++++++++ .../src/pgvector-adapter.ts | 13 +- 4 files changed, 216 insertions(+), 4 deletions(-) create mode 100644 .changeset/38510-keyword-idf-once.md create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts diff --git a/.changeset/38510-keyword-idf-once.md b/.changeset/38510-keyword-idf-once.md new file mode 100644 index 00000000000..cda9bd8fa32 --- /dev/null +++ b/.changeset/38510-keyword-idf-once.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +perf(knowledge-pgvector): the keyword leg computes each term's IDF once per search, not once per candidate row + +Clause-②: no +Metadata-protocol: none + +The keyword score evaluated `ln(1.0 + (n - d + 0.5) / (d + 0.5))` for every term on every candidate row. A Chinese, Japanese or Korean question carries up to 16 pieces, and a piece that most passages hold makes nearly every row a candidate, so most of a search went to those `ln()` calls. Each term's weight is now computed once, in a materialized step, and a candidate's score multiplies its hits by those weights. The arithmetic stays `numeric`, so every score, and every tie, is the one the per-row form gave: search results and their order do not change. On a 67,447-passage bench of 218 unspaced Chinese questions, keyword-leg p95 went from about 3.9 s to about 1.6 s. No extension, no index and no fingerprint change; nothing to do on upgrade. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts new file mode 100644 index 00000000000..5ec072541f3 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts @@ -0,0 +1,117 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword leg's IDF on a LIVE PostgreSQL: the statement a search sends + * computes each term's weight once (`idf-once.test.ts` pins its shape), and + * every candidate's score equals, digit for digit, the per-row form it + * replaced, `hits × ln(1.0 + (n - d + 0.5) / (d + 0.5))` evaluated on each + * row in the same `numeric` arithmetic — so the ranking, ties included, is + * the one the per-row form gave. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { poolFromPg, type PgPoolLike } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector keyword IDF'); + +const store = liveStore('kpg_idf'); + +const source: KnowledgeSource = { + name: 'idf_once', + label: 'idf_once', + adapter: 'under_test', + source: { kind: 'object', object: 'article', content: ['body'] }, +} as KnowledgeSource; + +function doc(n: string, content: string): KnowledgeDocument { + const id = `${source.name}:${n}`; + return { id, sourceId: source.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] }; +} + +/** A pool that hands every statement on, and records each ranking statement with its values. */ +function recording(inner: PgPoolLike): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } { + const ranked: Array<{ text: string; values: unknown[] }> = []; + const note = (text: string, values?: unknown[]) => { + if (/\bkw AS \(/.test(text)) ranked.push({ text, values: values ?? [] }); + }; + return { + ranked, + pool: { + query: async (text, values) => { + note(text, values); + return inner.query(text, values); + }, + connect: async () => { + const client = await inner.connect(); + return { + query: async (text, values) => { + note(text, values); + return client.query(text, values); + }, + release: (err) => client.release(err), + }; + }, + } as PgPoolLike, + }; +} + +// Terms held by every passage, by most, by a few and by one, so the weights +// span the range, and both kinds of match: a word term on the tsvector and a +// substring term by LIKE. +const PASSAGES = [ + '公司员工出差住宿标准为每晚三百元,pump X-200 维修', + '公司仓库盘点每月一次,由物流部负责', + '公司合同到期前三十天提醒客户续约', + '公司出差审批由部门经理负责,pump 保修一年', + '公司住宿费报销需要发票', + '公司年假每年十天', + '公司 X-200 型号的保修期为两年', +]; + +describe.skipIf(!PG_URL)('knowledge-pgvector keyword IDF on a LIVE PostgreSQL', () => { + afterAll(() => store.dropAll()); + + for (const query of ['公司出差住宿标准需要审批吗', 'pump X-200 公司 出差']) { + it(`scores every candidate exactly as the per-row form does: ${query}`, async () => { + const live = recording(poolFromPg(store.pool())); + const adapter = store.adapter({ pool: live.pool, embedder: new FakeEmbedder() }); + await adapter.upsert( + PASSAGES.map((p, i) => doc(String(i + 1), p)), + { source, reason: 'manual', index: { fingerprint: 'fp-idf', recipeHash: 'rh-idf' } }, + ); + const hits = await adapter.search(query, { source, topK: PASSAGES.length }); + expect(hits.length).toBeGreaterThan(0); + expect(live.ranked).toHaveLength(1); + const { text, values } = live.ranked[0]; + + // The statement's own steps (every CTE, so every bound value keeps its + // place and type), and its own score expression. + const steps = text.slice(0, text.search(/\s+SELECT p\.chunk_id, p\.document_id/)); + expect(steps).toMatch(/^WITH .*\bidf AS MATERIALIZED \(.*\bkw AS \(/s); + const score = /SELECT h\.chunk_id, h\.distance, (.+?) AS score FROM hits h CROSS JOIN idf w/.exec(text)?.[1]; + expect(score).toBeDefined(); + const terms = (steps.match(/ AS h\d+\b/g) ?? []).length; + expect(terms).toBeGreaterThan(1); + + // The per-row form, written independently of the adapter. + const perRow = Array.from( + { length: terms }, + (_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`, + ).join(' + '); + const compared = await store.pool().query<{ chunk_id: string; once: string; per_row: string; weights: number }>( + `${steps} + SELECT h.chunk_id, (${score})::text AS once, (${perRow})::text AS per_row, + (SELECT count(*) FROM idf)::int AS weights + FROM hits h CROSS JOIN stats s CROSS JOIN idf w ORDER BY h.chunk_id`, + values, + ); + expect(compared.rows.length).toBeGreaterThan(1); + expect(compared.rows[0].weights).toBe(1); + for (const row of compared.rows) expect([row.chunk_id, row.once]).toEqual([row.chunk_id, row.per_row]); + // The scores are not all one value, so the comparison sees the weights. + expect(new Set(compared.rows.map((r) => r.once)).size).toBeGreaterThan(1); + }); + } +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts new file mode 100644 index 00000000000..061011514bc --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts @@ -0,0 +1,80 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword leg's IDF, without a database: the statement a search sends + * computes each term's weight once, in its own materialized step, and scores + * a candidate by multiplying its hits by those weights, so no `ln()` runs per + * candidate row. The live counterpart, `idf-once.live-postgres.test.ts`, holds + * the scores equal to the per-row form. + */ + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js'; +import { keywordTerms } from '../sql.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'idf', label: 'idf', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +/** A store with one stable active generation, which records each ranking statement. */ +function recordingPool(): { pool: PgPoolLike; ranked: string[] } { + const ranked: string[] = []; + const answer = async (text: string): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('AS distance')) ranked.push(text); + return { rows: [] as R[] }; + }; + return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked }; +} + +/** The text of the CTE `name` in `sql`, from its opening parenthesis to the one that closes it. */ +function cte(sql: string, name: string): string { + const head = new RegExp(`\\b${name} AS (MATERIALIZED )?\\(`).exec(sql); + expect(head, `the statement holds a CTE named ${name}`).not.toBeNull(); + let depth = 0; + const start = head!.index + head![0].length - 1; + for (let i = start; i < sql.length; i++) { + if (sql[i] === '(') depth += 1; + if (sql[i] === ')' && --depth === 0) return sql.slice(head!.index, i + 1); + } + throw new Error(`the CTE ${name} is not closed`); +} + +const lnCount = (text: string) => (text.match(/\bln\(/g) ?? []).length; + +describe('knowledge-pgvector keyword IDF', () => { + // A 16-term unspaced question (a figure, pieces of three and of two), and a + // spaced one mixing a word term with a substring term. + for (const query of ['出差住宿费2000元以下需要审批吗', 'pump X-200 出差']) { + it(`computes each term's IDF once per search, not per candidate row: ${query}`, async () => { + const { pool, ranked } = recordingPool(); + const adapter = new PgvectorKnowledgeAdapter({ id: 'idf', pool, embedder: new FakeEmbedder() }); + await adapter.search(query, { source, topK: 5, index: { fingerprint: 'fp' } }); + expect(ranked).toHaveLength(1); + const sql = ranked[0]; + const terms = keywordTerms(query).length; + expect(terms).toBeGreaterThan(1); + + // One ln() per term in the whole statement, every one of them in the + // materialized idf step, which reads the one-row stats and nothing else. + const idf = cte(sql, 'idf'); + expect(idf).toMatch(/^idf AS MATERIALIZED \(/); + expect(idf).toMatch(/ FROM stats\)$/); + expect(lnCount(sql)).toBe(terms); + expect(lnCount(idf)).toBe(terms); + for (let i = 0; i < terms; i++) expect(idf).toContain(`ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`); + + // The score a candidate gets: its hits times the weights, no ln() per row. + const kw = cte(sql, 'kw'); + expect(lnCount(kw)).toBe(0); + const score = Array.from({ length: terms }, (_, i) => `h.h${i} * w.w${i}`).join(' + '); + expect(kw).toContain(`SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w`); + // No float8 cast anywhere in the arithmetic: numeric keeps every tie as it was. + expect(sql).not.toMatch(/float8|double precision/); + }); + } +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index fbc0e2efe86..c73f0f0a0b2 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -675,9 +675,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { onCandidate.push(`c.content ${op} $${params.length}::text`); } } - const idf = onCandidate - .map((_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`) - .join(' + '); + // Each term's IDF is computed once per search, in `idf`, and a candidate's + // score multiplies its hits by those weights: written per row, the 16 + // `ln()` terms of a CJK question ran on every candidate. The arithmetic + // stays `numeric`, so every score, and so every tie, is the per-row one. + const score = onCandidate.map((_, i) => `h.h${i} * w.w${i}`).join(' + '); ctes.push( // Passages of equal keyword score are ranked by cosine distance, so the // keyword leg never reorders by chunk id what the vector leg ranks. @@ -687,9 +689,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { FROM cand c CROSS JOIN LATERAL (SELECT ${PASSAGE_TSVECTOR.replace('content', 'c.content')} AS tsv) v)`, `stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n, ${onCandidate.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM hits)`, + `idf AS MATERIALIZED (SELECT ${onCandidate + .map((_, i) => `ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`) + .join(', ')} FROM stats)`, `kw AS ( SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM ( - SELECT h.chunk_id, h.distance, ${idf} AS score FROM hits h CROSS JOIN stats s + SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w ) scored ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`, ); legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw'); From 0a71cde79367347da27918a705fa2c8390308124 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:48:36 +0000 Subject: [PATCH 060/178] feat(cli): os migrate meta --stored lists the stored permission sets whose View All / Modify All lost their field reach in 19 (#38399) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #37375 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 运维在升级到 19 前后跑一次存量元数据迁移预览,就能看到哪些存库的权限集因“查看全部/修改全部”不再放开字段而受影响,以及每条的一行修法;之前没有任何命令能列出它们。 - 属于“字段权限三轴拆分”收尾:兑现维护者对存库权限集的裁决(存库集按 19 新含义读取、不改写)要求的“一步自查”。 - 只读清单,不写库、不改退出码;列错最多是多列或漏列一条提示,可直接撤回本 PR。 - 无。 ## What changes `os migrate meta --stored` now prints a read-only review list of the stored permission sets (`sys_metadata`) that ruling A on #36055 leaves on the 19 meaning: every `objects` entry, the `'*'` entry included, that carries `viewAllRecords: true` or `modifyAllRecords: true` and no `viewAllFields`. One line per entry names the set, its scope, the object entry and the bits, followed by the one-line fix (`viewAllFields: true` on that entry, applied through the metadata API) and the Modify All caveats. It is modelled on the existing decision-mode review list of the `flow-decision-mode-inclusive-explicit` flip, end to end: - `@objectstack/metadata-protocol`: `collectViewAllFieldsReview(body)` runs the ADR-0087 D2 entry `permission-view-all-fields-beside-record-bypass` itself over `{ permissions: [body] }` and keeps only the paths it would write; each listed entry is named by its own `objects` key, matched against the path the conversion spells for it, so a key holding a dot or a line terminator is named rather than rejected. That makes it one predicate, not two, so the list is exactly what `os migrate meta --from 18` rewrites in a source. `migrateStoredMetadata` fills a new report list, `viewAllFieldsReview` (exported type `StoredViewAllFieldsReview`), for every stored `permission` row, on preview and `--apply` alike. It moves no count, no row outcome and no verdict, and writes nothing. `formatStoredMigrationReport` prints it beside the "already on protocol" verdict. - `@objectstack/cli`: `meta.ts` adds the empty list to the report it builds itself when `sys_metadata` does not exist yet, so `--json` always carries the key. - `@objectstack/spec`: the protocol-19 semantic entry's upgrade text said "No command lists the affected stored sets yet", which this PR makes false. Its description and its one-step check now name `os migrate meta --stored`. Text only. No new flag or option. `--type` narrows the list like the rest of the report. The published surface widens in three additive places, hence `Clause-②: yes (widening)` at `patch` (AGENTS.md Post-Task Checklist step 3, a non-protocol widening): the exported type `StoredViewAllFieldsReview` from `@objectstack/metadata-protocol`, the new member `viewAllFieldsReview` on the published `StoredMigrationReport`, and the matching `viewAllFieldsReview` field in the `os migrate meta --stored --json` report. The same member also rides on the `POST /meta/_migrate-stored` response payload and `client.meta.migrateStored()`, which return the same report. Nothing is removed or narrowed. ## Why Maintainer ruling A on #36055 keeps stored permission sets on the 19 meaning and asks the upgrade text to give operators a one-step check of which stored sets are affected. Until now nothing listed them (re-measured on `main` at 2efcedd9: no producer of such a list in `packages/metadata-protocol/src` or `packages/cli/src`). ## Tests - `packages/metadata-protocol/src/protocol.stored-migration.test.ts`, new `describe`: the list (row, set, entry, bits) on a preview and the row stays canonical; `--apply` writes nothing (no history row, bytes identical); controls (`viewAllFields` either value, no bypass, a non-permission row) plus the positive; `--type` narrowing; the ONE PREDICATE pin against `applyMetaMigrations(…, 18, 19)`; the renderer text beside the verdict; no section when there is nothing to review. - `packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts` (new): the command prints the list and the fix beside the verdict, stays a preview, `--json` carries `viewAllFieldsReview` and stays clean, and the absent-`sys_metadata` path answers an empty list. Ablation (`scripts/ablation-replace.mjs`, restored to a HEAD-equal blob every time): - Key naming (review finding S1): `const object = objectByPath.get(path);` replaced by the earlier path pattern `/^permissions\[0\]\.objects\.(.+)\.viewAllFields$/`: exactly the new case with keys holding `\n`, `\r`, U+2028, U+2029 and a dot goes red (1 failed / 54 passed), on the "unknown shape" throw that rejected the whole pass; restored blob == HEAD 03b22caa106b. - Producer: `if (singular === 'permission') {` → `if (false && …)` in `protocol-save.ts`: 4 of the 7 new protocol cases go red (the 3 that do not read the producer stay green), 50 others pass. - Renderer, through `dist/`: the formatter's list filtered to empty, `@objectstack/metadata-protocol` rebuilt, marker proven live by `ablation-dist-preflight.mjs` (present in 2 built files). The CLI text case goes red and the two `--json` cases stay green, as they do not read the renderer. Restore leg: rebuilt, marker absent from all 24 built files, 3/3 green.
Local results (head 792a0ece6 unless stated) - `@objectstack/metadata-protocol`: whole suite 375 files passed / 9 skipped, 23654 tests passed (lock VERDICT command-exit 0; run before the comment-only `protocol.ts` revert); `protocol.stored-migration.test.ts` 54/54; typecheck exit 0. - `@objectstack/cli`: `--project unit` 447/449 files at 8ba549b8. The 2 others (`published-subpath-console.pin`, `published-subpath-hook-body.pin`) refused because the CLI was not built, then passed after the build at 2b3ec660 together with the three edited stored-pass files (5 files, 37 tests). typecheck (with `check:test-typecheck`) exit 0. The `integration` layer is declared to CI. - `@objectstack/spec`: `src/migrations` + `retired-key-removal-version.pin` 6 files / 282 tests; `check:generated` all 14 artifacts current; `check:spec-changes`, `check:upgrade-guide`, typecheck exit 0; `check:doc-authoring` exit 0. - Derived gate families (`dispatch-gates.mjs --commands`): 101 derived, 101 run, each exit 0; `--ran` reconciliation: "101 run, 0 NOT-MEASURED (a DERIVED zero — all 101 recorded an exit code and none of them is 3)". On the way, the run found `check:facade-delegation-only` red on a `protocol.ts` doc paragraph and `check:test-source-alias` red on the edited CLI tests; both are fixed in this PR. - eslint (`--no-inline-config`) on the 9 changed `.ts` files: exit 0. - Patch round (declaration line only), head 135393ac8 after merging `origin/main` (c610020e2, then b926d37fc; no conflict, none of this PR's files moved on main): changeset gates (`check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check:changeset-gate-self-tests`, `check-closing-keyword-parity`, `check:nul-bytes`) exit 0; full `turbo run build` 124/124; spec `check:generated` all 14 artifacts current; `protocol.stored-migration.test.ts` 54/54, the five CLI stored-pass and subpath-pin files 37/37, spec `src/migrations` 209/209; derived union 101 derived, 101 run, each exit 0, and `--ran`: "101 run, 0 NOT-MEASURED (a DERIVED zero — all 101 recorded an exit code and none of them is 3)"; `overlap-check.mjs` clean. - Patch round 2 (review S1, N1, N3), head 8dad9543d after merging `origin/main` a2205a85a (no conflict, none of this PR's files moved on main): full `turbo run build` 124/124; `protocol.stored-migration.test.ts` 55/55; the three CLI stored-pass files 8/8; metadata-protocol and cli typecheck exit 0; derived union 101 derived, 101 run, each exit 0, `--ran` a DERIVED zero of NOT-MEASURED; `overlap-check.mjs` clean.
## Acceptance notes - Surface amendment beyond the claim's file list, each re-checked with `check-handover.mjs --inflight --card=37375` (all clear) before editing: `packages/metadata-protocol/src/stored-migration.ts`, `packages/metadata-protocol/src/protocol-save.ts`, `packages/metadata-protocol/src/index.ts` (the existing review list's producer and renderer live there, not in `meta.ts`); `packages/metadata-protocol/src/protocol.stored-migration.test.ts` (beside it); `packages/cli/test/migrate-meta-stored-failed.test.ts` (a report fixture); `packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts` (the upgrade text this PR makes false). - `protocol.ts` (a facade under `check:facade-delegation-only`) is deliberately untouched: a doc paragraph there took it 9 lines over its ceiling, so the list is documented beside its type in `stored-migration.ts` only. - The three CLI test files this PR edits now load the command's dynamically imported packages at module top, as `check:test-source-alias` prescribes for a changed test file. - Organization-scoped legacy rows are reported `skipped` before their body is read, so, like the decision list, this list does not name them. - Not in this PR, release-owned: the same stale sentence ("No command lists the affected stored sets yet; a review list is follow-up #37375") is in the released `19.0.0-next.2` `CHANGELOG.md` entries of `@objectstack/spec`, `cli`, `core`, `lint` and `metadata-core`, and in `.changeset/pre/36055-view-all-stops-voting-on-fields.md`. Per AGENTS.md these are corrected in a dedicated docs-only PR, never in a code PR. - Not in this PR: `content/docs/deployment/cli.mdx` documents `decisionModeReview` for `os migrate meta --stored` and does not yet document `viewAllFieldsReview`. - Not in this PR (ruled out by the claim): the Studio `viewAllFields` control. ## Verification Read first, by risk: `packages/metadata-protocol/src/stored-migration.ts` (`collectViewAllFieldsReview`, the path regex and the formatter section), `packages/metadata-protocol/src/protocol-save.ts` (the `singular === 'permission'` block), `packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts`. Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run src/protocol.stored-migration.test.ts -t "View All Fields"`. Expect 7 passing cases. ## 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. - [x] 3. No formatter ran; `pnpm lint` passes. - [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/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_017xRBcUuJz2sQYZQYRiwPzr)_ --------- Co-authored-by: Claude --- ...7375-stored-view-all-fields-review-list.md | 27 ++++ .../migrate/meta.stored-actor.test.ts | 16 ++ .../meta.stored-view-all-fields.test.ts | 144 +++++++++++++++++ packages/cli/src/commands/migrate/meta.ts | 1 + .../test/migrate-meta-stored-failed.test.ts | 16 ++ packages/metadata-protocol/src/index.ts | 1 + .../metadata-protocol/src/protocol-save.ts | 25 ++- .../src/protocol.stored-migration.test.ts | 138 +++++++++++++++++ .../metadata-protocol/src/stored-migration.ts | 145 +++++++++++++++++- ...-view-all-modify-all-cast-no-field-vote.ts | 8 +- 10 files changed, 516 insertions(+), 5 deletions(-) create mode 100644 .changeset/37375-stored-view-all-fields-review-list.md create mode 100644 packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts diff --git a/.changeset/37375-stored-view-all-fields-review-list.md b/.changeset/37375-stored-view-all-fields-review-list.md new file mode 100644 index 00000000000..13b936d0585 --- /dev/null +++ b/.changeset/37375-stored-view-all-fields-review-list.md @@ -0,0 +1,27 @@ +--- +'@objectstack/cli': patch +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +feat(cli): `os migrate meta --stored` lists the stored permission sets whose View All / Modify All no longer read fields in 19 + +Clause-②: yes (widening) +Metadata-protocol: none + +From protocol 19, View All (`viewAllRecords`) and Modify All (`modifyAllRecords`) widen records only and cast no field vote, and a permission set stored in a deployment (`sys_metadata`, for example saved in Studio) is read with that meaning and never rewritten on upgrade. The upgrade asks for a one-step check of which stored sets are affected; `os migrate meta --stored` now prints it. + +On a preview and an `--apply` run alike, the command lists every stored permission set's `objects` entry, the `'*'` entry included, that carries `viewAllRecords: true` or `modifyAllRecords: true` and no `viewAllFields`, one line per entry with the set, its scope and the bits: + +```text +◆ 2 object entry(ies) in 1 stored permission set row(s) hold View All or Modify All and no `viewAllFields` — since protocol 19 they read no field another set hides; listed for review, never rewritten: + • permission/ops_auditor [env-wide] — objects entry 'ops_ticket' (viewAllRecords) + • permission/ops_auditor [env-wide] — objects entry '*' (viewAllRecords, modifyAllRecords) +``` + +The fix, where the set's holders should still read every field of that object: add `viewAllFields: true` to the entry through the metadata API (Studio's permission matrix has no control for it). Beside Modify All the set's own `readable: false` rows now bind and no edit is restored; grant an edit with an explicit `editable: true` field row. Declaring `viewAllFields` either way, `true` or `false`, takes the entry off the list. + +The list is read-only: it writes nothing, moves no count and does not change the exit code or the "already on protocol" verdict. `--type` narrows it like the rest of the report. It uses the same predicate as the source conversion `permission-view-all-fields-beside-record-bypass` (`os migrate meta --from 18`), so it names exactly the entries that conversion rewrites in a source. + +- `@objectstack/metadata-protocol`: `StoredMigrationReport` gains `viewAllFieldsReview` (exported type `StoredViewAllFieldsReview`: `id`, `name`, `organizationId`, `packageId`, `state`, `object`, `bits`), and `formatStoredMigrationReport` prints it. `os migrate meta --stored --json` carries the same key, as an empty list on a database with no `sys_metadata` table yet, and so do the `POST /meta/_migrate-stored` response payload and `client.meta.migrateStored()`, which return the same report. +- `@objectstack/spec`: the upgrade text of the protocol-19 semantic entry `permission-view-all-modify-all-cast-no-field-vote` no longer says that no command lists the affected stored sets; its description and its one-step check now name `os migrate meta --stored`. Text only: no schema, key or behaviour changes. diff --git a/packages/cli/src/commands/migrate/meta.stored-actor.test.ts b/packages/cli/src/commands/migrate/meta.stored-actor.test.ts index f093bd22ed9..cbbfd0390cf 100644 --- a/packages/cli/src/commands/migrate/meta.stored-actor.test.ts +++ b/packages/cli/src/commands/migrate/meta.stored-actor.test.ts @@ -21,6 +21,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; const boot = vi.hoisted(() => vi.fn()); vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); @@ -47,6 +62,7 @@ const CLEAN_REPORT = { failed: 0, rows: [], decisionModeReview: [], + viewAllFieldsReview: [], }; const migrateStoredMetadata = vi.fn(); diff --git a/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts b/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts new file mode 100644 index 00000000000..9ace1ae7660 --- /dev/null +++ b/packages/cli/src/commands/migrate/meta.stored-view-all-fields.test.ts @@ -0,0 +1,144 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os migrate meta --stored` — the review list of stored permission sets whose + * View All / Modify All lost their field reach in protocol 19 (maintainer + * ruling option A on #36055). + * + * A stored set keeps the 19 meaning (the bits widen records only), and the + * upgrade text owes operators a one-step check of which stored sets are + * affected. The pass names each `objects` entry carrying `viewAllRecords` or + * `modifyAllRecords` and no `viewAllFields` under `viewAllFieldsReview`; this + * file pins what the COMMAND prints and emits for it: the list and its fix in + * the terminal, beside the on-protocol verdict, read-only (exit 0), and the + * key on `--json`, including the report the command builds itself when + * `sys_metadata` does not exist yet. + * + * The boot is replaced, so no database is opened; the command's own parse, + * control flow and the real report renderer run. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; + +const boot = vi.hoisted(() => vi.fn()); +vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); +vi.mock('../../utils/migrate-occupancy-gate.js', () => ({ + OCCUPANCY_HINT: 'occupancy hint', + probeMigrationTarget: vi.fn(async () => ({ status: 'free' })), +})); +vi.mock('../../utils/data-migration-plugins.js', () => ({ buildDataMigrationPlugins: vi.fn(async () => []) })); + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +/** oclif builds its whole command table on the first `run()` in a process. */ +const RUN_TIMEOUT = 60_000; + +const SCOPE = { id: 'r_1', name: 'ops_auditor', organizationId: null, packageId: null, state: 'active' as const }; + +/** An on-protocol run that names two entries of one stored set for review. */ +const REPORT = { + apply: false, + protocol: '19.0.0', + scanned: 1, + canonical: 1, + pending: 0, + rewritten: 0, + skipped: 0, + failed: 0, + rows: [], + decisionModeReview: [], + viewAllFieldsReview: [ + { ...SCOPE, object: 'ops_ticket', bits: ['viewAllRecords'] }, + { ...SCOPE, object: '*', bits: ['viewAllRecords', 'modifyAllRecords'] }, + ], +}; + +const migrateStoredMetadata = vi.fn(); +let tableAbsent: (name: string) => boolean; +let written: string[]; +let printed: string[]; +let stdout: ReturnType; +let stderr: ReturnType; +let log: ReturnType; + +beforeEach(() => { + migrateStoredMetadata.mockReset(); + migrateStoredMetadata.mockResolvedValue(REPORT); + tableAbsent = () => false; + boot.mockReset(); + boot.mockResolvedValue({ + kernel: { getService: (name: string) => (name === 'protocol' ? { migrateStoredMetadata } : undefined) }, + dbLabel: 'file:test.db', + tableAbsent: (name: string) => tableAbsent(name), + shutdown: vi.fn(async () => {}), + }); + written = []; + printed = []; + // `emitJson` awaits the write's DRAIN callback, so the double invokes it. + stdout = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, enc?: unknown, cb?: unknown) => { + written.push(String(chunk)); + const done = typeof enc === 'function' ? enc : cb; + if (typeof done === 'function') done(); + return true; + }) as typeof process.stdout.write); + stderr = vi.spyOn(process.stderr, 'write').mockImplementation((() => true) as typeof process.stderr.write); + log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + printed.push(args.map(String).join(' ')); + }); +}); +afterEach(() => { + stdout.mockRestore(); + stderr.mockRestore(); + log.mockRestore(); +}); + +describe('os migrate meta --stored — the stored permission sets View All / Modify All no longer open fields for (ruling A on #36055)', () => { + it('prints each listed entry and the `viewAllFields: true` fix, beside the on-protocol verdict', async () => { + await MigrateMeta.run(['--stored'], { root: CLI_ROOT }); + + const text = printed.join('\n'); + expect(text).toMatch(/2 object entry\(ies\) in 1 stored permission set row\(s\) hold View All or Modify All/); + expect(text).toContain("permission/ops_auditor [env-wide] — objects entry 'ops_ticket' (viewAllRecords)"); + expect(text).toContain("permission/ops_auditor [env-wide] — objects entry '*' (viewAllRecords, modifyAllRecords)"); + expect(text).toContain('add `viewAllFields: true` to the entry through the metadata API'); + expect(text).toMatch(/already on protocol/); + // Read-only: the list asks nothing of the pass, so the preview asks for no write. + expect(migrateStoredMetadata.mock.calls[0][0].apply).toBe(false); + }, RUN_TIMEOUT); + + it('--json carries the list under `viewAllFieldsReview`, and the run stays clean', async () => { + await MigrateMeta.run(['--stored', '--json'], { root: CLI_ROOT }); + + const out = JSON.parse(written.join('')); + expect(out.viewAllFieldsReview.map((r: { object: string }) => r.object)).toEqual(['ops_ticket', '*']); + expect(out.clean).toBe(true); + }, RUN_TIMEOUT); + + it('a database with no `sys_metadata` yet answers an empty list, not a missing key', async () => { + tableAbsent = (name) => name === 'sys_metadata'; + + await MigrateMeta.run(['--stored', '--json'], { root: CLI_ROOT }); + + expect(migrateStoredMetadata).not.toHaveBeenCalled(); + const out = JSON.parse(written.join('')); + expect(out).toMatchObject({ scanned: 0, decisionModeReview: [], viewAllFieldsReview: [] }); + }, RUN_TIMEOUT); +}); diff --git a/packages/cli/src/commands/migrate/meta.ts b/packages/cli/src/commands/migrate/meta.ts index 6da115733f1..94dd806f8e1 100644 --- a/packages/cli/src/commands/migrate/meta.ts +++ b/packages/cli/src/commands/migrate/meta.ts @@ -1606,6 +1606,7 @@ export default class MigrateMeta extends Command { failed: 0, rows: [], decisionModeReview: [], + viewAllFieldsReview: [], }; const report: StoredMigrationReport = reads.absent('sys_metadata') ? noStoredRows diff --git a/packages/cli/test/migrate-meta-stored-failed.test.ts b/packages/cli/test/migrate-meta-stored-failed.test.ts index 2d955871a93..28f1acd37b5 100644 --- a/packages/cli/test/migrate-meta-stored-failed.test.ts +++ b/packages/cli/test/migrate-meta-stored-failed.test.ts @@ -25,6 +25,21 @@ import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { stripVTControlCharacters } from 'node:util'; import MigrateMeta from '../src/commands/migrate/meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; const boot = vi.hoisted(() => vi.fn()); vi.mock('../src/utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); @@ -85,6 +100,7 @@ function reportOf(rows: ReturnType[], apply = false) { failed: rows.length, rows, decisionModeReview: [], + viewAllFieldsReview: [], }; } diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 57e8016f5bc..09b8f0a7af8 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -261,6 +261,7 @@ export type { StoredMigrationReport, StoredMigrationRow, StoredMigrationTodo, + StoredViewAllFieldsReview, } from './stored-migration.js'; export { diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 2597a2ee9b8..104a3ca909a 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -39,7 +39,7 @@ import { translatedEchoNotices, } from './protocol-translated-echo.js'; import { PROTOCOL_VERSION, stripReadDecorations } from '@objectstack/spec/kernel'; -import { collectDecisionModeReview } from './stored-migration.js'; +import { collectDecisionModeReview, collectViewAllFieldsReview } from './stored-migration.js'; import type { StoredFlowCanonicalization, StoredMigrationNotice, @@ -2650,6 +2650,7 @@ export class ProtocolSaveFacet { failed: 0, rows: [], decisionModeReview: [], + viewAllFieldsReview: [], }; // Two scoped queries rather than one unfiltered scan: `state` is an @@ -2813,6 +2814,28 @@ export class ProtocolSaveFacet { } } + // [ruling A on #36055] The View All Fields review list — REPORT ONLY, + // the same posture as the decision list above. A stored permission + // set's `objects` entry with View All or Modify All and no + // `viewAllFields` read every field before protocol 19 and reads no + // field another set hides now; by ruling the row keeps that new + // meaning (no pass rewrites it), and this names each such entry so + // an operator can add `viewAllFields: true` where the set meant to + // read every field. Read off the stored body, before the chain, so + // it touches no count, no outcome and no write. + if (singular === 'permission') { + for (const entry of collectViewAllFieldsReview(body)) { + report.viewAllFieldsReview.push({ + id: base.id, + name: base.name, + organizationId, + packageId, + state, + ...entry, + }); + } + } + // Flow rows need the automation engine's canonicalizer — its // registration preview judges plugin nodes against the live // registry — supplied by the caller (#4454) or resolved from the diff --git a/packages/metadata-protocol/src/protocol.stored-migration.test.ts b/packages/metadata-protocol/src/protocol.stored-migration.test.ts index 034c8cc6891..bcf25936e40 100644 --- a/packages/metadata-protocol/src/protocol.stored-migration.test.ts +++ b/packages/metadata-protocol/src/protocol.stored-migration.test.ts @@ -36,7 +36,9 @@ import { applyMetaMigrations } from '@objectstack/spec/migrations'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { DECISION_MODE_REVIEW_CONVERSION_ID, + VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID, collectDecisionModeReview, + collectViewAllFieldsReview, formatStoredMigrationReport, storedMigrationClean, } from './stored-migration.js'; @@ -1092,6 +1094,142 @@ describe('migrateStoredMetadata — the decision review list: stored rows take f }); }); +describe('migrateStoredMetadata — the View All Fields review list: stored permission sets take the 19 meaning, and are LISTED, never rewritten (ruling A on #36055)', () => { + // Maintainer ruling option A on #36055: a stored permission set whose + // `objects` entry carries View All or Modify All and no `viewAllFields` + // takes the protocol-19 meaning on upgrade (the bits widen records only and + // cast no field vote) — no stored-row rewrite — and the upgrade text gives + // operators a one-step check of which stored sets are affected. This is it. + const setBody = (name: string, objects: Record>) => ({ + name, + label: 'Ops Auditor', + objects, + fields: { 'ops_ticket.cost': { readable: false } }, + }); + /** View All alone, Modify All alone and the wildcard entry with both: all three listed. */ + const affected = () => setBody('ops_auditor', { + ops_ticket: { allowRead: true, viewAllRecords: true }, + ops_asset: { allowRead: true, allowEdit: true, allowDelete: true, modifyAllRecords: true }, + '*': { allowRead: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + ops_note: { allowRead: true, allowEdit: true }, + }); + const permissionRow = (name: string, body: unknown, extra: Record = {}) => + ({ type: 'permission', name, metadata: body, ...extra }); + + it('a stored set with View All / Modify All and no `viewAllFields` is LISTED — row, set, entry and bits — and the row is canonical', async () => { + const { engine, tables } = makeStubEngine([permissionRow('ops_auditor', affected())]); + const before = JSON.stringify(metaRows(tables)); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata(); + + const scope = { id: metaRows(tables)[0]!.id, name: 'ops_auditor', organizationId: null, packageId: null, state: 'active' }; + expect(report.viewAllFieldsReview).toEqual([ + { ...scope, object: 'ops_ticket', bits: ['viewAllRecords'] }, + { ...scope, object: 'ops_asset', bits: ['modifyAllRecords'] }, + { ...scope, object: '*', bits: ['viewAllRecords', 'modifyAllRecords'] }, + ]); + // ON protocol: listed, not pending — the list moves no count and no verdict. + expect(report).toMatchObject({ scanned: 1, canonical: 1, pending: 0, skipped: 0, failed: 0, rows: [] }); + expect(storedMigrationClean(report)).toBe(true); + expect(JSON.stringify(metaRows(tables))).toBe(before); + }); + + it('`--apply` changes nothing for it: no rewrite, no history row, no `viewAllFields` written — and the list is the same', async () => { + const { engine, tables } = makeStubEngine([permissionRow('ops_auditor', affected())]); + const before = JSON.stringify(metaRows(tables)); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata({ apply: true }); + + expect(report.viewAllFieldsReview.map((r) => `${r.name}:${r.object}`)) + .toEqual(['ops_auditor:ops_ticket', 'ops_auditor:ops_asset', 'ops_auditor:*']); + expect(report).toMatchObject({ canonical: 1, rewritten: 0, failed: 0 }); + expect(historyRows(tables)).toHaveLength(0); + expect(JSON.stringify(metaRows(tables))).toBe(before); + expect(JSON.parse(metaRows(tables)[0]!.metadata).objects.ops_ticket).not.toHaveProperty('viewAllFields'); + }); + + it('CONTROLS — `viewAllFields` declared either way, no record bypass, and a non-permission row are NOT listed', async () => { + expect(collectViewAllFieldsReview(setBody('s', { + ops_secret: { allowRead: true, viewAllRecords: true, viewAllFields: false }, + ops_report: { allowRead: true, modifyAllRecords: true, allowEdit: true, allowDelete: true, viewAllFields: true }, + ops_note: { allowRead: true, allowEdit: true, viewAllRecords: false }, + }))).toEqual([]); + // A flow that happens to carry an `objects` map is not a permission set. + const { engine } = makeStubEngine([{ type: 'flow', name: 'f', metadata: affected() }]); + const report = await new ObjectStackProtocolImplementation(engine).migrateStoredMetadata(); + expect(report.viewAllFieldsReview).toEqual([]); + // …and the POSITIVE for the same builder, so the controls cannot pass vacuously. + expect(collectViewAllFieldsReview(affected()).map((r) => r.object)).toEqual(['ops_ticket', 'ops_asset', '*']); + }); + + it('an `objects` key holding a line terminator or a dot is still named, and the pass still answers a report', async () => { + // `objects` is a record of arbitrary strings, so a stored key may hold any + // of these. Each entry below carries a bypass bit and no `viewAllFields`, + // so the conversion emits a path for every one of them. + const keys = ['crm\nlead', 'crm\rlead', 'crm
lead', 'crm
lead', 'crm.lead']; + const body = setBody('odd_keys', Object.fromEntries(keys.map((k) => [k, { allowRead: true, viewAllRecords: true }]))); + const { engine } = makeStubEngine([permissionRow('odd_keys', body)]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata(); + + expect(report.viewAllFieldsReview.map((r) => r.object)).toEqual(keys); + expect(report.viewAllFieldsReview.every((r) => r.bits.join() === 'viewAllRecords')).toBe(true); + expect(report).toMatchObject({ scanned: 1, canonical: 1, failed: 0 }); + }); + + it('`--type` narrows it like every other part of the report: a run over flows alone lists no permission set', async () => { + const { engine } = makeStubEngine([permissionRow('ops_auditor', affected())]); + const protocol = new ObjectStackProtocolImplementation(engine); + + expect((await protocol.migrateStoredMetadata({ types: ['flow'] })).viewAllFieldsReview).toEqual([]); + expect((await protocol.migrateStoredMetadata({ types: ['permission'] })).viewAllFieldsReview).toHaveLength(3); + }); + + it('ONE PREDICATE — the list is exactly what the `--from 18` chain writes `viewAllFields` at, through the same registry entry', () => { + const body = affected(); + const bodyBytes = JSON.stringify(body); + + const listed = collectViewAllFieldsReview(body).map((r) => `permissions[0].objects.${r.object}.viewAllFields`); + const chain = applyMetaMigrations({ permissions: [body] }, 18, 19); + const written = chain.applied + .filter((a) => a.conversionId === VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID) + .map((a) => a.path); + + expect(written).toHaveLength(3); + expect(listed).toEqual(written); + // The listing ran the entry and discarded its output: the body is untouched. + expect(JSON.stringify(body)).toBe(bodyBytes); + }); + + it('the renderer prints the list with the one-line fix, beside — not instead of — the on-protocol verdict', async () => { + const { engine } = makeStubEngine([permissionRow('ops_auditor', affected(), { state: 'draft' })]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const text = formatStoredMigrationReport(await protocol.migrateStoredMetadata()).join('\n'); + + expect(text).toMatch(/3 object entry\(ies\) in 1 stored permission set row\(s\) hold View All or Modify All and no `viewAllFields`/); + expect(text).toContain("permission/ops_auditor [env-wide, draft] — objects entry 'ops_ticket' (viewAllRecords)"); + expect(text).toContain("permission/ops_auditor [env-wide, draft] — objects entry '*' (viewAllRecords, modifyAllRecords)"); + expect(text).toContain('add `viewAllFields: true` to the entry through the metadata API'); + expect(text).toMatch(/already on protocol/); + }); + + it('CONTROL — a run with nothing to review prints no review section', async () => { + const { engine } = makeStubEngine([permissionRow('ops_auditor', setBody('ops_auditor', { + ops_ticket: { allowRead: true, viewAllRecords: true, viewAllFields: true }, + }))]); + const protocol = new ObjectStackProtocolImplementation(engine); + + const report = await protocol.migrateStoredMetadata(); + + expect(report.viewAllFieldsReview).toEqual([]); + expect(formatStoredMigrationReport(report).join('\n')).not.toMatch(/stored permission set row\(s\) hold View All/); + }); +}); + describe('migrateStoredMetadata — the v18 stored shapes refused with no lossless rewrite are LISTED, never rewritten (#23269, #23270, #23271)', () => { // Each of these rows reads as on protocol to every conversion — nothing // rewrites it — while the parse or the boot refuses it after the upgrade. diff --git a/packages/metadata-protocol/src/stored-migration.ts b/packages/metadata-protocol/src/stored-migration.ts index fcc137f9848..03b22caa106 100644 --- a/packages/metadata-protocol/src/stored-migration.ts +++ b/packages/metadata-protocol/src/stored-migration.ts @@ -235,6 +235,56 @@ export interface StoredMigrationReport { * and no verdict. See {@link StoredDecisionModeReview}. */ decisionModeReview: StoredDecisionModeReview[]; + /** + * Stored permission-set `objects` entries whose View All / Modify All stopped + * reading fields at protocol 19 and that carry no `viewAllFields` (ruling A + * on #36055) — in scan order, whatever each row's outcome, on a preview and + * an apply run alike. REPORT ONLY, like {@link decisionModeReview}: nothing + * in this list is ever written, and it moves no count and no verdict. See + * {@link StoredViewAllFieldsReview}. + */ + viewAllFieldsReview: StoredViewAllFieldsReview[]; +} + +/** + * One `objects` entry of one stored permission set whose field reach changed + * at protocol 19 — LISTED for an operator to review, never rewritten. + * + * The shape: an entry (the `'*'` entry included) carrying + * `viewAllRecords: true` or `modifyAllRecords: true` and no `viewAllFields` + * key. Before protocol 19 the two bits cast a vote on every field of the + * object, so such a set read (and, under Modify All, edited) a field another + * set hid; from 19 they widen records only. By maintainer ruling (option A on + * #36055) a stored set takes that new meaning on upgrade: `os migrate meta + * --from 18` writes `viewAllFields: true` beside the bit in a SOURCE, whose age + * the operator asserts, and no pass writes it onto a stored row, since Studio + * saves sets today and nothing says a row predates the flip. So the row is on + * protocol as it stands — this entry is not residue, it does not make the row + * `pending`, and it never flips {@link storedMigrationClean}. The fix, where the + * set's holders should still read every field of the object, is adding + * `viewAllFields: true` to the entry through the metadata API (Studio's + * permission matrix has no control for it). + * + * The predicate is not restated here: {@link collectViewAllFieldsReview} runs + * the ADR-0087 D2 entry `permission-view-all-fields-beside-record-bypass` + * itself over the stored body and keeps only where it would write — so this + * list is, by construction, the set of entries the `--from 18` chain rewrites + * in a source. + */ +export interface StoredViewAllFieldsReview { + /** `sys_metadata.id` of the permission-set row. */ + id: string; + /** The permission set's name. */ + name: string; + /** `null` = the env-wide overlay bucket. */ + organizationId: string | null; + /** `null` = a package-less (global) overlay row. */ + packageId: string | null; + state: 'active' | 'draft'; + /** The `objects` key of the entry: an object name, or `'*'` for the wildcard entry. */ + object: string; + /** The record-bypass bits the entry carries, in this order: `viewAllRecords`, then `modifyAllRecords`. */ + bits: Array<'viewAllRecords' | 'modifyAllRecords'>; } /** @@ -271,7 +321,9 @@ export interface StoredMigrationReport { * The decision review list ({@link StoredMigrationReport.decisionModeReview}) * is not a skip class and never moves this verdict either: a row it names is ON * protocol — by ruling it takes the protocol-18 meaning as stored — so there is - * nothing for any run of this pass to do about it. + * nothing for any run of this pass to do about it. The same holds for the + * View All Fields review list ({@link StoredMigrationReport.viewAllFieldsReview}), + * whose rows take the protocol-19 meaning as stored. */ export function storedMigrationClean(report: StoredMigrationReport): boolean { return report.pending === 0 && report.failed === 0; @@ -341,6 +393,73 @@ export function collectDecisionModeReview( }); } +/** + * The ADR-0087 D2 entry whose predicate {@link collectViewAllFieldsReview} runs + * (ruling A on #36055): the conversion `os migrate meta --from 18` replays over + * authored sources to write `viewAllFields: true` beside View All / Modify All. + */ +export const VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID = 'permission-view-all-fields-beside-record-bypass'; + +/** + * The `objects` entries of ONE stored permission-set body that the review list + * names — see {@link StoredViewAllFieldsReview} for what they are and why a + * stored row keeps them as they are (ruling A on #36055). + * + * **One predicate, not two**, as {@link collectDecisionModeReview}: the D2 + * entry's own `apply` runs over `{ permissions: [body] }` and only the paths it + * WOULD write `viewAllFields` at are kept; the stack it returns is discarded + * unread and the entry is copy-on-write, so nothing here reaches a write or + * touches the body. No earlier conversion writes `viewAllRecords`, + * `modifyAllRecords` or `viewAllFields`, so the stored body and the canonical + * one give the same answer. + * + * ⛔ Throws when the entry is gone from the registry, or names a path of a + * shape this reader does not know: a list that silently came back empty would + * tell every deployment "no permission set to review". The entry leaves the + * registry only when the chain floor passes protocol 18; the upgrade this list + * serves is then outside the supported window, and the list goes with it. + */ +export function collectViewAllFieldsReview( + body: unknown, +): Array<{ object: string; bits: Array<'viewAllRecords' | 'modifyAllRecords'> }> { + if (body === null || typeof body !== 'object' || Array.isArray(body)) return []; + const entry = ALL_CONVERSIONS.find((c) => c.id === VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID); + if (!entry) { + throw new Error( + `the View All Fields review list runs the conversion '${VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID}', and the ` + + 'registry no longer carries it. Remove the review list together with the conversion.', + ); + } + const paths: string[] = []; + entry.apply({ permissions: [body as Record] }, (detail) => { + paths.push(detail.path); + }); + const objects = (body as { objects?: Record> }).objects ?? {}; + // The object name is read off the entry's OWN key, never parsed back out of + // the path: `objects` is a record of arbitrary strings, so a stored key can + // hold a dot or a line terminator, and a pattern over the path would reject + // a path the conversion legitimately emitted, throwing for a stored row + // rather than for registry drift. Each key's path is spelled exactly as the + // conversion spells it, and only a path no key produces is an unknown shape. + const objectByPath = new Map( + Object.keys(objects).map((name): [string, string] => [`permissions[0].objects.${name}.viewAllFields`, name]), + ); + return paths.map((path) => { + const object = objectByPath.get(path); + if (object === undefined) { + throw new Error( + `the conversion '${VIEW_ALL_FIELDS_REVIEW_CONVERSION_ID}' reported a path of an unknown shape ` + + `('${path}'), so the View All Fields review list cannot name the entry it is about.`, + ); + } + const objectEntry = objects[object] ?? {}; + const bits: Array<'viewAllRecords' | 'modifyAllRecords'> = []; + if (objectEntry.viewAllRecords === true) bits.push('viewAllRecords'); + if (objectEntry.modifyAllRecords === true) bits.push('modifyAllRecords'); + return { object, bits }; + }); +} + /** Read `nodes[1].config.body.nodes[0]`-style paths — the spelling the conversions emit. */ function readAtPath(root: unknown, path: string): unknown { let current: unknown = root; @@ -439,6 +558,30 @@ export function formatStoredMigrationReport(report: StoredMigrationReport): stri ); } + // The same posture as the decision list above, for protocol 19's flip: these + // rows ARE on protocol (a stored set takes the 19 meaning as it stands, by + // ruling), so the section sits beside the verdict without contradicting it. + const viewAll = report.viewAllFieldsReview; + if (viewAll.length > 0) { + const setRows = new Set(viewAll.map((r) => r.id)).size; + lines.push( + `◆ ${viewAll.length} object entry(ies) in ${setRows} stored permission set row(s) hold View All or Modify All ` + + 'and no `viewAllFields` — since protocol 19 they read no field another set hides; listed for review, ' + + 'never rewritten:', + ); + for (const r of viewAll) { + lines.push(` • permission/${r.name} ${describeScope(r)} — objects entry '${r.object}' (${r.bits.join(', ')})`); + } + lines.push( + ' Before protocol 19 View All and Modify All also opened every field of the object; they now widen ' + + 'records only. Where the set\'s holders should still read every field of that object, add ' + + '`viewAllFields: true` to the entry through the metadata API (Studio\'s permission matrix has no ' + + 'control for it). Beside Modify All the set\'s own `readable: false` rows now bind and no edit is ' + + 'restored: grant one with an explicit `editable: true` field row. Declaring `viewAllFields` either ' + + 'way takes the entry off this list. No run of this pass writes it.', + ); + } + if (report.scanned === 0) { // "Nothing to convert" and "nothing was looked at" are different claims, // and only the first is a pass. A run pointed at the wrong project — the diff --git a/packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts b/packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts index 01eea8fe1f4..dbe6dddee48 100644 --- a/packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts +++ b/packages/spec/src/migrations/entries/semantic/19.permission-view-all-modify-all-cast-no-field-vote.ts @@ -58,8 +58,9 @@ export const entry: SemanticMigration = { + 'STORED permission sets (Studio-saved, in `sys_metadata`): they are NOT rewritten on upgrade and are ' + 'read with the 19 meaning, by maintainer ruling. Studio\'s permission matrix has no `viewAllFields` ' + 'control today (it keeps the key when it saves a set that already carries it), so restore a stored ' - + 'set\'s reads by adding `viewAllFields: true` to its entry through the metadata API. No command lists ' - + 'the affected stored sets yet. The error direction is fewer fields seen, never a field opened.', + + 'set\'s reads by adding `viewAllFields: true` to its entry through the metadata API. ' + + '`os migrate meta --stored` lists every affected entry of a stored set (`viewAllFieldsReview`, read-only: ' + + 'it writes nothing). The error direction is fewer fields seen, never a field opened.', acceptanceCriteria: 'Before or after moving a deployment to protocol 19, the one-step check, for every permission set in ' + 'source and every one stored in the deployment: the set is ' @@ -69,7 +70,8 @@ export const entry: SemanticMigration = { + 'Modify All it does not restore a field the same set\'s own `readable: false` row hides: that row now ' + 'hides the field from the set\'s holders, so delete it where they should still read the field. Sets in ' + 'source: run `os migrate meta --from 18 --write`, which adds the bit to every such entry, then delete it ' - + 'where the set should NOT read fields another set hides. Stored sets: they are not rewritten and read ' + + 'where the set should NOT read fields another set hides. Stored sets: `os migrate meta --stored` lists ' + + 'each affected entry; they are not rewritten and read ' + 'with the 19 meaning; add the bit to each affected entry through the metadata API (Studio has no ' + 'control for it today). Then, where a Modify All holder must still EDIT a field, add an explicit ' + '`editable: true` field row in the set that should edit it: for a field another set locks, and for a ' From 9e5be7bb461274c8adf3204f2a179f86a485cf7d Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:54:38 +0000 Subject: [PATCH 061/178] chore(pm-dispatch): a new repository's charter lives in that repository; objectstack keeps a lanes/ pointer (#38522) 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)_ Part of #35238 Clause-②: no Metadata-protocol: none Rule-change: yes — a new repository's onboarding step changes: its seat charter is now written in that repository, and objectstack keeps only a pointer file under `lanes/` (before, objectstack wrote the charter itself). The text applies the maintainer's step-7 ruling quoted in the body of the parent card (「包括 hotcrm 每个仓库的规则都在自己仓库」, 2026-11-18), but the onboarding sentence itself is this PR's wording, so it is declared `yes`, not `ruled`. ## 维护者速读 - 用户无感:车队内部的接入说明里,新仓库的岗位规则从“写在本仓”改为“写在新仓库自己那里,本仓只留一个指路文件”。 - 属于“每个仓库的规则回到自己仓库”那一步,补上合并后的 hotcrm 指路改动留下的一句旧说法。 - 出错的影响只是下一个新仓库接入时规则写错地方,可直接撤回这一行。 - 要你做什么:本改动动了车队规则,需要你审阅并合并。 ## What changes **Round 2 (head `9d2dd69b34`):** a merge of `origin/main` (`63acc6cde5`, after #38480 landed) that resolves the adjacent-row conflict in the ratchet script by keeping both rows, plus body fixes from the review records. The net diff against `main` is still the same two hunks (+2 −2). One line of `.claude/skills/pm-dispatch/references/cross-repo-coordination.md` (line 9), and that file's ceiling row in `scripts/pm/check-skill-line-ratchet.mjs`. Before: ```text - 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、写 `lanes/.md` 宪章;应用仓无分诊席。 ``` After: ```text - 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、宪章住新仓(`lanes/.md` 仅指针);应用仓无分诊席。 ``` The first two steps and the closing clause (application repositories have no triage seat) are unchanged. The pointer form is the one `lanes/hotcrm.md` took in #38488. **Byte ceiling: raised 4920 → 4936 (+16, the landed bytes).** The file sat at headroom 0, and this wording, which names both halves (charter in the new repository; `lanes/.md` as a pointer only), costs 16 bytes more than the old third step. No other rule was trimmed to pay, per the dispatch order. The raise cites the ruled text it carries: the maintainer's step-7 ruling quoted in the body of card #35238 (「包括 hotcrm 每个仓库的规则都在自己仓库」, 2026-11-18 16:19–16:20Z). That ruling has no separate ruling-record comment id. The closest precedents for citing a ruling quoted in a card body with no record id are the `filing-gate.md` row (the rule card's body ruling) and the ratchet header's own citation of the ruling quoted in the body of card #35229. The `area-lease.md` row also names a record id, which this row does not. **Restatement sweep.** `grep` over `.claude/**` and `scripts/pm/` for 宪章, `lanes/.md`, `新仓` and "charter": the old step appears only on this line. Line 10 of the same file already says hotcrm's charter lives in hotcrm (`docs/PRIORITIES.md`). The English "charter" hits in `scripts/pm/` are unrelated senses (a gate's own purpose, the pm-dispatch skill as a whole). Nothing else to fix. ## Tests No behaviour changed (one prose line and one ceiling number), so there is no new test and no ablation. Read at head `9d2dd69b34`: - `node scripts/pm/check-skill-line-ratchet.mjs`: `.claude/skills/pm-dispatch/references/cross-repo-coordination.md is 4936 bytes (ceiling 4936; headroom 0)`, and the table-row pin for it reads 0 (pin 0). - `node scripts/pm/check-skill-line-ratchet.mjs --self-test`: `116 cases pass`. This is the only script that reads this file's size; no other script reads the sentence (grep for its words under `scripts/` finds nothing).
Derived gates (dispatch-gates --commands, 40 families): 40 exit 0, at head 9d2dd69b34 Round 2: all 40 ran in one `os-verify-lock.sh` call at head `9d2dd69b34` (VERDICT command-exit 0, held 1104s on a shared box). Before them, the same call built `@objectstack/lint` and its dependencies (exit 0), so `check:doc-formula-expressions` had its prerequisite. Every family exited 0, among them `pnpm check:pm-skill-ratchet`, `pnpm check:pm-dispatch-gates`, `pnpm --filter @objectstack/lint run check:doc-formula-expressions`, `pnpm check:skill-frame-sync`, `pnpm check:pm-governed-merges`, `pnpm check:pm-record-recognisers`, `pnpm check:nul-bytes` and `node scripts/pm/check-harness-current.mjs --self-test`. In round 1, `check:pm-dispatch-gates` and `check:doc-formula-expressions` were NOT MEASURED; both are measured now (delta contract review N3). `dispatch-gates --ran`: `40 derived famil(ies) accounted for — 40 run, 0 NOT-MEASURED`.
`overlap-check` at head `9d2dd69b34`: merges cleanly onto `origin/main` (`63acc6cde5`), with no open PR sharing a file. #38480, which edited the `triage-duties.md` row right below this row, merged at 07:49Z; the round-2 merge keeps that row as `main` has it and this row at 4936. ## Acceptance notes - `skip-changeset`: `.claude/**` and `scripts/pm/**` are not published, so the label goes on at creation. - The ceiling raise (+16) is explained under What changes. It needs the contract review to accept the citation, a ruling quoted in the card body. ## Verification Two-minute check: `node scripts/pm/check-skill-line-ratchet.mjs | grep cross-repo` prints `cross-repo-coordination.md is 4936 bytes (ceiling 4936; headroom 0)`. Then read line 9 of `.claude/skills/pm-dispatch/references/cross-repo-coordination.md` beside `references/lanes/hotcrm.md`. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. (no names added) - [x] 3. No formatter ran; `pnpm lint` passes. (CI runs `pnpm lint`) - [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. (publishes nothing: `skip-changeset`) - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (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. (the 维护者速读 block is in Chinese, as the fleet rules require) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oPfjnm2yWHEwkiYrn)_ Co-authored-by: Claude --- .../skills/pm-dispatch/references/cross-repo-coordination.md | 2 +- scripts/pm/check-skill-line-ratchet.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/skills/pm-dispatch/references/cross-repo-coordination.md b/.claude/skills/pm-dispatch/references/cross-repo-coordination.md index 76b6a7c650c..1246715f0a1 100644 --- a/.claude/skills/pm-dispatch/references/cross-repo-coordination.md +++ b/.claude/skills/pm-dispatch/references/cross-repo-coordination.md @@ -6,7 +6,7 @@ - 单车道仓 `repo:*` 席自理机械三务,⛔ 不产 `domain:*`;决策卡入本仓收件箱,不落 objectstack。 - 机械三务 = 自扫 sweep、自打 `type`、自做首触(含 `finding`;业务理由归召唤的总监席)。 - 新仓登记是一张清单:座位贴、标签、类别归属、门禁盘点、写身份锁移植(deny + hooks)。 -- 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、写 `lanes/.md` 宪章;应用仓无分诊席。 +- 新仓三件:加入 `GOVERNED_REPOS`、安装车队 App、宪章住新仓(`lanes/.md` 仅指针);应用仓无分诊席。 - 新仓准入只问一句:真需要常设席位吗;hotcrm 宪章住 hotcrm 仓 `docs/PRIORITIES.md`(The seat 节)。 - 车道可分席(席号 `· seat N`):忙时一车道开多席,闲时收归一席;每席独立座位贴。 - 认领评论带 `Seat: <席>#N` 行申报席号(缺省席 1);同席认领互斥,他席认领不触发自退。 diff --git a/scripts/pm/check-skill-line-ratchet.mjs b/scripts/pm/check-skill-line-ratchet.mjs index 97aac7c9cad..296f0c41dd8 100644 --- a/scripts/pm/check-skill-line-ratchet.mjs +++ b/scripts/pm/check-skill-line-ratchet.mjs @@ -111,7 +111,7 @@ export const CEILINGS = new Map([ ['.claude/skills/pm-dispatch/references/security-findings.md', 3934], ['.claude/skills/pm-dispatch/references/external-contributions.md', 2006], ['.claude/skills/pm-dispatch/references/reading-discipline.md', 3822], - ['.claude/skills/pm-dispatch/references/cross-repo-coordination.md', 4920], + ['.claude/skills/pm-dispatch/references/cross-repo-coordination.md', 4936], // raised 4920 → 4936 (+16, the landed bytes) by the ruled text (a new repository's charter lives in that repository; objectstack keeps a pointer file under `lanes/`), the maintainer's ruling quoted in the body of card #35238, step 7 (「包括 hotcrm 每个仓库的规则都在自己仓库」, 2026-11-18) ['.claude/skills/pm-dispatch/references/triage-duties.md', 13692], // lowered 13709 → 13692 by the decision-analysis tier-line PR (its pointer to the deleted worked 速读 example dropped); before that: edited byte-neutral by the re-basing PR (12399 → 12399); raised 12399 → 13559 (+1160, the landed bytes) by the rulings whose rows are written in it: ruling records 7031931263 (rows 2–5: 「adr接受你的建议」, 「只考虑合并没人认领的,没开始开发的,你负责处理」, 「影响评测的卡不能关,这个会影响到AI的开发效果」, 「adr和skills修改相对是重要的」), 7032145340 (row 6: 「同意」) and 7032418455 (row 7: 「你分诊的时候是不是应该同时评估大概的卡大小作为参考」); review record 7038100802 triggered the part of rows 2, 3 and 6 added in fix round 1 (one close reason, the sweep roll-over, the never-fold list of standing exclusions) and is a trigger, not a ruling; lowered 13559 → 13544 by the PR that moved the tier and effort values to the one home; raised 13544 → 13709 (+165, the landed bytes) by ruling record 7135874506 (items B4, B7 and C1: 「照推荐:采纳 5 条」) ['.claude/skills/pm-dispatch/references/execution-duties.md', 22249], // raised 19810 → 20148 (+338) by ruling records 7031931263 (row 2, the weekly ADR card: 「adr接受你的建议」) and 7032145340 (row 6, the lane seat claims the weekly sweep card: 「同意」); 20148 → 20154 (+6) by ruling record 7073679594 (the L2 review effort line moves to `high` on the review sweep's readings: 「C」, under ruling 7073045669 point 4); 20154 → 20277 (+123) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): a hold is Blocked-by + pm:blocked on the card, the probe covers card threads; 20277 → 22158 (+1881) by ruling record 7076315104 (the one home for tier and effort, the 定档 section: 「要把规则文字同统一整理一下,避免散落在各处,避免ai犯错」); raised 22158 → 22316 (+158) by ruling record 7076315104 (Q13, the decision card 「定一下:五条新增规则要不要写进技能」: 「五条都写」) (the coordinator session, the area thread and the director's effort); lowered 22316 → 22307 by the PR that drops the triage suggestion line (item C1 of ruling record 7135874506); lowered 22307 → 22249 to its landed size by the #35237 slice-12 pointer PR ['.claude/skills/pm-dispatch/references/filing-gate.md', 9124], // raised 9096 → 9101 (+5) by ruling record 7075909669 (#36203 items 1-5: 「同意五条都改」): same-epic order is the later card's Blocked-by; raised 8386 → 9096 (+710, the landed bytes) by the rulings whose rows are written in it: the rule card's body ruling (row 1, a dedupe hit on an open same-mechanism card ends in a comment: 「感觉你的第二种方案也很好啊」) and ruling record 7032145340 (row 6, the weekly sweep card entry rule and triage's move at first touch: 「同意」); review record 7038100802 triggered the quota line's pointer to row 1 (fix round 1) and is a trigger, not a ruling; lowered 9101 → 9089 by the PR that moved the tier and effort values to the one home; raised 9089 → 9124 (+35, the landed bytes) by ruling record 7135874506 (item A1: 「照推荐:采纳 5 条」) From e68d23b86353bf45d2c5b3cfe533d9d4e420d4a3 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:03:33 +0000 Subject: [PATCH 062/178] feat(console): the console reads and edits forms as form items (#38484) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #37087 Clause-②: yes Metadata-protocol: none Skills-docs: none — no metadata an author writes changes; the console reads and writes the `form` type card ② added. ## 维护者速读 - 用户能看到什么变化:Setup 的公开表单页看起来不变,只是改读改写表单类型;在 Studio 里打开一个表单(地址 `…/metadata/form/表单名`)就是表单设计器,能改字段、必填、分组、标题、地址和提交后的提示,存草稿再发布;控制台自己的表单页改读表单类型。表单类型暂不进 Studio 菜单(下一张 PR)。 - 为什么做:ADR-0159 把表单独立成 `form` 元数据,控制台要改读改写它,后面才能退役开发者页的公开表单页。 - 出错会怎样:最坏是某个表单在 Setup 里开关失败、或在 Studio 里存不上;设计器没有开关,保存和发布都按当时存着的开关写回,所以不会把 Setup 关掉的表单重新打开;匿名打开和提交不经这张 PR 的代码;可整体撤回。 - 要你做什么:契约审核(L2)未完成,先不用批;审核通过后席位会附审核记录请你批。 ## What changes ADR-0159 D9 for the console, card ③ PR 1 of 2 (the seat's claim 7248756424, amendment 7248849494). Every console surface here reads and writes the `form` type; the server's projection (ADR-0159 D5, completed by #38453) serves an old-shape form there too. 1. **Setup → Configuration → Public forms** (`ui/packages/app-shell/src/views/setup/`): the list read is `GET /meta/form`; the row reader takes the `form` item itself (no `viewKind` filter, no `config` hop). The two layered reads, the save paths, the reset and the override save name `form`. A switch saves `authorableForm(effective)` with `sharing.enabled` set: the read's `_` keys and the old shape's `data` are left out, since `FormSchema` refuses `data`. The shipped-off judgement reads the app's own document from the `form` layered read's `code` with the spec's `formExplicitlyWithdraws` (ADR-0159 D6 rule 6). A row whose app document cannot be read (`code: null`) is shown as status unknown and offers no switch. 2. **The #36784 designer becomes the `form` editor** (`studio-design/publicForm/`): `publicFormDesign.ts` reads and writes the top-level body. `PublicFormsDesigner.tsx` now holds `FormItemEditor`, which edits one form, and `FormItemPage`, registered as the `form` type's `EditPage` and `CreatePage`. It has no switch: `storedNow` reads `sharing.enabled` and `sharing.allowAnonymous` again at every save and publish, and a draft whose sharing differs is saved again before it is published. A form an installed app ships is saved as a declared override in the app's `.custom` pair. A form with no public link (one an action opens) is edited without an address. The new-name and address checks read the effective `form` list plus `form` drafts. The designer's own list and the Form-tab switch from #36784 are not carried over. 3. **List columns and registration** (`formListColumns.tsx`; the `form` resource is registered in `services/builtinComponents.tsx` beside the other lazy editor pages, so `metadata-admin/registry.ts` stays free of side effects): name (shows `title` when there is no `label`), label, object, public address and status. `/meta/types` serves no list layout for `form`, so these are the client's own `listColumns`. `form` stays out of Studio's menu. 4. **`FormPage`** (`ui/apps/console/src/components/FormPage.tsx`): the internal route reads `GET /api/v1/meta/form/NAME`. The anonymous route is unchanged. 5. **Strings**: new `engine.studio.publicForms.*` and `engine.list.col.publicAddress` / `publicState` keys in `./namespaces/studio` (en, zh). This PR removes no key. Outside the claimed file surface (reported to the seat): - `ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx`: one branch, so that a `form` item in a package's Studio area opens `FormItemPage` with the area's `customization`, `publishNonce` and `onDraftSaved`. Only the area's surface holds a read-only base's customization. Without it, an installed app's form could not be saved as its override. - `ui/packages/app-shell/src/services/builtinComponents.tsx`: the `form` resource's registration (`listColumns`, lazy `EditPage` / `CreatePage`). The claim named `metadata-admin/registry.ts`, but a registration there makes that module side-effectful and `check-side-effects-array` refuses it; every other editor page registers here. - `ui/packages/app-shell/src/views/runtime-metadata-persistence.ts`: `RuntimeArtifactType` gains `'form'`, and a `form` save invalidates the view caches the way a `view` save does, because Setup's switch goes through `saveAndPublishInPackage('form', …)`. Read first (by risk): 1. `studio-design/publicForm/PublicFormsDesigner.tsx`, `storedNow`, `save` and `publish`: the no-switch rule. 2. `setup/publicForms.ts`, `switchPublicForm` / `authorableForm` / `markShippedOff`: the body a switch writes over an old-shape form. 3. `studio-design/publicForm/publicFormDesign.ts`, `publicFormItemOf`: what is kept, and what is dropped (`data`, `viewKind`, `config`, `_` keys). ## Tests - `publicFormDesign.test.ts` (29): the top-level body both ways; a new form passes `FormSchema.safeParse`; an old-shape projected item is written back without `data` or `_formDefinedIn`; sharing is written as read (off stays off, an unchanged address keeps the stored `publicLink`, a changed one becomes `/forms/SLUG`); a form with no public link; `isPublicFormItem`. - `PublicFormsDesigner.test.tsx` (14, the #36784 tests re-pointed to the `form` shape): create, taken address and name, delete, the no-switch rule at save and at publish, the publish re-save of a draft whose sharing differs, reads that fail, a form with no public link, an old-shape save without `data`. Every write is asserted as type `form` with a body `FormSchema` accepts. - `setup/publicForms.test.ts`, `PublicFormsSetupPage.test.tsx`: the list read and both layered reads are `form`; the shipped-off judgement from the `form` layered `code`; a row whose app document cannot be read is status unknown with no switch; a switch over an old-shape row writes no `data`. - `FormPage.*` (about 30 files): the internal route reads `/meta/form/NAME`; the fixtures moved to the top-level body. - `PublicFormsDesigner.test.tsx` (+2, head `48a01c7ff7`, L2 S2): "shows the server's address refusal its own check missed (409 FORM_ADDRESS_TAKEN) as the address clash, at save and at publish" and "CONTROL: shows any other 409 as a pending draft". Ablation (the `FORM_ADDRESS_TAKEN` branch deleted): 1 failed, 15 passed, the failure is the address case (received the pending-draft sentence), the CONTROL stayed green; restored to the HEAD blob. - `FormPage.recordObject.test.tsx` (+1, L2 S3): "Log Time on a task: /meta/form/NAME is read, the form renders the record, and the submit writes it". The real `ActionRunner` runs `{type:'form', target:'showcase_task.edit'}` with record 42; FormPage reads exactly one `/api/v1/meta/form/showcase_task.edit` and no `/meta/view`, renders the record and PATCHes `/data/showcase_task/42`. ## Acceptance notes - Setup's address-clash refusal (`409 FORM_ADDRESS_TAKEN`) still shows one sentence that does not name the form holding the address: naming it needs a new key in all 11 locale files, outside this surface. Carrier: PR 2 of #37087, under claim amendment 7251711074 (card item 1, "shows the refusal with both names"; L2 S1, L1 R2). - A form an action opens: checked live on head `48a01c7ff7` and pinned by a test (see Verification, L2 S3). - This PR removes no translation key, so the removed-key probe is owed by PR 2. ## Remaining `formViews` / `viewKind: 'form'` hits under `ui/` Docblocks only in `FormPage.tsx`, `recordFormNavigation.ts`, `SchemaForm.tsx`, `clientValidation.ts`, `registry.ts`, `view-item-normalize.ts`, `freeze-schema.ts` and `imported-defaults.ts`; the view editor's own form arm (`anchors.ts`, `ViewPreview.tsx`, `view-item-normalize.ts`), which still edits a `view`; `MetadataProvider.tsx`, kept on purpose for packages that still ship forms in `views:`; and the developer `PublicFormsPage`, which PR 2 retires. ## Verification - Tests on head 83c51d8238: app-shell `ConditionWidget.conditionScope`, `studio-design/publicForm`, `StudioMetadataArea.*`, `views/setup` and `runtime-metadata-persistence.*`: 35 files, 458 passed. An earlier run of all of `views/metadata-admin`, `views/studio-design` and `views/setup` was red only on the conditionScope exhaustiveness check, while `form` was registered in `registry.ts`; moving the registration fixed it (the targeted run above). Also `packages/i18n` plus the console's `src/components` and the two form-page tests in `src/__tests__`: 173 files, 2618 passed, 13 skipped. - Type checks: `@object-ui/console` `type-check` exit 0 (after building its dependencies). - Gates: `dispatch-gates --commands` derived 28 families, each run and recorded; `--ran` reconciles 28 derived, 28 run, 0 NOT-MEASURED. `pnpm --dir ui exec vitest run scripts/` was killed by memory (SIGKILL, exit 1) while a build ran beside it; run again alone it exits 0, recorded as an extra line. - Dogfood (`examples/app-showcase`, `objectstack dev`, console dev server, signed in as the seeded admin): - Setup lists both showcase forms as `form` items, both on. Switching Contact off makes `GET /forms/contact-us` and its submit answer 404; switching it on again answers 200. - Studio opens the old-shape `showcase_inquiry.contact` at `/studio/com.example.showcase/metadata/form/showcase_inquiry.contact`. Removing `message` is refused (the object requires it). Adding `source` as required, removing `company` and retitling, then save and publish: the anonymous form serves the new title and fields, a submit without `source` answers `400 VALIDATION_FAILED`, with it `201`. - Off in Setup, then edited and published in Studio: the form stays off (404) and Setup still shows it off. Switched on again, it serves the newest title. - New form: the title Contact us is refused because its address is taken (confirm disabled); Demo signup is created in the app's `.custom` pair, published, and opens and accepts a submit (`201`). - Studio's `form` list shows the label/title, name, object, address and status columns. - Screenshots: `/mnt/project-files/card-37087/pr1-dogfood/` (seat 3's project files). - Patch round, head `48a01c7ff7` (L2 S2 and S3; the designer's 409 mapping, two tests, one changeset sentence): `PublicFormsDesigner.test.tsx`, `publicFormDesign.test.ts` and `FormPage.recordObject.test.tsx` 3 files, 55 passed; `@object-ui/app-shell` and `@object-ui/console` `type-check` exit 0; `pnpm --dir ui exec vitest run scripts/` 172 passed, 2 skipped. The server's refusal (`formAddressClashRefusal`, `packages/metadata-protocol/src/protocol-form-writes.ts`) carries status 409 and code `FORM_ADDRESS_TAKEN` and names the holder only in its prose, so the editor maps the code to the shipped `addressTaken` key (no structured holder for `addressTakenBy`; no key added). - Live check of a form an action opens (head `48a01c7ff7`, `examples/app-showcase`): on task "Build homepage", the header action Log Time (`showcase_log_time`, type `form`, target `showcase_task.form`) navigates to `/apps/com.example.showcase/forms/showcase_task.form?recordId=…&recordObject=showcase_task`; `GET /api/v1/meta/form/showcase_task.form` answers 200 and no `/meta/view/NAME` is read; the form renders prefilled; Submit sends `PATCH /api/v1/data/showcase_task/…` 200 and the record reads the new title. Screenshots and the network log: `/mnt/project-files/card-37087/pr1-dogfood/s3-*.png`, `s3-network.json`; the live 409 envelope: `s2-envelope-probe.txt` (project files of the seat 5 project). - Dogfood battery (`pnpm --filter @objectstack/dogfood test` under os-verify-lock, closure built as CI does, no shard, no path): head `d5581291b6` · VERDICT exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · failures: none. The head moved since by the patch round's four `ui/` files and the changeset only; none is in the dogfood closure. ## Ablation of the no-switch rule (L1-b R1, card Done-when "ablate: build the designer's save from the base's body") Measured at head `d5581291b6`, in a throwaway detached worktree, through `scripts/ablation-replace.mjs` (HEAD-blob restore with hash check), from the `ui/` root under os-verify-lock: `pnpm exec vitest run --maxWorkers=2 --reporter=verbose packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.test.ts`. - Ablation (one line, `PublicFormsDesigner.tsx`, the single point where both `save` and `publish` read the sharing through `storedNow`): the sharing is taken from the body as it was opened, `form.base.sharing`, before the effective, draft and code layers. - Baseline: 2 files passed, 43/43 tests (14 + 29). - Ablated: 2 failed, 41 passed. Red: - "has no switch: saves and publishes the form's sharing as it is stored at that time, not as it was when the form was opened" (`PublicFormsDesigner.test.tsx:376`, `expected true to be false` on `sharing.enabled`; the save leg); - "publishes an installed app's form with the switch as stored at the app, after it was switched off" (`PublicFormsDesigner.test.tsx:425`, the publish-time re-save carrying the switched-off sharing never happened; the publish leg). - `publicFormDesign.test.ts` stayed 29/29, as expected (`publicFormItemOf` writes whatever sharing it is handed). - Restored: blob `0e7cb3887b` equals HEAD, `git diff HEAD` empty, 43/43 green again. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibxQiu6MyZ2ngLJtA5Y --------- Co-authored-by: Claude --- .changeset/37087-console-reads-form-items.md | 15 + .../formPageRequiredMarker-10178.test.tsx | 7 +- .../src/__tests__/internalFormShell.test.tsx | 5 +- .../FormPage.conditionalRules.test.tsx | 9 +- ...rmPage.externalWriteRefusal-30334.test.tsx | 5 +- .../FormPage.fieldSpan-37559.test.tsx | 7 +- .../src/components/FormPage.fieldSpec.test.ts | 2 +- .../FormPage.formViewChrome-26843.test.tsx | 21 +- .../FormPage.inAppShell-13433.test.tsx | 22 +- .../FormPage.inlineLocaleEntry-13380.test.tsx | 7 +- .../FormPage.loadRefusal-29186.test.tsx | 5 +- .../components/FormPage.maxLength.test.tsx | 9 +- .../FormPage.notFound-27446.test.tsx | 2 +- .../FormPage.optionLabelLocale-26452.test.tsx | 7 +- .../FormPage.predicateScope.test.tsx | 11 +- .../src/components/FormPage.recordId.test.tsx | 21 +- .../components/FormPage.recordObject.test.tsx | 50 +- .../src/components/FormPage.redirect.test.tsx | 15 +- .../FormPage.refusalMarks-27417.test.tsx | 5 +- .../FormPage.refusalText-29019.test.tsx | 5 +- .../FormPage.retiredFieldType-10176.test.tsx | 5 +- .../FormPage.retiredWidget-10471.test.tsx | 5 +- .../FormPage.richTextHints-12110.test.tsx | 7 +- .../components/FormPage.sectionGroup.test.tsx | 5 +- .../FormPage.serverDefaults.test.tsx | 9 +- ...ormPage.sharedFieldResolver-10179.test.tsx | 5 +- .../FormPage.sharedWidgets-10179.test.tsx | 5 +- .../src/components/FormPage.submit.test.tsx | 13 +- .../FormPage.tabbedLayout-26843.test.tsx | 5 +- .../console/src/components/FormPage.test.ts | 129 +-- ui/apps/console/src/components/FormPage.tsx | 126 +-- ...ormPage.upfrontWriteRefusal-29187.test.tsx | 5 +- .../src/components/FormPage.viewSpec.test.ts | 30 +- .../components/FormPage.visibleWhen.test.tsx | 9 +- .../FormPage.visibleWhenFault-8069.test.tsx | 5 +- .../FormPage.widgetDegrade-10472.test.tsx | 5 +- .../FormPage.wizardSteps-27224.test.tsx | 5 +- .../src/services/builtinComponents.tsx | 21 + .../src/views/runtime-metadata-persistence.ts | 10 +- .../views/setup/PublicFormsSetupPage.test.tsx | 27 +- .../src/views/setup/PublicFormsSetupPage.tsx | 4 +- .../src/views/setup/publicForms.test.ts | 101 +- .../app-shell/src/views/setup/publicForms.ts | 143 +-- .../studio-design/StudioMetadataArea.tsx | 14 + .../publicForm/PublicFormsDesigner.test.tsx | 527 +++++++++ .../publicForm/PublicFormsDesigner.tsx | 1006 +++++++++++++++++ .../publicForm/formListColumns.tsx | 69 ++ .../publicForm/publicFormDesign.test.ts | 395 +++++++ .../publicForm/publicFormDesign.ts | 529 +++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 56 + ui/packages/i18n/src/namespaces/studio/zh.ts | 56 + 51 files changed, 3100 insertions(+), 461 deletions(-) create mode 100644 .changeset/37087-console-reads-form-items.md create mode 100644 ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/publicForm/formListColumns.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.test.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/publicForm/publicFormDesign.ts diff --git a/.changeset/37087-console-reads-form-items.md b/.changeset/37087-console-reads-form-items.md new file mode 100644 index 00000000000..8bbd154cbaa --- /dev/null +++ b/.changeset/37087-console-reads-form-items.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +feat(console): the console reads and edits forms as `form` items (objectstack#37087, ADR-0159) + +- **Setup → Public forms** lists and switches `form` items: the list is the `form` read, a switch saves the `form` item (its body with `sharing.enabled` set, without the `data` an old-shape form is served with), and "Restore package original" resets the `form` override. What the page shows is unchanged: every public form, on and off, its address and preview; a form its installed app ships switched off reads as off. A form whose app's own document cannot be read now offers no switch. +- **Studio's form editor**: the public form designer is the `form` type's editor (`EditPage` and `CreatePage`), with list columns for name, label, object, public address and status. It reads and writes the `form` item, whose body is at the top level, and has no switch: every save and publish writes `sharing.enabled` and `sharing.allowAnonymous` as they are stored at that moment, so a publish never opens a form Setup switched off. A form an installed app ships is saved as a declared override in the app's customization package. When the server refuses a save or publish because another form already uses the address, the editor says the address is taken, not that a draft is pending. The `form` type stays out of Studio's menu for now. +- **The console's own form page** (the signed-in one an action of type `form` opens) reads `GET /api/v1/meta/form/NAME`. The anonymous form route is unchanged. +- New `engine.studio.publicForms.*` and `engine.list.col.publicAddress` / `engine.list.col.publicState` strings in `./namespaces/studio` (en, zh). + +Clause-②: yes +Metadata-protocol: none diff --git a/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx b/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx index 6d6cd139cd2..7886d7e1aad 100644 --- a/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx +++ b/ui/apps/console/src/__tests__/formPageRequiredMarker-10178.test.tsx @@ -59,12 +59,11 @@ const OBJECT_SCHEMA = { }, }; -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'freeform', 'agree', 'optin'] }], }, @@ -89,7 +88,7 @@ async function renderForm() { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/__tests__/internalFormShell.test.tsx b/ui/apps/console/src/__tests__/internalFormShell.test.tsx index 564f073e0c6..55ba3cfef98 100644 --- a/ui/apps/console/src/__tests__/internalFormShell.test.tsx +++ b/ui/apps/console/src/__tests__/internalFormShell.test.tsx @@ -146,9 +146,8 @@ import { App } from '../App'; const INTERNAL_VIEW = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { type: 'simple', sections: [{ fields: ['title'] }] }, + ...{ type: 'simple', sections: [{ fields: ['title'] }] }, }; const OBJECT_SCHEMA = { name: 'showcase_task', fields: { title: { type: 'text', label: 'Title' } } }; const PUBLIC_FORM = { @@ -163,7 +162,7 @@ beforeEach(() => { vi.stubGlobal( 'fetch', vi.fn(async (url: string) => { - const body = String(url).includes('/meta/view/') + const body = String(url).includes('/meta/form/') ? INTERNAL_VIEW : String(url).includes('/meta/object/') ? OBJECT_SCHEMA diff --git a/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx b/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx index 62ccc876f07..9b832c69bbe 100644 --- a/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx +++ b/ui/apps/console/src/components/FormPage.conditionalRules.test.tsx @@ -76,14 +76,13 @@ function withRules(rules: Record>) { return { ...BASE_SCHEMA, fields }; } -/** Wrap sections in the `/meta/view/:name` envelope the internal route reads. */ -function viewEnvelope(sections: unknown[]) { +/** Wrap sections in the `/meta/form/:name` item the internal route reads. */ +function formItem(sections: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }; } @@ -134,7 +133,7 @@ function renderInternal(sections: unknown[], opts: RenderOpts = {}) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(sections) }, + { match: '/meta/form/', body: formItem(sections) }, { match: '/meta/object/', body: opts.objectSchema ?? BASE_SCHEMA }, ...(opts.extraRoutes ?? []), ]), diff --git a/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx b/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx index ccac444b655..556ada25067 100644 --- a/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx +++ b/ui/apps/console/src/components/FormPage.externalWriteRefusal-30334.test.tsx @@ -56,9 +56,8 @@ function stubInternal(refusal: { status: number; body: unknown }) { const view = { name: 'spare_parts.form', object: 'spare_parts', - viewKind: 'form', label: 'Spare part', - config: { type: 'simple', sections: [{ fields: ['name'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name'] }] }, }; const object = { name: 'spare_parts', label: 'Spare part', fields: FIELDS }; vi.stubGlobal( @@ -68,7 +67,7 @@ function stubInternal(refusal: { status: number; body: unknown }) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx b/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx index 31afb8e56fa..5760d5ab08b 100644 --- a/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx +++ b/ui/apps/console/src/components/FormPage.fieldSpan-37559.test.tsx @@ -41,13 +41,12 @@ const OBJECT_SCHEMA = { }, }; -function viewEnvelope(fields: unknown[], columns: number) { +function formItem(fields: unknown[], columns: number) { return { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { type: 'simple', sections: [{ label: 'Task', columns, fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', columns, fields }] }, }; } @@ -72,7 +71,7 @@ function renderForm(fields: unknown[], columns = 2) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(fields, columns) }, + { match: '/meta/form/', body: formItem(fields, columns) }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/components/FormPage.fieldSpec.test.ts b/ui/apps/console/src/components/FormPage.fieldSpec.test.ts index 779f226f1f2..5cfc2f2bbd5 100644 --- a/ui/apps/console/src/components/FormPage.fieldSpec.test.ts +++ b/ui/apps/console/src/components/FormPage.fieldSpec.test.ts @@ -15,7 +15,7 @@ * The measurement that chose the route: the console's copy was a strict subset * — 9 of the shared type's 26 keys, every one of them identical, none of them * console-only — sitting in a position that describes an **authored document** - * (`FormSectionSpec.fields`, read straight off `/meta/view/:name`), not a + * (`FormSectionSpec.fields`, read straight off `/meta/form/:name`), not a * narrower thing this app authors. The narrow, renderer-honoured shape is a * separate type that already exists here, `RenderableField`. So the two names * were one contract, and the console's copy simply described it wrongly: legal diff --git a/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx b/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx index 9d805433666..d691f84e9c6 100644 --- a/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx +++ b/ui/apps/console/src/components/FormPage.formViewChrome-26843.test.tsx @@ -34,25 +34,24 @@ const OBJECT_SCHEMA = { }, }; -function viewBody(form: Record) { - return { - name: 'showcase_inquiry.intake', - object: 'showcase_inquiry', - viewKind: 'form', - label: 'Intake', - config: { type: 'simple', sections: [{ fields: ['title', 'channel'] }], ...form }, - }; +function formBody(form: Record) { + return { type: 'simple', sections: [{ fields: ['title', 'channel'] }], ...form }; +} + +/** The `form` item `/meta/form/:name` serves: identity and body at the top level. */ +function formItem(form: Record) { + return { name: 'showcase_inquiry.intake', object: 'showcase_inquiry', label: 'Intake', ...formBody(form) }; } function stubFetch(form: Record) { return vi.fn(async (url: string) => { const path = String(url); - const body = path.includes('/meta/view/') - ? viewBody(form) + const body = path.includes('/meta/form/') + ? formItem(form) : path.includes('/meta/object/') ? OBJECT_SCHEMA : path.includes('/forms/intake') - ? { slug: 'intake', object: 'showcase_inquiry', form: viewBody(form).config, objectSchema: OBJECT_SCHEMA } + ? { slug: 'intake', object: 'showcase_inquiry', form: formBody(form), objectSchema: OBJECT_SCHEMA } : path.includes('/data/showcase_inquiry/r1') ? { record: { id: 'r1', title: 'Stored', channel: 'email' } } : null; diff --git a/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx b/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx index a57ad8a3df9..b2e3c88a2c1 100644 --- a/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx +++ b/ui/apps/console/src/components/FormPage.inAppShell-13433.test.tsx @@ -32,16 +32,14 @@ import { appRoutes } from '../AppContent'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** A container's default form: no view label, no form `title` — what Log Time opens. */ -const UNLABELLED_VIEW = { - name: 'showcase_task.form', - object: 'showcase_task', - viewKind: 'form', - config: { - type: 'simple', - sections: [{ name: 'task', label: 'Task details', fields: ['title'] }], - }, +const UNLABELLED_BODY = { + type: 'simple', + sections: [{ name: 'task', label: 'Task details', fields: ['title'] }], }; +/** A `form` item that names itself nowhere: no `label`, no `title`. */ +const UNLABELLED_VIEW = { name: 'showcase_task.form', object: 'showcase_task', ...UNLABELLED_BODY }; + const OBJECT_SCHEMA = { name: 'showcase_task', label: 'Task', @@ -65,7 +63,7 @@ function stubFetch(view: unknown = UNLABELLED_VIEW) { const method = (init?.method ?? 'GET').toUpperCase(); const u = String(url); let body: unknown; - if (u.includes('/meta/view/')) body = view; + if (u.includes('/meta/form/')) body = view; else if (u.includes('/meta/object/')) body = OBJECT_SCHEMA; else if (method === 'GET' && u.includes('/data/showcase_task/task-42')) body = GET_RESPONSE; else if (method === 'POST' && u.includes('/data/showcase_task')) body = POST_RESPONSE; @@ -127,14 +125,14 @@ describe('the heading of an internal form (objectui#13433)', () => { }); it('an authored form `title` heads the form', async () => { - vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, config: { ...UNLABELLED_VIEW.config, title: 'Log time' } })); + vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, title: 'Log time' })); renderInternal({ url: '/forms/showcase_task.form' }); expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(/^Log time$/); }); it('control: the view’s own label still wins', async () => { - vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, label: 'Quick edit', config: { ...UNLABELLED_VIEW.config, title: 'Log time' } })); + vi.stubGlobal('fetch', stubFetch({ ...UNLABELLED_VIEW, label: 'Quick edit', title: 'Log time' })); renderInternal({ url: '/forms/showcase_task.form' }); expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(/^Quick edit$/); @@ -191,7 +189,7 @@ describe('Cancel on an internal form (objectui#13433)', () => { ok: true, status: 200, statusText: 'OK', - json: async () => ({ object: 'showcase_task', form: UNLABELLED_VIEW.config, objectSchema: OBJECT_SCHEMA }), + json: async () => ({ object: 'showcase_task', form: UNLABELLED_BODY, objectSchema: OBJECT_SCHEMA }), text: async () => '', }) as unknown as Response), ); diff --git a/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx b/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx index 8e8d19148d6..2f1dc316964 100644 --- a/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx +++ b/ui/apps/console/src/components/FormPage.inlineLocaleEntry-13380.test.tsx @@ -98,12 +98,11 @@ const FORM = { const PUBLIC_PAYLOAD = { slug: 'support', object: API_NAME, form: FORM, objectSchema: CASE_SCHEMA }; -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'support_case.intake', object: API_NAME, - viewKind: 'form', label: 'Support', - config: FORM, + ...FORM, }; // ─── Harness ────────────────────────────────────────────────────────────── @@ -136,7 +135,7 @@ function renderSurface(surface: Surface, lang: Lang) { surface === 'public' ? [{ match: '/forms/support', body: PUBLIC_PAYLOAD }] : [ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: CASE_SCHEMA }, // The signed-in visitor's bundle, answered empty: the authored copy // is what renders. diff --git a/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx b/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx index 064ed963256..b2d3156c389 100644 --- a/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx +++ b/ui/apps/console/src/components/FormPage.loadRefusal-29186.test.tsx @@ -27,9 +27,8 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); const VIEW = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { type: 'simple', sections: [{ fields: ['title', 'hours'] }] }, + ...{ type: 'simple', sections: [{ fields: ['title', 'hours'] }] }, }; const OBJECT = { @@ -80,7 +79,7 @@ function openEdit(refusal: { status: number; body: unknown }) { writes += 1; return answer(true, 200, {}); } - if (String(url).includes('/meta/view/')) return answer(true, 200, VIEW); + if (String(url).includes('/meta/form/')) return answer(true, 200, VIEW); if (String(url).includes('/meta/object/')) return answer(true, 200, OBJECT); if (String(url).includes(`/data/showcase_task/${RECORD_ID}`)) { return answer(false, refusal.status, refusal.body); diff --git a/ui/apps/console/src/components/FormPage.maxLength.test.tsx b/ui/apps/console/src/components/FormPage.maxLength.test.tsx index a678aeb4a8a..a3d163bebd1 100644 --- a/ui/apps/console/src/components/FormPage.maxLength.test.tsx +++ b/ui/apps/console/src/components/FormPage.maxLength.test.tsx @@ -63,14 +63,13 @@ const OBJECT_SCHEMA = { }, }; -/** Wrap a section's fields in the `/meta/view/:name` envelope this route reads. */ -function viewEnvelope(fields: unknown[]) { +/** Wrap a section's fields in the `/meta/form/:name` item this route reads. */ +function formItem(fields: unknown[]) { return { name: 'showcase_task.intake', object: 'showcase_task', - viewKind: 'form', label: 'Task intake', - config: { type: 'simple', sections: [{ label: 'Task', fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields }] }, }; } @@ -96,7 +95,7 @@ function renderForm(fields: unknown[]) { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(fields) }, + { match: '/meta/form/', body: formItem(fields) }, { match: '/meta/object/', body: OBJECT_SCHEMA }, ]), ); diff --git a/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx b/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx index 834cfcbc507..ce5fbc138dd 100644 --- a/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx +++ b/ui/apps/console/src/components/FormPage.notFound-27446.test.tsx @@ -27,7 +27,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** Answers the `/meta/view` read with `status`; nothing else is reachable. */ function stubViewRead(status: number) { return vi.fn(async (url: string) => { - if (!String(url).includes('/meta/view/no_such_form')) throw new Error(`unstubbed fetch: ${url}`); + if (!String(url).includes('/meta/form/no_such_form')) throw new Error(`unstubbed fetch: ${url}`); const body = { error: { code: 'RESOURCE_NOT_FOUND', message: 'Metadata item not found or access denied.' } }; return { ok: status >= 200 && status < 300, diff --git a/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx b/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx index 5fee21f1492..bbf7460f6cb 100644 --- a/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx +++ b/ui/apps/console/src/components/FormPage.optionLabelLocale-26452.test.tsx @@ -46,12 +46,11 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.form', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'status', 'priority'] }], }, @@ -106,7 +105,7 @@ function json(body: unknown): Response { function stubServer(record: Record) { return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input instanceof Request ? input.url : input); - if (url.includes('/meta/view/')) return json(VIEW_ENVELOPE); + if (url.includes('/meta/form/')) return json(FORM_ITEM); if (url.includes('/meta/object/')) { const lang = new Headers(init?.headers).get('Accept-Language'); seenLanguages.push(lang); diff --git a/ui/apps/console/src/components/FormPage.predicateScope.test.tsx b/ui/apps/console/src/components/FormPage.predicateScope.test.tsx index 17664d205d5..aacfb5050bd 100644 --- a/ui/apps/console/src/components/FormPage.predicateScope.test.tsx +++ b/ui/apps/console/src/components/FormPage.predicateScope.test.tsx @@ -147,13 +147,12 @@ function withRules(rules: Record>) { return { ...BASE_SCHEMA, fields }; } -function viewEnvelope(sections: unknown[]) { +function formItem(sections: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }; } @@ -188,7 +187,7 @@ function renderInternalWithScope( vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: viewEnvelope(sections) }, + { match: '/meta/form/', body: formItem(sections) }, { match: '/meta/object/', body: objectSchema }, ]), ); @@ -398,8 +397,8 @@ describe('#6110 hop 1 — `/forms/:name` publishes the SESSION principal', () => 'fetch', stubFetch([ { - match: '/meta/view/', - body: viewEnvelope([ + match: '/meta/form/', + body: formItem([ { label: 'Basics', fields: ['priority'] }, { label: 'Compensation', visibleWhen: GATE, fields: ['notes'] }, ]), diff --git a/ui/apps/console/src/components/FormPage.recordId.test.tsx b/ui/apps/console/src/components/FormPage.recordId.test.tsx index 256df603402..7face78183e 100644 --- a/ui/apps/console/src/components/FormPage.recordId.test.tsx +++ b/ui/apps/console/src/components/FormPage.recordId.test.tsx @@ -51,13 +51,12 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -/** The FormView metadata `/meta/view/:name` serves — `showcase_task.edit`. */ -const VIEW_ENVELOPE = { +/** The FormView metadata `/meta/form/:name` serves — `showcase_task.edit`. */ +const FORM_ITEM = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'hours'] }], }, @@ -158,7 +157,7 @@ function renderInternal(query = '') { /** The happy-path route table: metadata + object schema + the record read. */ function editRoutes(extra: Parameters[0] = []) { return stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/task-42', body: GET_RESPONSE }, { method: 'PATCH', match: '/data/showcase_task/task-42', body: PATCH_RESPONSE }, @@ -239,7 +238,7 @@ describe('?recordId= makes the internal form an EDIT (ruling point 1)', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/task-42', body: GET_RESPONSE }, { @@ -280,7 +279,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 404, statusText: 'Not Found' }, ]), @@ -299,7 +298,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 403, statusText: 'Forbidden' }, ]), @@ -312,7 +311,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', @@ -336,7 +335,7 @@ describe('a recordId this route cannot honour FAILS CLOSED (ruling point 2)', () vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/', status: 404, statusText: 'Not Found' }, ]), @@ -383,7 +382,7 @@ describe('control: no recordId ⇒ the create path is unchanged', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { method: 'POST', diff --git a/ui/apps/console/src/components/FormPage.recordObject.test.tsx b/ui/apps/console/src/components/FormPage.recordObject.test.tsx index 16ab9997b70..06e14824d1d 100644 --- a/ui/apps/console/src/components/FormPage.recordObject.test.tsx +++ b/ui/apps/console/src/components/FormPage.recordObject.test.tsx @@ -56,17 +56,17 @@ import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { createI18n } from '@object-ui/i18n'; +import { ActionRunner } from '@object-ui/core'; import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** `showcase_task.edit` — the FormView the mis-scoped action targets. */ -const VIEW_ENVELOPE = { +const FORM_ITEM = { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title', 'hours'] }], }, @@ -152,7 +152,7 @@ function renderInternal(query = '') { /** The happy-path route table: metadata + object schema + the record read. */ function editRoutes(extra: Parameters[0] = []) { return stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/42', body: GET_RESPONSE }, { @@ -210,7 +210,7 @@ describe('a recordObject naming another object FAILS CLOSED (#4292)', () => { // is compared against, so it cannot be known any earlier. Everything after // that point is skipped, including the object schema. expect(calls.filter((c) => c.url.includes('/data/'))).toHaveLength(0); - expect(calls.map((c) => c.url).filter((u) => u.includes('/meta/view/'))).toHaveLength(1); + expect(calls.map((c) => c.url).filter((u) => u.includes('/meta/form/'))).toHaveLength(1); }); it('and no write can follow, since there is no form to submit', async () => { @@ -280,7 +280,7 @@ describe('control: recordId with NO recordObject keeps #4278 behaviour', () => { vi.stubGlobal( 'fetch', stubFetch([ - { match: '/meta/view/', body: VIEW_ENVELOPE }, + { match: '/meta/form/', body: FORM_ITEM }, { match: '/meta/object/', body: OBJECT_SCHEMA }, { match: '/data/showcase_task/42', @@ -333,3 +333,41 @@ describe('control: the PUBLIC /f/:slug path ignores recordObject too', () => { expect(screen.queryByText(/Refusing to open it/)).not.toBeInTheDocument(); }); }); + +/** + * objectstack#37087 (ADR-0159 D9) — an action of type `form` opens its form, + * read as a `form` item. The real `ActionRunner` produces the URL a record's + * Log Time button navigates to; this route, mounted where the console mounts + * it, reads the form at `GET /api/v1/meta/form/NAME` (never `/meta/view`), + * renders it with the record's values, and submits. + */ +describe('an action of type `form` opens its form through the `form` read (#37087)', () => { + it('Log Time on a task: /meta/form/NAME is read, the form renders the record, and the submit writes it', async () => { + const runner = new ActionRunner({ record: { id: '42' }, objectName: 'showcase_task' }); + let to = ''; + runner.setNavigationHandler((url) => { + to = url; + }); + await runner.execute({ type: 'form', target: 'showcase_task.edit' }); + expect(to).toBe('/forms/showcase_task.edit?recordId=42&recordObject=showcase_task'); + + vi.stubGlobal('fetch', editRoutes()); + render( + + + } /> + record page
} /> + + , + ); + + expect(await screen.findByLabelText(/Title/)).toHaveValue('Write the report'); + const metaReads = calls.filter((c) => c.method === 'GET' && c.url.includes('/meta/')).map((c) => c.url); + expect(metaReads.filter((u) => u.endsWith('/api/v1/meta/form/showcase_task.edit'))).toHaveLength(1); + expect(metaReads.filter((u) => u.includes('/meta/view'))).toHaveLength(0); + + await userEvent.click(screen.getByRole('button', { name: /Submit/ })); + await waitFor(() => expect(calls.some((c) => c.method === 'PATCH')).toBe(true)); + expect(calls.find((c) => c.method === 'PATCH')!.url).toContain('/data/showcase_task/42'); + }); +}); diff --git a/ui/apps/console/src/components/FormPage.redirect.test.tsx b/ui/apps/console/src/components/FormPage.redirect.test.tsx index 8ec3d1993ba..a29256d8e23 100644 --- a/ui/apps/console/src/components/FormPage.redirect.test.tsx +++ b/ui/apps/console/src/components/FormPage.redirect.test.tsx @@ -55,13 +55,12 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); /** The console mount the framework CLI configures for an embedded deployment. */ const MOUNT = '/_console'; -function viewEnvelope(submitBehavior: unknown) { +function formItem(submitBehavior: unknown) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title'] }], submitBehavior, @@ -170,7 +169,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -217,7 +216,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks?ref={{record.id}}' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks?ref={{record.id}}' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -237,7 +236,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/t/{{record.slug}}' }), + '/meta/form/': formItem({ kind: 'redirect', url: '/t/{{record.slug}}' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': { ...CREATE_RESPONSE, @@ -282,7 +281,7 @@ describe('a ruled relative url is an in-shell route', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: '/thanks', delayMs: 60 }), + '/meta/form/': formItem({ kind: 'redirect', url: '/thanks', delayMs: 60 }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -306,7 +305,7 @@ describe('an out-of-contract destination is refused, not followed', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'redirect', url: 'https://example.com/thanks' }), + '/meta/form/': formItem({ kind: 'redirect', url: 'https://example.com/thanks' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), diff --git a/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx b/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx index 95db4a078ab..488144c6881 100644 --- a/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx +++ b/ui/apps/console/src/components/FormPage.refusalMarks-27417.test.tsx @@ -95,9 +95,8 @@ function stubInternal(refusal: { status: number; body: unknown }) { const view = { name: 'showcase_inquiry.contact', object: 'showcase_inquiry', - viewKind: 'form', label: 'Contact', - config: { type: 'simple', sections: [{ fields: ['name', 'email', 'company'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email', 'company'] }] }, }; const object = { name: 'showcase_inquiry', label: 'Inquiry', fields: FIELDS }; vi.stubGlobal( @@ -115,7 +114,7 @@ function stubInternal(refusal: { status: number; body: unknown }) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx b/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx index d57aa5b3747..c5215005d2f 100644 --- a/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx +++ b/ui/apps/console/src/components/FormPage.refusalText-29019.test.tsx @@ -64,9 +64,8 @@ function stubInternal(refusal: Refusal) { const view = { name: 'qar8_fsb.form', object: 'qar8_fsb', - viewKind: 'form', label: 'Feedback', - config: { type: 'simple', sections: [{ fields: ['name', 'email'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email'] }] }, }; const object = { name: 'qar8_fsb', label: 'Feedback', fields: FIELDS }; vi.stubGlobal( @@ -76,7 +75,7 @@ function stubInternal(refusal: Refusal) { posts += 1; return answer(false, refusal.status, refusal.body); } - if (String(url).includes('/meta/view/')) return answer(true, 200, view); + if (String(url).includes('/meta/form/')) return answer(true, 200, view); if (String(url).includes('/meta/object/')) return answer(true, 200, object); throw new Error(`unstubbed fetch: ${url}`); }), diff --git a/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx b/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx index 78b8344dced..4557555fbce 100644 --- a/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx +++ b/ui/apps/console/src/components/FormPage.retiredFieldType-10176.test.tsx @@ -108,13 +108,12 @@ const ROUTES = [ render: () => { stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: FIELD_NAMES }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx b/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx index 01c789c5c85..2b83e94c730 100644 --- a/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx +++ b/ui/apps/console/src/components/FormPage.retiredWidget-10471.test.tsx @@ -109,13 +109,12 @@ const ROUTES = [ render: () => { stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: SECTION_FIELDS }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: SECTION_FIELDS }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx b/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx index f3ac22bd9e9..be3cb7720f1 100644 --- a/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx +++ b/ui/apps/console/src/components/FormPage.richTextHints-12110.test.tsx @@ -100,7 +100,7 @@ function stubFetch(routes: Array<{ match: string; body: unknown }>) { /** * Render one of the two routes over the same object and the same section: * the anonymous `/f/:slug` page (`GET /forms/:slug`), or the authed internal - * `/forms/:name` page (`GET /meta/view/:name` + `GET /meta/object/:name`). + * `/forms/:name` page (`GET /meta/form/:name` + `GET /meta/object/:name`). */ function renderSurface(surface: Surface) { if (surface === 'public') { @@ -135,13 +135,12 @@ function renderSurface(surface: Surface) { 'fetch', stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'hc_case.intake', object: 'hc_case', - viewKind: 'form', label: 'Case intake', - config: { type: 'simple', sections: [{ label: 'Request', fields: SECTION_FIELDS }] }, + ...{ type: 'simple', sections: [{ label: 'Request', fields: SECTION_FIELDS }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx b/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx index 8f29489ae82..f842f84793f 100644 --- a/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx +++ b/ui/apps/console/src/components/FormPage.sectionGroup.test.tsx @@ -134,13 +134,12 @@ function renderInternal(sections: unknown[], type = 'simple') { 'fetch', stubFetch([ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'ticket.edit', object: 'ticket', - viewKind: 'form', label: 'Ticket', - config: { type, sections }, + ...{ type, sections }, }, }, { match: '/meta/object/', body: TICKET }, diff --git a/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx b/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx index ea585c844bd..a2215ae5e48 100644 --- a/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx +++ b/ui/apps/console/src/components/FormPage.serverDefaults.test.tsx @@ -107,13 +107,12 @@ const OBJECT_SCHEMA = { const FIELD_NAMES = ['title', 'status', 'owner', 'remind_at', 'priority', 'stage']; -function viewEnvelope() { +function formItem() { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections: [{ label: 'Task', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields: FIELD_NAMES }] }, }; } @@ -184,7 +183,7 @@ function renderPublic() { } const CREATE_ROUTES = { - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }; @@ -338,7 +337,7 @@ describe('counter-probes — what the filter must NOT eat', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task/task-7': STORED_RECORD, }), diff --git a/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx b/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx index 7916488d934..4b8558ab669 100644 --- a/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx +++ b/ui/apps/console/src/components/FormPage.sharedFieldResolver-10179.test.tsx @@ -71,13 +71,12 @@ vi.mock('@object-ui/fields', async (importOriginal) => { function renderForm(objectFields: Record, viewFields: unknown[]) { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, }, }, { match: '/meta/object/', body: { name: 'probe', label: 'Probe', fields: objectFields } }, diff --git a/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx b/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx index d70861c5fb3..dd86817c0e7 100644 --- a/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx +++ b/ui/apps/console/src/components/FormPage.sharedWidgets-10179.test.tsx @@ -98,13 +98,12 @@ let writes: Array<{ method: string; body: Record }> = []; function stubFetch() { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'showcase_order.intake', object: 'showcase_order', - viewKind: 'form', label: 'Order intake', - config: { type: 'simple', sections: [{ label: 'Order', fields: FIELD_NAMES }] }, + ...{ type: 'simple', sections: [{ label: 'Order', fields: FIELD_NAMES }] }, }, }, { match: '/meta/object/', body: OBJECT_SCHEMA }, diff --git a/ui/apps/console/src/components/FormPage.submit.test.tsx b/ui/apps/console/src/components/FormPage.submit.test.tsx index e126f348728..8bb40382fec 100644 --- a/ui/apps/console/src/components/FormPage.submit.test.tsx +++ b/ui/apps/console/src/components/FormPage.submit.test.tsx @@ -36,14 +36,13 @@ import { FormPage } from './FormPage'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -/** The FormView metadata `/meta/view/:name` serves for the internal path. */ -function viewEnvelope(submitBehavior?: unknown) { +/** The FormView metadata `/meta/form/:name` serves for the internal path. */ +function formItem(submitBehavior?: unknown) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Log Time', - config: { + ...{ type: 'simple', sections: [{ label: 'Task', fields: ['title'] }], ...(submitBehavior ? { submitBehavior } : {}), @@ -158,7 +157,7 @@ describe('internal submit — default behaviour (ruling point 2)', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), @@ -192,7 +191,7 @@ describe('internal submit — default behaviour (ruling point 2)', () => { vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope(), + '/meta/form/': formItem(), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': { object: 'showcase_task', record: { title: 'x' } }, }), @@ -212,7 +211,7 @@ describe('an explicitly declared submitBehavior still wins (ruling point 3)', () vi.stubGlobal( 'fetch', stubFetch({ - '/meta/view/': viewEnvelope({ kind: 'thank-you', title: 'Logged', message: 'Time saved.' }), + '/meta/form/': formItem({ kind: 'thank-you', title: 'Logged', message: 'Time saved.' }), '/meta/object/': OBJECT_SCHEMA, '/data/showcase_task': CREATE_RESPONSE, }), diff --git a/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx b/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx index 24b63d10300..43dfa4ab8fe 100644 --- a/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx +++ b/ui/apps/console/src/components/FormPage.tabbedLayout-26843.test.tsx @@ -48,13 +48,12 @@ function stubFetch(form: Record, objectSchema: unknown = OBJECT if (init?.method === 'POST') { submits.push({ url: path, body: JSON.parse(String(init.body)) }); } - const body = path.includes('/meta/view/') + const body = path.includes('/meta/form/') ? { name: 'showcase_ticket.intake', object: 'showcase_ticket', - viewKind: 'form', label: 'Intake', - config: { type: 'tabbed', sections: THREE_SECTIONS, ...form }, + ...{ type: 'tabbed', sections: THREE_SECTIONS, ...form }, } : path.includes('/meta/object/') ? objectSchema diff --git a/ui/apps/console/src/components/FormPage.test.ts b/ui/apps/console/src/components/FormPage.test.ts index ec73e2024fe..7ffba17e08e 100644 --- a/ui/apps/console/src/components/FormPage.test.ts +++ b/ui/apps/console/src/components/FormPage.test.ts @@ -689,121 +689,56 @@ describe('readLoadedRecord', () => { }); /** - * objectui#2208 — the server's `/meta/view/:name` returns the flattened - * ExpandedViewItem envelope `{ name, object, viewKind, label, config }`; - * the form spec lives under `config`. Pre-fix the loader read sections off - * the envelope itself → every internal form rendered zero fields + a bare - * Submit that "succeeded". List views reaching the forms route (the - * framework#2554 collision fallout) rendered the same false positive - * instead of an actionable error. + * objectstack#37087 (ADR-0159) — the internal route reads `/meta/form/:name`, + * which serves a `form` item: identity and form body at the top level (no + * `config` wrapper, ruled question 5), an old-shape form included (the + * server's projection, D5). objectui#2208's false positive (zero fields and a + * bare Submit) cannot come back through a `config` hop, because there is none; + * a list name answers `404` on the `form` read (`FormPage.notFound-27446`). */ describe('resolveInternalForm', () => { - const envelope = { + const formItem = { name: 'showcase_task.tabbed', object: 'showcase_task', - viewKind: 'form', label: 'Tabbed', - scope: 'package', - config: { - type: 'tabbed', - data: { provider: 'object', object: 'showcase_task' }, - sections: [{ name: 'overview', label: 'Overview', fields: ['title', 'status'] }], - }, + type: 'tabbed', + sections: [{ name: 'overview', label: 'Overview', fields: ['title', 'status'] }], }; - it('unwraps the ExpandedViewItem envelope: form spec comes from config', () => { - const out = resolveInternalForm('showcase_task.tabbed', envelope); + it('reads the form body, the object and the label off the `form` item itself', () => { + const out = resolveInternalForm('showcase_task.tabbed', formItem); expect(out.form.type).toBe('tabbed'); expect(out.form.sections).toHaveLength(1); expect(out.label).toBe('Tabbed'); expect(out.object).toBe('showcase_task'); }); - it('accepts the { item: envelope } wrapper', () => { - const out = resolveInternalForm('showcase_task.tabbed', { item: envelope }); + it('accepts the { item } wrapper', () => { + const out = resolveInternalForm('showcase_task.tabbed', { item: formItem }); expect(out.form.sections).toHaveLength(1); expect(out.object).toBe('showcase_task'); }); - // objectui#13433 — no fallback to the view NAME: a form that names itself + // objectui#13433 — no fallback to the form NAME: a form that names itself // nowhere is headed by its object's label, resolved by `FormPage` at render - // (`FormPage.inAppShell-13433.test.tsx`). The raw qualified name was what - // the showcase's Log Time page was headed by. - it('answers no label when neither envelope nor config carry one, rather than the view name', () => { - const { label: _l, ...noLabel } = envelope; - const out = resolveInternalForm('showcase_task.tabbed', noLabel); - expect(out.label).toBeUndefined(); - }); - - it('reads the form config’s `title` when the envelope carries no label', () => { - const { label: _l, ...noLabel } = envelope; - const out = resolveInternalForm('showcase_task.tabbed', { - ...noLabel, - config: { ...noLabel.config, title: 'Tabbed edit' }, - }); - expect(out.label).toBe('Tabbed edit'); - }); - - it('throws an actionable error for a non-form view instead of rendering an empty form', () => { - const listView = { - name: 'showcase_task.default', - object: 'showcase_task', - viewKind: 'list', - label: 'All Tasks', - config: { type: 'grid', data: { provider: 'object', object: 'showcase_task' }, columns: ['title'] }, - }; - expect(() => resolveInternalForm('showcase_task.default', listView)).toThrow(/list view, not a form view/); - }); - - it('throws for a flattened runtime-overlay list row that lost its viewKind (framework#2555 fallout)', () => { - // A personalization PUT persisted the raw config at the top level; the - // pre-heal server returns it with name/object/label but NO viewKind and - // NO config envelope. It must not pass for a legacy bare form spec. - const pollutedOverlay = { - name: 'showcase_task.default', - object: 'showcase_task', - label: 'All Tasks', - type: 'grid', - data: { provider: 'object', object: 'showcase_task' }, - columns: [{ field: 'title' }], - sort: [{ id: '29200fa8-c416-471e-9ca3-913f9308ad89', field: 'estimate_hours', order: 'desc' }], - }; - expect(() => resolveInternalForm('showcase_task.default', pollutedOverlay)).toThrow(/grid view, not a form view/); - }); - - it('throws for a flattened list body whose viewKind sits at the top level (healed overlay row)', () => { - const healedOverlay = { - name: 'showcase_task.default', - object: 'showcase_task', - viewKind: 'list', - label: 'All Tasks', - type: 'grid', - data: { provider: 'object', object: 'showcase_task' }, - columns: [{ field: 'title' }], - }; - expect(() => resolveInternalForm('showcase_task.default', healedOverlay)).toThrow(/list view, not a form view/); - }); - - it('still accepts a bare legacy form spec (no envelope)', () => { - const bare = { - type: 'simple', - label: 'Quick Edit', - data: { provider: 'object', object: 'task' }, - sections: [{ label: 'Main', fields: ['title'] }], - }; - const out = resolveInternalForm('task.quick', bare); - expect(out.form).toBe(bare as any); - expect(out.label).toBe('Quick Edit'); - // object resolved from the spec's data binding - expect(out.object).toBe('task'); - }); - - it('accepts the legacy { item: { spec } } wrapper', () => { - const out = resolveInternalForm('task.quick', { - item: { spec: { type: 'simple', object: 'task', sections: [] } }, - }); - expect(out.object).toBe('task'); - expect(out.form.type).toBe('simple'); + // (`FormPage.inAppShell-13433.test.tsx`). + it('answers no label when the item carries neither label nor title, rather than the name', () => { + const { label: _l, ...noLabel } = formItem; + expect(resolveInternalForm('showcase_task.tabbed', noLabel).label).toBeUndefined(); + }); + + it('reads the form’s `title` when the item carries no label, and the label before the title', () => { + const { label: _l, ...noLabel } = formItem; + expect(resolveInternalForm('showcase_task.tabbed', { ...noLabel, title: 'Tabbed edit' }).label).toBe('Tabbed edit'); + expect(resolveInternalForm('showcase_task.tabbed', { ...formItem, title: 'Tabbed edit' }).label).toBe('Tabbed'); + }); + + it('reads the object from the item’s `object` binding only — a `config` wrapper is not unwrapped', () => { + // The old `view` envelope: nothing is read from under `config`. + const old = { name: 'showcase_task.tabbed', viewKind: 'form', config: { type: 'tabbed', data: { provider: 'object', object: 'showcase_task' }, sections: [] } }; + const out = resolveInternalForm('showcase_task.tabbed', old); + expect(out.object).toBeUndefined(); + expect(out.form.sections).toBeUndefined(); }); }); diff --git a/ui/apps/console/src/components/FormPage.tsx b/ui/apps/console/src/components/FormPage.tsx index 9b116902d44..d9153e9e07f 100644 --- a/ui/apps/console/src/components/FormPage.tsx +++ b/ui/apps/console/src/components/FormPage.tsx @@ -3,7 +3,7 @@ /** * FormPage — single component that renders a FormView either as a public * anonymous form (`/f/:slug` → backend `GET/POST /api/v1/forms/:slug`) or - * as an authed internal form (`/forms/:name` → `GET /api/v1/meta/view/:name` + * as an authed internal form (`/forms/:name` → `GET /api/v1/meta/form/:name` * + `POST /api/v1/data/:object`). * * Both modes share the same renderer; the difference is only in how the @@ -286,36 +286,22 @@ interface ObjectFieldDef { } /** - * The form layouts a form view declares (FormViewSpec.type) — `simple`, - * `tabbed` and `wizard` since ADR-0050 (#27155 / #27159): `split`, `drawer` - * and `modal` left the enum, and the spec refuses each at parse. - */ -const FORM_SPEC_TYPES = new Set(['simple', 'tabbed', 'wizard']); - -/** - * The form CONFIG plus the view identity that travels beside it (objectui#5596). + * The form body plus the identity label that travels beside it (objectui#5596). * * {@link FormViewSpec} is the converged form contract and carries no `label`: * `@objectstack/spec`'s `FormViewSchema` REJECTS that key outright - * (`unrecognized_keys`, measured against the installed 17.0.0) — a form config + * (`unrecognized_keys`, measured against the installed 17.0.0) — a form body * says `title`, not `label`. Until #5596 this file's hand copy declared `label` * on the form type, which read as "a FormView may be labelled" and is not true. * - * The value those reads actually find is the VIEW's identity label, and both - * bodies this renderer accepts carry it one way or another: - * - * - the `ExpandedViewItem` envelope (#2208) puts it beside `config`, and - * {@link resolveInternalForm} already reads it from there; - * - a FLATTENED runtime overlay has no envelope at all — the config and the - * identity share one object, which is exactly what the spec publishes as - * `VIEW_METADATA_MEMBERS.formOverlay` (`FormViewSchema` extended with - * `label` / `object` / `viewKind` / ...). On that branch `form === body`, so - * the label is reachable through the form variable. + * The value that read finds is the form's identity label: a `form` item + * (ADR-0159 D2) carries `label` beside its body at the top level, its name in + * lists, so the body {@link resolveInternalForm} hands the renderer carries it. * * So the key is declared HERE, on the body this renderer unwraps, and not on the * form contract shared with `packages/app-shell`. Narrowed to `string` because - * every read below assigns it into a `string` slot; the spec's own overlay types - * it `I18nLabel`, whose inline locale-map arm this renderer resolves for a field + * every read below assigns it into a `string` slot; the spec types it + * `I18nLabel`, whose inline locale-map arm this renderer resolves for a field * entry's copy ({@link buildSections}, objectui#13380) but not for this label. */ type FormViewBody = FormViewSpec & { label?: string }; @@ -1788,77 +1774,49 @@ async function loadPublicForm(slug: string): Promise { } /** - * Unwrap a `/meta/view/:name` response into the {@link FormViewBody} the renderer - * consumes. Since the ADR-0017 registrar the server returns the flattened - * ExpandedViewItem envelope — `{ name, object, viewKind, label, config: - * { type, sections, … } }` — with the actual form spec nested under - * `config`. Pre-fix, this loader read `sections`/`label` off the envelope - * itself and rendered every internal form as zero fields plus a bare - * Submit that "succeeded" (objectui#2208). Older servers / seeded rows may - * still serve `{ item: { spec } }` or the bare spec, so all shapes are - * accepted. - * - * Also rejects non-form views loudly: a list-view name reaching this route - * (e.g. an action target hit by the framework#2554 key collision) used to - * render as that same empty-form false positive. + * Unwrap a `/meta/form/:name` response into the {@link FormViewBody} the + * renderer consumes (ADR-0159, objectstack#37087). The `form` read serves a + * `form` item: its identity (`name`, `object`, `label`) and its form body at + * the top level (ADR-0159 ruled question 5: no `config` wrapper). An old-shape + * form (a container's `form`, a `formViews` entry, a `viewKind: 'form'` item) + * is served in the same shape, through the server's one projection + * (ADR-0159 D5), so this page reads one shape only. The read answers the + * item bare or as `{ item }`. + * + * A name that is no form (a list view's, an action target that names a list) + * answers `404` on the `form` read, so it reaches the not-found state, never an + * empty form (objectui#2208's false positive). */ export function resolveInternalForm( - name: string, - viewBody: unknown, + // The name the page was opened with: the `form` read already answered for it. + _name: string, + formBody: unknown, ): { label: string | undefined; object?: string; form: FormViewBody } { - const body = viewBody as Record | null; - const item = body?.item ?? body; - const spec = item?.spec ?? item; - const isEnvelope = - spec && typeof spec === 'object' - && spec.config && typeof spec.config === 'object' - && ('viewKind' in spec || 'object' in spec); - // viewKind may sit on the envelope OR on a flattened list-view body - // (runtime personalization overlays are persisted with the config at the - // top level), so read it wherever it is. - const viewKind: string | undefined = - spec && typeof spec === 'object' ? spec.viewKind : undefined; - if (viewKind && viewKind !== 'form') { - throw new Error( - `View "${name}" is a ${viewKind} view, not a form view — check the action or link that targets it.`, - ); - } - const form: FormViewBody = isEnvelope ? spec.config : spec; - // A flattened list config carries no viewKind at all but declares a grid/ - // kanban/… visualization type no form renderer understands — same false - // positive, same loud failure. - if (!viewKind && form && typeof form === 'object' && typeof form.type === 'string' - && !FORM_SPEC_TYPES.has(form.type)) { - throw new Error( - `View "${name}" is a ${form.type} view, not a form view — check the action or link that targets it.`, - ); - } + const body = formBody as Record | null; + const form: FormViewBody = body?.item ?? body; return { - // The view's identity label, then the form config's `title` — the same - // order `loadPublicForm` reads the public payload in (objectui#8408), and - // for the same reason: `title` is the spec-legal key naming a form, and - // `form.label` (a flattened overlay's identity label) must not outrank it. + // The form's own label (its name in lists), then its `title` — the + // identity label first, as the page read it off the view item before + // (objectui#8408). // // No fallback to `name` (objectui#13433). A container's default form — // `showcase_task.form`, what the showcase's Log Time opens — carries - // neither key, and the page was headed by that raw qualified view name. + // neither key, and the page was headed by that raw qualified name. // Undefined here means "names itself nowhere"; `FormPage` heads it with // the object's label instead, as the public route does. - label: (isEnvelope ? spec.label : undefined) ?? form?.title ?? form?.label, - // `data.object` is a declared FormView key since objectui#5596, so this no - // longer needs `as any` — only a narrowing to the one arm that carries an - // object name (`ViewDataSchema`'s `provider: 'object'`), read defensively - // because the body itself is untrusted. - object: (isEnvelope ? spec.object : undefined) - ?? (form?.data as { object?: string } | undefined)?.object - ?? spec?.object, + label: (form as { label?: string } | null)?.label ?? form?.title, + // The form's one binding (ADR-0159 D2), read defensively because the body + // itself is untrusted. + object: typeof (form as { object?: unknown } | null)?.object === 'string' + ? (form as { object: string }).object + : undefined, form, }; } /** * "No such form" on either route (objectstack-ai/objectstack#27446, #27756): - * the internal `/meta/view` read or the public `/forms/:slug` resolver + * the internal `/meta/form` read or the public `/forms/:slug` resolver * answered 404. Both answer 404 for a form that does not exist and for one the * caller may not read, on purpose, so the page says the one thing both mean — * nothing here by that name. @@ -1913,13 +1871,13 @@ async function loadInternalForm( recordObject?: string | null, channel?: ApiFetch, ): Promise { - const viewRes = await apiFetch(`/meta/view/${encodeURIComponent(name)}`, undefined, channel); - if (viewRes.status === 404) throw new FormNotFoundError(`Form metadata not found: view/${name}`); - if (!viewRes.ok) { - throw new Error(`Could not load form metadata (${viewRes.status}): view/${name}`); + const formRes = await apiFetch(`/meta/form/${encodeURIComponent(name)}`, undefined, channel); + if (formRes.status === 404) throw new FormNotFoundError(`Form metadata not found: form/${name}`); + if (!formRes.ok) { + throw new Error(`Could not load form metadata (${formRes.status}): form/${name}`); } - const viewBody = await viewRes.json(); - const { label, object: objectName, form } = resolveInternalForm(name, viewBody); + const formBody = await formRes.json(); + const { label, object: objectName, form } = resolveInternalForm(name, formBody); if (!objectName) { throw new Error(`FormView "${name}" is missing an "object" target`); } diff --git a/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx b/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx index cdecde24f66..f8621c0368a 100644 --- a/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx +++ b/ui/apps/console/src/components/FormPage.upfrontWriteRefusal-29187.test.tsx @@ -55,9 +55,8 @@ beforeEach(() => { const view = { name: `${OBJECT}.form`, object: OBJECT, - viewKind: 'form', label: 'Feedback', - config: { type: 'simple', sections: [{ fields: ['name', 'email'] }] }, + ...{ type: 'simple', sections: [{ fields: ['name', 'email'] }] }, }; const publicPayload = { slug: 'feedback', @@ -74,7 +73,7 @@ beforeEach(() => { posts += 1; return answer(403, { error: 'denied', code: 'PERMISSION_DENIED' }); } - if (u.includes('/meta/view/')) return answer(200, view); + if (u.includes('/meta/form/')) return answer(200, view); if (u.includes('/meta/object/')) return answer(200, { name: OBJECT, label: 'Feedback', fields: FIELDS }); if (u.includes(`/data/${OBJECT}/r1`)) { return answer(200, { object: OBJECT, id: 'r1', record: { id: 'r1', name: 'Ada', email: 'ada@example.com' } }); diff --git a/ui/apps/console/src/components/FormPage.viewSpec.test.ts b/ui/apps/console/src/components/FormPage.viewSpec.test.ts index 1101a5c16bf..e1fe7b2a4d5 100644 --- a/ui/apps/console/src/components/FormPage.viewSpec.test.ts +++ b/ui/apps/console/src/components/FormPage.viewSpec.test.ts @@ -152,9 +152,9 @@ export function formContainerContractPins(): void { // ── PIN G — `label` did not follow the form contract. It was on this file's // removed `FormViewSpec`, and `@objectstack/spec`'s `FormViewSchema` REJECTS - // it (`unrecognized_keys` — a form config is titled, not labelled). It is view - // IDENTITY: it arrives on the `ExpandedViewItem` envelope, or beside the - // config on a flattened runtime overlay. So it lives on `FormPage.tsx`'s own + // it (`unrecognized_keys` — a form body is titled, not labelled). It is form + // IDENTITY: a `form` item carries it beside its body at the top level + // (ADR-0159 D2). So it lives on `FormPage.tsx`'s own // `FormViewBody`, which is what `resolveInternalForm` returns — NOT on the // contract shared with `packages/app-shell`. type ResolvedBody = ReturnType['form']; @@ -200,29 +200,15 @@ describe('objectui#5596 — the console renders the shared container specs', () expect(asString[0].columns).toBe(3); }); - it('reads the view label off the body, not off the form config', () => { - // Envelope branch: identity sits beside `config` (objectui#2208). - const envelope = resolveInternalForm('contact_form', { - name: 'contact_form', + it('reads the form label off the `form` item, beside its body', () => { + const item = resolveInternalForm('contact.contact_form', { + name: 'contact.contact_form', object: 'contact', - viewKind: 'form', label: 'Contact us', - config: { type: 'simple', sections: [{ fields: ['name'] }] }, - }); - expect(envelope.label).toBe('Contact us'); - expect(envelope.object).toBe('contact'); - - // Flattened-overlay branch: no envelope at all, so the identity keys and the - // form config share one object — the shape `@objectstack/spec` publishes as - // `VIEW_METADATA_MEMBERS.formOverlay`. This is the branch the removed - // `FormViewSpec.label` key was really describing. - const flattened = resolveInternalForm('contact_form', { type: 'simple', - label: 'Contact us', - data: { provider: 'object', object: 'contact' }, sections: [{ fields: ['name'] }], }); - expect(flattened.label).toBe('Contact us'); - expect(flattened.object).toBe('contact'); + expect(item.label).toBe('Contact us'); + expect(item.object).toBe('contact'); }); }); diff --git a/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx b/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx index a0ec8edf53c..aff6bdbe8a6 100644 --- a/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx +++ b/ui/apps/console/src/components/FormPage.visibleWhen.test.tsx @@ -97,14 +97,13 @@ const OBJECT_SCHEMA = { }, }; -/** Wrap a section's fields in the `/meta/view/:name` envelope this route reads. */ -function viewEnvelope(fields: unknown[]) { +/** Wrap a section's fields in the `/meta/form/:name` item this route reads. */ +function formItem(fields: unknown[]) { return { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections: [{ label: 'Task', fields }] }, + ...{ type: 'simple', sections: [{ label: 'Task', fields }] }, }; } @@ -147,7 +146,7 @@ function renderInternal(fields: unknown[], query = '', extraRoutes: Parameters = [ { method: 'GET', - match: '/meta/view/', + match: '/meta/form/', body: { name: 'showcase_task.edit', object: 'showcase_task', - viewKind: 'form', label: 'Task', - config: { type: 'simple', sections }, + ...{ type: 'simple', sections }, }, }, { method: 'GET', match: '/meta/object/', body: objectSchema }, diff --git a/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx b/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx index e325c98c6b6..b87913f7e49 100644 --- a/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx +++ b/ui/apps/console/src/components/FormPage.widgetDegrade-10472.test.tsx @@ -51,13 +51,12 @@ const UNREGISTERED = 'no_such_widget'; function renderForm(objectFields: Record, viewFields: unknown[]) { const routes: Array<{ match: string; body: unknown }> = [ { - match: '/meta/view/', + match: '/meta/form/', body: { name: 'probe.form', object: 'probe', - viewKind: 'form', label: 'Probe', - config: { type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, + ...{ type: 'simple', sections: [{ label: 'Probe', fields: viewFields }] }, }, }, { match: '/meta/object/', body: { name: 'probe', label: 'Probe', fields: objectFields } }, diff --git a/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx b/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx index b5ace36fe15..810456b2b3d 100644 --- a/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx +++ b/ui/apps/console/src/components/FormPage.wizardSteps-27224.test.tsx @@ -53,13 +53,12 @@ function stubFetch(form: Record, objectSchema: unknown = OBJECT if (init?.method === 'POST') { submits.push({ url: path, body: JSON.parse(String(init.body)) }); } - const body = path.includes('/meta/view/') + const body = path.includes('/meta/form/') ? { name: 'showcase_ticket.intake', object: 'showcase_ticket', - viewKind: 'form', label: 'Intake', - config: { type: 'wizard', sections: THREE_SECTIONS, ...form }, + ...{ type: 'wizard', sections: THREE_SECTIONS, ...form }, } : path.includes('/meta/object/') ? objectSchema diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index a2217604194..633e78723c9 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -19,6 +19,7 @@ import { lazy, Suspense } from 'react'; import { registerAppComponent } from './componentRegistry.js'; import { lazyPage, LazyPageFallback as MetadataAdminFallback } from './lazyPage.js'; import { registerMetadataResource } from '../views/metadata-admin/registry.js'; +import { FORM_LIST_COLUMNS } from '../views/studio-design/publicForm/formListColumns.js'; import { CONNECTOR_CREDENTIALS_REF } from '../views/setup/connectorCredentials.js'; import { CONNECTOR_CONNECTIONS_REF } from '../views/setup/connectorConnections.js'; import { PERMISSION_SET_ASSIGNMENT_REF, POSITION_HOLDERS_REF } from '../views/setup/peopleAssignments.js'; @@ -453,6 +454,26 @@ registerMetadataResource({ listFilter: (item) => !isAggregatedViewContainer(item), }); +// objectstack#37087 (ADR-0159 D9) — the `form` type: its list's columns and +// its own editor, Studio's form designer (`studio-design/publicForm/`), on +// the item and on `…/form/new`. The editor loads the first time a form opens. +// `form` stays out of Studio's menu (`studioMenuPlacement.ts`). +const FormItemEditPage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemEditPage), +); +const FormItemCreatePage = lazyPage('form', () => + import('../views/studio-design/publicForm/PublicFormsDesigner.js').then((m) => m.FormItemCreatePage), +); +registerMetadataResource({ + type: 'form', + domain: 'ui', + searchableFields: ['name', 'label', 'title', 'object'], + // `/meta/types` serves no list layout for `form`: these are the console's own. + listColumns: FORM_LIST_COLUMNS, + EditPage: FormItemEditPage, + CreatePage: FormItemCreatePage, +}); + registerMetadataResource({ type: 'dashboard', label: 'Dashboards', diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 9d40e9949ee..54021b522ce 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -55,8 +55,10 @@ import { overrideDraftBody } from './studio-design/customizeOverride.js'; * `PageSchema`) joins the original three (#1541): a record page is edited in * the browser and staged/published through the same `/meta` draft model. * objectstack#37359 — `mapping`, a shared import mapping saved from the import - * wizard, is created the same way: into a package of the app, published at once. */ -export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping'; + * wizard, is created the same way: into a package of the app, published at once. + * objectstack#37087 — `form` (ADR-0159), the public form Setup switches and + * Studio's form editor saves, through the same package targets. */ +export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping' | 'form'; /** * The metadata `name` (the `:name` in `/meta/page/:name`) for an object's @@ -318,7 +320,9 @@ function invalidateViewCaches( name: string, ctx: RuntimePersistCtx, ): void { - if (type !== 'view') return; + // [#37087] A `form` save over an old shape removes the old-shape `view` row + // at that address (ADR-0159 card ②), so the object's cached views are stale too. + if (type !== 'view' && type !== 'form') return; const objectName = ctx.objectName; if (!objectName || !name) return; const invalidate = ctx.dataSource?.invalidateViewKeys; diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx index e6bcc341241..3197c24781c 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -15,6 +15,8 @@ import { MemoryRouter } from 'react-router-dom'; const fake = vi.hoisted(() => ({ items: [] as unknown[], + listed: [] as string[], + layeredTypes: [] as string[], listFails: null as string | null, layered: (_name: string, _packageId?: string): { code?: unknown; effective?: unknown; draft?: unknown } => ({}), packages: new Map(), @@ -35,7 +37,8 @@ vi.mock('../../providers/AdapterProvider.js', () => { const adapter = { getClient: () => ({ meta: { - getItems: async () => { + getItems: async (type: string) => { + fake.listed.push(type); if (fake.listFails) throw new Error(fake.listFails); return { items: fake.items }; }, @@ -50,7 +53,10 @@ vi.mock('@object-ui/react', async (importOriginal) => ({ })); vi.mock('../metadata-admin/useMetadata.js', async (importOriginal) => { const client = { - layered: async (_type: string, name: string, options?: { packageId?: string }) => fake.layered(name, options?.packageId), + layered: async (type: string, name: string, options?: { packageId?: string }) => { + fake.layeredTypes.push(type); + return fake.layered(name, options?.packageId); + }, save: (...args: unknown[]) => fake.save(...args), publish: async () => ({}), reset: async () => ({}), @@ -70,13 +76,14 @@ const sharing = (enabled?: boolean) => ({ allowAnonymous: true, publicLink: 'contact-us', }); +/** A `form` item (ADR-0159): its body at the top level. */ const form = (enabled: boolean | undefined, extra: Record = {}) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled) }, + title: 'Contact us', + sharing: sharing(enabled), ...extra, }); @@ -107,6 +114,8 @@ const ADMIN = ['manage_platform_settings', 'manage_metadata']; beforeEach(() => { fake.items = []; + fake.listed = []; + fake.layeredTypes = []; fake.listFails = null; fake.layered = () => ({}); fake.packages = new Map(); @@ -129,6 +138,8 @@ describe('PublicFormsSetupPage', () => { fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); render(, { wrapper: host(['manage_platform_settings']) }); expect(await screen.findByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'true'); + // [#37087] The list is the effective `form` read. + expect(fake.listed).toEqual(['form']); expect(screen.getByTestId('public-forms-no-switch')).toHaveTextContent('«publicFormsSetup.noSwitchPermission»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); @@ -146,12 +157,14 @@ describe('PublicFormsSetupPage', () => { expect(row).toHaveAttribute('data-shipped-off', 'true'); expect(screen.getByTestId('public-form-shipped-off-web_to_lead')).toHaveTextContent('«publicFormsSetup.shippedOff»'); expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); + // [#37087] The app's own document is the `form` layered read's. + expect(fake.layeredTypes.every((type) => type === 'form')).toBe(true); }); } it('a list read that fails says so in business words, never the server\'s own message', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - fake.listFails = 'GET /api/v1/meta/view failed: ECONNRESET upstream'; + fake.listFails = 'GET /api/v1/meta/form failed: ECONNRESET upstream'; render(, { wrapper: host(ADMIN) }); const alert = await screen.findByTestId('public-forms-load-failed'); expect(alert).toHaveTextContent('«publicFormsSetup.loadFailed»'); @@ -170,6 +183,8 @@ describe('PublicFormsSetupPage', () => { await waitFor(() => expect(row).toHaveAttribute('data-unknown', 'true')); expect(row).toHaveAttribute('data-on', 'false'); expect(screen.getByTestId('public-form-unknown-web_to_lead')).toHaveTextContent('«publicFormsSetup.statusUnknown»'); + // Not knowing whether it is live, the page offers no switch: Refresh reads it again. + expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); }); it('a switch over a pending draft says so and does not read as done', async () => { @@ -197,7 +212,7 @@ describe('PublicFormsSetupPage', () => { ] as const) { (fake.toast.error as ReturnType).mockClear(); fake.save = async () => { - throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/view/web_to_lead'), { status }); + throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/form/web_to_lead'), { status }); }; const { unmount } = render(, { wrapper: host(ADMIN) }); fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx index 169a0eda27c..2f942e20b6e 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -129,7 +129,7 @@ function PublicFormsSetupBody() { (async () => { try { if (!client?.meta?.getItems) throw new Error('meta.getItems is not available on this client'); - const answer = await client.meta.getItems('view'); + const answer = await client.meta.getItems('form'); const rows = await markShippedOff(publicFormRowsOf(answer), metadataClient as any); if (live) setRead({ kind: 'ready', rows }); } catch (err) { @@ -277,7 +277,7 @@ function PublicFormsSetupBody() {
void flip(row, next)} aria-label={t(row.on ? 'publicFormsSetup.switchOffLabel' : 'publicFormsSetup.switchOnLabel', { name: row.title, diff --git a/ui/packages/app-shell/src/views/setup/publicForms.test.ts b/ui/packages/app-shell/src/views/setup/publicForms.test.ts index 0bc794c30ed..70e1b14597d 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.test.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -24,15 +24,20 @@ const sharing = (enabled: boolean, extra: Record = {}) => ({ ...extra, }); +/** A served `form` item (ADR-0159): its body at the top level. */ const formItem = (overrides: Record = {}, enabled = true) => ({ name: 'web_to_lead', object: 'crm_lead', - viewKind: 'form', label: 'Contact us', _packageId: 'crm', - config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled), sections: [] }, + title: 'Contact us', + sharing: sharing(enabled), + sections: [], ...overrides, }); +/** The same form as the effective read projects an app's old view shape (ADR-0159 D5). */ +const projectedItem = (overrides: Record = {}, enabled = true) => + formItem({ data: { provider: 'object', object: 'crm_lead' }, _formDefinedIn: 'view', ...overrides }, enabled); describe('publicFormRowOf', () => { it('lists a form open to anonymous intake as on', () => { @@ -51,26 +56,29 @@ describe('publicFormRowOf', () => { }); it('does not list an internal form: not anonymous, or no address', () => { - const notAnonymous = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } } }); - const noLink = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: true } } }); - const noSharing = formItem({ config: { title: 'x' } }); + const notAnonymous = formItem({ sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } }); + const noLink = formItem({ sharing: { enabled: true, allowAnonymous: true } }); + const noSharing = formItem({ sharing: undefined }); expect(publicFormRowOf(notAnonymous)).toBeNull(); expect(publicFormRowOf(noLink)).toBeNull(); expect(publicFormRowOf(noSharing)).toBeNull(); }); - it('does not list a view that is not a form, or one with no config', () => { - expect(publicFormRowOf(formItem({ viewKind: 'list' }))).toBeNull(); - expect(publicFormRowOf(formItem({ config: null }))).toBeNull(); + it('lists a form an app still ships as an old view shape, as the effective read projects it', () => { + expect(publicFormRowOf(projectedItem())).toEqual(publicFormRowOf(formItem())); + }); + + it('does not list an item with no name, or nothing', () => { + expect(publicFormRowOf(formItem({ name: '' }))).toBeNull(); expect(publicFormRowOf(null)).toBeNull(); }); it('names a form by its served label, else its title, else its first section, else its name; a package-less item has none', () => { expect(publicFormRowOf(formItem({ label: undefined }))?.title).toBe('Contact us'); - const sectioned = { sharing: sharing(true), sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; - expect(publicFormRowOf(formItem({ label: undefined, config: sectioned }))?.title).toBe('Get in touch'); - expect(publicFormRowOf(formItem({ label: '', config: { sharing: sharing(true) } }))?.title).toBe('web_to_lead'); - expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', config: { sharing: sharing(true) } }))?.title).toBe( + const sectioned = { title: undefined, sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; + expect(publicFormRowOf(formItem({ label: undefined, ...sectioned }))?.title).toBe('Get in touch'); + expect(publicFormRowOf(formItem({ label: '', title: undefined }))?.title).toBe('web_to_lead'); + expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', title: undefined }))?.title).toBe( 'web_to_lead', ); expect(publicFormRowOf(formItem({ _packageId: undefined }))?.packageId).toBeNull(); @@ -81,7 +89,7 @@ describe('publicFormRowsOf', () => { it('reads `{ items }` or a bare array, drops internal forms and sorts by the name shown', () => { const b = formItem({ name: 'b_form', label: 'Beta' }); const a = formItem({ name: 'a_form', label: 'Alpha' }); - const list = formItem({ name: 'all', viewKind: 'list' }); + const list = formItem({ name: 'all', sharing: undefined }); expect(publicFormRowsOf({ items: [b, list, a] }).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf([b, a]).map((r) => r.name)).toEqual(['a_form', 'b_form']); expect(publicFormRowsOf(undefined)).toEqual([]); @@ -94,6 +102,10 @@ describe('overrideHoldsOnlySwitch', () => { const override = { ...formItem({}, false), _layer: 'custom', overrides: { package: 'crm', basedOn: '3.0.0' } }; expect(overrideHoldsOnlySwitch(override, base)).toBe(true); }); + it('[#37087] is true over an old-shape base: its projection\'s `data` binding and marker are not design', () => { + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '3.0.0' } }; + expect(overrideHoldsOnlySwitch(override, projectedItem())).toBe(true); + }); it('is false when the override also changes the design', () => { const override = { ...formItem({ label: 'Talk to us' }, false), @@ -130,10 +142,11 @@ describe('switchPublicForm', () => { expect(out).toBe('published'); expect(client.save).toHaveBeenCalledTimes(1); const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; - expect([type, name]).toEqual(['view', 'web_to_lead']); + expect([type, name]).toEqual(['form', 'web_to_lead']); expect(options).toMatchObject({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm' }); - expect(body).toEqual({ ...stripped(doc), config: { ...doc.config, sharing: sharing(false) } }); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm' }); + expect(body).toEqual({ ...stripped(doc), sharing: sharing(false) }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm' }); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -147,9 +160,9 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); expect(body._packageId).toBeUndefined(); - expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.publish).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.reset).not.toHaveBeenCalled(); }); @@ -158,10 +171,10 @@ describe('switchPublicForm', () => { const client = clientOf((_n, pkg) => (pkg === 'crm' ? { code: doc, effective: doc } : { code: null, effective: null })); const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); await switchPublicForm(row, false, client, {}, doors); - expect(client.layered).toHaveBeenNthCalledWith(1, 'view', 'web_to_lead', { packageId: 'crm.custom' }); - expect(client.layered).toHaveBeenNthCalledWith(2, 'view', 'web_to_lead', { packageId: 'crm' }); + expect(client.layered).toHaveBeenNthCalledWith(1, 'form', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.layered).toHaveBeenNthCalledWith(2, 'form', 'web_to_lead', { packageId: 'crm' }); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(false)); + expect(body.sharing).toEqual(sharing(false)); }); it('switching back on restores the app\'s own form when the override held nothing but the switch', async () => { @@ -173,7 +186,7 @@ describe('switchPublicForm', () => { const out = await switchPublicForm(row, true, client, { dataSource: { invalidateViewKeys } as any }, doors); expect(out).toBe('restored'); expect(client.reset).toHaveBeenCalledTimes(1); - expect(client.reset).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.reset).toHaveBeenCalledWith('form', 'web_to_lead', { packageId: 'crm.custom' }); expect(client.save).not.toHaveBeenCalled(); expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); }); @@ -189,7 +202,7 @@ describe('switchPublicForm', () => { const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toMatchObject({ packageId: 'crm.custom' }); expect(body.label).toBe('Talk to us'); - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); }); @@ -203,7 +216,7 @@ describe('switchPublicForm', () => { expect(out).toEqual({ kind: 'earlier-version', basedOn: '2.0.0' }); expect(client.reset).not.toHaveBeenCalled(); const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; - expect(body.config.sharing).toEqual(sharing(true)); + expect(body.sharing).toEqual(sharing(true)); // The override keeps the version it declared: re-basing is a person's call. expect(body.overrides).toEqual({ package: 'crm', basedOn: '2.0.0' }); }); @@ -220,13 +233,14 @@ describe('switchPublicForm', () => { describe('a form the installed app ships switched off', () => { const shippedOff = { 'enabled: false': formItem({}, false), - 'no enabled': formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: { allowAnonymous: true, publicLink: 'contact-us' } } }), + 'no enabled': formItem({ sharing: { allowAnonymous: true, publicLink: 'contact-us' } }), + 'enabled: false, as an old shape': projectedItem({}, false), }; const doors = () => listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); for (const [how, base] of Object.entries(shippedOff)) { it(`(${how}) is never switched on: nothing is written, and the refusal says the app ships it off`, async () => { - expect(baseShipsFormOff(base, 'web_to_lead')).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // No override yet: the list serves the app's own document. const fresh = clientOf(() => ({ code: base, effective: base })); const freshDoors = doors(); @@ -257,9 +271,9 @@ describe('switchPublicForm', () => { } it('(allowAnonymous: false) the routes\' own rule: an app that ships the form closed to anonymous visitors withdraws it, even once an override opens it', async () => { - const base = formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(true, { allowAnonymous: false }) } }); + const base = formItem({ sharing: sharing(true, { allowAnonymous: false }) }); const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; - expect(baseShipsFormOff(base, 'web_to_lead', override)).toBe(true); + expect(baseShipsFormOff(base)).toBe(true); // The served override reads on, by the candidates rule alone. const served = publicFormRowOf({ ...override, _packageId: 'crm' })!; expect(served.on).toBe(true); @@ -280,9 +294,26 @@ describe('switchPublicForm', () => { expect(marked.shippedOff).toBeUndefined(); }); + it('[#37087] does not read a form as on when the read answers no document of the app\'s own', async () => { + const client = clientOf(() => ({ code: null, effective: formItem() })); + const [marked] = await markShippedOff([publicFormRowOf(formItem())!], client, doors()); + expect(marked).toMatchObject({ on: false, unknown: true }); + // …and switching it on writes nothing. + await expect(switchPublicForm(row, true, client, {}, doors())).rejects.toMatchObject({ reason: 'load-failed' }); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('[#37087] withdraws by the form\'s name whatever slug the served override declares (ADR-0159 D6 rule 6)', async () => { + const base = formItem({}, false); + const elsewhere = { ...stripped(formItem({ sharing: sharing(true, { publicLink: 'elsewhere' }) })), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const client = clientOf(() => ({ code: base, effective: elsewhere })); + const [marked] = await markShippedOff([publicFormRowOf({ ...elsewhere, _packageId: 'crm' })!], client, doors()); + expect(marked).toMatchObject({ on: false, shippedOff: true }); + }); + it('leaves a form the app ships on, a writable package\'s form and a form with no package as listed', async () => { const on = formItem(); - expect(baseShipsFormOff(on, 'web_to_lead')).toBe(false); + expect(baseShipsFormOff(on)).toBe(false); const client = clientOf((name) => ({ code: name === 'own' ? formItem({}, false) : on, effective: on })); const listedDoors = listed({ crm: { writable: false, version: '3.0.0' }, mine: { writable: true } }); const rows = [ @@ -335,12 +366,22 @@ describe('switchPublicForm', () => { for (const c of [ok, unreadable]) expect(c.save).not.toHaveBeenCalled(); }); + it('[#37087] saves an old shape\'s switch as a `form` item: no `data`, no projection marker', async () => { + const doc = projectedItem(); + const client = clientOf(() => ({ code: doc, effective: doc })); + await switchPublicForm(row, false, client, {}, listed({ crm: { writable: true } })); + const [type, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(type).toBe('form'); + expect(body).toEqual({ ...stripped(formItem()), sharing: sharing(false) }); + expect('data' in body).toBe(false); + }); + it('saves a form that names no package where it lives', async () => { const doc = formItem({ _packageId: undefined }); const client = clientOf(() => ({ code: doc, effective: doc })); const out = await switchPublicForm({ ...row, packageId: null }, false, client, {}, listed({})); expect(out).toBe('published'); - expect(client.layered).toHaveBeenCalledWith('view', 'web_to_lead', {}); + expect(client.layered).toHaveBeenCalledWith('form', 'web_to_lead', {}); const [, , , options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); }); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index 44496fc6d31..0c70321c873 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -8,8 +8,8 @@ * * ## Which forms are listed, and which are on * - * A public form is a form view item whose form the server's one rule - * (`anonymousFormIntakeCandidates`, `@objectstack/spec/ui`) opens to anonymous + * A public form is a `form` item (ADR-0159) whose `sharing` the server's one + * rule (`anonymousFormIntakeSlug`, `@objectstack/spec/ui`) opens to anonymous * intake. The rule reads three keys of its `sharing`: the switch `enabled`, * `allowAnonymous` and the `publicLink` slug. This module reads none of them * itself (the routes and this page must never disagree, objectui#11545): @@ -20,9 +20,13 @@ * whose author never made it anonymous or gave it no address is an internal * form, and is not listed. * - * The list read is the effective one (`GET /meta/view`, ADR-0146 D8): an + * The list read is the effective one (`GET /meta/form`, ADR-0146 D8): an * installed app's form switched off in its customization package is served - * switched off, so it lists as off. + * switched off, so it lists as off. A form an app still ships as an old view + * shape is served there as its projection (ADR-0159 D5, marked + * `_formDefinedIn: 'view'`), and every read and write below names `form`: + * a switch saved over an old shape is a `form` item ({@link authorableForm}), + * which supersedes the old shape at that address (card ②'s write rule). * * ## Where a switch is saved * @@ -44,15 +48,17 @@ * * ## A form the app ships switched off * - * An installed app whose own document keeps a form's address but switches it - * off (`enabled: false` or `allowAnonymous: false`, matched by slot or by - * slug) WITHDRAWS it: the anonymous routes judge the app's own document as a - * kill switch that no override re-opens (`anonymousFormIntakeWithdrawnIn`, - * pinned in `packages/rest/src/public-form-withdrawal-effective-read.test.ts`). - * This page judges it with that same function, imported from the spec. A - * switch the app's document omits counts as off too, as the stack schema - * parses it (`enabled` defaults to `false`). Such a form is listed, never as - * on ({@link markShippedOff}), and switching it on writes nothing and says the + * An installed app whose own document of a form keeps its address but switches + * it off (`enabled: false` or `allowAnonymous: false`) WITHDRAWS it: the + * anonymous routes judge the app's own document as a kill switch that no + * override re-opens, by the form's name whatever slug either side declares + * (`formExplicitlyWithdraws` in the doors' layer, `formIntakeLayer`, ADR-0159 D6 + * rule 6). This page judges it with that same function, imported from the + * spec, on the app's own document as the `form` layered read serves it (its + * `code`, the projection of an old shape included). A switch the app's + * document omits counts as off too, as the stack schema parses it (`enabled` + * defaults to `false`). Such a form is listed, never as on + * ({@link markShippedOff}), and switching it on writes nothing and says the * app ships it switched off. * * A switch is refused, and nothing is written, over a draft already pending @@ -64,7 +70,7 @@ * nothing to read. */ -import { anonymousFormIntakeCandidates, anonymousFormIntakeWithdrawnIn, anonymousFormObjectName } from '@objectstack/spec/ui'; +import { anonymousFormIntakeSlug, formExplicitlyWithdraws } from '@objectstack/spec/ui'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { resolveDashboardEditTarget, @@ -84,7 +90,7 @@ const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Arr /** One public form, as the list read serves it. */ export interface PublicFormRow { - /** The form view item's name: the metadata address every write names. */ + /** The `form` item's name: the metadata address every write names. */ name: string; /** What the page shows as its name ({@link shownName}). */ title: string; @@ -118,46 +124,45 @@ const text = (v: unknown): string | undefined => (typeof v === 'string' && v.tri /** * The name a form is shown by, in the words its author gave it: the served - * (translated) label, else the form's title or label, else the label of its - * first section (what the form's own page heads it with), else its name - * without the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). + * (translated) label, else the form's title, else the label of its first + * section (what the form's own page heads it with), else its name without + * the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). */ function shownName(item: FormDoc): string { - const config: FormDoc = isDoc(item.config) ? item.config : {}; - const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined; + const first = Array.isArray(item.sections) ? item.sections.find(isDoc) : undefined; const dot = item.name.lastIndexOf('.'); return ( text(item.label) ?? - text(config.title) ?? - text(config.label) ?? + text(item.title) ?? text(first?.label) ?? (dot >= 0 && dot < item.name.length - 1 ? item.name.slice(dot + 1) : item.name) ); } +/** The slug the rule opens `form` at, or `null`. */ +const openSlug = (form: FormDoc): string | null => anonymousFormIntakeSlug(form.sharing); + /** - * The public form a served view item carries, or `null` (module header): a - * `viewKind: 'form'` item whose `config` the rule opens once its switch is on. - * The list serves view ITEMS only, so a form is its item's `config`. + * The public form a served `form` item is, or `null` (module header): an item + * whose `sharing` the rule opens once its switch is on. A `form` item carries + * its body at the top level, the projection of an old shape included. */ export function publicFormRowOf(item: unknown): PublicFormRow | null { - if (!isDoc(item) || item.viewKind !== 'form' || !isDoc(item.config) || typeof item.name !== 'string') return null; - const switchedOn = anonymousFormIntakeCandidates({ ...item, config: withSwitch(item.config, true) }); - const listed = switchedOn.find((c) => c.key === item.name); - if (!listed) return null; - const on = anonymousFormIntakeCandidates(item).some((c) => c.key === item.name); + if (!isDoc(item) || typeof item.name !== 'string' || !item.name) return null; + const slug = openSlug(withSwitch(item, true)); + if (slug === null) return null; const packageId = typeof item._packageId === 'string' && item._packageId ? item._packageId : null; return { name: item.name, title: shownName(item), - object: anonymousFormObjectName(item, item.config), - slug: listed.slug, - on, + ...(typeof item.object === 'string' && item.object ? { object: item.object } : {}), + slug, + on: openSlug(item) !== null, packageId, }; } -/** Every public form of a `GET /meta/view` answer (`{ items }`, or a bare array), sorted by name shown. */ +/** Every public form of a `GET /meta/form` answer (`{ items }`, or a bare array), sorted by name shown. */ export function publicFormRowsOf(answer: unknown): PublicFormRow[] { const items: unknown[] = Array.isArray(answer) ? answer : isDoc(answer) && Array.isArray(answer.items) ? answer.items : []; const rows: PublicFormRow[] = []; @@ -198,10 +203,15 @@ export class PublicFormSwitchRefusal extends Error { } } -/** A document without the read's `_` decorations. */ -function authored(doc: FormDoc): FormDoc { +/** + * A served form as a `form` item a save takes: without the read's `_` + * decorations (the projection's `_formDefinedIn` included) and without + * `data`, the old shape's binding, which a `form` item never carries: it is + * bound by its `object` (ADR-0159 D2; the save refuses `data` by name). + */ +export function authorableForm(doc: FormDoc): FormDoc { const out: FormDoc = {}; - for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_')) out[key] = value; + for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_') && key !== 'data') out[key] = value; return out; } @@ -219,34 +229,26 @@ function canonical(value: unknown): string { */ export function overrideHoldsOnlySwitch(override: FormDoc, base: FormDoc): boolean { const strip = (doc: FormDoc) => { - const out = authored(doc); + const out = withSwitch(authorableForm(doc), true); delete out.overrides; - if (isDoc(out.config)) out.config = withSwitch(out.config, true); return out; }; return canonical(strip(override)) === canonical(strip(base)); } /** - * Whether an installed app's own document `base` of the form `name` ships it - * switched off (module header), judged by the routes' own rule: `base` - * withdraws the form `served` carries (the effective item, an override - * included; `base` itself when omitted), matched by slot or by slug - * (`anonymousFormIntakeWithdrawnIn`). The served form is judged with its switch - * on, the state a switch-on would leave it in. A switch the app's document - * omits counts as off as well, as the stack schema parses it, so the console - * fails closed where the routes do. + * Whether an installed app's own document `base` of a form ships it switched + * off (module header), judged by the routes' own rule: the doors close a form + * whose name's body explicitly withdraws it (`formExplicitlyWithdraws`), + * whatever slug the served form declares (ADR-0159 D6 rule 6). A switch the + * app's document omits counts as off as well, as the stack schema parses it, + * so the console fails closed where the routes do. */ -export function baseShipsFormOff(base: unknown, name: string, served?: unknown): boolean { - if (!isDoc(base) || !isDoc(base.config)) return false; - const named = { ...base, name }; - const view: FormDoc = isDoc(served) ? { ...served, name } : named; - const probe = isDoc(view.config) ? { ...view, config: withSwitch(view.config, true) } : view; - const candidates = anonymousFormIntakeCandidates(probe).filter((c) => c.key === name); - if (candidates.some((c) => anonymousFormIntakeWithdrawnIn([named], probe, c))) return true; +export function baseShipsFormOff(base: unknown): boolean { + if (!isDoc(base)) return false; + if (formExplicitlyWithdraws(base) !== undefined) return true; // An omitted switch: the app's document would open the form switched on, but does not as written. - const wouldOpen = anonymousFormIntakeCandidates({ ...named, config: withSwitch(base.config, true) }).some((c) => c.key === name); - return wouldOpen && !anonymousFormIntakeCandidates(named).some((c) => c.key === name); + return openSlug(withSwitch(base, true)) !== null && openSlug(base) === null; } type FormLayers = { code?: unknown; effective?: unknown; draft?: unknown }; @@ -264,10 +266,10 @@ async function readFormLayers(name: string, target: ResolvedTarget, client: Pick : target.kind === 'package' ? { packageId: target.packageId } : { packageId: target.pair ?? target.base }; - const layers = await client.layered('view', name, at); + const layers = await client.layered('form', name, at); // A listed pair that does not hold the form yet holds nothing: its base's document is read. if (target.kind === 'customization' && target.pair && !isDoc(layers.effective) && !isDoc(layers.code)) { - return client.layered('view', name, { packageId: target.base }); + return client.layered('form', name, { packageId: target.base }); } return layers; } @@ -296,8 +298,9 @@ export async function markShippedOff( if (target.kind !== 'customization') return row; try { const layers = await readFormLayers(row.name, target, client); - const served = isDoc(layers.effective) ? layers.effective : layers.code; - return baseShipsFormOff(layers.code, row.name, served) ? { ...row, on: false, shippedOff: true } : row; + // No document of the app's own: whether the routes serve the form is not known. + if (!isDoc(layers.code)) return { ...row, on: false, unknown: true }; + return baseShipsFormOff(layers.code) ? { ...row, on: false, shippedOff: true } : row; } catch { return { ...row, on: false, unknown: true }; } @@ -328,25 +331,27 @@ export async function switchPublicForm( throw new PublicFormSwitchRefusal('load-failed', err instanceof Error ? err.message : String(err)); } const effective = isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null; - if (!effective || !isDoc(effective.config)) throw new PublicFormSwitchRefusal('load-failed', row.name); - const switched = { ...authored(effective), config: withSwitch(effective.config, on) }; + if (!effective) throw new PublicFormSwitchRefusal('load-failed', row.name); + const switched = withSwitch(authorableForm(effective), on); - if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('view', row.name, switched, persist); - if (target.kind === 'package') return saveAndPublishInPackage('view', row.name, switched, target.packageId, persist); + if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('form', row.name, switched, persist); + if (target.kind === 'package') return saveAndPublishInPackage('form', row.name, switched, target.packageId, persist); // An installed app: this environment's customization, in the app's pair. const declared = declaredOverrideOf(effective, target.base); const override = declared ? effective : null; const base = isDoc(layers.code) ? layers.code : null; // The app ships the form switched off: no override re-opens it, so nothing is written. - if (on && baseShipsFormOff(base, row.name, effective)) throw new PublicFormSwitchRefusal('shipped-off', target.base); - if (on && override && base && isDoc(base.config)) { - const baseOn = anonymousFormIntakeCandidates({ ...base, name: row.name }).some((c) => c.key === row.name); + // No document of the app's own: nothing tells whether it ships the form switched off. + if (on && !base) throw new PublicFormSwitchRefusal('load-failed', row.name); + if (on && baseShipsFormOff(base)) throw new PublicFormSwitchRefusal('shipped-off', target.base); + if (on && override && base) { + const baseOn = openSlug(base) !== null; if (baseOn && overrideHoldsOnlySwitch(override, base) && target.pair) { // A draft pending over the override is its saver's: nothing is removed under it. if (isDoc(layers.draft)) return 'pending-draft'; // "Restore package original": the pair's row of the form is removed. - await client.reset('view', row.name, { packageId: target.pair }); + await client.reset('form', row.name, { packageId: target.pair }); if (row.object) persist.dataSource?.invalidateViewKeys?.(row.object, row.name); emitMetadataRefresh(); return 'restored'; @@ -356,7 +361,7 @@ export async function switchPublicForm( if (body === null) throw new PublicFormSwitchRefusal('no-version', target.base); const saveTarget = await ensureDashboardSaveTarget(target, doors); if (saveTarget.kind !== 'customization') throw new PublicFormSwitchRefusal('no-package', target.base); - const outcome = await saveAndPublishInPackage('view', row.name, body, saveTarget.packageId, persist); + const outcome = await saveAndPublishInPackage('form', row.name, body, saveTarget.packageId, persist); // Switched on over an override taken from an earlier version of the app: the form stays on that version. if (on && outcome === 'published' && declared && target.basedOn && declared.basedOn !== target.basedOn) { return { kind: 'earlier-version', basedOn: declared.basedOn }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx index 5fbec23127f..b31aa9c6419 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx @@ -64,6 +64,7 @@ import { StudioBundleItemEditor } from './StudioBundleItemEditor.js'; import { AutomationsPillar } from './AutomationsPillar.js'; import { DataPillar } from './DataPillar.js'; import { StudioPermissionSetPage } from './StudioPermissionSetPage.js'; +import { FormItemPage } from './publicForm/PublicFormsDesigner.js'; import { BUNDLE_MEMBER_PARAM, getMetadataResource } from '../metadata-admin/registry.js'; import { ITEM_TOOL_TAB_PARAM } from '../item-tools/ItemToolTabs.js'; import type { StudioBaseCustomization } from './StudioDesignSurface.js'; @@ -266,6 +267,19 @@ function AreaItemOpen({ /> ); } + // objectstack#37087 — a form opens Studio's form editor (its registered + // `EditPage`), handed what only the area's surface holds: a read-only base's + // customization, where a form the app ships is saved as a declared override. + if (type === 'form' && host?.packageId) { + return ( + + ); + } return ; } diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx new file mode 100644 index 00000000000..67790ad802a --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.test.tsx @@ -0,0 +1,527 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36444, objectstack#37087 — Studio's `form` editor, over a + * metadata client double: the HotCRM acceptance walk on the CRM example's lead + * form, read and written as a `form` item (ADR-0159). + * + * - editing an installed app's form (make Phone required, remove Title, change + * the title) saves a draft in its customization package, declaring the + * override, then publishes it there; the app's own package is never written; + * - an old-shape form (served through the projection, with `data`) is saved + * as a `form` item without it; + * - removing a field the object requires is refused, with the reason; + * - a new form (four fields) is drafted where the editor is open; + * - an address another form uses is refused, and nothing can be saved; + * - the preview renders the form being edited; + * - a form the app ships cannot be deleted; a form of a writable package can; + * - a new form's name may be no other form's; + * - the editor has no switch: a save and a publish carry the form's sharing as + * stored at that time (a form Setup switched off stays off), and write + * nothing when it cannot be read; + * - the server's address refusal its own check missed (`409 + * FORM_ADDRESS_TAKEN`) is shown as the address clash, and any other `409` + * as a pending draft. + * + * The runtime form renderer is stubbed: it renders the sections it is given. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +vi.mock('@object-ui/plugin-form', async (importOriginal) => ({ + ...(await importOriginal>()), + ObjectForm: ({ schema }: { schema: { sections: Array<{ label?: string; fields: Array<{ field: string; required?: boolean }> }> } }) => ( +
+ {schema.sections.map((s, i) => ( +
+ {s.label &&

{s.label}

} + {s.fields.map((f) => ( + + {f.field} + + ))} +
+ ))} +
+ ), +})); +vi.mock('../../../assistant/assistantBus.js', () => ({ emitMetadataRefresh: vi.fn() })); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +import { FormSchema } from '@objectstack/spec/ui'; +import { FormItemEditor } from './PublicFormsDesigner'; + +afterEach(cleanup); + +const BASE = 'com.example.crm'; +const PAIR = 'com.example.crm.custom'; + +const lead = { + name: 'crm_lead', + fields: { + name: { type: 'text', label: 'Lead Name', required: true }, + company: { type: 'text', label: 'Company' }, + email: { type: 'email', label: 'Email', required: true }, + phone: { type: 'phone', label: 'Phone' }, + title: { type: 'text', label: 'Title' }, + score: { type: 'formula', label: 'Score' }, + }, +}; + +/** The CRM's contact-us form, as its `form` item. */ +const contactUs = (): Record => ({ + name: 'crm_lead.web_to_lead', + object: 'crm_lead', + type: 'simple', + sections: [ + { + name: 'contact_us', + label: 'Contact us', + columns: 1, + fields: [{ field: 'name', required: true }, { field: 'company' }, { field: 'email', required: true }, { field: 'phone' }, { field: 'title' }], + }, + ], + sharing: { enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true }, +}); + +const drafted = { + name: 'crm_lead.event_rsvp', + object: 'crm_lead', + label: 'Event RSVP', + sections: [{ name: 'main', fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }], + sharing: { enabled: true, publicLink: '/forms/event-rsvp', allowAnonymous: true }, +}; + +function clientDouble(opts: { owner?: string; appDoc?: Record } = {}) { + const owner = opts.owner ?? BASE; + const appDoc = opts.appDoc ?? contactUs(); + // What is stored now: the served contact-us form (Setup may switch it meanwhile), and the drafts saved. + // The served form is read at the package that ships it (a read at a customization package finds no served item there). + const stored = { + served: { ...appDoc, _packageId: owner } as Record, + drafts: new Map>([['crm_lead.event_rsvp', drafted]]), + /** A layered read fails (the server is unreachable). */ + readsFail: false, + }; + const client = { + stored, + list: vi.fn(async () => [ + stored.served, + { name: 'crm_lead.quick_add', object: 'crm_lead', sections: [], _packageId: owner }, + { ...contactUs(), name: 'crm_account.signup', object: 'crm_account', sharing: { enabled: false, allowAnonymous: true, publicLink: '/forms/signup' }, _packageId: owner }, + ]), + listDrafts: vi.fn(async () => [{ type: 'form', name: 'crm_lead.event_rsvp', packageId: owner }]), + getDraft: vi.fn(async (_t: string, name: string) => stored.drafts.get(name) ?? null), + get: vi.fn(async (type: string, name: string) => (type === 'object' && name === 'crm_lead' ? lead : null)), + layered: vi.fn(async (_t: string, name: string, options?: { packageId?: string }) => { + if (stored.readsFail) throw new Error('503 Service Unavailable'); + const draft = stored.drafts.get(name) ?? null; + if (name !== 'crm_lead.web_to_lead') return { code: null, effective: null, draft }; + const atOwner = options?.packageId === undefined || options.packageId === owner; + return { code: atOwner ? appDoc : null, effective: atOwner ? stored.served : null, draft }; + }), + save: vi.fn(async (_t: string, name: string, body: Record) => { + stored.drafts.set(name, body); + return {}; + }), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), + }; + return client; +} + +/** Setup switches the served contact-us form on or off. */ +function switchServed(client: ReturnType, enabled: boolean) { + const served = client.stored.served; + client.stored.served = { ...served, sharing: { ...served.sharing, enabled } }; +} + +const customization = () => ({ + base: BASE, + baseLabel: 'CRM', + basedOn: '4.0.0', + walled: false, + pairId: null, + ensure: vi.fn(async () => PAIR), + ensurePackage: vi.fn(), + marks: { state: 'loaded' } as never, +}); + +function renderEditor(client: ReturnType, extra: Partial> = {}) { + const onDraftSaved = vi.fn(); + const onCreated = vi.fn(); + const onDeleted = vi.fn(); + render( + , + ); + return { onDraftSaved, onCreated, onDeleted }; +} + +const OWN = { readOnly: false, customization: null, packageId: 'com.acme.sales' } as const; + +/** A new form of the lead object, its title typed (the address follows it). */ +async function startNew(user: ReturnType, title: string) { + await user.selectOptions(await screen.findByTestId('public-form-create-object'), 'crm_lead'); + await user.type(screen.getByTestId('public-form-create-title'), title); +} + +describe('Studio form editor (objectstack#36444, objectstack#37087)', () => { + it('edits an installed app\'s form as a customization: Phone required, Title removed, a new title; then publishes it there', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + const custom = customization(); + const { onDraftSaved } = renderEditor(client, { customization: custom as never }); + await screen.findByTestId('public-form-title'); + await screen.findByTestId('public-form-required-phone'); + + await user.click(screen.getByTestId('public-form-required-phone')); + await user.click(screen.getByTestId('public-form-remove-title')); + const title = screen.getByTestId('public-form-title'); + await user.clear(title); + await user.type(title, 'Talk to sales'); + + // The live preview follows the edit. + expect(screen.getByTestId('public-form-preview-title')).toHaveTextContent('Talk to sales'); + expect(screen.getByTestId('preview-field-phone')).toHaveAttribute('data-required', 'true'); + expect(screen.queryByTestId('preview-field-title')).toBeNull(); + + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + expect(custom.ensure).toHaveBeenCalled(); + const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['form', 'crm_lead.web_to_lead']); + expect(options).toMatchObject({ mode: 'draft', packageId: PAIR, surface: 'studio', ifNoneMatch: '*' }); + expect(body.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); + expect(body._packageId).toBeUndefined(); + expect(body.label).toBe('Talk to sales'); + expect(body.title).toBe('Talk to sales'); + expect(body.config).toBeUndefined(); + expect(body.sections[0].fields).toEqual([ + { field: 'name', required: true }, + { field: 'company' }, + { field: 'email', required: true }, + { field: 'phone', required: true }, + ]); + expect(body.sharing).toEqual({ enabled: true, publicLink: '/forms/contact-us', allowAnonymous: true }); + expect(FormSchema.safeParse(body).success).toBe(true); + expect(onDraftSaved).toHaveBeenCalledWith({ type: 'form', name: 'crm_lead.web_to_lead' }); + + await user.click(await screen.findByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: PAIR })); + // Nothing is ever written to the app's own package. + for (const call of [...client.save.mock.calls, ...client.publish.mock.calls] as unknown as unknown[][]) { + expect(JSON.stringify(call)).not.toContain(`"packageId":"${BASE}"`); + } + }); + + it('saves an old-shape form (served through the projection) as a `form` item, without its `data`', async () => { + const user = userEvent.setup(); + const projected = { ...contactUs(), data: { provider: 'object', object: 'crm_lead' }, _formDefinedIn: 'view' }; + const client = clientDouble({ appDoc: projected }); + renderEditor(client); + await user.type(await screen.findByTestId('public-form-title'), 'Contact us'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [type, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(type).toBe('form'); + expect(body.data).toBeUndefined(); + expect(body._formDefinedIn).toBeUndefined(); + expect(FormSchema.safeParse(body).success).toBe(true); + }); + + it('refuses to remove a field the object requires, and says why', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + await user.click(await screen.findByTestId('public-form-remove-email')); + expect(screen.getByTestId('public-form-notice')).toHaveTextContent('“Email” cannot be removed: the object requires it'); + expect(screen.getByTestId('public-form-field-email')).toBeInTheDocument(); + // And it stays required: its box is checked and cannot be cleared. + expect(screen.getByTestId('public-form-required-email')).toBeChecked(); + expect(screen.getByTestId('public-form-required-email')).toBeDisabled(); + }); + + it('creates a new form with four fields, drafted where the editor is open, then opens it at its own address', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + const { onCreated } = renderEditor(client, { ...OWN, name: null }); + await startNew(user, 'Demo signup'); + expect(screen.getByTestId('public-form-create-address')).toHaveValue('demo-signup'); + await waitFor(() => expect(screen.getByTestId('public-form-create-confirm')).toBeEnabled()); + await user.click(screen.getByTestId('public-form-create-confirm')); + + // Starts with the fields the object requires; two more are added. + expect(await screen.findByTestId('public-form-field-name')).toBeInTheDocument(); + expect(screen.getByTestId('public-form-field-email')).toBeInTheDocument(); + await user.selectOptions(screen.getByTestId('public-form-add-field-main'), 'company'); + await user.selectOptions(screen.getByTestId('public-form-add-field-main'), 'phone'); + // A formula is never offered. + expect(within(screen.getByTestId('public-form-add-field-main')).queryByText('Score')).toBeNull(); + + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['form', 'crm_lead.demo_signup']); + expect(options).toMatchObject({ mode: 'draft', packageId: 'com.acme.sales', ifNoneMatch: '*' }); + expect(body).toMatchObject({ name: 'crm_lead.demo_signup', object: 'crm_lead', label: 'Demo signup' }); + expect(body.sections[0].fields.map((f: { field: string }) => f.field)).toEqual(['name', 'email', 'company', 'phone']); + expect(body.sharing).toEqual({ enabled: true, allowAnonymous: true, publicLink: '/forms/demo-signup' }); + expect(body.overrides).toBeUndefined(); + expect(FormSchema.safeParse(body).success).toBe(true); + expect(onCreated).toHaveBeenCalledWith('crm_lead.demo_signup', 'com.acme.sales'); + }); + + it('refuses an address another form uses, switched off or not, and saves nothing', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + renderEditor(client, { name: null }); + await startNew(user, 'Contact us'); + await waitFor(() => + expect(screen.getByTestId('public-form-create-address-problem')).toHaveTextContent('Another form already uses this address'), + ); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // The address of a switched-off form of another object is taken too. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'signup'); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + cleanup(); + + // An existing form moved onto another's address cannot be saved. + renderEditor(client); + const address = await screen.findByTestId('public-form-address'); + await waitFor(() => expect(client.getDraft).toHaveBeenCalled()); + await user.clear(address); + await user.type(address, 'event-rsvp'); + expect(await screen.findByTestId('public-form-address-problem')).toHaveTextContent('crm_lead.event_rsvp'); + expect(screen.getByTestId('public-form-save')).toBeDisabled(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('groups fields into a named section', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + await user.click(await screen.findByTestId('public-form-add-section')); + const sections = within(screen.getByTestId('public-form-sections')).getAllByTestId(/^public-form-section-label-/); + expect(sections).toHaveLength(2); + await user.clear(sections[1]); + await user.type(sections[1], 'About you'); + expect(screen.getAllByTestId('preview-section')).toHaveLength(2); + expect(screen.getByText('About you', { selector: 'h4' })).toBeInTheDocument(); + }); + + it('does not delete a form the app ships; deletes one of a writable package', async () => { + const user = userEvent.setup(); + renderEditor(clientDouble()); + expect(await screen.findByTestId('public-form-delete-shipped')).toHaveTextContent('switch it off in Setup'); + cleanup(); + + const own = clientDouble({ owner: 'com.acme.sales' }); + const { onDeleted } = renderEditor(own, OWN); + await user.click(await screen.findByTestId('public-form-delete')); + await user.click(screen.getByTestId('public-form-delete-yes')); + await waitFor(() => expect(own.reset).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: 'com.acme.sales' })); + expect(onDeleted).toHaveBeenCalled(); + }); + + it('refuses a new form whose name another form of the object already has', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + renderEditor(client, { name: null }); + // `quick add` names the new form `crm_lead.quick_add`: the object's internal form. + await startNew(user, 'Quick add'); + expect(screen.getByTestId('public-form-create-address')).toHaveValue('quick-add'); + await waitFor(() => + expect(screen.getByTestId('public-form-create-address-problem')).toHaveTextContent('Another form already uses this address'), + ); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // A form only drafted too. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'event-rsvp'); + expect(screen.getByTestId('public-form-create-confirm')).toBeDisabled(); + // A free one is accepted. + await user.clear(screen.getByTestId('public-form-create-address')); + await user.type(screen.getByTestId('public-form-create-address'), 'all-leads'); + expect(screen.getByTestId('public-form-create-confirm')).toBeEnabled(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('has no switch: saves and publishes the form\'s sharing as it is stored at that time, not as it was when the form was opened', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + const title = await screen.findByTestId('public-form-title'); + expect(screen.queryByRole('switch')).toBeNull(); + expect(screen.getByTestId('public-form-switch-in-setup')).toHaveTextContent('Setup'); + // Switched off in Setup after the form was opened here. + switchServed(client, false); + await user.type(title, '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(body.sharing.enabled).toBe(false); + expect(body.title).toBe('!'); + + // Switched back on before the draft is published: the draft is brought in line first. + switchServed(client, true); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledTimes(1)); + expect(client.save).toHaveBeenCalledTimes(2); + const [, , again, options] = client.save.mock.calls[1] as unknown as [string, string, any, any]; + expect(again.sharing.enabled).toBe(true); + expect(again.title).toBe('!'); + expect(options).toMatchObject({ mode: 'draft', packageId: 'com.acme.sales' }); + expect(client.save.mock.invocationCallOrder[1]).toBeLessThan(client.publish.mock.invocationCallOrder[0]); + }); + + it('publishes a draft whose sharing is the stored one without saving it again', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledTimes(1)); + expect(client.save).toHaveBeenCalledTimes(1); + }); + + it('publishes an installed app\'s form with the switch as stored at the app, after it was switched off', async () => { + const user = userEvent.setup(); + const client = clientDouble(); + const custom = customization(); + renderEditor(client, { customization: custom as never }); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + expect((client.save.mock.calls[0] as unknown as [string, string, any])[2].sharing.enabled).toBe(true); + + // Switched off in Setup while the draft waits: the draft (on) is saved again, off, before it goes live. + switchServed(client, false); + // The draft read for display comes back translated; the one written back is the stored draft, never that. + client.getDraft.mockImplementation(async (_t: string, name: string) => { + const d = client.stored.drafts.get(name); + return d ? { ...d, title: '¡Gracias!' } : null; + }); + client.layered.mockClear(); + await user.click(screen.getByTestId('public-form-publish')); + await waitFor(() => expect(client.publish).toHaveBeenCalledWith('form', 'crm_lead.web_to_lead', { packageId: PAIR })); + // The customization package serves nothing yet, so the switch is read where the app ships the form. + expect(client.layered.mock.calls.slice(0, 2).map((c) => (c as unknown[])[2])).toEqual([{ packageId: PAIR }, { packageId: BASE }]); + expect(client.save).toHaveBeenCalledTimes(2); + const [, , again, options] = client.save.mock.calls[1] as unknown as [string, string, any, any]; + expect(again.sharing.enabled).toBe(false); + expect(again.title).toBe('!'); + expect(again.overrides).toEqual({ package: BASE, basedOn: '4.0.0' }); + expect(options).toMatchObject({ mode: 'draft', packageId: PAIR }); + expect(client.save.mock.invocationCallOrder[1]).toBeLessThan(client.publish.mock.invocationCallOrder[0]); + }); + + it('saves nothing when the form\'s switch cannot be read', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + client.stored.readsFail = true; + await user.click(screen.getByTestId('public-form-save')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('publishes nothing when the draft cannot be read', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + + // The read fails outright. + client.stored.readsFail = true; + await user.click(screen.getByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + // The read answers, but with no draft in it. + await user.click(screen.getByRole('button', { name: 'Dismiss' })); + expect(screen.queryByTestId('public-form-notice')).toBeNull(); + client.stored.readsFail = false; + client.stored.drafts.delete('crm_lead.web_to_lead'); + await user.click(screen.getByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toBeInTheDocument(); + expect(client.publish).not.toHaveBeenCalled(); + expect(client.save).toHaveBeenCalledTimes(1); + }); + + it('edits a form with no public address (one an action opens) without asking for one', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + const internal = { name: 'crm_lead.quick_add', object: 'crm_lead', sections: [{ name: 'main', fields: [{ field: 'name', required: true }, { field: 'email', required: true }] }], _packageId: 'com.acme.sales' }; + client.layered.mockImplementation(async (_t: string, name: string) => ({ + code: null, + effective: name === 'crm_lead.quick_add' ? internal : null, + draft: client.stored.drafts.get(name) ?? null, + })); + renderEditor(client, { ...OWN, name: 'crm_lead.quick_add' }); + await user.type(await screen.findByTestId('public-form-title'), 'Quick add'); + expect(screen.queryByTestId('public-form-address')).toBeNull(); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(1)); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(body.sharing).toBeUndefined(); + expect(body.title).toBe('Quick add'); + }); + + /** A refusal as the metadata client throws it: the envelope's status and code on the error. */ + const refusal = (status: number, code: string, message: string) => Object.assign(new Error(message), { status, code }); + + it('shows the server\'s address refusal its own check missed (409 FORM_ADDRESS_TAKEN) as the address clash, at save and at publish', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + // Another form took the address after this one was read: the editor's own check saw it free. + client.save.mockRejectedValueOnce( + refusal(409, 'FORM_ADDRESS_TAKEN', "The form 'crm_lead.web_to_lead' cannot open the public address '/forms/contact-us': the form 'crm_lead.other' holds it."), + ); + await user.click(screen.getByTestId('public-form-save')); + const notice = await screen.findByTestId('public-form-notice'); + expect(notice).toHaveTextContent('Another form already uses this address. Choose a different one.'); + expect(notice).not.toHaveTextContent('draft of this form pending'); + + // The same refusal at publish (a draft whose address another form took after it was saved). + await user.click(screen.getByRole('button', { name: 'Dismiss' })); + await user.click(screen.getByTestId('public-form-save')); + await waitFor(() => expect(client.save).toHaveBeenCalledTimes(2)); + client.publish.mockRejectedValueOnce(refusal(409, 'FORM_ADDRESS_TAKEN', 'taken')); + await user.click(await screen.findByTestId('public-form-publish')); + expect(await screen.findByTestId('public-form-notice')).toHaveTextContent('Another form already uses this address. Choose a different one.'); + }); + + it('CONTROL: shows any other 409 as a pending draft', async () => { + const user = userEvent.setup(); + const client = clientDouble({ owner: 'com.acme.sales' }); + renderEditor(client, OWN); + await user.type(await screen.findByTestId('public-form-title'), '!'); + client.save.mockRejectedValueOnce(refusal(409, 'METADATA_CONFLICT', 'A draft exists.')); + await user.click(screen.getByTestId('public-form-save')); + const notice = await screen.findByTestId('public-form-notice'); + expect(notice).toHaveTextContent('Someone else has a draft of this form pending. Reopen the form to see it.'); + expect(notice).not.toHaveTextContent('already uses this address'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx new file mode 100644 index 00000000000..f38d6e4f03e --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/publicForm/PublicFormsDesigner.tsx @@ -0,0 +1,1006 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Studio's `form` editor (objectstack#36444, objectstack#37087, ADR-0159 D9): + * the page a `form` item opens on, and the page its list's New opens. Pick a + * form's fields (fillable ones only), drag them into order, mark them required + * and group them into named sections; set its title, description, after-submit + * message and address; see it live as it is edited. A new form is made here + * too, and a form of a writable package deleted. + * + * The editor reads and writes the `form` item, whose body sits at the top + * level (ADR-0159 ruled question 5). Saves go through Studio's draft → publish + * path: Save draft writes the form's draft where it is edited (its package, or + * on an installed app its customization package, as a declared override of a + * form the app ships), and Publish puts it live. + * + * The editor has no switch: switching a form on or off is Setup's (Setup → + * Public forms). Its save is a whole-document override at the address Setup's + * switch-only override sits at (ADR-0159 D4), so every save and publish writes + * `sharing.enabled` and `sharing.allowAnonymous` as they are stored at that + * moment, read again then: a publish from here never opens a form Setup + * switched off. + * + * The rules (fillable fields, object-required fields, the address) are + * `publicFormDesign.ts`'s. + */ + +import * as React from 'react'; +import { useHref, useLocation, useNavigate, useSearchParams } from 'react-router-dom'; +import { toast } from 'sonner'; +import { ArrowDown, ArrowUp, GripVertical, Loader2, Plus, Trash2, X } from 'lucide-react'; +import type { MetadataClient } from '@object-ui/data-objectstack'; +import { ObjectForm } from '@object-ui/plugin-form'; +import { SchemaRendererProvider, useAdapter, useMetadata } from '@object-ui/react'; +import { emitMetadataRefresh } from '../../../assistant/assistantBus.js'; +import { t, tFormat, useMetadataLocale } from '../../metadata-admin/i18n.js'; +import { useMetadataClient } from '../../metadata-admin/useMetadata.js'; +import { useMetadataAreaHost } from '../../metadata-admin/metadataAreaHost.js'; +import { declaredOverrideOf, overrideDraftBody } from '../customizeOverride.js'; +import { formPreviewSource } from '../DataPillarHelpers.js'; +import { authorableForm } from '../../setup/publicForms.js'; +import type { StudioBaseCustomization, StudioSavedDraft } from '../StudioPillarKit.js'; +import { + addressProblem, + fieldsOnForm, + fillableFields, + missingRequiredFields, + newPublicFormModel, + newPublicFormName, + previewSectionsOf, + publicFormItemOf, + publicFormModelOf, + removeFieldRefusal, + slugFromTitle, + takenAddresses, + withField, + withFieldMoved, + withoutField, + withoutSection, + withRequired, + withSection, + withSectionLabel, + withSectionMoved, + type PublicFormModel, +} from './publicFormDesign.js'; + +type FormDoc = Record; + +const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Array.isArray(v); + +/** The `form` metadata type (ADR-0159). */ +const FORM_TYPE = 'form'; + +/** The open form: what was read, and the buffer being edited. */ +interface OpenForm { + name: string; + /** The stored document the buffer started from (`null`: a new form). */ + base: FormDoc | null; + /** The package whose row serves the form, or `null` for a new or draft-only one. */ + owner: string | null; + /** A draft of it is pending where it is saved. */ + hasDraft: boolean; + /** Where its draft is read and written: a package id, or `null` before the ensure door names the pair. */ + at: string | null; + model: PublicFormModel; + dirty: boolean; +} + +/** An object a new form can submit into. */ +export interface FormEditorObject { + name: string; + label: string; +} + +export interface FormItemEditorProps { + /** The form to open, or `null` to make a new one. */ + name: string | null; + client: MetadataClient; + /** The package the editor is open on, or `null` where none is (the cross-package leg). */ + packageId: string | null; + /** The open package is read-only (an installed app). */ + readOnly: boolean; + /** On a read-only base, its customization package. */ + customization: StudioBaseCustomization | null; + publishNonce?: number; + onDraftSaved?: (saved?: StudioSavedDraft) => void; + /** A new form's first draft was saved: the host opens it at its own address. */ + onCreated?: (name: string, packageId: string) => void; + /** The form was deleted: the host goes back to the list. */ + onDeleted?: () => void; + locale: string; + /** The data source the live preview renders with (it never writes). */ + previewDataSource: unknown; + /** The objects a new form may submit into. */ + objects?: readonly FormEditorObject[]; + /** The address of the anonymous form route (`useHref('/f')`), for the address preview. */ + formRoute?: string; +} + +/** The address prefix shown before the slug. */ +function addressPrefix(formRoute: string | undefined): string { + const origin = typeof window !== 'undefined' ? window.location.origin : ''; + return `${origin}${formRoute ?? '/f'}/`; +} + +/** The status of a refusal the client threw, if it carries one. */ +const statusOf = (err: unknown): unknown => (err as { status?: unknown })?.status; + +/** The code of a refusal the client threw, if it carries one. */ +const codeOf = (err: unknown): unknown => (err as { code?: unknown })?.code; + +/** + * The server's code for a form left open on an address another form holds + * (ADR-0159 ruled question 3, `409`). Its envelope names the holding form only + * in the message's prose, so the editor shows its own address sentence. + */ +const FORM_ADDRESS_TAKEN = 'FORM_ADDRESS_TAKEN'; + +export function FormItemEditor(props: FormItemEditorProps): React.ReactElement { + const { name, client, packageId, readOnly, customization, publishNonce = 0, onDraftSaved, locale } = props; + const [taken, setTaken] = React.useState>(new Map()); + /** Every form name of the environment, published or only drafted: a new form's name must be none of them. */ + const [formNames, setFormNames] = React.useState>(new Set()); + /** The package that serves each published form. */ + const [owners, setOwners] = React.useState | null>(null); + const [listError, setListError] = React.useState(null); + const [listNonce, setListNonce] = React.useState(0); + const [open, setOpen] = React.useState(null); + const [objectDef, setObjectDef] = React.useState(null); + const [busy, setBusy] = React.useState(null); + const [notice, setNotice] = React.useState(null); + const [creating, setCreating] = React.useState<{ object: string; title: string; slug: string; slugTouched: boolean } | null>( + name === null ? { object: '', title: '', slug: '', slugTouched: false } : null, + ); + const [confirmDelete, setConfirmDelete] = React.useState(false); + const [dragging, setDragging] = React.useState(null); + + const canWrite = !readOnly || (customization !== null && !customization.walled); + const objectName = open?.model.object ?? creating?.object ?? ''; + const fields = React.useMemo(() => fillableFields(objectDef), [objectDef]); + const fieldLabel = React.useMemo(() => new Map(fields.map((f) => [f.name, f.label])), [fields]); + const requiredByObject = React.useMemo( + () => new Set(fields.filter((f) => f.objectRequired).map((f) => f.name)), + [fields], + ); + + // The environment's forms: the addresses they hold and the names they use, + // published or only drafted, and the package that serves each. + React.useEffect(() => { + let live = true; + setListError(null); + (async () => { + try { + const [published, drafts] = await Promise.all([ + client.list(FORM_TYPE), + client.listDrafts({ type: FORM_TYPE }).catch(() => []), + ]); + const items = (published ?? []).filter(isDoc); + const seen = new Set(items.map((i) => i.name).filter((n): n is string => typeof n === 'string')); + const draftItems: FormDoc[] = []; + for (const d of drafts ?? []) { + if (!d?.name || seen.has(d.name)) continue; + const body = await client.getDraft(FORM_TYPE, d.name, d.packageId ? { packageId: d.packageId } : {}).catch(() => null); + const doc = isDoc(body) && isDoc((body as FormDoc).item) ? (body as FormDoc).item : body; + if (isDoc(doc)) draftItems.push({ ...doc, name: d.name }); + } + if (!live) return; + setTaken(takenAddresses([...items, ...draftItems])); + setFormNames(new Set([...seen, ...(drafts ?? []).map((d) => d?.name).filter((n): n is string => typeof n === 'string')])); + setOwners(new Map(items.map((i) => [String(i.name), typeof i._packageId === 'string' ? i._packageId : null]))); + } catch (err) { + if (live) setListError(err instanceof Error ? err.message : String(err)); + } + })(); + return () => { + live = false; + }; + }, [client, listNonce, publishNonce]); + + // The object the open (or new) form submits into: its fields. + React.useEffect(() => { + let live = true; + if (!objectName) { + setObjectDef(null); + return; + } + client + .get('object', objectName) + .then((def) => { + if (live) setObjectDef(isDoc(def) ? def : null); + }) + .catch(() => { + if (live) setObjectDef(null); + }); + return () => { + live = false; + }; + }, [client, objectName]); + + /** Where an existing form's draft is read and saved. */ + const addressOf = React.useCallback( + (owner: string | null): string | null => { + if (!readOnly) return packageId ?? owner; + // An installed app: the customization package, once it exists. + return customization?.pairId ?? null; + }, + [readOnly, packageId, customization], + ); + + const openForm = React.useCallback( + async (formName: string, owner: string | null) => { + setNotice(null); + setConfirmDelete(false); + setBusy('load'); + try { + const at = addressOf(owner); + // The form as it stands: read at its own address, else at the package that serves it. + let layers = await client.layered(FORM_TYPE, formName, at ? { packageId: at } : owner ? { packageId: owner } : {}); + if (!isDoc(layers.effective) && !isDoc(layers.code) && !isDoc((layers as FormDoc).draft) && owner) { + layers = await client.layered(FORM_TYPE, formName, { packageId: owner }); + } + const draft = isDoc((layers as FormDoc).draft) ? ((layers as FormDoc).draft as FormDoc) : null; + const stored = draft ?? (isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null); + if (!stored) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: formName })); + setOpen({ + name: formName, + base: stored, + owner, + hasDraft: !!draft, + at, + model: publicFormModelOf({ ...stored, name: formName }), + dirty: false, + }); + } catch (err) { + setNotice(err instanceof Error ? err.message : String(err)); + } finally { + setBusy(null); + } + }, + [client, addressOf, locale], + ); + + // An existing form opens once the environment's forms say which package serves it. + const opened = React.useRef(null); + React.useEffect(() => { + if (name === null || owners === null || opened.current === name) return; + opened.current = name; + void openForm(name, owners.get(name) ?? null); + }, [name, owners, openForm]); + + const edit = (next: PublicFormModel) => setOpen((o) => (o ? { ...o, model: next, dirty: true } : o)); + + const problem = open?.model.public ? addressProblem(open.model.slug, open.model.name, taken) : null; + const missing = open ? missingRequiredFields(open.model, requiredByObject) : []; + const isNew = open !== null && open.base === null; + const shippedByApp = open !== null && readOnly && open.owner !== null && open.owner === customization?.base; + + /** + * The form's sharing as stored now (`sharing.enabled`, `sharing.allowAnonymous`), + * and its pending draft as stored (the layered read, untranslated). + * Switching is Setup's, never the editor's, so a save carries the sharing as + * it stands at save time, not as it stood when the form was opened: the + * served item when there is one, else the draft or the shipped document; a + * form never stored keeps what the editor made. Throws when it cannot be + * read, so nothing is written on a guess. + */ + const storedNow = async (form: OpenForm): Promise<{ enabled: boolean; allowAnonymous: boolean; draft: FormDoc | null }> => { + // A form never stored: nothing to read yet. + if (form.base === null && !form.hasDraft) { + return { enabled: form.model.enabled, allowAnonymous: form.model.allowAnonymous, draft: null }; + } + const sharingIn = (doc: unknown): FormDoc | undefined => (isDoc(doc) && isDoc(doc.sharing) ? doc.sharing : undefined); + const read = async (at: string | null) => client.layered(FORM_TYPE, form.name, at ? { packageId: at } : {}); + const where = form.at ?? form.owner; + const reads = [(await read(where)) as FormDoc]; + const draft = isDoc(reads[0].draft) ? (reads[0].draft as FormDoc) : null; + // Saved at a customization package: the served item may be read at the package that ships it. + if (!isDoc(reads[0].effective) && form.owner && form.owner !== where) reads.push((await read(form.owner)) as FormDoc); + const first = (layer: 'effective' | 'draft' | 'code') => reads.map((r) => sharingIn(r[layer])).find((v) => v !== undefined); + const sharing = first('effective') ?? first('draft') ?? first('code'); + if (sharing === undefined) { + // A form with no sharing at all (one an action opens) has no switch to keep. + const anyDoc = reads.some((r) => isDoc(r.effective) || isDoc(r.draft) || isDoc(r.code)); + if (anyDoc && !form.model.public) return { enabled: form.model.enabled, allowAnonymous: form.model.allowAnonymous, draft }; + throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: form.model.title || form.name })); + } + return { enabled: sharing.enabled === true, allowAnonymous: sharing.allowAnonymous === true, draft }; + }; + + /** Where a save lands, and the body it writes. */ + const writeTarget = async (model: PublicFormModel): Promise<{ packageId: string; body: FormDoc }> => { + const body = publicFormItemOf(model, open?.base ?? null); + if (!readOnly) { + const at = open?.at ?? packageId; + if (!at) throw new Error(t('engine.studio.publicForms.noPackage', locale)); + return { packageId: at, body }; + } + if (!customization || customization.walled) throw new Error(t('engine.studio.publicForms.readOnly', locale)); + const pair = await customization.ensure(); + if (!shippedByApp) return { packageId: pair, body }; + // A form the app ships is customized as a declared override, never edited in the app. + const declared = declaredOverrideOf(open?.base, customization.base) ? body : overrideDraftBody(body, customization.base, customization.basedOn); + if (!declared) throw new Error(t('engine.studio.publicForms.noVersion', locale)); + return { packageId: pair, body: declared }; + }; + + /** A refusal of the server, in the editor's words where it has some (a clash, a pending draft). */ + const refusalText = (err: unknown): string => { + // The address clash the editor's own check missed (another form took the address after it was read). + if (statusOf(err) === 409 && codeOf(err) === FORM_ADDRESS_TAKEN) return t('engine.studio.publicForms.addressTaken', locale); + if (statusOf(err) === 409) return t('engine.studio.publicForms.draftConflict', locale); + return err instanceof Error ? err.message : String(err); + }; + + const save = async () => { + if (!open || problem || missing.length > 0) return; + setBusy('save'); + setNotice(null); + try { + const now = await storedNow(open); + const target = await writeTarget({ ...open.model, enabled: now.enabled, allowAnonymous: now.allowAnonymous }); + await client.save(FORM_TYPE, open.model.name, target.body, { + mode: 'draft', + packageId: target.packageId, + surface: 'studio', + // A form nobody has drafted yet: a draft written meanwhile is never overwritten. + ...(open.hasDraft ? {} : { ifNoneMatch: '*' }), + } as never); + const saved = publicFormModelOf({ ...target.body, name: open.model.name }); + setOpen({ + ...open, + at: target.packageId, + hasDraft: true, + dirty: false, + base: target.body, + model: { ...open.model, enabled: saved.enabled, allowAnonymous: saved.allowAnonymous }, + }); + onDraftSaved?.({ type: FORM_TYPE, name: open.model.name }); + toast.success(tFormat('engine.studio.publicForms.saved', locale, { name: open.model.title || open.model.name })); + setListNonce((n) => n + 1); + if (open.base === null) props.onCreated?.(open.model.name, target.packageId); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const publish = async () => { + if (!open?.hasDraft || open.dirty || !open.at) return; + setBusy('publish'); + setNotice(null); + try { + // The draft goes live with the sharing as it stands now: a draft that carries another is saved again first. + const { enabled, allowAnonymous, draft } = await storedNow(open); + if (!draft) throw new Error(tFormat('engine.studio.publicForms.unreadable', locale, { name: open.model.title || open.model.name })); + const draftSharing: FormDoc = isDoc(draft.sharing) ? draft.sharing : {}; + if (open.model.public && ((draftSharing.enabled === true) !== enabled || (draftSharing.allowAnonymous === true) !== allowAnonymous)) { + const body: FormDoc = { ...authorableForm(draft), sharing: { ...draftSharing, enabled, allowAnonymous } }; + await client.save(FORM_TYPE, open.model.name, body, { mode: 'draft', packageId: open.at, surface: 'studio' } as never); + } + await client.publish(FORM_TYPE, open.model.name, { packageId: open.at }); + toast.success(tFormat('engine.studio.publicForms.published', locale, { name: open.model.title || open.model.name })); + setOpen({ ...open, hasDraft: false, owner: open.owner ?? open.at }); + emitMetadataRefresh(); + setListNonce((n) => n + 1); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const discard = async () => { + if (!open) return; + if (!open.hasDraft) { + // Nothing saved: the buffer goes back to what was read. + if (open.base) setOpen({ ...open, model: publicFormModelOf({ ...open.base, name: open.name }), dirty: false }); + return; + } + if (!open.at) return; + setBusy('discard'); + try { + await client.reset(FORM_TYPE, open.model.name, { state: 'draft', packageId: open.at }); + onDraftSaved?.(); + setListNonce((n) => n + 1); + const published = owners?.has(open.model.name) === true; + setOpen(null); + if (published) await openForm(open.model.name, open.owner); + else props.onDeleted?.(); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const remove = async () => { + if (!open || shippedByApp) return; + setBusy('delete'); + setNotice(null); + try { + const at = open.at ?? open.owner; + if (open.hasDraft && at) await client.reset(FORM_TYPE, open.model.name, { state: 'draft', packageId: at }); + if (owners?.has(open.model.name)) { + const owner = owners.get(open.model.name) ?? at; + await client.reset(FORM_TYPE, open.model.name, { packageId: owner ?? undefined }); + } + toast.success(tFormat('engine.studio.publicForms.deleted', locale, { name: open.model.title || open.model.name })); + onDraftSaved?.(); + emitMetadataRefresh(); + setOpen(null); + setConfirmDelete(false); + setListNonce((n) => n + 1); + props.onDeleted?.(); + } catch (err) { + setNotice(refusalText(err)); + } finally { + setBusy(null); + } + }; + + const newName = creating && creating.object && creating.slug ? newPublicFormName(creating.object, creating.slug) : ''; + const createProblem = creating ? addressProblem(creating.slug, newName, taken) : null; + // The new form's name may be no other form's (published or only drafted). + const nameTaken = !!newName && formNames.has(newName); + + const create = () => { + if (!creating || !creating.object || !creating.title.trim() || createProblem || nameTaken) return; + const model = newPublicFormModel(creating.object, creating.title.trim(), creating.slug, objectDef); + setCreating(null); + setOpen({ name: model.name, base: null, owner: null, hasDraft: false, at: readOnly ? null : packageId, model, dirty: true }); + }; + + // A new form starts with the fields its object requires, once the object is read. + React.useEffect(() => { + setOpen((o) => { + if (!o || o.base !== null || o.hasDraft || !objectDef) return o; + const required = fillableFields(objectDef).filter((f) => f.objectRequired).map((f) => f.name); + let model = o.model; + for (const field of required) model = withField(model, field, null, new Set(required)); + return model === o.model ? o : { ...o, model }; + }); + }, [objectDef]); + + /** Ask to remove a field: refused, with the reason, for one the object requires. */ + const askRemoveField = (field: string) => { + if (!open) return; + if (removeFieldRefusal(field, requiredByObject)) { + setNotice(tFormat('engine.studio.publicForms.requiredByObject', locale, { field: fieldLabel.get(field) ?? field })); + return; + } + setNotice(null); + edit(withoutField(open.model, field, requiredByObject)); + }; + + const prefix = addressPrefix(props.formRoute); + const problemText = (p: string | null) => + p === 'empty' + ? t('engine.studio.publicForms.addressEmpty', locale) + : p === 'shape' + ? t('engine.studio.publicForms.addressShape', locale) + : p === 'taken' + ? t('engine.studio.publicForms.addressTaken', locale) + : null; + + const input = + 'h-8 w-full rounded-md border border-input bg-background px-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60'; + const smallBtn = + 'inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs font-medium hover:bg-muted disabled:pointer-events-none disabled:opacity-50'; + const primaryBtn = + 'inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50'; + + const editable = canWrite && !!open; + + return ( +
+ {/* The editor's one toolbar row. */} +
+

+ {open ? open.model.title || open.model.name : t('engine.studio.publicForms.newTitle', locale)} +

+ {open && {open.model.name}} +
+ {open && ( + <> + {open.hasDraft && !open.dirty && ( + + {t('engine.studio.publicForms.draftChip', locale)} + + )} + {canWrite && ( + <> + + + + + )} + + )} +
+
+ +
+ {/* The editor. */} +
+ {creating ? ( +
+ {!canWrite &&

{t('engine.studio.publicForms.readOnly', locale)}

} + + + +

{t('engine.studio.publicForms.newHint', locale)}

+
+ + {props.onDeleted && ( + + )} +
+
+ ) : !open ? ( +
+ {notice || listError ? ( +

+ {notice ?? listError} +

+ ) : ( + + )} +
+ ) : ( +
+ {!canWrite &&

{t('engine.studio.publicForms.readOnly', locale)}

} + {notice && ( +
+ {notice} + +
+ )} + {missing.length > 0 && ( +

+ {tFormat('engine.studio.publicForms.missingRequired', locale, { + fields: missing.map((f) => fieldLabel.get(f) ?? f).join(', '), + })} +

+ )} + +
+ +