Skip to content
Merged
25 changes: 25 additions & 0 deletions .changeset/37604-platform-record-followups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
'@objectstack/metadata': patch
'@objectstack/metadata-protocol': patch
---

fix(metadata)!: a version the platform registered is never restored into a package's row, and adopting orphans leaves the platform's own record where the platform keeps it

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`

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped, and no stored row is rewritten. What moves is that the three restore doors refuse a restore they wrote before, and that the adoption of orphans leaves one kind of row it rebound before; there is nothing for a migration to rewrite and no tombstone. -->

**BREAKING**, in two places, each a write that happened before and is now refused or left out:

- **A version the platform registered is never restored into a package's row**, at all three restore doors: the metadata service's `rollback`, and the metadata protocol's `rollbackMetaItem` and the restore limb of `revertCommit`. Refused with `409 RESOURCE_CONFLICT`, naming the fix, nothing written (`revertCommit` reports the item in `failed[]` and still reverts the commit's other items). Before, once the platform had withdrawn its record of a name, the name's one remaining holder was a package, a version attributed to the environment counted as that package's, and a rollback (naming the package or bare) wrote the platform's body into the package's row; `revertCommit` of a package's commit did the same wherever the commit's version was one the platform registered.
What to do: to make that body the package's item, save it again naming the package.
- **`POST /api/v1/packages/:id/adopt-orphans` (`reassignOrphanedMetadata`) leaves the platform's own record**, the package-less row whose body carries the platform's mark: it is the record the platform registers at every boot, not an orphan. Before, the adoption rebound it to the target package, mark and all. Every other orphan is adopted as before.
What to do: nothing.

Also in `@objectstack/metadata`:

- `isPlatformRecordRow(row)` is exported: the one reader of whether a stored row is the platform's own record (its package column names no package, its body carries the platform's mark and names none), asked by `refusePlatformRecordRestore`, the metadata protocol's overlay census and its adoption of orphans, so they cannot disagree. `refusePlatformRecordRestore` now reads a row bound to a package by its column as that package's, whatever its body keeps, and takes an optional fourth argument, the version a restore would write and the package whose row it writes.
- The refusal of a restore whose row is the platform's own record now says that 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.
- `listPackageBindings` names a loader that the read lost once in `errors`, and does not read that loader's rows a second time.
21 changes: 1 addition & 20 deletions packages/metadata-protocol/src/protocol-diff-delete-load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ import { captureStoredExpressionChange, fillStoredExpressionChange } from './pro
import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js';
import type { ProtocolHost } from './protocol-host.js';
import { packagelessHolderRefusal, packagelessRowHeldBaseAddress } from './protocol-save.js';
import { isPlatformOrigin } from '@objectstack/metadata';
import { isPlatformRecordRow } from '@objectstack/metadata';

/**
* [#33308] The row slot a `sys_metadata` row is: its bound package, or `null`
Expand Down Expand Up @@ -1857,22 +1857,3 @@ export class ProtocolDiffDeleteLoadFacet {
return { references: out };
}
}

/**
* [#37013] Whether a stored `sys_metadata` row is the platform's own record:
* bound to no package by its column, and its body carries the platform's mark
* where the metadata service reads it (`isPlatformOrigin`,
* `@objectstack/metadata`). A body that does not parse is not.
*/
function isPlatformRecordRow(record: { package_id?: unknown; metadata?: unknown }): boolean {
if (typeof record.package_id === 'string' && record.package_id !== '') return false;
let body: unknown = record.metadata;
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {
return false;
}
}
return isPlatformOrigin(body);
}
9 changes: 8 additions & 1 deletion packages/metadata-protocol/src/protocol-package-commits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { packageScopedRowWhere } from './sys-metadata-repository.js';
import { overlayMemberWhere } from './migrations/overlay-index.js';
import type { SysMetadataRepository } from './sys-metadata-repository.js';
import { ConflictError, assertProtocolCompat } from '@objectstack/metadata-core';
import { isPlatformRecordRow } from '@objectstack/metadata';
import {
planUnmanagedImport,
UNMANAGED_SEED_TYPE,
Expand Down Expand Up @@ -897,7 +898,13 @@ export class ProtocolPackageCommitsFacet {
(r) => (r?.package_id == null || r.package_id === '' || r.package_id === 'sys_metadata')
// [#23198] An overlay of an artifact item keeps its binding
// (ADR-0070); see the header. The type folds as the save's does.
&& !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name)),
&& !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name))
// [#37604] …nor the platform's own record: the package-less row
// the platform registers at every boot is no orphan an author
// left behind, and rebound it would become the target's item,
// mark and all (`isPlatformRecordRow`, `@objectstack/metadata`,
// the one reader the restore refusal and the overlay census ask).
&& !isPlatformRecordRow(r),
);

// [ADR-0029 D9.9, ADR-0086 D3, #28776] ⭐ THE OWNER JUDGES, in the save
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#37604 item 2] `reassignOrphanedMetadata` (`POST /api/v1/packages/:id/adopt-orphans`)
* never rebinds the platform's own record: a package-less row whose body
* carries the platform's mark is the record the platform registers at every
* boot, not an orphan an author left behind. The one reader of that fact is
* `isPlatformRecordRow` (`@objectstack/metadata`), the reader the restore
* refusal and the overlay census ask.
*
* BASE (main 4e10d4bf): the adoption rebound that row to the target package,
* so the platform's record became the package's item, mark and all.
*/

import { describe, expect, it } from 'vitest';
import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
import { ObjectStackProtocolImplementation } from './protocol.js';
// Pay the source's dynamic `@objectstack/lint` load during collection, never inside a case.
import '@objectstack/lint';

type Row = { id: string; type: string; name: string; state: string; package_id: string | null; metadata: string };

/** `sys_metadata` alone, the empty filter the adoption reads with, the producer's own update dispatch. */
function makeEngine(rows: Row[]) {
const store = new Map(rows.map((r) => [r.id, { ...r }]));
const engine = {
async find(table: string, opts?: { where?: Record<string, unknown>; limit?: number }) {
if (table !== 'sys_metadata') return [];
if (opts?.limit !== undefined || Object.keys(opts?.where ?? {}).length !== 0) {
throw new Error(`fake engine: unsupported read ${JSON.stringify(opts)}`);
}
return [...store.values()];
},
async update(_table: string, data: Record<string, unknown>, opts: { where: Record<string, unknown> }) {
assertEngineUpdateDispatch(data, opts);
const row = store.get(String(opts.where.id));
if (!row) return { id: null };
Object.assign(row, data);
return { id: row.id };
},
};
return { engine, store };
}

const skillRow = (id: string, name: string, body: Record<string, unknown>, packageId: string | null = null): Row => ({
id, type: 'skill', name, state: 'active', package_id: packageId,
metadata: JSON.stringify({ name, label: name, instructions: 'help', ...body }),
});

describe('[#37604] adopt-orphans leaves the platform\'s own record where the platform keeps it', () => {
it('the platform\'s package-less row is not rebound; the environment\'s own orphan beside it is (BASE: both rebound)', async () => {
const { engine, store } = makeEngine([
skillRow('platform', 'helper', { _provenance: 'platform' }),
skillRow('orphan', 'notes', {}),
]);
const protocol = new ObjectStackProtocolImplementation(engine as never);

const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' });

expect(store.get('platform')!.package_id).toBeNull();
expect(store.get('orphan')!.package_id).toBe('app.base');
expect(res.reassigned).toEqual([{ type: 'skill', name: 'notes' }]);
expect(res.reassignedCount).toBe(1);
});

it('control: a package-less row whose body names a package is no platform record, and is adopted', async () => {
const { engine, store } = makeEngine([
skillRow('named', 'helper', { _provenance: 'platform', _packageId: 'com.acme.crm' }),
]);
const protocol = new ObjectStackProtocolImplementation(engine as never);

const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' });

expect(store.get('named')!.package_id).toBe('app.base');
expect(res.reassignedCount).toBe(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,82 @@ describe('[#37130] the protocol\'s restore doors refuse a restore whose row is t
expect(((await primed.getPlatformItem('skill', 'helper')) as { label?: string } | undefined)?.label).toBe('platform v2');
});
});

/**
* [#37604 item 1] After the platform withdraws its own record of a name (its
* package-less row is gone, its versions stay in history attributed to the
* environment), the name's one remaining holder is a package, and a version
* attributed to the environment is that sole slot's (`isVersionOf`). A
* version the platform registered is still never restored into the
* package's row: `409 RESOURCE_CONFLICT`, nothing written.
*
* BASE (main 4e10d4bf): the rollback wrote the platform's v1 into the
* package's row, so a read naming the package answered the platform's body.
*/
describe('[#37604] a version the platform registered is never restored into a package\'s row', () => {
const PKG = 'com.acme.crm';

/** The platform's record (v1, v2), the package's own row (v3), then the platform's withdrawal. */
async function withdrawnPlatformRecord() {
const harness = makeEngine();
const protocol = new ObjectStackProtocolImplementation(harness.engine);
await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v1') });
await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v2') });
const mark = (row: Row) => { row.metadata = JSON.stringify({ ...JSON.parse(String(row.metadata)), _provenance: 'platform' }); };
for (const row of harness.historyRows.filter((r) => r.name === 'helper')) mark(row);
// The withdrawal: the platform's package-less row is deleted, its history stays.
harness.rows.splice(harness.rows.findIndex((r) => r.name === 'helper'), 1);
const pkgBody = JSON.stringify({ ...skill('package rules'), _packageId: PKG });
harness.rows.push({
id: 'row_pkg', type: 'skill', name: 'helper', state: 'active', organization_id: null, package_id: PKG,
version: 3, checksum: 'pkg', source: 'database', metadata: pkgBody,
});
harness.historyRows.push({
id: 'hist_pkg', type: 'skill', name: 'helper', version: 3, organization_id: null, package_id: PKG,
operation_type: 'update', checksum: 'pkg', metadata: pkgBody,
});
return { ...harness, protocol };
}

for (const [door, request] of [
['naming the package', { packageId: PKG }],
['naming no package (the name\'s one holder)', {}],
] as const) {
it(`rollbackMetaItem ${door}: refused 409 RESOURCE_CONFLICT, the package's row byte-identical (BASE: the platform's v1 written into it)`, async () => {
const { protocol, rows } = await withdrawnPlatformRecord();
const before = JSON.stringify(rows);

const refused = await protocol.rollbackMetaItem({ type: 'skill', name: 'helper', toVersion: 1, ...request }).catch((error) => error);

expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
expect(String(refused.message)).toContain('the platform registered');
expect(JSON.stringify(rows)).toBe(before);
});
}

// [#37604 N2] The commit names its package, as `recordPackageCommit` always writes it: the restore limb
// reads that package's row, so the scenario is reachable through `revertCommit` too.
it('revertCommit of a commit that names its package: the platform\'s version lands in failed[] 409-coded, the package\'s row byte-identical (BASE: written into it)', async () => {
const { protocol, rows, serveCommit } = await withdrawnPlatformRecord();
const before = JSON.stringify(rows);
serveCommit({
id: 'c1', commit_id: 'c1', organization_id: null, package_id: PKG, operation: 'apply', message: 'the package\'s commit under revert', created_at: '2026-01-01T00:00:00Z',
items: JSON.stringify([{ type: 'skill', name: 'helper', existedBefore: true, prevVersion: 1 }]),
});

const res = await protocol.revertCommit({ commitId: 'c1' });

expect(res.failed).toHaveLength(1);
expect(res.failed[0]).toMatchObject({ type: 'skill', name: 'helper', code: 'RESOURCE_CONFLICT' });
expect(res.failed[0]!.error).toContain('the platform registered');
expect(res.revertedCount).toBe(0);
expect(JSON.stringify(rows)).toBe(before);
});

it('control: the package\'s own version is restored into its row', async () => {
const { protocol, rows } = await withdrawnPlatformRecord();
await protocol.rollbackMetaItem({ type: 'skill', name: 'helper', toVersion: 3, packageId: PKG });
const stored = JSON.parse(String(rows.find((r) => r.package_id === PKG)!.metadata));
expect(stored.label).toBe('package rules');
});
});
8 changes: 8 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10658,6 +10658,14 @@ export class ObjectStackProtocolImplementation implements
* real orphan object, and whether an adoption refuses, renames or leaves
* the prefix unjudged is the maintainer's question (#28776's ruling). A
* draft is judged by both owner judges when it is promoted.
*
* ## [#37604] The platform's own record is no orphan
*
* A package-less row whose body carries the platform's mark is the record
* the platform registers at every boot (`isPlatformRecordRow`,
* `@objectstack/metadata`), kept beside a package's item of the name in a
* slot of its own. It is left as it is stored, as an artifact-backed
* overlay is: rebound, it would become the target's item, mark and all.
*/
async reassignOrphanedMetadata(request: {
targetPackageId: string;
Expand Down
15 changes: 12 additions & 3 deletions packages/metadata-protocol/src/sys-metadata-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1944,7 +1944,8 @@ export class SysMetadataRepository implements MetadataRepository {
* platform's own record (`refusePlatformRecordRestore`,
* `@objectstack/metadata`: `409 RESOURCE_CONFLICT`, the metadata
* service's `rollback` prescription), read where the write reads it,
* before anything is written. The protocol's two restore doors
* before anything is written. [#37604] So is a version the platform
* registered, restored into a package's row. The protocol's two restore doors
* (`rollbackMetaItem`, the restore limb of `revertCommit`) state it.
* Omitted → no such check: an undo write puts back what the same
* operation found, byte for byte.
Expand Down Expand Up @@ -2022,8 +2023,16 @@ export class SysMetadataRepository implements MetadataRepository {
where: this.whereFor(ref, 'active', 'packageId' in opts ? (opts.packageId ?? null) : undefined, member),
context: { isSystem: true },
});
// [#37130] The row this restore writes, judged before the write.
if (opts.refusePlatformRecord === true) refusePlatformRecordRestore(ref.type, ref.name, activeRow as Record<string, unknown> | null);
// [#37130] The row this restore writes, judged before the write. [#37604]
// …and the version it writes: one the platform registered is never
// written into a package's row.
if (opts.refusePlatformRecord === true) {
refusePlatformRecordRestore(ref.type, ref.name, activeRow as Record<string, unknown> | null, {
historyRow: row as Record<string, unknown>,
version: targetVersion,
intoPackageId: 'packageId' in opts ? (opts.packageId ?? null) : ((activeRow as { package_id?: string | null } | null)?.package_id ?? null),
});
}
const activePackageId =
(activeRow as { package_id?: string | null } | null)?.package_id ?? null;
const currentActive = activeRow ? this.rowToItem(ref, activeRow) : null;
Expand Down
4 changes: 4 additions & 0 deletions packages/metadata/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export {
// [#37130] The platform's record is never restored: the one refusal the
// metadata service's rollback and the metadata protocol's restore doors ask.
refusePlatformRecordRestore,
// [#37604 N5] …and the one reader of whether a stored row is the platform's
// own record, which that refusal, the protocol's overlay census and its
// adoption of orphans ask.
isPlatformRecordRow,
type DatabaseLoaderOptions,
type MetadataHistoryAddress,
} from './loaders/database-loader.js';
Expand Down
Loading
Loading