Skip to content

Commit f3028c5

Browse files
fix(rest,runtime): the draft and layered _env reads of a name only disabled packages hold answer their own 404 (#38633)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9St4eUWHFcCKuRUrCZPperJ)_ Fixes #34261 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:搭建者在环境地址下打开某个名字的草稿、草稿预览或分层视图,而这个名字只由已停用的包持有时,现在看到“不存在”,不再看到点名那个停用包的冲突提示;普通读取早已如此。 - 为什么做:同一地址换个开关答案就不同,违背维护者“停用就该全部消失”的原则;本卡把剩下的三种读法补齐。 - 出错会怎样:最坏情况是本该显示的草稿被答成“不存在”,或停用包重新出现在冲突提示里;不会泄露其他包的草稿(有专门测试守住),撤回这个改动即可恢复原样。 - 要你做什么:无。 ## What changes `GET /meta/:type/_env/:name` answered `404` for a name only disabled packages hold since #33385. For a caller `mayReadPendingDrafts` admits, three spellings of that read still answered `409 RESOURCE_CONFLICT` naming the disabled package. Each now answers its bare by-name read's 404 and names no package, on `RestServer` and the runtime dispatcher alike: | read at `_env` | before | after | |---|---|---| | `?state=draft` (any case) | `409 RESOURCE_CONFLICT` naming the disabled holder | `404 NO_DRAFT` (the by-name draft read's answer, per the ADR-0150 2026-11-26 note) | | `?preview=draft` | `409` | `404 RESOURCE_NOT_FOUND` | | `?layers=true` | `409` | `404 RESOURCE_NOT_FOUND` | **Mechanism (measured, and it changes the suggested route).** The marked refusal (`DISABLED_HOLDERS_ONLY_REFUSAL`) used to be swallowed only for the plain read. If the three arms were simply judged by the plain read too, a leak opens. In the test with a draft-reading engine double, an enabled package C held a stored draft of the name and the registry did not hold it. The bare `?state=draft` and `?preview=draft` served C's draft to an admitted builder while the plain read withheld the name. So `_env` would have served C's draft. That ablation reds the new guard pin on all 20 types, on both transports. So `admitEnvironmentAddress` now judges **the read the caller is answered**: - the plain read must withhold the name, as before; - for an admitted draft switch, that same draft read (`getMetaItem` with `state: 'draft'` / `previewDrafts: true`, the arguments the item read sends) must withhold it as well. Its `404 NO_DRAFT` counts as withheld. If it serves an item or throws anything else, the refusal stands; - the layered view (`?layers=`, when the protocol has a layered read) is judged by the plain read. Its chain (`createMetaLayeredAnswer` step 1b) withholds every layer whenever the plain read withholds a disabled holder's item. The pins show this with C's draft and with C's unhydrated active row. The judge reads no draft switch of its own. It receives the switches the call site already declared with their `mayReadPendingDrafts` admission (`isDraftRead`, `previewDrafts` in the runtime, `answeredRead` on REST). So the `[#20338]` draft-switch census in `meta-draft-read-builder-gate.test.ts` still counts exactly its ledgered sites. Landing: `packages/rest/src/meta-qualified-item-route.ts` and `packages/runtime/src/domains/meta.ts`, plus their tests and the changeset. One more file, outside the claimed surface: `scripts/engine-double-contract.pinned.json` gains two add-only rows. It is written by `node scripts/check-engine-double-contract.mjs --write`, because the two test files' `findOne` doubles now route through `assertEngineFindOnePredicate` and the gate's ledger records that pinned coverage. The producer of the mark, `packages/metadata-protocol/src/protocol-exact-qualifier.ts`, is untouched. **ADR text this makes stale (outside this PR's surface, `docs/adr/**`).** In ADR-0150's 2026-11-26 note, this sentence: "Three reads at `_env` still answer `409` at this head (`?state=draft`, `?preview=draft`, `?layers=true`), and card #34261 carries their move to `404`." Proposed replacement: "At `_env`, `?state=draft` answers `404 NO_DRAFT` and `?preview=draft` and `?layers=true` answer `404`, each judged by the read the caller is answered; an enabled package's stored draft that the plain read does not see keeps the `409` for the draft reads (#34261)." ## Tests - `packages/rest/src/meta-qualified-item-route.test.ts` and `packages/runtime/src/domains/meta-qualified-item-read.test.ts`: #33995's CONTROL ("an admitted draft switch or the layered view refuses 409, as on main") is replaced, per type over `PACKAGE_SCOPED_READ_TYPES` (20 types), by two pins: - **the flip**: `_env` with `state=draft` / `DRAFT` answers `[404, NO_DRAFT]`, and `preview=draft` / `layers=true` answer `[404, RESOURCE_NOT_FOUND]`. This holds with no row and with a package-less draft (the holder's customization) stored, and the answer never names the holder or the draft. A caller not admitted to drafts still gets `[404, RESOURCE_NOT_FOUND]`. CONTROL: once re-enabled, each of the four refuses `409` naming the holder. - **the guard**: an enabled package's stored draft. The bare `?state=draft`, `?preview=draft` and `?package=C&state=draft` serve it (named, so the `409` leg cannot pass vacuously). `_env` draft reads answer `[409, RESOURCE_CONFLICT]` and never that draft. `?layers=true` answers 404 at the bare read and at `_env`. With C's unhydrated active row, `_env?layers=true` follows the plain read: `409` on the four row-served types, else `404`. CONTROL: an enabled registry holder's own draft is still served at the bare read, and `_env` refuses it naming that holder. - The engine doubles' `findOne` now reads the stored rows, behind a per-pin opt-in (`findOneReadsStoredRows`, reset in `beforeEach`). The old CONTROL's draft row was never readable through the old `findOne → null`. ## Acceptance notes - The `409` that remains for a draft read over an enabled package's stored draft names the disabled registry holder as its candidate, not the enabled package that holds the draft. Plain `_env` over an unhydrated active row already pins the same thing as a CONTROL (review#2 S4). This PR leaves it unchanged. - The FROM→TO 404 pins of #33385 (plain `_env`) are unchanged. ## Verification All readings are on `objectstack-ai/objectstack`. The final head is `e24d418ae`, and the base is `7213177e`. <details><summary>Package suites (final head e24d418)</summary> - `pnpm --filter @objectstack/rest test`: Test Files 441 passed (441), Tests 9073 passed, 351 skipped (9424) - `pnpm --filter @objectstack/runtime test`: Test Files 656 passed (656), Tests 12521 passed, 25 skipped (12546) - `pnpm --filter @objectstack/rest --filter @objectstack/runtime typecheck`: exit 0, and `check:test-typecheck: OK` on both </details> <details><summary>Ablations (each restored with git checkout HEAD)</summary> - Draft-arm judge removed (the plain-read-only route), final head: REST 20 failed of 437, runtime 20 failed of 443. All failures are the stored-draft guard pin, one per type, and the assertion bodies show the gamma draft served at `_env`. - Source restored to base `7213177e` (test files kept): REST 40 failed of 437, runtime 40 failed of 443. Those are the flip pin (409 where 404 is pinned) and the guard pin's layered leg, 20 types each. </details> <details><summary>Local gate subset (dispatch-gates --commands, 83 families, final head)</summary> - 82 exit 0. `check:engine-double-contract` was red at the first head, because the `findOne` doubles did not route through the predicate. It is fixed in this PR and exits 0. - NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test` exits 3. Its pinned positive-control commit `621a4876` cannot be reached from this clone even after `git fetch --deepen=1500`. CI runs it. - `dispatch-gates --ran`: 83 derived, 83 run, 0 UNRUN. - `overlap-check.mjs`: VERDICT clean, merging cleanly against origin/main and against #38497, which shares the pinned ledger file. </details> Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/meta-qualified-item-route.test.ts -t "answers its own 404"` should show 20 tests passing. Then revert the `withholds(switches)` line in `meta-qualified-item-route.ts`: the "stored draft" pins should go red, with the gamma draft served in the assertion body. Read first: `packages/rest/src/meta-qualified-item-route.ts` `admitEnvironmentAddress` (the two-step judge), `packages/runtime/src/domains/meta.ts` (the same judge and its call site's `layeredView` choice), then the guard pin in either test file. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmRar3Kkg6SpwVgaaVE --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3fbcce2 commit f3028c5

6 files changed

Lines changed: 288 additions & 98 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/rest': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
fix(rest,runtime): the draft and layered `_env` reads of a name only disabled packages hold answer their own 404
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
`GET /meta/:type/_env/:name` already answered `404` for a name that only disabled packages hold. Three spellings of the same read still answered `409 RESOURCE_CONFLICT` and named the disabled package: `?state=draft`, `?preview=draft` and `?layers=true`, for a caller who may read pending drafts. Each now answers what the bare by-name read answers, on both transports (`RestServer` and the runtime dispatcher), and names no package:
12+
13+
- `?state=draft` (any case): `404 NO_DRAFT`
14+
- `?preview=draft`: `404 RESOURCE_NOT_FOUND`
15+
- `?layers=true`: `404 RESOURCE_NOT_FOUND`
16+
17+
A package-less draft stored under such a name is the disabled holder's customization, so it is withheld too. Once the holder is enabled again, each read refuses `409` and names it, as before.
18+
19+
The door judges the read the caller actually gets. For a draft read, both the plain read and the draft read must withhold the name. Sometimes an enabled package holds a stored draft of the name that the plain read does not see, and the bare draft read serves that draft to an admitted builder. In that case `_env` keeps the `409` and never serves the draft. The layered view is judged by the plain read, because its chain withholds every layer whenever the plain read withholds a disabled holder's item.
20+
21+
FROM → TO for a client: a `409` on these three reads of a disabled-only name becomes a `404` (`NO_DRAFT` for `?state=draft`). Both are refusals, so code that already handles a missing item needs no change.

‎packages/rest/src/meta-qualified-item-route.test.ts‎

Lines changed: 80 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import { describe, it, expect, beforeEach, vi } from 'vitest';
1818
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
19-
import { PACKAGE_SCOPED_READ_TYPES, SchemaRegistry } from '@objectstack/objectql';
19+
import { PACKAGE_SCOPED_READ_TYPES, SchemaRegistry, assertEngineFindOnePredicate } from '@objectstack/objectql';
2020
import { RestServer } from './rest-server.js';
2121

2222
const A = 'com.acme.alpha';
@@ -82,8 +82,12 @@ const storedRowsMatching = (where: Record<string, unknown> | undefined) => store
8282
return (row[key] ?? null) === value;
8383
}));
8484

