Skip to content

feat(metadata): listPackageBindings reads an item's package from its stored row's package column - #37187

Merged
objectstack-fleet[bot] merged 8 commits into
mainfrom
claude/project-thread-olnt1r
Nov 26, 2026
Merged

objectstack-fleet[bot] merged 8 commits into
mainfrom
claude/project-thread-olnt1r

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Warren · project thread

Fixes #37039

Clause-②: yes (widening)
Metadata-protocol: none

维护者速读

  • 用户无感:平台多了一个读法,能直接从数据库那一行记录的「所属包」读出每条元数据属于哪个应用,原有读法一个字节都不变。
  • 为什么做:云端「记录范围 AI 问询」要判断一条技能属于哪个应用,现在只能看元数据正文里作者自己写的标记,这次给它一个以库行为准的读法。
  • 出错会怎样:只影响新读法的调用方(云端还没接入);老数据那一列为空时返回「不属于任何应用」,可以随时撤回这个 PR。
  • 要你做的:无。

What changes

The contract choice: a new optional member on the metadata service contract, beside listDiagnosed, rather than an option on list or query (both keep their shapes, so every existing caller is unchanged).

  1. Contract (packages/spec/src/contracts/metadata-service.ts): IMetadataService.listPackageBindings?(type) answers { items: MetadataPackageBinding[]; degraded; errors }. Each item is { name, data, packageId, source } for one item list(type) answers, in its order. source: 'row' means a stored row holds the item and packageId is that row's package column (null when the column is empty). source: 'registration' means no stored row holds it and packageId is the package its registration files it under (null for none). New export MetadataPackageBinding. The api-surface and export-origins snapshots are regenerated.

  2. DatabaseLoader (packages/metadata/src/loaders/database-loader.ts): every row read records its column through storedRowColumnPackageId, the column only (empty or the sys_metadata sentinel reads null). storedRowPackageId now calls it before its body fallback, so its behaviour is unchanged. Two new members:

    • loadRowBindings(type): loadManySlots' entries in its order, each with rowPackageId. loadManySlots now shares one body (typeRowSlots) with it.
    • rowPackageIdOf(item): the column of the row a plural read handed that very object out from.
      Both are declared optional on MetadataLoader; MetadataRowBinding is exported.
  3. MetadataManager (packages/metadata/src/metadata-manager.ts): listPackageBindings(type). readListUncached is split so the keyed walk (readListKeyed) is shared, and listedInSlotOrder now answers keys. An item is a stored row's item when either of these holds:

    • it is the very body loadMany read from a row. This covers the registry's copy the boot priming pass registers, which is keyed by its body's stamp; a withEntryPackage stamped copy is traced back to its origin.
    • a row loader holds a row under the key list lists the item by.
      Otherwise its binding is its registration's: the slot's package for a type stored per (package, name), else the package its body names.
  4. Docs (content/docs/kernel/contracts/metadata-service.mdx, head f22d3cb): the interface block, a listPackageBindings section and the types table name the member, after the docs drift check listed the contract page.

Behaviour of list, listDiagnosed, query, loadMany, loadManyKeyed and loadManySlots is unchanged (the full metadata suite is green).

Why

Cloud ADR-0118 D2 states a skill's package binding as the stored row's own. The cloud#4935 build (cloud PR #4967) found no read that returns it: MetadataManager.query derives packageId from item bodies, storedRowPackageId falls back to the body stamp, and list() returns bodies only. A body's _packageId stamp is whatever the row's author wrote. The column is what the store's write path recorded. How cloud consumes this is cloud#4973, after a pin move.

Tests