85+
/** [#34261] Whether the double's `findOne` reads {@link storedRows} — the read a stored draft is served through. */
86+
let findOneReadsStoredRows = false;
87+
8588
beforeEach(() => {
8689
storedRows = [];
90+
findOneReadsStoredRows = false;
8791
registry = new SchemaRegistry({ multiTenant: false });
8892
for (const id of [A, B, C]) {
8993
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop()! } as never, 'code');
@@ -92,7 +96,11 @@ beforeEach(() => {
9296
registry,
9397
// [#33385] Stored `sys_metadata` rows for `find`: equality on each `where` key, nothing else.
9498
find: vi.fn(async (_object: string, opts?: { where?: Record<string, unknown> }) => storedRowsMatching(opts?.where)),
95-
findOne: vi.fn().mockResolvedValue(null),
99+
// [#34261] …and for `findOne`, the first such row, only where a pin opts in.
100+
findOne: vi.fn(async (object: string, opts?: { where?: Record<string, unknown> }) => {
101+
assertEngineFindOnePredicate(object, opts);
102+
return (findOneReadsStoredRows ? storedRowsMatching(opts?.where)[0] : undefined) ?? null;
103+
}),
96104
insert: vi.fn(),
97105
update: vi.fn(),
98106
delete: vi.fn(),
@@ -432,41 +440,86 @@ describe('#32183 — a disabled package holds no name: the by-name read judges t
432440
}
433441
});
434442

435-
// [#33385, review S1] CONTROL — the door judges the read it admits. A
436-
// draft read (`?state=draft`, `?preview=draft`) and the deprecated
437-
// layered view (`?layers=`) are not the read naming no package that
438-
// judged the name, so a marked refusal stands for them: `main`'s 409,
439-
// never an enabled package's draft or stored row at `_env`.
440-
it(`${type}: only a disabled holder in the registry — \`_env\` with an admitted draft switch or the layered view refuses 409, as on main, a caller not admitted to drafts is answered the plain read's 404, never an enabled package's draft or row`, async () => {
441-
const refusedAtEnv = async (query: Record<string, string>) => {
442-
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
443-
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]);
444-
// [review#2 S4] Its candidate is the disabled registry holder, as on main;
445-
// the enabled package holding the name through its row is not named.
446-
expect(env.body?.details?.candidates, JSON.stringify(env.body)).toEqual([{ kind: 'package', packageId: B }]);
447-
for (const label of [`gamma draft ${type}`, `gamma row ${type}`]) expect(JSON.stringify(env.body ?? null)).not.toContain(label);
448-
};
443+
// [#34261, ADR-0150 2026-11-26 note] FROM `_env` 409 naming the disabled
444+
// holder (#33385 left an admitted draft switch and the layered view
445+
// there) TO each read's own 404, naming no package: `?state=draft` the
446+
// by-name draft read's `404 NO_DRAFT`, `?preview=draft` and `?layers=`
447+
// the plain read's `404 RESOURCE_NOT_FOUND`.
448+
it(`${type}: only a disabled holder — \`_env\` with an admitted draft switch or the layered view answers its own 404, naming no package; re-enabled, each refuses naming it`, async () => {
449+
const answers: Array<[Record<string, string>, number, string]> = [
450+
[{ state: 'draft' }, 404, 'NO_DRAFT'],
451+
[{ state: 'DRAFT' }, 404, 'NO_DRAFT'],
452+
[{ preview: 'draft' }, 404, 'RESOURCE_NOT_FOUND'],
453+
[{ layers: 'true' }, 404, 'RESOURCE_NOT_FOUND'],
454+
];
455+
findOneReadsStoredRows = true;
449456
ship(type, 'solo', B);
450457
registry.disablePackage(B);
451-
// An enabled package's draft row, and no active row of the name.
452-
storedRows.push({ id: 'draft_gamma', type, name: 'solo', state: 'draft', package_id: C,
453-
metadata: JSON.stringify({ name: 'solo', label: `gamma draft ${type}` }) });
454-
const draftReads: Record<string, string>[] = [{ state: 'draft' }, { state: 'DRAFT' }, { preview: 'draft' }];
455-
for (const query of draftReads) await refusedAtEnv(query);
458+
// Its package-less draft is the holder's customization, withheld with it.
459+
const customDraft = { id: 'draft_env', type, name: 'solo', state: 'draft', package_id: null,
460+
metadata: JSON.stringify({ name: 'solo', label: `custom draft ${type}` }) };
461+
for (const rows of [[], [customDraft]]) {
462+
storedRows = rows;
463+
for (const [query, status, code] of answers) {
464+
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
465+
expect([env.status, codeOf(env), query, rows.length], JSON.stringify(env.body)).toEqual([status, code, query, rows.length]);
466+
for (const text of [B, `custom draft ${type}`, `beta ${type}`]) expect(JSON.stringify(env.body ?? null)).not.toContain(text);
467+
}
468+
}
456469
// A caller `mayReadPendingDrafts` does not admit is answered the plain
457-
// read whatever it sends, so `_env` answers it as the plain read does:
458-
// 404, never the draft, and never a 409 naming the disabled holder.
470+
// read whatever it sends: 404, as before.
459471
(rest as any).resolveExecCtx = async () => ({ userId: 'u_member' });
460-
for (const query of draftReads) {
472+
for (const query of [{ state: 'draft' }, { preview: 'draft' }]) {
461473
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
462474
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([404, 'RESOURCE_NOT_FOUND', query]);
463-
for (const text of [`gamma draft ${type}`, B]) expect(JSON.stringify(env.body ?? null)).not.toContain(text);
475+
expect(JSON.stringify(env.body ?? null)).not.toContain(B);
464476
}
465477
(rest as any).resolveExecCtx = async () => ({ isSystem: true, userId: 'u1' });
466-
// An enabled package's unhydrated active row: the layered view.
478+
// CONTROL — the holder enabled: every one of these reads refuses naming it, unchanged.
479+
registry.enablePackage(B);
480+
for (const [query] of answers) refusedNaming(await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query), [B], [A]);
481+
});
482+
483+
// [#34261] CONTROL — the guard the draft arms carry: an enabled package's
484+
// stored draft that the plain read does not see. The bare draft reads
485+
// serve it to an admitted builder, so `_env` keeps the refusal for them
486+
// (judged by the draft read itself) and never serves it; the layered
487+
// view withholds it, as the bare layered view does.
488+
it(`${type}: only a disabled holder in the registry, and an enabled package's stored draft — the bare draft reads serve it, \`_env\` draft reads refuse 409 and the layered view answers 404, never that draft`, async () => {
489+
findOneReadsStoredRows = true;
490+
ship(type, 'solo', B);
491+
registry.disablePackage(B);
492+
storedRows = [{ id: 'draft_gamma', type, name: 'solo', state: 'draft', package_id: C,
493+
metadata: JSON.stringify({ name: 'solo', label: `gamma draft ${type}` }) }];
494+
for (const query of [{ state: 'draft' }, { preview: 'draft' }, { package: C, state: 'draft' }]) {
495+
const bare = await drive(ITEM, { type, name: 'solo' }, query);
496+
expect([bare.status, labelOf(bare), query], JSON.stringify(bare.body)).toEqual([200, `gamma draft ${type}`, query]);
497+
}
498+
for (const query of [{ state: 'draft' }, { preview: 'draft' }]) {
499+
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, query);
500+
expect([env.status, codeOf(env), query], JSON.stringify(env.body)).toEqual([409, 'RESOURCE_CONFLICT', query]);
501+
expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma draft ${type}`);
502+
}
503+
for (const [path, params] of [[ITEM, { type, name: 'solo' }], [QUALIFIED, { type, ns: '_env', name: 'solo' }]] as const) {
504+
const layered = await drive(path, params, { layers: 'true' });
505+
expect([layered.status, codeOf(layered), path], JSON.stringify(layered.body)).toEqual([404, 'RESOURCE_NOT_FOUND', path]);
506+
expect(JSON.stringify(layered.body ?? null)).not.toContain(`gamma draft ${type}`);
507+
}
508+
// An enabled package's unhydrated active row: the layered view refuses
509+
// where the plain read serves the row, as plain `_env` does, else 404.
467510
storedRows = [{ id: 'row_gamma', type, name: 'solo', state: 'active', package_id: C,
468511
metadata: JSON.stringify({ name: 'solo', label: `gamma row ${type}` }) }];
469-
await refusedAtEnv({ layers: 'true' });
512+
const env = await drive(QUALIFIED, { type, ns: '_env', name: 'solo' }, { layers: 'true' });
513+
expect([env.status, codeOf(env)], JSON.stringify(env.body))
514+
.toEqual(ROW_SERVED_TYPES.includes(type) ? [409, 'RESOURCE_CONFLICT'] : [404, 'RESOURCE_NOT_FOUND']);
515+
expect(JSON.stringify(env.body ?? null)).not.toContain(`gamma row ${type}`);
516+
// CONTROL — an enabled registry holder's own draft is still served to
517+
// an admitted builder at the bare read, and `_env` refuses naming it.
518+
ship(type, 'own', A);
519+
storedRows = [{ id: 'draft_alpha', type, name: 'own', state: 'draft', package_id: A,
520+
metadata: JSON.stringify({ name: 'own', label: `alpha draft ${type}` }) }];
521+
expect(labelOf(await drive(ITEM, { type, name: 'own' }, { state: 'draft' }))).toBe(`alpha draft ${type}`);
522+
refusedNaming(await drive(QUALIFIED, { type, ns: '_env', name: 'own' }, { state: 'draft' }), [A], [B]);
470523
});
471524

472525
it(`${type}: only disabled holders — the layered view serves none of their layers, at any address`, async () => {

‎packages/rest/src/meta-qualified-item-route.ts‎

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
* every holder;
1616
* - `_env`: the environment's own item, or `409` naming every served
1717
* holder (`admitEnvironmentQualifier`), read as a caller with no package;
18-
* a name only disabled packages hold answers that read's `404` (#33385).
18+
* a name only disabled packages hold answers that read's `404` (#33385),
19+
* its draft and layered reads included (#34261).
1920
*
2021
* D5's order, as the runtime dispatcher's `/meta` domain reads the same path:
2122
* a sub-resource literal in the last position keeps its route — registered
@@ -59,7 +60,8 @@ type MetaItemAddress =
5960
interface QualifiedAddressProtocol {
6061
resolveMetaItemAddress?(request: { type: string; segment: string; name: string }): MetaItemAddress | undefined;
6162
admitEnvironmentQualifier?(request: { type: string; name: string; member?: string }): void;
62-
getMetaItem?(request: { type: string; name: string; member?: string }): Promise<{ item?: unknown } | undefined>;
63+
getMetaItem?(request: { type: string; name: string; member?: string; state?: 'draft'; previewDrafts?: true }): Promise<{ item?: unknown } | undefined>;
64+
getMetaItemLayered?: unknown;
6365
}
6466

6567
/**
@@ -71,6 +73,19 @@ interface QualifiedAddressProtocol {
7173
*/
7274
const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal');
7375

76+
/**
77+
* [#34261] The switches of the read the item read answers this caller, beyond
78+
* the plain read: an admitted draft switch (`?state=draft` is `state`,
79+
* `?preview=draft` is `previewDrafts`), as the item read hands them to
80+
* `getMetaItem`. The layered view (`?layers=`) adds none: its chain withholds
81+
* every layer whenever the plain read withholds a disabled holder's item
82+
* (`createMetaLayeredAnswer` step 1b).
83+
*/
84+
interface EnvironmentReadSwitches {
85+
readonly state?: 'draft';
86+
readonly previewDrafts?: true;
87+
}
88+
7489
/**
7590
* Admit `_env` for `request`, or throw the protocol's refusal. A refusal
7691
* marked {@link DISABLED_HOLDERS_ONLY_REFUSAL} is admitted when the read
@@ -79,30 +94,38 @@ const DISABLED_HOLDERS_ONLY_REFUSAL = Symbol.for('objectstack.metadata-protocol.
7994
* serves an item or refuses, a package holds the name through a stored row
8095
* the registry has not read, and the refusal stands.
8196
*
82-
* [#33385, review S1] Only the read that judged the name is admitted this
83-
* way. An admitted draft read (`?state=draft`, `?preview=draft`) or the
84-
* deprecated layered view (`?layers=`) reads other rows than the plain read,
85-
* so for it the marked refusal stands, as on `main` (`readsAsJudged`, asked
86-
* only once the refusal is marked).
97+
* [#34261, ADR-0150 2026-11-26 note] The read judged is the one the caller is
98+
* answered. An admitted draft read (`?state=draft`, `?preview=draft`) is
99+
* admitted when the plain read AND that draft read withhold the name, so it
100+
* answers its own 404 (`404 NO_DRAFT` for `?state=draft`, as the by-name
101+
* draft read answers); an enabled package's stored draft the plain read does
102+
* not see keeps the refusal, and is never served at `_env`. The layered view
103+
* (`?layers=`) is judged by the plain read and answers its own 404.
87104
*/
88105
async function admitEnvironmentAddress(
89106
p: QualifiedAddressProtocol,
90107
request: { type: string; name: string; member?: string },
91-
readsAsJudged: () => Promise<boolean>,
108+
answeredRead: () => Promise<EnvironmentReadSwitches>,
92109
): Promise<void> {
93110
try {
94111
p.admitEnvironmentQualifier?.(request);
95112
} catch (refusal) {
96113
if ((refusal as Record<symbol, unknown> | null)?.[DISABLED_HOLDERS_ONLY_REFUSAL] !== true
97-
|| typeof p.getMetaItem !== 'function'
98-
|| !(await readsAsJudged())) throw refusal;
99-
let withheld: boolean;
100-
try {
101-
withheld = (await p.getMetaItem(request))?.item == null;
102-
} catch {
103-
throw refusal;
104-
}
105-
if (!withheld) throw refusal;
114+
|| typeof p.getMetaItem !== 'function') throw refusal;
115+
const getMetaItem = p.getMetaItem.bind(p);
116+
const withholds = async (switches: EnvironmentReadSwitches): Promise<boolean> => {
117+
try {
118+
return (await getMetaItem({ ...request, ...switches }))?.item == null;
119+
} catch (error) {
120+
// The strict draft read's absence is its `404 NO_DRAFT` (no
121+
// other read throws it); any other failure is no withheld name.
122+
if ((error as { code?: unknown } | null)?.code === 'NO_DRAFT') return true;
123+
return false;
124+
}
125+
};
126+
if (!(await withholds({}))) throw refusal;
127+
const switches = await answeredRead();
128+
if (Object.keys(switches).length > 0 && !(await withholds(switches))) throw refusal;
106129
}
107130
}
108131

@@ -161,16 +184,19 @@ export function registerMetaQualifiedItemRoute(
161184
query.package = address.packageId;
162185
} else {
163186
const member = typeof query.member === 'string' && query.member !== '' ? query.member : undefined;
164-
// [#33385, review S1] The read the item read answers this caller: the
165-
// plain read unless `?layers=` asks for the layered view, or a
166-
// draft switch is sent by a caller `mayReadPendingDrafts` admits.
167-
const readsAsJudged = async (): Promise<boolean> => {
168-
if (wantsMetaItemLayers(query)) return false;
187+
// [#33385, review S1, #34261] The read the item read answers this
188+
// caller: the layered view when `?layers=` asks for it and the
189+
// protocol has one (the item read answers it first, before
190+
// either draft switch), else the draft switches a caller
191+
// `mayReadPendingDrafts` admits, else the plain read.
192+
const answeredRead = async (): Promise<EnvironmentReadSwitches> => {
193+
if (wantsMetaItemLayers(query) && typeof p.getMetaItemLayered === 'function') return {};
169194
const draft = (value: unknown) => typeof value === 'string' && value.toLowerCase() === 'draft';
170-
if (!draft(query.state) && !draft(query.preview)) return true;
171-
return !mayReadPendingDrafts(await this.resolveExecCtx(environmentId, req).catch(rethrowAuthzStoreUnavailable));
195+
if (!draft(query.state) && !draft(query.preview)) return {};
196+
if (!mayReadPendingDrafts(await this.resolveExecCtx(environmentId, req).catch(rethrowAuthzStoreUnavailable))) return {};
197+
return { ...(draft(query.state) ? { state: 'draft' as const } : {}), ...(draft(query.preview) ? { previewDrafts: true as const } : {}) };
172198
};
173-
await admitEnvironmentAddress(p, { type: params.type, name: params.name, ...(member ? { member } : {}) }, readsAsJudged);
199+
await admitEnvironmentAddress(p, { type: params.type, name: params.name, ...(member ? { member } : {}) }, answeredRead);
174200
}
175201
await readItem(asItemRead(req, params, query), res);
176202
} catch (error: any) {

0 commit comments

Comments
 (0)