packages/metadata/src/loaders/database-loader.test.ts, new top-level describe [#37039] (7 cases):

  • loadRowBindings: a row whose body stamp (BETA) differs from its column (ALPHA) answers ALPHA. A legacy row with an empty column and a BETA stamp answers null. A row with neither answers null. CONTROL: each entry's slot package stays loadManySlots' (ALPHA, BETA, none).
  • loadRowBindings of a type outside the by-package set (view) reads the column too.
  • Manager level, skill, after the boot priming pass: every primed row answers row with its column. That includes differs, which list lists twice (once as the registry copy under the BETA slot, once as the row under ALPHA), and both answer ALPHA. The legacy row answers null while its body still carries BETA. Bodies equal list('skill') in order.
  • An item no stored row holds (MemoryLoader host) answers registration with its registered package, or null.
  • A row loader whose loadRowBindings throws makes the answer degraded with the error named, and the primed copy still answers its row's column.
  • (L2 round 1, S1) The R7-A agent legacy row: after the boot pass binds its empty column, listPackageBindings('agent') answers the bound package with source: 'row' in the same process, and a fresh loadRowBindings agrees.
  • (L2 round 1, S2) A skill row whose stored body is a JSON primitive beside a normal row: loadMany and list still serve the normal row, as on main.
Local runs (head 07ff6c0; re-run after merging main and after the L2 fix)
  • pnpm --filter @objectstack/metadata typecheck && pnpm --filter @objectstack/metadata test: VERDICT command-exit 0, Test Files 83 passed (83), Tests 2703 passed (2703).
  • After merging main (583ad09): metadata typecheck exit 0; vitest run in packages/metadata: 83 files, 2803 passed. The text merge had dropped main's knowledge-adapter rows from the two contracts snapshots; check:generated --fix regenerated them, and each now equals main plus this PR's one line.
  • After the L2 fix (233d98b, same code as 783d587): the two new tests failed before the fix (S1 got null, S2 threw Invalid value used as weak map key) and pass after; vitest run in packages/metadata: 83 files, 2805 passed; metadata typecheck exit 0; spec check:generated: all 14 up to date.
  • pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/spec check:generated: check:api-surface and check:export-origins stale (the new export), then check:generated --fix regenerated exactly those two; every other gate ✓.
  • Derived gate families (dispatch-gates.mjs --commands): 91 commands; 87 exit 0; 4 exit 3 = NOT MEASURED locally (prerequisite missing, not a verdict): check-plugin-teardown-shape.mjs --self-test (shallow clone), @objectstack/lint check:doc-formula-expressions, check:dual-build-cjs-loads and check:lean-entry-closure (no full-workspace dist). CI on 07ff6c0: 58 success, 11 skipped, 0 failed (Lint & Repo Gates, TypeScript Type Check, Test Core 10/10, Build Core, Governed Surface Queue Guard, Dogfood Regression Gate and the UI contexts all success).

Acceptance notes

  • list(type) lists a stored row twice when its body's package stamp differs from its column. The boot priming pass registers the row's body under the stamp's slot, and the row loader's item is admitted under the column's slot. This is measured in the manager-level test above and is unchanged here. listPackageBindings answers both with the row's column. carrier: the seat decides whether this is a card.
  • For cloud#4973: the boot priming pass binds a legacy row's empty column from its own body (R7-A, bindReadRowPackage), but never from a body that names its package by the _packageId stamp alone (metadata: measure the 18.3.0 environment rows that carry the host's stamp in their stored body, and decide whether a stamp-removal migration is owed (follow-up of #32791) #32985). So a legacy row whose body carries a packageId envelope answers that package as its column, on the boot that binds it and after. A row bound by the stamp alone keeps answering null.

Verification

Two-minute check: pnpm --filter @objectstack/metadata exec vitest run src/loaders/database-loader.test.ts -t 37039. Expect 7 passed. The differs row's two entries both read com.alpha.app, and legacy reads null.

Read first: MetadataManager.listPackageBindings and readRowColumnOf (the identity path for primed copies), then DatabaseLoader.typeRowSlots (the loadManySlots refactor).

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic.
  • 2. Every name I added uses the casing for its kind.
  • 3. No formatter ran; pnpm lint passes.
  • 4. One issue, one branch off an up-to-date main, one pull request.
  • 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset.
  • 6. packages/spec touched: its generated artifacts are regenerated and committed.
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English.
  • The Before Submitting list in CONTRIBUTING.md is done.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JQwxbXcTgn3UMemcSRTDMs

…stored row's column

Regenerates the spec contracts api-surface and export-origins snapshots for the new
MetadataPackageBinding export, and adds the changeset.

Claude-Session: https://claude.ai/code/session_01JQwxbXcTgn3UMemcSRTDMs
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 25, 2026
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/metadata, @objectstack/spec, touching 35 documentable anchor(s). ⚠️ 3 changed file(s) yielded no anchor (packages/metadata/src/index.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

38 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json 9ffe37153c59b0b3a64c629b9fc7d4e16e144840.

⛔ 17 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 3 changed file(s) yielded no anchor (packages/metadata/src/index.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json) — pages documenting those are invisible to this run
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 179 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 9ffe37153c59b0b3a64c629b9fc7d4e16e144840 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 179a77ca83fbe5d1f45bdf31186af1f989a8f9c5 — the merge of head 783d58770850e6357437832279c56aebce407de1 into base 9ffe37153c59b0b3a64c629b9fc7d4e16e144840, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 179a77ca83fbe5d1f45bdf31186af1f989a8f9c5 && git checkout 179a77ca83fbe5d1f45bdf31186af1f989a8f9c5
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 9ffe37153c59b0b3a64c629b9fc7d4e16e144840 783d58770850e6357437832279c56aebce407de1 && git checkout -B drift-repro 9ffe37153c59b0b3a64c629b9fc7d4e16e144840 && git merge --no-ff 783d58770850e6357437832279c56aebce407de1

node scripts/docs-audit/affected-docs.mjs --json 9ffe37153c59b0b3a64c629b9fc7d4e16e144840

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 9ffe37153c59b0b3a64c629b9fc7d4e16e144840 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

The text merge dropped main's knowledge-adapter rows; regenerated from source.

Claude-Session: https://claude.ai/code/session_01JQwxbXcTgn3UMemcSRTDMs
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbXcTgn3UMemcSRTDMs

Contract-review-claim: session_01JQwxbXcTgn3UMemcSRTDMs · head 583ad09 · 2026-11-26T01:02Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbXcTgn3UMemcSRTDMs

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 583ad09de4504b9e7adba596b701a85d2067a0d0
Local-runs: none
Scope: packages/spec/src/contracts/metadata-service.ts + packages/metadata/src/metadata-manager.ts, packages/metadata/src/loaders/database-loader.ts, packages/metadata/src/loaders/loader-interface.ts, packages/metadata/src/index.ts
Security-touching: yes
Rule-change-verified: none

PR #37187 for card #37039. Read: the card body and its five comments (triage first touch 7137854671, claim round 1 7150624417, os-dev-report 7151625614, triage knock 7158504687, claim round 2 7179153240; no ruling and no earlier contract-review record among them), the PR body, the ten-file list, the net diff origin/main...583ad09d (merge base d558de0), and the check-runs on the head. Cited code read in the tree at this head, and cloud ADR-0118 D2, which the contract cites.

Outside this record, the lane seat's ACCEPT at TIER_DEFAULT: .changeset/37039-row-package-binding.md (② reads its level and its two declaration lines only), content/docs/kernel/contracts/metadata-service.mdx, packages/metadata/src/loaders/database-loader.test.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json.

Check-runs on the head as read at 2026-11-26T01:12Z (pushed about 01:00Z): 67 runs, 26 success, 10 skipped, 31 in progress, 0 failed. Completed green: Lint & Repo Gates and all eight Lint · contexts, Type Check · source gates, Type Check · debt ledger, Check Changeset, Governed Surface Queue Guard, Spec property liveness, PR-body guards, Dogfood Regression Gate, Build Docs, Live E2E UI, Flag docs affected by code changes, Check Documentation Links, Check PR Size. Still running, so not yet a verdict: Test Core 1 to 10, Build Core, Type Check · workspace, Type Check · consumer gates, Type Check UI, Test UI 1 to 16, Build & E2E UI. This record does not stand in for them; the all-green check before landing is the seat's.

① Derived judgments

  • @objectstack/spec/contracts gains one export, the interface MetadataPackageBinding, and IMetadataService gains one OPTIONAL member, listPackageBindings?(type). A widening of the published surface: right. No implementer of the contract and no caller breaks, and no wrapper in the tree forwards a fixed member list (every consumer of the sibling listDiagnosed feature-detects on the service itself).
  • No accept-set change. The hunk is TypeScript interface text, no Zod schema moves, and nothing a metadata author can write is added, refused or re-read. Metadata-protocol: none: right.
  • The two generated snapshots each gain exactly the line the new export implies: right.
  • @objectstack/metadata gains MetadataManager.listPackageBindings, DatabaseLoader.loadRowBindings and rowPackageIdOf, two optional members on MetadataLoader, and the type export MetadataRowBinding. All additive: right.
  • "Every existing read is unchanged" (card item 4, PR body, changeset): right for storedRowPackageId (ENVIRONMENT_HISTORY_MARK is the literal sys_metadata it compared before, database-loader.ts:285), for loadManySlots (same entries and order through typeRowSlots), for list and listDiagnosed (readListKeyed plus listedInSlotOrder answering keys maps back to the same values in the same order) and for withEntryPackage (same return, one WeakMap write). WRONG in one case: S2 below.
  • The new read is uncached and walks the loaders twice. It joins no cache entry of list, so it cannot change what list serves: right.

② Semver level

  • The changeset names @objectstack/spec and @objectstack/metadata, the two packages the diff publishes from, both at patch. With Metadata-protocol: none the level is patch by AGENTS.md Post-Task item 3 ("a non-protocol change, widening or breaking, ships patch"). The level matches.
  • The Clause-② line reads yes (widening) in the PR body, in the changeset body and on both claims, line-initial in the first two. It matches the diff: a new optional member and a new export on a published contract, nothing removed or tightened.
  • Check Changeset is green on this head.

③ Boundary flags

  • open_questions in the os-dev-report: empty. Nothing to answer.
  • The report's out-of-scope finding, repeated as the PR's first acceptance note (list lists a stored row twice when its body's stamp differs from its column): confirmed by reading, and it predates this diff. The registry keys the primed copy by the body's stamp (storeWriteKey), admitLoaderSlots admits the row under the column's slot, and neither shadows the other. This diff does not change it; the new read inherits it and answers both entries with the same name, the same column and source: 'row'. It deserves a card, because the first consumer of the new read (cloud#4973) will receive two entries for one row and must not count them as two skills. Not blocking here. The carrier is the seat, as the note says.
  • The PR's second acceptance note (a legacy row the boot pass binds "can answer that package as its column" after a boot): not true on the boot that does the binding. See S1.
  • The four derived gates the dev could not measure locally (exit 3): answered by CI, not by this record. Their lint families are green on this head; the build and test families were still running when read.
  • Security: no hits path is under skills/** or ui/skills/**, so the path-based label instruction does not apply. The yes on the line above is meant, narrowly: the contract hunk teaches a trust rule (a body's package stamp is what the row's author wrote; a consumer that gates on the binding reads the column and treats a degraded answer as unknown), and cloud ADR-0118 D2 uses that binding to decide which skills load and under which tool allow-set. No permission, credential, token or authentication code changes. Whether that earns the security label is the seat's call.
  • Rule change: no path under .claude/**, and the PR body declares no Rule-change: line. None.
  • SQL push-down: no finding. loadRowBindings reuses readTypeRows, the one type-wide query loadManySlots already issues, with the same filter and the same cache entry. It materialises no new id set. The match of rows to listed items is against the in-memory registry, which SQL cannot see, so there is no in-app join that could push down.
  • Author: the PR's user.login is objectstack-fleet[bot]. No off-relay author to name.
  • File surface: the ten files of the diff are exactly the round-2 claim's surface. No docs/adr/**, no skills/**.

④ Design judgment

packages/spec/src/contracts/metadata-service.ts (hits). The contract choice holds. A sibling member keeps list and query byte-identical, which is card item 4, and optional-like-listDiagnosed is the right shape for a member only a row-backed service can answer; the text forbids substituting list. Against cloud ADR-0118 D2: D2 has the registry read the binding "as the protocol states it, which for a record the write door saved is derived from the row's package column", says a skill bound to no package does not load, and says the sys_metadata sentinel names none. The contract's two arms, its null for an empty column and the sentinel reading null (storedRowColumnPackageId) agree with all three, and null is the fail-closed direction for that consumer. Against the card: items 1 to 3 are each a sentence of the jsdoc, and source is the mark item 3 asks for. The contract as written is sound; what follows is where the code does not yet meet it.

Implementing files, against the contract sentence by sentence.

S1 (should-fix) — listPackageBindings answers the column as it was READ, and the boot priming pass rewrites that column after the read. DatabaseLoader.handOut records rowPackageId on the copy it hands out (database-loader.ts:1303). The pass registers that copy with skipSourceLoader, register calls bindReadRowPackage (metadata-manager.ts:1385-1386), and for a legacy row whose body names its own packageId that method writes package_id (database-loader.ts:1354) and never touches readRowColumns. listPackageBindings asks the identity path first (metadata-manager.ts:1858-1859), so for the rest of that process the item answers packageId: null, source: 'row' while its row's column holds the package. The key path one line below would read the fresh column and is never reached. The next boot answers the package. The scenario is the existing test [R7-A] an agent legacy row (database-loader.test.ts:1998) followed by one listPackageBindings('agent'); no test in the diff covers it. This contradicts the contract sentence "an item a stored row holds answers source: 'row' and that row's column", and it makes the PR's acceptance note for cloud#4973 true only from the boot after the binding one. The error is fail-closed under ADR-0118 D2 (bound to none, so not loaded), which is why it is not graded higher; but the answer changes across a restart with no write in between, and a consumer cannot tell. Fix shape: record the bound column on the handed-out item when bindReadRowPackage writes it, or resolve the identity path against the row as it stands, and pin it with the R7-A scenario.

S2 (should-fix) — readTypeRows now throws on a row that main serves. this.readRowColumns.set(data, ...) (database-loader.ts:1259) runs on whatever rowToData returns, and rowToData returns a JSON primitive unchanged (applyConversionsToStoredItem returns a non-object as it is, packages/spec/src/conversions/stored.ts:127). A WeakMap refuses a non-object key with a TypeError. It is thrown inside the try, rethrowUnlessTableUnprovisioned rethrows it, and the whole type's plural read fails: loadMany, loadManyKeyed and loadManySlots, so list answers degraded with none of that loader's rows of the type and the boot pass primes none of them. On main the same row (a metadata column holding 5, true or a double-encoded string) is pushed and handed out as a spread copy, and every other row of the type is served. No writer in this tree stores such a body (register refuses a non-document), and an unparseable column already fails the read on main, so the exposure is a hand-written or corrupted row. But card item 4, the PR body and the changeset all promise the existing reads unchanged, and after this diff one such row costs the whole type, object included. Fix shape: set the entry only when data is an object. One line, plus a pin.

N1 (nit) — the contract says a row loader that could not be read "leaves items it holds answering 'registration'" (metadata-service.ts:459-460). The registry's primed copies of that loader's rows still answer 'row' by identity, as the PR's fifth test pins. The sentence is safe to act on, since a degraded answer is unknown either way, but it says more than the code does.

N2 (nit) — a datasource: loader that does not implement the optional loadRowBindings has its rows answered 'registration' with degraded: false. DatabaseLoader is the only datasource: loader in the tree, so nothing reaches this today. A follow-up card could have the manager report such a loader as unread.

N3 (nit) — when both walks lose the same loader, errors names it twice and reportLoaderReadFailure fires twice for one read.

N4 (nit) — rowColumns.get(key)! (metadata-manager.ts:1860) asserts away null, a legal value there. The runtime value is right; the type is narrower than the value.

N5 (nit) — "and nowhere else" (metadata-service.ts:445) reads broader than the member's own second arm, which binds an item with no row by its registration.

The nits may ride the head that closes S1 and S2, or stand as accepted deviations. None changes a verdict.

Break attempts that held.

  • Key agreement: rowColumns is keyed by the same expression admitLoaderSlots uses (storeSlotKey over the served body and entry.packageId, else the body's package), and by entry.name for the other types, as admitLoaderItems does. First row of a key wins on both sides, in the same loader order.
  • A registry item the pass primed from a FILE while a stored row shares its key: no identity entry, so the key path answers the row's fresh column. Right.
  • A withEntryPackage stamped copy: traced to its origin through stampedCopyOrigins, so a row bound by its column alone still answers by identity.
  • A customization row held for a package (pluralEntryCustomizedHolders): keyed under the holder's slot, answers its own empty column, null. Literal to the contract.
  • A code registration whose key a legacy row shares answers 'row' and the row's column, null for an empty one: the manager's stated rule, fail-closed.
  • in its order: both reads go through readListKeyed and listedInSlotOrder; bundled types keep the slot-first order.
  • Ambiguous-stem errors still throw out of the new read, as out of list.
  • loader-interface.ts and index.ts: the two optional members and the export say what DatabaseLoader does, except that rowPackageIdOf is the column as read (S1).

Nothing here is graded above should-fix. S1 and S2 are open on this head and each owes a delta review of its fix.

Implemented-by: claude/project-thread-olnt1r
Reviewed-by: session_01JQwxbXcTgn3UMemcSRTDMs

Independence pair: the review was rendered by an isolated sub-agent served at CONTRACT_REVIEW_TIER, whose inputs were the card, the PR and the head's check-runs, and not the dispatching seat's conclusions. session_01JQwxbXcTgn3UMemcSRTDMs adopts and posts it. The diff was produced on branch claude/project-thread-olnt1r.

VERDICT: PASS

…bound; primitive-body rows no longer fail the read

- bindReadRowPackage records the package it writes into the column against
  the handed-out body, so the primed copy answers the bound package with
  source 'row' (the cached rows are already invalidated by the update).
- A row whose stored body is a JSON primitive is skipped when recording its
  column, so the type's plural read serves the other rows instead of throwing.
- listPackageBindings reads the keyed column without a non-null assertion.
- IMetadataService.listPackageBindings jsdoc: a degraded row loader's primed
  copies still answer 'row'; "nowhere else" narrowed to the body stamp.

Claude-Session: https://claude.ai/code/session_01JQwxbXcTgn3UMemcSRTDMs
Co-authored-by: Claude <noreply@anthropic.com>
…answers the bound package

Claude-Session: https://claude.ai/code/session_01JQwxbXcTgn3UMemcSRTDMs
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbXcTgn3UMemcSRTDMs

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 783d58770850e6357437832279c56aebce407de1
Local-runs: none
Scope: packages/spec/src/contracts/metadata-service.ts + packages/metadata/src/metadata-manager.ts, packages/metadata/src/loaders/database-loader.ts, packages/metadata/src/loaders/loader-interface.ts, packages/metadata/src/index.ts
Security-touching: yes
Rule-change-verified: none

Delta review of PR #37187 for card #37039, by the reviewer of the round-1 record on head 583ad09d (PR comment 7179564385), which left S1 and S2 open. Read this round: the card body and its five comments (unchanged since round 1; no ruling, no record), the PR body (its declaration lines, test section and acceptance notes read as in round 1) and its ten-file list (the same ten paths), the delta git diff 583ad09d 783d5877 (commits 233d98b and 783d587; five files, 67 insertions, 10 deletions), the net diff against main where the delta touches it (merge base still d558de0), and the check-runs on this head. The hunks the delta does not touch are as the round-1 record judged them.

S1: closed
S2: closed

No must-fix, no should-fix.

Outside this record, the lane seat's ACCEPT at TIER_DEFAULT: .changeset/37039-row-package-binding.md (② reads its level and its two declaration lines only), content/docs/kernel/contracts/metadata-service.mdx, packages/metadata/src/loaders/database-loader.test.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json.

Check-runs on the head as read at 2026-11-26T01:25Z (CI had just started): 37 runs so far, 12 success, 9 skipped, 16 in progress, 0 failed. Completed green: Check Changeset, Governed Surface Queue Guard, Spec property liveness, PR-body guards, Dogfood Regression Gate, Lint · PM dispatch-gates, Lint · scoped · tooling self-tests, Flag docs affected by code changes, Check Documentation Links, Check PR Size. Still running, so not yet a verdict: the other six Lint · contexts, all four Type Check · contexts, Build Core, Build Docs, Build UI Deps, Live E2E UI, and the two shard plans; the Test Core and Test UI shards had not been created yet. This record does not stand in for them; the all-green check before landing is the seat's.

① Derived judgments

  • The delta adds no export, no member and no signature. In packages/spec it changes jsdoc text only, so the two generated snapshots owe no regeneration: right.
  • In @objectstack/metadata it adds one private method (DatabaseLoader.recordRowColumn), one statement in bindReadRowPackage, and a typed local in listPackageBindings. No public surface moves: right.
  • Accept-set: unchanged. Metadata-protocol: none still right.
  • "Every existing read is unchanged", which round 1 judged wrong in one case, is now right: the WeakMap write is guarded, so readTypeRows treats a primitive-body row as main does (S2 below).
  • The net diff against main is the same ten files (448 insertions, 15 deletions). The round-1 judgments on the published surface stand: one new export MetadataPackageBinding, one new optional member listPackageBindings?, additive members on MetadataManager, DatabaseLoader and MetadataLoader, the type export MetadataRowBinding. A widening: right.

② Semver level

  • The changeset front matter is untouched: @objectstack/spec and @objectstack/metadata at patch, which is the level Metadata-protocol: none takes (AGENTS.md Post-Task item 3). The delta fixes two defects inside the same unreleased addition and publishes nothing further, so the level still matches.
  • The Clause-② line still reads yes (widening), line-initial, in the PR body and in the changeset body, and still matches the diff.
  • The one changeset sentence the delta rewrites (a legacy row whose empty column the boot pass binds answers the package the pass wrote) agrees with the code at this head. It is prose, the lane seat's.
  • Check Changeset is green on this head.

③ Boundary flags

  • No new dev flag and no open_questions entry reached the card or the PR body since round 1. The round-1 answers stand, including the duplicate-listing finding (predates the diff, deserves a card, the seat carries it).
  • The PR body's second acceptance note (a legacy row the boot pass binds "can answer that package as its column" after a boot), which round 1 found untrue on the binding boot, is true in the tree at this head.
  • The PR body's test section still says five cases; the describe now holds seven. PR-body prose, the seat's to refresh or leave.
  • Security: unchanged from round 1. No hits path is under skills/** or ui/skills/**. The yes is meant, narrowly: the contract jsdoc, reworded in this delta, still teaches which package binding a gating consumer may trust. No permission, credential, token or authentication code changes. The label is the seat's call.
  • Rule change: no path under .claude/**, and the PR body declares no Rule-change: line. None.
  • SQL push-down: no finding. The delta adds no query. bindReadRowPackage issues the same find and the same single-row update as before.
  • Author: the PR's user.login is objectstack-fleet[bot].
  • File surface: the delta stays inside the round-2 claim's surface.

④ Design judgment

S1, closed. bindReadRowPackage now records the bound package on the handed-out item directly after the update that writes it (database-loader.ts:1367, recordRowColumn(item, read.packageId)), before invalidate. item is the very copy handOut gave the priming pass, the one register stores and readRowColumnOf asks by identity, so the identity path answers the column as the pass left it. The recorded value is exactly what the update wrote. If the update throws, nothing is recorded, which is the right order. A second call for the same item returns early and changes nothing. The fix is the first fix shape round 1 named, and it is pinned: the R7-A scenario followed by listPackageBindings('agent') answers the bound package with source: 'row', and a fresh loader's loadRowBindings agrees (database-loader.test.ts:4846). The contract sentence "an item a stored row holds answers source: 'row' and that row's column" now holds on the binding boot.

S2, closed. Every write to readRowColumns goes through recordRowColumn (database-loader.ts:1314), which sets the entry only for a non-null object. The three call sites are readTypeRows (1259), handOut (1303) and the S1 line (1367); no direct set remains. A row whose stored body is a JSON primitive is skipped there and otherwise flows through readTypeRows exactly as on main, so the type's other rows are served. Pinned: a skill row whose metadata is 42 beside a normal row, read through loadMany and through list (database-loader.test.ts:4869). In the new read such a row has no identity entry and answers by key, its own empty or filled column, like any other listed row.

packages/spec/src/contracts/metadata-service.ts (hits), the jsdoc edits.

  • N5, closed. "never on the body's package stamp" (line 445) replaces "and nowhere else", and "a stored item's package binding" scopes the sentence to items with a row. It no longer contradicts the member's second arm.
  • N1, closed. The degraded sentence now names the exception the code has: a copy the registry primed from that loader's rows still answers 'row'. That is what readRowColumnOf does when loadRowBindings throws, and the PR's degraded test pins it.
  • N6 (nit) — the same sentence says the primed copy answers "the column it was read with" (line 462). After the S1 fix a copy whose row the pass bound answers the column the pass wrote, not the one the read found. The main arm ("that row's column") and the changeset both say it correctly; this clause is one step behind. It cannot change what a consumer does, since the sentence ends by telling it to treat a degraded answer as unknown.

packages/metadata/src/metadata-manager.ts, the typing edit.

  • N4, closed. keyedColumn is typed string | null | undefined and null is no longer asserted away (lines 1860-1861). For every entry a typed loader can return, the answer is identical to round 1's: rowPackageId is string | null, so a held key always answers 'row'. An entry from an untyped loader that omits rowPackageId now falls through to 'registration' where it used to answer 'row' with an undefined package. That is N2's hypothetical loader again, not a new case in the tree.

Did the delta introduce anything new? One residual, graded a nit.

  • N7 (nit) — bindReadRowPackage returns early when the fresh row already holds the package (row.package_id === read.packageId, database-loader.ts:1337), and on that path the item keeps the null it was read with. Within one process this path is not reachable with a stale item: the pass reads a type once, and a read after the bind is fresh. It needs a second process to bind the row between this process's plural read and its own bind attempt, that is, two nodes on their first boot over the same unbound legacy row. The loser then answers null for that row until it restarts. This is outside S1, which was the deterministic single-process case, and it is fail-closed. A registry copy is in any case as old as the process's last read of its row, for the body list serves and for the column alike. A follow-up card could record the fresh row's column on that early return, one line.

N2 and N3 stand as round 1 left them: accepted deviations, N2 a follow-up card candidate.

Break attempts on the delta that held.

  • A withEntryPackage stamped copy is never in legacyReadRows, so no bind runs for it and nothing goes stale; its origin still answers by identity.
  • A row the pass refuses to bind (stamp-only body, another writer's source, a slot another row holds) returns before the update, and its copy keeps the null its row still holds. Right.
  • The recorded value cannot be the sys_metadata sentinel or empty: read.packageId comes from storedRowPackageId, which admits neither.
  • rowPackageIdOf still answers undefined for an object the loader did not hand out; the guard only narrows what is stored.
  • loader-interface.ts and index.ts are untouched and still describe what DatabaseLoader does. With S1 closed, rowPackageIdOf no longer lags the row on the binding boot.

Nits alone remain. They end the round: N6 and N7 are left as accepted deviations or follow-up cards, since a fix to either moves the head.

Implemented-by: claude/project-thread-olnt1r
Reviewed-by: session_01JQwxbXcTgn3UMemcSRTDMs

Independence pair: the review was rendered by an isolated sub-agent served at CONTRACT_REVIEW_TIER, the same reviewer as round 1, whose inputs were the card, the PR, the delta and the head's check-runs, and not the dev's report or the dispatching seat's conclusions. session_01JQwxbXcTgn3UMemcSRTDMs adopts and posts it. The diff was produced on branch claude/project-thread-olnt1r.

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbXcTgn3UMemcSRTDMs

席位核对

ACCEPT · head 783d58770850e6357437832279c56aebce407de1 · Area: cloud zone · read 2026-11-26T01:53Z

Checklist (l1-review-checklist.md), mechanical items from l1-face.mjs --pr 37187 at this head: shape, first line Fixes #37039, no closing keyword on another card, no releases path, changeset covers both published packages (@objectstack/spec, @objectstack/metadata, patch), declarations Clause-②: yes (widening) · Metadata-protocol: none, skills-docs not owed, dogfood not owed — all ok. Checks at this head: 62 success · 12 expected skip · 0 failed · 0 pending; Lint & Repo Gates and TypeScript Type Check success.

  • Fixes is right: the PR delivers all four card items (row column read, legacy row → null with no body fallback, registration binding marked source: 'registration', existing reads unchanged) and the acceptance tests (column wins over a differing stamp, legacy → null, neither → null, manager-level skill).
  • Sentence reads (owed by face): .changeset/37039-row-package-binding.md — each bullet checked against listPackageBindings, storedRowColumnPackageId, recordRowColumn/bindReadRowPackage at this head, including the rewritten legacy-row sentence (783d587). content/docs/kernel/contracts/metadata-service.mdx — the interface line, the listPackageBindings section and table, and the types-table row match the contract and code; the table's "null when the column is empty" still holds after S1 (a bound column is no longer empty).
  • Scope: the 10 files equal the round-2 claim's file surface. The two snapshot files are generated (each = main + one MetadataPackageBinding line, verified by diff against main after check:generated --fix).
  • Tests: real runs with output in the PR body; the two L2-fix tests were red before the fix (S1 null, S2 Invalid value used as weak map key) and green after; packages/metadata 83 files / 2805 passed.
  • L2: CONTRACT_REVIEW_TIER round 1 PASS with S1, S2 (comment 7179564385); delta PASS on this head, S1: closed, S2: closed, No must-fix, no should-fix. (comment 7179776919). Adopted: independent sub-agent, Scope covers hits (packages/spec/src/contracts/metadata-service.ts) plus the four implementing files.
  • Security-touching: yes is meant narrowly (the contract teaches which binding a gating consumer may trust); no permission, credential or auth code changes, so no security label.
  • Governed: check-governed-merges.mjs --pr 37187 → NOT governed, 463 lines ≤ 3000. landing-k.mjs: K = 5 < 15, no locale or shared-budget leg.

Accepted deviations / follow-ups (carrier: the area:cloud zone, not filed here): list() lists a stored row twice when its body stamp differs from its column (predates this PR); N2 (a datasource: loader without loadRowBindings answers registration undegraded; none exists in the tree); N3 (double error on a doubly-lost loader); N6 (one jsdoc clause says "the column it was read with" for a bound copy); N7 (two nodes racing on first boot over the same unbound legacy row leave the loser at null until restart, fail-closed).

Local deviation: local derived-gate run at 583ad09 was stopped at 82/114 when the fix round started; its non-zero exits were prerequisite gaps (exit 3) or stale local dist (check:docs-transcript-drift, check:dts-closure), and the CI families covering them are green at this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:cloud#1 · os-warren · session_01JQwxbXcTgn3UMemcSRTDMs

Landing #37187 at head 783d58770850e6357437832279c56aebce407de1 · 2026-11-26T01:53Z

probe reading
check-governed-merges.mjs --pr 37187 NOT governed · 463 changed lines ≤ 3000
pr-state via l1-face.mjs --pr 37187 62 success · 12 expected skip · 0 failed · 0 pending · floor checks success

State: ACCEPT 7180250767 + CONTRACT_REVIEW_TIER PASS 7179776919 on this head → pr_ready + auto-merge. On MERGED, Fixes #37039 closes the card and pm:dispatched is cleared.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 26, 2026 01:54
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 26, 2026
Merged via the queue into main with commit 5bf7242 Nov 26, 2026
75 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-olnt1r branch November 26, 2026 02:20
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ope, by the records a source indexes or by a parent through a listed lookup (objectstack-ai#37342)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8GWXHtfAHuZXmmZpkARr4Wi)_

Fixes objectstack-ai#37308

Clause-②: yes
Metadata-protocol: none

## 维护者速读

-
用户能看到什么变化:知识检索可以限定范围了:只在指定的几条记录里找,或者只在一份上级记录(比如一份制度)下面的条款里找,返回的前几条结果都来自范围内。
- 为什么做:属于「知识检索平台化」专题第三阶段,按您定的「也能指定上级对象(制度)」实现;之后给 AI 用的检索工具也会接上这个参数。
- 出错会怎样:范围只会缩小结果,不会放宽权限,每条结果仍按提问人的权限重新读取;最坏是限定范围后漏掉结果。没有数据迁移,撤回即可。
-
要你做什么:无需你操作。您已在卡片上同意的安全登记行已在(`d1ca7f01`)。开源向量库那个改动先合并了,本分支已合入主干,并让向量库也按范围过滤(在数据库里先筛再排序);由座位做差量复核后重新排队合并。「按记录返回」已合并并合入本分支;与开源向量库那个改动仍有文字冲突,后合并的一方处理。

## What changes

ADR-0161 K8 item 17, in the shape its dated note of 2026-11-25 (objectstack-ai#37324,
merged as `13ffe1c0`) gives it, built in one PR as the note says: the
member, its first reader in `knowledge-memory`, and the suite cases.

**`@objectstack/spec`** (types only, no metadata key):

- `KnowledgeSearchOptions.scope?: Array<{ object: string; ids: string[]
}>` (`packages/spec/src/contracts/knowledge-service.ts`): an option of
the service, not a contract member. Its TSDoc states the own-object and
parent readings, union, absent/empty, and the bounds with the coded
refusal.
- `AdapterSearchOptions.scope?: AdapterScopeTerm[]` and the exported
type `AdapterScopeTerm`
(`packages/spec/src/contracts/knowledge-adapter.ts`): `{ kind: 'record',
ids }` or `{ kind: 'metadata', field, ids }`. Its TSDoc states
absent/present/empty, the AND with `organizationIds` and `filter`, the
bounds an adapter can rely on (at most 10 terms, at most 500 ids each,
every id a non-empty string), and that the service checks every hit
after the answer, so an adapter returns the document's `metadata` on its
hits.
- Regenerated: `api-surface/contracts.json`,
`export-origins/contracts.json` (the new export).

**`@objectstack/service-knowledge`**:

- New `src/knowledge-search-scope.ts`:
- `readSearchScope`: the bounds, `SEARCH_SCOPE_MAX_ENTRIES = 10`,
`SEARCH_SCOPE_MAX_IDS = 500`. Past them it throws `code:
'VALIDATION_ERROR'`, `status: 400` (ADR-0112), naming the bound, before
anything else in `search` runs.
- `scopeTermsFor`: an entry naming the source's object gives a `record`
term. An entry naming another object gives a `metadata` term on the one
`metadataFields` member that is a `lookup` or `master_detail` field
whose `referenceTargetOf` is that object, read from the registered
definition. A `user` field, a withheld (credential-class or `internal`)
field, a field whose target cannot be read, two or more such fields, no
definition, and a `file` / `http` source all give nothing.
- `scopeCheck`: the hit check. It judges `sourceRecordId` or
`metadata[field]`, compares strings and numbers by `String(v)`, and
matches a list when any element matches. Anything else, or no value,
fails closed.
- `KnowledgeService.search`:
  - Validates first.
- `sourcesInScope` pairs each admitted source with its terms. A source
no entry reaches is not searched (debug). The two-lookup ambiguity is
logged once per source and object at `warn`, naming the fields.
- `searchRound` hands each adapter a copy of its terms and checks every
hit after the answer. The first drop for an adapter is logged once at
`warn`.
  - `answered` stays the adapter's own count.
- `src/testing.ts` (the contract suite):
  - New required `implements.scope`.
- Adapter-alone cases, run when `implements.scope` is true: a record
term filters before ranking (topK 1); a metadata term with a list value
returns the document's metadata; the number 7 matches `'7'`; terms are a
union; an empty list or a term with no ids ranks nothing; without the
member everything is ranked; with `organizationIds`, both apply.
- Cases through a real `KnowledgeService` for every adapter: an
own-object scope fills topK from in-scope passages; a parent scope works
through the listed lookup; an adapter with the member stripped answers
no out-of-scope hit, and the service logs once.
  - `serviceOver` gains `schemas`, `stripScope` and `logger`.

**`@objectstack/knowledge-memory`**: applies `scope` after the
organization filter and before scoring. It declares `implements.scope:
true`.

**`@objectstack/knowledge-pgvector`** (landed first, objectstack-ai#37337): applies
`scope` in the same inner `WHERE` as the organization filter, before
`ORDER BY` / `LIMIT`. A `record` term is `source_record_id =
ANY($n::text[])`; a `metadata` term holds when the stored jsonb value of
its field is a string or number equal to an id as text, or a list with
such an element. Ids and field names are bound parameters only. A scope
with no term that has ids answers `[]` before any query. Its live
contract run declares `implements.scope: true`.

**Docs**:

- `content/docs/protocol/knowledge.mdx`: a new "Record scope" section in
§5, a pointer in §3.4, the suite sample, and §4.1 / the adapter table
naming pgvector's record scope.
- `content/docs/ai/knowledge-rag.mdx`: a new "Searching inside chosen
records" section.

**Changeset**: patch for the four packages, with `Clause-②: yes` and
`Metadata-protocol: none`. The change adds no metadata key, and a
non-protocol widening ships patch.

## Tests

- New `src/__tests__/knowledge-search-scope.test.ts`: bounds (each
refusal, and the exact-bound acceptance), term building (each reading of
the note), and the hit check.
- `src/__tests__/knowledge-service.test.ts`, new describe "search scope
(ADR-0161 K8, item 17)":
- the card's acceptance: 20 records, two in scope, topK 5, a full page;
  - an ignoring adapter: no out-of-scope hit, one log;
  - an unreached object: no adapter asked, empty answer;
  - an unreadable scoped record yields no hit;
  - the bounds refuse before any adapter or engine call;
  - empty scope and empty ids answer nothing;
  - the two-lookup case logs once;
  - a numeric lookup value matches its string id;
- a parent scope makes no engine call naming the parent object, and an
adapter that widens the terms it was handed (more ids, an extra term)
still has every out-of-scope hit dropped; every round is handed the
service's own terms (review round 1);
- a scope with `groupBy`, and one with `granularity: 'record'`, over an
adapter that ignores the scope: every round is handed the record term
and no out-of-scope record answers (review round 2).
- The contract suite runs on `knowledge-memory` and both stubs.
- Mutation checks, run locally and reverted:
- `knowledge-memory` with its scope filter removed: 7 suite cases fail.
- `KnowledgeService` without the after-answer check: 7 cases fail across
the stubs and the service tests.
- Handing the adapter the live terms, or reading the parent object's
definition: the round-1 case fails.
- Skipping the scope under `groupBy`, skipping it under record
granularity, or the `groupBy` source filter rebuilding its entries
without the terms: the round-2 case fails.

**Local runs at `760716bc`** (after merging `main` at `98bda0ac`, which
brought objectstack-ai#37337):

- `pnpm --filter @objectstack/spec build` and `check:generated`: exit 0,
after the merge's deferred regeneration of `api-surface/contracts.json`
and `export-origins/contracts.json` (`4552e7c4`).
- `pnpm --filter @objectstack/service-knowledge typecheck` and
`check:test-typecheck`: exit 0. `test`: 13 files, 365 tests passed.
- `pnpm --filter @objectstack/knowledge-memory typecheck` and
`check:test-typecheck`: exit 0. `test`: 2 files, 56 tests passed.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0.
`test` against a local PostgreSQL 16 with pgvector,
`OS_TEST_POSTGRES_URL` set and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`: 4
files, 67 tests passed, every scope case of the suite among them (record
term, metadata term with a list, the number 7, union, empty, absent,
with `organizationIds`; through the service: own object, the parent
through the listed lookup, the member stripped). With the SQL scope
filter removed: 7 of them fail.
- `pnpm --filter @objectstack/core test:repo` (the census pin, at
`d1ca7f01`): 8 files, 110 tests passed.
- **Derived gates at `760716bc`.** `dispatch-gates --commands` derives
119 commands from the 19 changed paths (the 118 before, plus `pnpm
check:kernel-hook-pairs`). Each was run at this head with its output in
its own file and its exit code read before any pipe.
`check:dual-build-cjs-loads` first answered 3 (prerequisite not met: the
new `knowledge-pgvector` had no `dist/`); after `pnpm --filter
@objectstack/knowledge-pgvector build` it was run again, and the record
holds that run.

```text
Run reconciliation — 119 derived, 119 run, 0 NOT-MEASURED, 0 UNRUN.
✓ dispatch-gates --ran: 119 derived famil(ies) accounted for — 119 run, 0 NOT-MEASURED (a DERIVED zero — all 119 recorded an exit code and none of them is 3).
```

<details><summary>The 119 commands at <code>760716bc</code></summary>

| Command | Exit |
|:--|:--|
| `node scripts/check-adr-0087-registration.mjs --base origin/main` | 0
|
| `node scripts/check-adr-0087-registration.mjs --self-test` | 0 |
| `node scripts/check-adr-links.mjs` | 0 |
| `node scripts/check-adr-links.mjs --self-test` | 0 |
| `node scripts/check-changeset-no-major.mjs --base origin/main` | 0 |
| `node scripts/check-closing-keyword-parity.mjs` | 0 |
| `node scripts/check-closing-keyword-parity.mjs --self-test` | 0 |
| `node scripts/check-comment-mask-adoption.mjs` | 0 |
| `node scripts/check-comment-mask-adoption.mjs --self-test` | 0 |
| `node scripts/check-comment-mask-corpus.mjs` | 0 |
| `node scripts/check-dev-prereqs.mjs --self-test` | 0 |
| `node scripts/check-doc-route-spelling.mjs --advisory` | 0 |
| `node scripts/check-doc-route-spelling.mjs --self-test` | 0 |
| `node scripts/check-docs-section-name.mjs` | 0 |
| `node scripts/check-docs-section-name.mjs --self-test` | 0 |
| `node scripts/check-dts-emitted.mjs --self-test` | 0 |
| `node scripts/check-empty-changeset.mjs --base origin/main` | 0 |
| `node scripts/check-empty-changeset.mjs --self-test` | 0 |
| `node scripts/check-issue-citations.mjs` | 0 |
| `node scripts/check-plugin-teardown-shape.mjs` | 0 |
| `node scripts/check-plugin-teardown-shape.mjs --self-test` | 0 |
| `node scripts/check-section-landing-index.mjs` | 0 |
| `node scripts/check-section-landing-index.mjs --self-test` | 0 |
| `node scripts/check-tenant-audit-census.mjs` | 0 |
| `node scripts/check-tenant-audit-census.mjs --self-test` | 0 |
| `node scripts/ci/assert-turbo-remote-cache.mjs --self-test` | 0 |
| `node scripts/ci/plan-test-core-shards.mjs --self-test` | 0 |
| `node scripts/ci/prune-turbo-cache.mjs --self-test` | 0 |
| `node scripts/ci/snapshot-next.mjs --self-test` | 0 |
| `node scripts/docs-audit/check-affected-docs.mjs` | 0 |
| `node scripts/docs-audit/check-drift-comment.mjs` | 0 |
| `node scripts/pm/check-governed-queue-guard.mjs --self-test` | 0 |
| `node scripts/pm/release-rehearsal-clone.mjs --self-test` | 0 |
| `node scripts/release-pending-publish.mjs --self-test` | 0 |
| `pnpm --filter @objectstack/lint run check:doc-formula-expressions` |
0 |
| `pnpm --filter @objectstack/lint run check:doc-security-posture` | 0 |
| `pnpm --filter @objectstack/spec run check:api-surface` | 0 |
| `pnpm --filter @objectstack/spec run check:authorable-surface` | 0 |
| `pnpm --filter @objectstack/spec run check:browser-reachable-entries`
| 0 |
| `pnpm --filter @objectstack/spec run check:docs` | 0 |
| `pnpm --filter @objectstack/spec run check:dual-source-exports` | 0 |
| `pnpm --filter @objectstack/spec run check:duration-unit-keys` | 0 |
| `pnpm --filter @objectstack/spec run check:empty-state` | 0 |
| `pnpm --filter @objectstack/spec run check:entry-nameability` | 0 |
| `pnpm --filter @objectstack/spec run check:error-code-provenance` | 0
|
| `pnpm --filter @objectstack/spec run check:export-origins` | 0 |
| `pnpm --filter @objectstack/spec run check:exported-any` | 0 |
| `pnpm --filter @objectstack/spec run check:generated` | 0 |
| `pnpm --filter @objectstack/spec run check:liveness` | 0 |
| `pnpm --filter @objectstack/spec run check:llms-txt` | 0 |
| `pnpm --filter @objectstack/spec run check:skill-examples` | 0 |
| `pnpm --filter @objectstack/spec run check:skill-refs` | 0 |
| `pnpm --filter @objectstack/spec run check:strictness-ledger` | 0 |
| `pnpm --filter @objectstack/spec run check:variant-docs` | 0 |
| `pnpm --filter @objectstack/spec run check:yaml-examples` | 0 |
| `pnpm check:adr-anchors` | 0 |
| `pnpm check:adr-symbol-anchors` | 0 |
| `pnpm check:changeset-gate-self-tests` | 0 |
| `pnpm check:ci-filter-parity` | 0 |
| `pnpm check:closed-ceremony-text` | 0 |
| `pnpm check:corpus-claim-drift` | 0 |
| `pnpm check:cross-package-test-inputs` | 0 |
| `pnpm check:dispatcher-error-vocabulary` | 0 |
| `pnpm check:doc-anchors` | 0 |
| `pnpm check:doc-authoring` | 0 |
| `pnpm check:doc-frontmatter` | 0 |
| `pnpm check:docs-audit-scope` | 0 |
| `pnpm check:docs-redirects` | 0 |
| `pnpm check:docs-single-h1` | 0 |
| `pnpm check:docs-spec-enumerations` | 0 |
| `pnpm check:docs-transcript-drift` | 0 |
| `pnpm check:driver-memory-census` | 0 |
| `pnpm check:dts-closure` | 0 |
| `pnpm check:engine-double-contract` | 0 |
| `pnpm check:error-status-conformance` | 0 |
| `pnpm check:gitlink-declared` | 0 |
| `pnpm check:init-service-contract` | 0 |
| `pnpm check:issue-citations` | 0 |
| `pnpm check:kernel-hook-pairs` | 0 |
| `pnpm check:keyed-text-bounds` | 0 |
| `pnpm check:lean-entry-closure` | 0 |
| `pnpm check:logger-receiver-detach` | 0 |
| `pnpm check:merge-driver` | 0 |
| `pnpm check:nul-bytes` | 0 |
| `pnpm check:object-def-param-keys` | 0 |
| `pnpm check:objectql-double-limit` | 0 |
| `pnpm check:optional-error-sink` | 0 |
| `pnpm check:org-identifier` | 0 |
| `pnpm check:package-naming` | 0 |
| `pnpm check:page-declaration-shape` | 0 |
| `pnpm check:platform-object-tenancy-census` | 0 |
| `pnpm check:pm-expected-skips` | 0 |
| `pnpm check:pm-prior-rulings` | 0 |
| `pnpm check:published-files` | 0 |
| `pnpm check:published-readme-links` | 0 |
| `pnpm check:query-options-erasure` | 0 |
| `pnpm check:react-page-adapter-contract` | 0 |
| `pnpm check:refd-timer-probe` | 0 |
| `pnpm check:registry-log-declared` | 0 |
| `pnpm check:rest-log-spy-declared` | 0 |
| `pnpm check:role-word` | 0 |
| `pnpm check:settings-bind-window` | 0 |
| `pnpm check:skill-identifier-liveness` | 0 |
| `pnpm check:slot-lookup` | 0 |
| `pnpm check:sourcemap-no-sources-content` | 0 |
| `pnpm check:spec-docblock-symbol-anchors` | 0 |
| `pnpm check:spec-parsed-alias` | 0 |
| `pnpm check:startup-registry-verdict` | 0 |
| `pnpm check:system-context-census` | 0 |
| `pnpm check:test-source-alias` | 0 |
| `pnpm check:tier-file-adoption` | 0 |
| `pnpm check:type-check-coverage` | 0 |
| `pnpm check:type-check-debt` | 0 |
| `pnpm check:undeclared-dep-imports` | 0 |
| `pnpm check:vendor-version-stamps` | 0 |
| `pnpm check:vouch-for-reference-callers` | 0 |
| `pnpm check:watch-hint-literal` | 0 |
| `pnpm check:where-matcher` | 0 |
| `pnpm check:dual-build-cjs-loads` | 0 |

</details>

Earlier heads ran the 118 then derived, all exit 0: `857a2e20` (after
three prerequisites were met) and `ca5a0c11`.

## Acceptance notes

**The five points carried from objectstack-ai#37329's contract review:**

1. **Metadata on hits.** The requirement that an adapter return the
document's `metadata` is stated on `AdapterSearchOptions.scope` and on
`KnowledgeHit.metadata`
(`packages/spec/src/ai/knowledge-document.zod.ts`, added in the merge of
`main` under the seat's claim amendment, review ruling (b)). It is
pinned: the suite's metadata-term case and the parent case through the
service both assert `hit.metadata.policy`.
2. **Ids compared as strings.** Pinned on `scopeCheck`, on the adapter
in the suite, and through the service (a lookup stored as the number 7
matches `'7'`). Only strings and numbers compare. An object, `null` or a
boolean never matches, so `'[object Object]'` cannot be matched by
accident.
3. **An empty scope or an entry with no ids.** It is answered empty,
never refused and never read as "no scope", and no adapter is asked. Why
empty rather than refused: it reads as an empty set reads everywhere
else in this contract (`organizationIds: []`). A caller that computes
ids (the records on screen, a policy's children) then needs no special
case for "none". The tool argument (objectstack-ai#37311) can still refuse at its own
door.
4. **Bounds.** 10 entries and 500 ids per entry are stated on both
TSDocs and pinned. The 500 ids of one term fit one `IN` list, and a
search hands at most 5,000 ids in all. ⚑ This PR owes a ceiling-tier
contract review (CONTRACT_REVIEW_TIER) for the new member.
5. **The opaque `filter`.** Finding for the seat to file:
`KnowledgeSearchOptions.filter` / `AdapterSearchOptions.filter` has no
producer in this tree. The one non-test caller of
`IKnowledgeService.search`, `createKnowledgeTools`, passes none, and the
service gives it no guarantee after the answer. This PR leaves it
unchanged and builds nothing from it. Whether it retires is its own
card. Carrier: none · noted, not filed. Dedupe words: knowledge opaque
filter, AdapterSearchOptions filter retire, KnowledgeSearchOptions
filter producer.

**What the note left to this PR, decided here:**

- **Refill.** `answered` stays the adapter's own count, so whether a
source may hold more is still judged on what it returned. The refill
after the permission filter counts records among the hits that passed
both checks.
- A person's search over an ignoring adapter therefore still reaches
in-scope hits through the refill.
- The system identity gets one round, and may answer fewer than topK
(pinned).
- **Log levels.**
- An adapter whose hits the check drops: `warn`, once per adapter. It is
a deployment defect, and rule 2 says nothing is skipped silently.
- Two lookups to one parent: `warn`, once per source and object. It is
an authoring defect.
- A source a scope does not reach: `debug`, per search, because it is
normal under a scope.
  - Counts appear in logs only, never in the answer.
- **Entry shape.** An entry with another key (for example `field`) is
refused rather than ignored. A `field` key is the note's deferred
alternative, so it fails loud instead of silently reading as something
else. An id that is not a non-empty string is refused: the contract
types ids as strings, and a stored numeric value still matches its
string id.

**Surface and overlap:**

- Outside the claimed file list: the two generated spec artifacts
(`api-surface/contracts.json`, `export-origins/contracts.json`),
required by `check:generated` for the new export.
- `packages/spec/src/ai/knowledge-document.zod.ts`: one TSDoc sentence,
inside the claim as the seat amended it.
- `packages/core/src/security/second-object-read-exposure.pin.test.ts`:
one `CALLERS` row, kind `not-a-served-read`, for
`knowledge-search-scope.ts`, in its own commit `d1ca7f01`, after the
maintainer approved it on the card thread (2026-11-25 22:48Z). The
census pin requires every caller of `referenceTargetOf` to be
classified; the seat's review agrees with the kind. The row cites the
service case that a parent-scoped search makes no engine call naming the
parent object. Run at `d1ca7f01`: `pnpm --filter @objectstack/core
test:repo`, 8 files, 110 tests passed.
- No `scripts/adr-anchors` entry: review ruling (c), not owed.
- `knowledge-ragflow` does not run the suite and ignores `scope` (objectstack-ai#37004
retires it). The service's check keeps its answers in scope. A parent
scope answers nothing from it if its hits carry no metadata.
- objectstack-ai#37337 (objectstack-ai#37100, pgvector) merged before this PR's queue run, and
`main` is merged again at `93c70347`. `searchWithRefusals` validates the
scope first; the admitted sources are filtered by the scope, then by
`groupBy`, then planned (`planSearches` carries each source's terms
beside its fingerprint, `SearchTarget.scope`), and `searchRound` hands
the adapter both `index` and `scope`. The suite's `implements`, the
stubs, `knowledge-memory` and the protocol sample declare the generation
keys and `scope`.
- objectstack-ai#37335 (record-level return) merged first, and `main` was merged into
this branch at `67f11a57`. `search()` validates the scope, `groupBy` and
`granularity` first, then filters the admitted sources by the scope
(`sourcesInScope`) and then by `groupBy` (`sourcesGroupableBy`). Every
round of the record-level path goes through `searchRound`, so every
round is handed the terms and checked.
- `packages/plugins/knowledge-pgvector/**`: inside the claim as the seat
widened it after objectstack-ai#37337 landed (objectstack-ai#37308 item 4): the scope filter in
`search()`, `implements.scope`, and nothing else.
- `overlap-check` at `760716bc`: `main`, objectstack-ai#37265 and objectstack-ai#37187 merge
cleanly.

## Verification

Read first:

1. `packages/services/service-knowledge/src/knowledge-search-scope.ts`:
the whole module (bounds, term building, hit check).
2. `KnowledgeService.search` / `sourcesInScope` / `searchRound` /
`checkScope` in `knowledge-service.ts`: the three-line change at the top
of `search`, and the check after the answer.
3. The two TSDocs in `packages/spec/src/contracts/`.

Two-minute check: run `pnpm --filter @objectstack/service-knowledge exec
vitest run --maxWorkers=2 src/__tests__/knowledge-search-scope.test.ts
src/__tests__/knowledge-service.test.ts -t scope`. Then open the "search
scope" describe and read the acceptance case "20 records, two of them in
scope, topK 5".

---
_Generated by [Claude
Code](https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm)_

<!-- signed: repo:cloud#1 · os-warren · session_01JQwxbZmjM1KubX3ZAoJPPm
-->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…record, and the history selector refuses a package that neither holds nor ships the name (objectstack-ai#37423)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8B1Mg5PDzRbxsNX8cyVk17x)_

Fixes objectstack-ai#37130

Clause-②: yes (narrowing)
Metadata-protocol: none
Skills-docs: none — no `skills/` page teaches the protocol's restore
doors, the history `?package=` selector or `listPackageBindings`

## 维护者速读
-
用户能看到什么变化:环境管理员在历史版本里恢复或整批撤销时,平台自带的技能等记录不再被改写成旧版本,而是直接收到冲突提示和处理办法;按应用查看历史时,既没存过也没提供该名称的应用会被拒绝,不再串到环境自己的记录上。
- 为什么做:这是「平台技能与应用技能分开存放」(云端技能注册)的收尾,补上协议层的两个恢复入口,并顺带修掉同一读取链上的三处小问题。
- 出错会怎样:受影响的只是在环境里恢复平台自带记录旧版本、或按无关应用查历史的管理员,会收到冲突提示;改动可以直接撤回。
- 要你做什么:无

## What changes

1. **Card item 1 (R21).** The metadata protocol's `rollbackMetaItem` and
the restore limb of `revertCommit` refuse a restore whose row is the
platform's own record, with the metadata service's `rollback` refusal:
`409 RESOURCE_CONFLICT`, its prescription, nothing written. One rule for
the three doors: the refusal that lived privately in
`database-loader.ts` is now `refusePlatformRecordRestore(type, name,
row)`, exported by `@objectstack/metadata`, asked by
`DatabaseLoader.registerRollback` and by
`SysMetadataRepository.restoreVersion` when a door passes
`refusePlatformRecord: true` (both protocol restore doors do; the two
undo writes do not). It is judged on the active row `restoreVersion`
itself reads and writes. `revertCommit` puts the refused item in
`failed[]` and reverts the commit's other items (ADR-0067 D3 as
amended). The prescription now also names the environment's route (R23).
2. **Card item 2.** `historySlotOf` (the history, diff and rollback
doors' `?package=` selector) refuses a package that neither holds a row
of the name nor ships it with `409 not-held-by-qualifier`, also when the
name's package-less row is stored. Before, a read naming such a package
fell back to the package-less row and the selector addressed that row.
The package-less row is a package's slot only when the package ships the
name (ADR-0150 D4).
3. **Card item 3 (R22, R23 nits in code).** `PLATFORM_PROVENANCE`'s doc
names all three refused restore doors, words the snapshot rule exactly
(the platform's own record's publish snapshot, served as the answer,
keeps the mark at its top; a snapshot nested inside the answer never
carries it) and names the two undo writes by what they undo. The
stranded `storedRowBodyOf` doc comment in `database-loader.ts` sits on
its function again.
4. **Folded (a).** `list()` listed a stored row twice after the boot
priming pass when its body's `_packageId` stamp differed from its
package column. Measured: the loader keys the row by its column, and
`register(…, { skipSourceLoader: true })` filed the primed copy under
the body's stamp. The fix is in neither `list()` nor the loader: the
priming registration files such a stamped body under the column's slot
(`MetadataManager.primedRowSlot`), so a primed process answers as an
unprimed one does (one listing; a read naming the column's package
answers it; the stamp's answers nothing).
5. **Folded (b) N2.** Decision: fail closed. `listPackageBindings` is
`degraded`, naming the loader, over a `datasource:` loader that offers
no `loadRowBindings`. Reason: such a loader's items answer
`registration`, which is not their rows' binding, and the spec contract
already tells a gating consumer to treat a degraded answer as unknown,
so this needs no contract change. No such loader ships in the tree.
6. **Folded (c) N7.** Cheap fix, no cross-node coordination:
`bindReadRowPackage` already re-reads the row; it now records the column
as that re-read finds it, so the node whose boot pass lost the race
answers the bound package instead of `null` until restart.
7. **R16 re-verified, no code.** `getPublished` applies
`carriesPlatformStamp(item)` to the top level only and strips every
nested snapshot. Its four pins exist in `database-loader.test.ts`
("getPublished serves the mark on the top level only when the stored
item carries it there").

ADR-0010 note, for the weekly ADR revisions card (out of this PR's file
surface): the note should say "a restore whose row is the platform's own
record is refused (`409 RESOURCE_CONFLICT`) at the metadata service's
`rollback` and at the metadata protocol's `rollbackMetaItem` and the
restore limb of `revertCommit`", in place of "a rollback whose row is
the platform's own record is refused (`409`)".

## Deliberate correction

`check-empty-changeset` is red by design on this PR: it rewrites one
pending release note it did not add, because this PR made that note
false.

- Note: `.changeset/37013-platform-skill-own-slot.md` (pending, from
objectstack-ai#37021). Corrected at `43a6758f`, three sentences; the rest of the
bullet is byte-identical:
1. Before: "…and so do the metadata protocol's save door and its restore
doors (`rollbackMetaItem` and the restore limb of `revertCommit`);"
After: "…and so do the metadata protocol's save door and its restore
doors (`rollbackMetaItem` and the restore limb of `revertCommit`) on
every restore whose row is not the platform's own record;"
2. Before: "`rollback` whose row is the platform's own record is refused
(`409 RESOURCE_CONFLICT`, naming the fix), with nothing written." After:
"A restore whose row is the platform's own record is refused (`409
RESOURCE_CONFLICT`, naming the fix), with nothing written, at all three
restore doors: `rollback`, and the metadata protocol's
`rollbackMetaItem` and the restore limb of `revertCommit`."
3. Before: "`getPublished` serves it on the answer's top level only when
the stored item carries it there, and never inside a publish snapshot;"
After: "`getPublished` serves it on the answer's top level only when the
stored item carries it there (the platform's own record's publish
snapshot, served as the answer, keeps the mark it carries at its top),
and never on a snapshot nested inside the answer;"
- Confirmation: the same-head contract review record at
`CONTRACT_REVIEW_TIER` judges each rewritten sentence (pm-dispatch
`references/landing-operations.md`); the seat's ACCEPT points to it.

## Tests

Read first (by risk):
1. `packages/metadata-protocol/src/protocol-history-slots.ts` — the
`holdsSlot` line: the narrowing every `?package=` history, diff and
rollback request passes through.
2. `packages/metadata/src/metadata-manager.ts` — `primedRowSlot`, the
key a primed stored row is filed under.
3. `packages/metadata-protocol/src/sys-metadata-repository.ts` — the
`refusePlatformRecord` check inside `restoreVersion`.

New and changed pins:
- `protocol.platform-mark-rollback.test.ts`, new describe:
`rollbackMetaItem` refused 409 with the row byte-identical;
`revertCommit` puts the item in `failed[]` (code `RESOURCE_CONFLICT`)
and reverts the other item; RESTART: a process primed from the rows
answers a read naming the one package holder with that holder's item and
`getPlatformItem` with the platform's v2. Each was red on `5bf72422`
before the door lines (`expected { success: true, …(4) }`, `expected []
to have a length of 1`, `expected 'platform v1' to be 'package rules'`).
- `protocol-history-slots.test.ts`: the case that pinned "P does not
ship the name … the environment slot" is replaced by its refusal (the
branch the ruling removes), plus a two-holder refusal and a `.custom`
pair CONTROL.
- `protocol-diff-history-slots.33308.test.ts` and the dogfood file
`history-diff-two-holders-33308.dogfood.test.ts`: the case that
addressed the environment's slot through a package shipping nothing now
addresses it through a shipper (unit) or expects the 409 at the history
and diff doors (dogfood).
- `database-loader.test.ts`: (a) a new `list()` pin, and the objectstack-ai#37039
bindings case now expects `differs` once (it recorded the double
listing); N2 and N7 pins.

<details><summary>Ablation (each fix line removed, then restored with
git checkout)</summary>

| Ablated line | Red |
|:--|:--|
| `refusePlatformRecord: true` at `rollbackMetaItem` | 1: the
rollbackMetaItem pin |
| `refusePlatformRecord: true` at `revertCommit` | 2: the revertCommit
pin and the RESTART pin |
| the check in `restoreVersion` | 3: all three door pins |
| `holdsSlot = slot !== null && …` back to `slots.includes(slot)` | 3:
two selector pins and the 33308 diff case |
| `primedRowSlot` not passed to `writeRegistryEntry` | 2: the new
`list()` pin and the objectstack-ai#37039 bindings case |
| N2 `degraded = true` | 1: the N2 pin |
| N7 column record after the re-read | 1: the N7 pin |
| `refusePlatformRecordRestore` answering nothing | 2: the service
`rollback` pins of objectstack-ai#37013 |

</details>

<details><summary>Package runs</summary>

- `pnpm --filter @objectstack/metadata test` at `abc706ce`: Test Files
83 passed (83), Tests 2808 passed (2808).
- `pnpm --filter @objectstack/metadata --filter
@objectstack/metadata-protocol typecheck` at `abc706ce`: both Done, exit
0.
- `pnpm --filter @objectstack/metadata-protocol test` at `955a3452` (the
last commit touching either package before the changeset and the merge
of main, which touched neither): Test Files 370 passed, 9 skipped (379);
Tests 23440 passed, 45 skipped (23485). Re-run at `abc706ce` under the
verify lock: same counts, command exit 0. `pnpm --filter
@objectstack/dogfood test` at `abc706ce` under the lock: Test Files 487
passed, 3 skipped (490); Tests 4128 passed, 68 skipped (4196); exit 0.

</details>

## Acceptance notes

- Declaration: the claim reads `Clause-②: no (narrowing…)`. The diff
also widens the public surface (the `refusePlatformRecordRestore` export
and the `refusePlatformRecord` option of `restoreVersion`), so it
declares `yes (narrowing)`.
- The unreleased `.changeset/37013-platform-skill-own-slot.md` still
carries two of round 4's texts (R22 c and d: "of a failed batch row
write", and the protocol doors reading the mark's one definition) and
"never inside a publish snapshot". That file is outside this claim's
file surface; carrier: the seat, as a deliberate correction with the
next text edit.
- Round 4's R21 paragraph also named one more reading (a version the
platform registered is attributed to the environment in history, so
after the platform withdraws its record under a one-holder name a
rollback naming the package can write it into the package's row). Not in
this claim's scope and not changed here; carrier: the seat.
- objectstack-ai#37187's N3 and N6 were not folded into this card and are untouched.
- Reading, not measured end to end: the `GET
/meta/:type/:name/published` overlay branch serves a stored row's own
body, as round 4 read it; a snapshot nested in that body is served as
stored.

## Verification

Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec
vitest run src/protocol.platform-mark-rollback.test.ts
src/protocol-history-slots.test.ts` after building
`@objectstack/metadata`; expect 6 and 17 passed, including the three
`[objectstack-ai#37130]` door pins and the two `[objectstack-ai#37130]` selector refusals.

<details><summary>Local gates at abc706c</summary>

`node scripts/pm/dispatch-gates.mjs --commands` derived 72 commands; all
72 run, 70 exit 0 at `abc706ce`. Two exit 3 (prerequisite not met, NOT
MEASURED; CI runs both): `node scripts/check-plugin-teardown-shape.mjs
--self-test` (shallow clone), `pnpm check:dual-build-cjs-loads` (unbuilt
packages outside this diff). `pnpm check:type-check-debt` re-run: exit
0. `dispatch-gates --ran`: "72 derived famil(ies) accounted for — 70
run, 2 NOT-MEASURED". `overlap-check --pr=37387`: merges cleanly with
origin/main and objectstack-ai#37387.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01JQwxba3jmfHtmkWfFXfVTc
<!-- signed: repo:cloud#1 · os-warren · session_01JQwxba3jmfHtmkWfFXfVTc
-->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…nto a package's row, and adopt-orphans leaves the platform's record (objectstack-ai#37640)

Fixes objectstack-ai#37604

Clause-②: yes (narrowing)
Metadata-protocol: none
Skills-docs: none — no `skills/` page teaches restoring a
platform-registered version, adopting orphans over the platform's
record, or `listPackageBindings`

## 维护者速读
-
用户能看到什么变化:平台撤回某个内置记录后,管理员按包回滚(或回退某个包的提交)时,如果选中的是平台自己登记的那个版本,会被明确拒绝并提示改为重新保存;"领养孤儿元数据"不再把平台内置记录划进某个包;其余操作不变。
- 为什么做:这是平台内置技能、智能体、工具那一轮收尾留下的两处边角,防止平台自己的内容被悄悄写进某个包里,变成那个包的东西。
- 出错会怎样:只涉及两个少见的管理操作;被拒绝时什么都不写,本改动可直接撤回。
- 要你做什么:无。

## What changes

**Item 1 — a version the platform registered is never restored into a
package's row.** Reproduced on main first (pins red on base, readings
below): after the platform withdraws its record of a skill, the name's
one remaining holder is the package, a version attributed to the
environment counts as that package's slot (`isVersionOf` /
`isAddressedVersion`, M1), and a rollback naming the package, or bare,
answered `Reverted to version 1 (package=com.acme.crm)` and wrote the
platform's body into the package's row. It reproduced at all three
restore doors: the metadata service's `rollback`, and the protocol's
`rollbackMetaItem` and restore limb of `revertCommit` (the last for a
commit that names its package, as `recordPackageCommit` always writes
it; that limb passes no `versionOf`, so it reaches this whenever the
commit's version is one the platform registered).

Route taken: **the loud refusal**, `409 RESOURCE_CONFLICT`, the envelope
of `refusePlatformRecordRestore`, nothing written; `revertCommit` lands
the item in `failed[]` and still reverts the commit's other items.
Judged on the four axes:
- real business need: the scenario is the one the platform's withdrawal
produces for a name a package also ships (the objectstack-ai#37013 slot model),
measured at three doors, not a speculative surface;
- long-term soundness: one rule in the producer
(`@objectstack/metadata`) that all three doors ask, rather than a
per-door filter of which versions a package "wrote";
- keeping AI from writing wrong metadata: a refusal that names the fix
("save it again naming the package") beats a silently narrower version
list — an author or agent sees why, and nothing is written behind its
back;
- no scope growth: no new code, reason value, key or route; `restore
only the package's own versions` would have meant re-defining the M1
attribution rule that history reads share, a larger change for the same
outcome.

The refusal lives in `refusePlatformRecordRestore` as an optional fourth
argument (the version's history row, its number, and the package whose
row is written). The version is judged by its history row with the one
reader below: attributed to no package or to the environment, and its
body carries the platform's mark and names no package. A version
restored into the package-less row (the environment's own item) is left
as before.

**Item 2 — adopt-orphans leaves the platform's own record.** Reproduced
on main: `reassignOrphanedMetadata` rebound the platform's package-less
row to the target package. It now skips a row `isPlatformRecordRow`
reads as the platform's record, as it skips an artifact-backed overlay;
every other orphan is adopted as before.

**N5 — one platform-row reader.** `isPlatformRecordRow(row)` is now
exported from `@objectstack/metadata` (`database-loader.ts`): the
package column names no package (empty, or the environment's history
mark) and the body carries the platform's mark and names no package.
`refusePlatformRecordRestore`, the protocol's overlay census
(`protocol-diff-delete-load.ts`, whose private copy is deleted — the
only edit in that file) and the adoption ask it. Consequence: a
package-bound row whose body keeps the mark is no longer refused by the
row rule (it was refused, prescribing to name the package already
named).

**N1** — the refusal's prescription now says re-saving a version's body
as the environment's own item "holds until the platform's next
registration at boot writes its record back".

**N2** — new pins ride `rollbackMetaItem` (named and bare) and
`revertCommit` with a commit that names its package.

**objectstack-ai#37187 N3** — `listPackageBindings` skips, in its row walk, a loader
the list walk already lost: named once in `errors`, reported once, its
rows not read a second time.

**objectstack-ai#37187 N6** — one doc-comment sentence in
`packages/spec/src/contracts/metadata-service.ts`: a primed copy answers
its row's column as the registry last knew it (the column the boot
priming pass wrote when it bound the row, else the column it was read
with).

**N3 (objectstack-ai#37423 review) — dropped.**
`.changeset/37013-platform-skill-own-slot.md` is no longer pending: the
prerelease `chore: version packages (next)` (`33a31dc7`) compiled it
into `packages/metadata/CHANGELOG.md` and
`packages/metadata-protocol/CHANGELOG.md` and moved it to
`.changeset/pre/`. The same holds for the 37130 note that N1 mentions,
so N1 changes the runtime message only. A factual fix to a compiled
entry belongs in a docs-only PR, not here. N4 needed nothing.

Serial constraints: `protocol-save.ts` is untouched;
`protocol-diff-delete-load.ts` carries only the shared reader (an import
swap and the deleted private copy); `sys-metadata-repository.ts` carries
one call-site change.

Public surface: `isPlatformRecordRow` (new export) and the optional
fourth argument of `refusePlatformRecordRestore`. With the two refusals,
that is why this declares `Clause-②: yes (narrowing)`, not the claim's
`no`. `Metadata-protocol: none`: no key, accepted value, code or route
changes; level `patch`, BREAKING banner and ADR-0087 marker in
`.changeset/37604-platform-record-followups.md`.

## Tests

-
`packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts`:
`rollbackMetaItem` naming the package and bare, and `revertCommit` of a
commit naming the package, each asserting `code: RESOURCE_CONFLICT`,
`status: 409`, the message's "the platform registered", and the rows
byte-identical; plus a control that the package's own version still
restores.
-
`packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts`:
the platform's row stays unbound while the environment orphan beside it
is adopted; a control that a package-less row whose body names a package
is adopted.
- `packages/metadata/src/loaders/database-loader.test.ts`: the service
door's `rollback` named and bare after a real `register(..., { origin:
'platform' })` + `unregister(..., { origin: 'platform' })`; N5 reader
and refusal envelope pins; the objectstack-ai#37187 N3 pin.

<details><summary>Red on base (main 4e10d4b)</summary>

- protocol door: 2 failed, `expected { success: true, … } to match
object { code: 'RESOURCE_CONFLICT', … }`; received message `Reverted to
version 1 (package=com.acme.crm) — type=skill, name=helper [seq=3]`.
- adopt-orphans: 1 failed, `expected 'app.base' to be null`.
- service door: 2 failed, `expected { name: 'data_explorer', … } to
match object { code: 'RESOURCE_CONFLICT', … }`.
</details>

<details><summary>Ablations (fix committed first; each mutation landed
via scripts/ablation-replace.mjs, rebuilt, dist preflight checked,
restored to HEAD and rebuilt)</summary>

- version refusal disabled: `database-loader.test.ts` 2 failed / 498
passed; protocol files 3 failed / 9 passed (the two `rollbackMetaItem`
pins and the `revertCommit` pin).
- lost-loader skip disabled: the objectstack-ai#37187 N3 pin failed (1 / 500).
- reader's column check removed: the two N5 pins failed (2 / 500).
- adopt-orphans filter disabled: the adopt pin failed (1 / 2).
</details>

<details><summary>Suites after the merge of main (33a31dc)</summary>

- `@objectstack/metadata` and `@objectstack/metadata-protocol`
typecheck: exit 0 (tree of 478efd8).
- `@objectstack/metadata` vitest: Test Files 83 passed, Tests 2814
passed (tree of 478efd8).
- `@objectstack/metadata-protocol` vitest: Test Files 371 passed / 9
skipped, Tests 23446 passed / 45 skipped (478efd8). The head d96a1a9
adds one module-top import to the new adopt pin (check:test-source-alias
asked for it).
- `@objectstack/spec` build + `check:generated`: all 14 generated
artifacts up to date.
- Local gates (exit 0): check-adr-0087-registration,
check-changeset-no-major, check-empty-changeset,
check-closing-keyword-parity, check-issue-citations,
check:durability-log-level, check:startup-registry-verdict,
check:doc-authoring, check:nul-bytes, check:undeclared-dep-imports,
check:facade-delegation-only, check:engine-double-contract,
check:test-source-alias, check:adr-anchors. NOT MEASURED:
check:published-readme-exports (exit 3, workspace not built),
check:dev-prereqs (workspace not built). The other derived families run
in CI.
- Full dogfood battery on the final head: running at PR open; its
reading goes to the dispatch report.
</details>

## Acceptance notes

- The two `.changeset/pre/` notes (37013, 37130) still carry "of a
failed batch row write" and the unqualified re-save prescription in the
compiled changelogs; not edited here (see N3 above).
- Other readers of the same fact remain in `database-loader.ts` (the
write path's `platformRow` and the platform withdrawal's `taken`); they
read `isPlatformOrigin` off the body alone. They were not N5's pair and
are left as they are; whether they should ask the shared reader is not
measured here.
- `restore only versions the package itself wrote` was the alternative
route; not taken, for the reasons above.

## Verification

Read first: `packages/metadata/src/loaders/database-loader.ts`
(`isPlatformRecordRow`, `refusePlatformRecordRestore`, the
`registerRollback` call),
`packages/metadata-protocol/src/sys-metadata-repository.ts`
(`restoreVersion`'s call),
`packages/metadata-protocol/src/protocol-package-commits.ts` (the orphan
filter).

Two minutes: `pnpm --filter @objectstack/metadata-protocol exec vitest
run --maxWorkers=2 src/protocol.platform-mark-rollback.test.ts
src/protocol.adopt-orphans-platform-record.test.ts` (after building
`@objectstack/metadata`) — expect 12 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Q4EjjQkY5yXZrN9BEA3rEK
<!-- signed: repo:objectstack#6 · hotlong ·
session_01Q4EjjQkY5yXZrN9BEA3rEK -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

元数据读取:存储的元数据要能按行上记录的包读出绑定,不从正文推断

2 participants