Skip to content

Commit 17cfbf8

Browse files
committed
fix(metadata): the boot pass binds a legacy row's empty package column, the column only (#31699 R7-A)
The priming pass skips the write-through into the loader an item was read from (R5-A). That loader now still binds the empty `package_id` column of the legacy row it handed the item out from, to the package that row's own stored body names: no body, no version, no history row, no insert (`DatabaseLoader.bindReadRowPackage`, called by `MetadataManager.register` in place of the skipped save). Never from the host's `applyProtection` stamp, never from a `loadMany` keying, never into a slot another row holds. `DatabaseLoader`'s plural reads hand out a copy of each cached body, so the pass's stamp no longer edits the read cache (R7-B). The changeset declares the FROM -> TO of a package-less row on a host with a `packageId`. `MetadataRegisterOptions` is exported from the package index (N10). Claude-Session: https://claude.ai/code/session_01Utp6CZu9RRx2o8sFUUpEPU Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6ed3bea commit 17cfbf8

7 files changed

Lines changed: 97 additions & 9 deletions

File tree

‎.changeset/31699-email-template-names-per-namespace.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ The bare-name one-holder rule (`bare-name-one-holder.ts`) has narrowed for `emai
2727

2828
- `MetadataManager`'s in-memory store keeps one slot per `(package, name)` for `email_template` (`PACKAGE_SLOTTED_STORE_TYPES` in `@objectstack/metadata`, now `api`, `agent`, `skill`, `action`, `email_template` and `permission`): two packages' templates of one name both stay in it, `get(type, name, packageId)` answers that package's own (never another package's), and `get` naming no package of a two-holder name refuses `409` naming both (D3), where the second package's item overwrote the first's. The loaders follow the same rules (`DatabaseLoader`, `MemoryLoader`): a save fills `package_id`; a rollback and a delete by name are refused as (5) and (6) state; and their unscoped reads keep every member of every slot (one row per `(package, name, member)`, the canonical locale stored as `bundle_member` NULL), so no locale of any package's bundle is dropped. `MetadataManager.loadMany` and `loadManyKeyed` likewise answer one entry per `(package, name, member)` for an email template, where they answered one per name; `loadMany` reads a row's package from its `package_id` column when the body carries no stamp, and hands such a body on stamped with it (`_packageId`).
2929
- The database loader's save of an email template (`DatabaseLoader.save`) writes the row of the member the body declares, FROM the slot's first row whatever its locale (so a save of `fr-FR` replaced the stored `en-US` body, and a boot's priming pass, which registers every stored member back, did so at every boot) TO that member's own row, inserting it with its `bundle_member` when the slot has none. It never writes over another member's row. A save whose body differs from its row only by a `_packageId` stamp naming the row's own package writes nothing. Every other type stored per `(package, name)` keeps one row per slot. Not a refusal: no write that succeeded before is refused.
30-
- A boot no longer writes back rows it read from the same loader: the priming pass registers each stored item without saving it into the loader it was read from (`MetadataManager.register`'s `skipSourceLoader`), and a file-system item still seeds the database loader.
30+
- A boot no longer writes back rows it read from the same loader: the priming pass registers each stored item without saving it into the loader it was read from (`MetadataManager.register`'s `skipSourceLoader`), and a file-system item still seeds the database loader. So on a host that declares its package (`MetadataPlugin`'s `packageId`), a package-less `DatabaseLoader` row moves FROM saved back at boot with the host's stamp (`_packageId`, `_provenance`), a new version and a history row, and for a type stored per `(package, name)` bound to the host, TO left as stored. The one write the pass still makes into the loader a row came from binds a legacy row's empty `package_id` column to the package that row's own stored body names, the column only (`DatabaseLoader.bindReadRowPackage`); a row whose body names no package stays package-less. `DatabaseLoader`'s `loadMany` and `loadManyKeyed` hand out a copy of each cached body, so the pass's stamp no longer reaches the loader's read cache.
3131

3232
So a package no longer has to rename an email template because a package of another namespace already ships one of that name, and each package's flows keep sending their own.
3333

‎packages/metadata/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*/
99

1010
// Main Manager
11-
export { MetadataManager, type WatchCallback, type MetadataManagerOptions, type MetadataUnregisterOptions } from './metadata-manager.js';
11+
export { MetadataManager, type WatchCallback, type MetadataManagerOptions, type MetadataRegisterOptions, type MetadataUnregisterOptions } from './metadata-manager.js';
1212

1313
// Plugin
1414
export {

‎packages/metadata/src/loaders/database-loader.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1934,7 +1934,10 @@ describe('[#31699 R5-A] the priming pass never writes back a row it read from th
19341934
(manager as any).loaders.clear();
19351935
for (const loader of [...fileSystem, ...loaders]) manager.registerLoader(loader);
19361936
await (plugin as any)._loadFromFileSystem({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } });
1937+
return manager;
19371938
};
1939+
/** What the manager's registry holds for `type`. */
1940+
const registered = (manager: MetadataManager, type: string) => [...((manager as any).registry.get(type)?.values() ?? [])];
19381941

19391942
beforeEach(() => {
19401943
driver = createMockDriver();
@@ -1973,4 +1976,33 @@ describe('[#31699 R5-A] the priming pass never writes back a row it read from th
19731976
rmSync(rootDir, { recursive: true, force: true });
19741977
}
19751978
});
1979+
1980+
// [R7-A; epic ruling 6809488921] The one write the skip still lets reach the source loader.
1981+
const seedAgent = (body: Record<string, unknown>) =>
1982+
driver.create('sys_metadata', {
1983+
id: 'legacy', type: 'agent', name: 'helper', state: 'active', version: 1, checksum: 'legacy', source: 'database',
1984+
package_id: null, metadata: JSON.stringify({ name: 'helper', label: 'Helper', ...body }),
1985+
});
1986+
const agentRow = async () => (await driver.findOne('sys_metadata', { where: { type: 'agent' } } as never)) as Record<string, any>;
1987+
1988+
it('[R7-A] an agent legacy row (empty column, stamped body): the column is bound, body, version and history unchanged', async () => {
1989+
await seedAgent({ _packageId: ALPHA });
1990+
const before = await agentRow();
1991+
const manager = await bootPass([new DatabaseLoader({ driver })], { packageId: 'com.host.app' });
1992+
expect(await agentRow()).toEqual({ ...before, package_id: ALPHA });
1993+
expect(vi.mocked(driver.update).mock.calls).toEqual([['sys_metadata', 'legacy', { package_id: ALPHA }]]);
1994+
expect(driver.create).toHaveBeenCalledTimes(1);
1995+
expect(registered(manager, 'agent')).toEqual([{ name: 'helper', label: 'Helper', _packageId: ALPHA, _provenance: 'package' }]);
1996+
});
1997+
1998+
it('[R7-A, R7-B] a package-less row on a host with a packageId stays package-less, no update; the loader\'s cache keeps it unstamped', async () => {
1999+
await seedAgent({});
2000+
const before = await agentRow();
2001+
const loader = new DatabaseLoader({ driver });
2002+
await bootPass([loader], { packageId: ALPHA });
2003+
expect(await agentRow()).toEqual(before);
2004+
expect(driver.update).not.toHaveBeenCalled();
2005+
expect(driver.create).toHaveBeenCalledTimes(1);
2006+
expect(await loader.loadMany('agent')).toEqual([{ name: 'helper', label: 'Helper' }]);
2007+
});
19762008
});

‎packages/metadata/src/loaders/database-loader.ts‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,8 @@ export class DatabaseLoader implements MetadataLoader {
345345
private readonly listCache?: LRUCache<string, string[]>;
346346
/** (type, name) → MetadataStats — primes `stat()` */
347347
private readonly statCache?: LRUCache<string, MetadataStats | null>;
348+
/** [#31699 R7-A] Each body a plural read handed out from a legacy row, with that row's id and package ({@link bindReadRowPackage}). */
349+
private readonly legacyReadRows = new WeakMap<object, { id: string; packageId: string }>();
348350

349351
constructor(options: DatabaseLoaderOptions) {
350352
if (!options.driver && !options.engine) {
@@ -1136,14 +1138,17 @@ export class DatabaseLoader implements MetadataLoader {
11361138
const data = this.rowToData(row);
11371139
if (data === null) continue;
11381140
const name = row.name;
1141+
const packageId = PACKAGE_SLOTTED_STORE_TYPES.has(type) ? storedRowPackageId(row) : undefined;
11391142
result.push({
11401143
name: typeof name === 'string' && name !== '' ? name : null,
11411144
data,
11421145
...(PACKAGE_SLOTTED_STORE_TYPES.has(type)
11431146
? {
1144-
packageId: storedRowPackageId(row),
1147+
packageId,
11451148
version: Number(row.version) || 0,
11461149
...(isBundledStoreType(type) ? { member: storedBundleMemberOf(type, data, row.bundle_member) ?? null } : {}),
1150+
// [#31699 R7-A] A legacy row: its package named by its stored body alone.
1151+
...(packageId !== undefined && packageId !== row.package_id ? { legacyRowId: String(row.id) } : {}),
11471152
}
11481153
: {}),
11491154
});
@@ -1162,7 +1167,40 @@ export class DatabaseLoader implements MetadataLoader {
11621167
type: string,
11631168
_options?: MetadataLoadOptions
11641169
): Promise<T[]> {
1165-
return (await this.unscopedTypeRows(type)).map(entry => entry.data) as T[];
1170+
return (await this.unscopedTypeRows(type)).map(entry => this.handOut(entry)) as T[];
1171+
}
1172+
1173+
/**
1174+
* [#31699 R7-B] A copy of a cached body, so a caller that stamps what it is
1175+
* handed (the boot priming pass's `applyProtection`) never edits the
1176+
* plural-read cache. A legacy row's copy is recorded for
1177+
* {@link bindReadRowPackage}.
1178+
*/
1179+
private handOut(entry: StoredTypeRow): Record<string, unknown> {
1180+
const copy = { ...entry.data };
1181+
if (entry.legacyRowId !== undefined && entry.packageId !== undefined) this.legacyReadRows.set(copy, { id: entry.legacyRowId, packageId: entry.packageId });
1182+
return copy;
1183+
}
1184+
1185+
/**
1186+
* [#31699 R7-A; epic ruling 6809488921] Bind the empty `package_id` column of
1187+
* the legacy row a plural read handed `item` out from to the package that
1188+
* row's own stored body names: the column only — no body, no version, no
1189+
* history row, no insert (#32347's column-only update). ⛔ Never from
1190+
* `item`'s stamp as it stands now, never a row the read did not hand out,
1191+
* and never into a slot another row of the name holds. `MetadataManager.register`
1192+
* calls it in place of the write-through it skips (`skipSourceLoader`).
1193+
*/
1194+
async bindReadRowPackage(type: string, name: string, item: object): Promise<void> {
1195+
const read = this.legacyReadRows.get(item);
1196+
if (!read) return;
1197+
const rows = await this._find(this.tableName, { where: this.baseFilter(type, name) });
1198+
const row = rows.find((candidate) => String(candidate.id) === read.id);
1199+
if (!row || row.package_id === read.packageId || storedRowPackageId(row) !== read.packageId) return;
1200+
const memberOf = (of: Record<string, unknown>) => storedBundleMemberOf(type, this.rowToData(of), of.bundle_member) ?? null;
1201+
if (rows.some((other) => other !== row && other.package_id === read.packageId && memberOf(other) === memberOf(row))) return;
1202+
await this._update(this.tableName, read.id, { package_id: read.packageId });
1203+
this.invalidate(type, name);
11661204
}
11671205

11681206
/**
@@ -1212,7 +1250,8 @@ export class DatabaseLoader implements MetadataLoader {
12121250
const keyed: MetadataKeyedItem<T>[] = [];
12131251
for (const entry of entries) {
12141252
if (entry.name === null) continue;
1215-
keyed.push(withPackage ? keyedRow<T>(entry.name, entry) : { name: entry.name, data: entry.data as T });
1253+
const data = this.handOut(entry);
1254+
keyed.push(withPackage ? keyedRow<T>(entry.name, { ...entry, data }) : { name: entry.name, data: data as T });
12161255
}
12171256
return keyed;
12181257
}
@@ -1859,6 +1898,8 @@ interface StoredTypeRow {
18591898
version?: number;
18601899
/** [#31699 R3-B] For a bundled by-package type, the member the row holds (`null`: the canonical one). */
18611900
member?: string | null;
1901+
/** [#31699 R7-A] For a by-package type's row whose `package_id` is empty and whose body names `packageId`: its id. */
1902+
legacyRowId?: string;
18621903
}
18631904

18641905
/** [#31699 R3-B] The unscoped read's key of a bundled type's row: its package, name and member. */

‎packages/metadata/src/loaders/loader-interface.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,14 @@ export interface MetadataLoader {
147147
*/
148148
loadManySlots?<T = any>(type: string): Promise<MetadataKeyedItem<T>[]>;
149149

150+
/**
151+
* [#31699 R7-A] Bind the empty `package_id` column of the legacy row this
152+
* loader's plural read handed `item` out from to the package that row's own
153+
* stored body names, the column only. Optional; `MetadataManager.register`
154+
* calls it in place of the write-through it skips (`skipSourceLoader`).
155+
*/
156+
bindReadRowPackage?(type: string, name: string, item: object): Promise<void>;
157+
150158
/**
151159
* Check if item exists
152160
* @param type The metadata type

‎packages/metadata/src/metadata-manager.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,9 @@ export type WatchCallback = (event: MetadataWatchEvent) => void | Promise<void>;
120120
* With it, an item {@link MetadataManager.loadMany} read from a loader is not
121121
* persisted back into that same loader; every other loader's write is
122122
* unchanged. The boot priming pass sets it, so a boot never writes back a row
123-
* it read from the store it read it from. Class-level, as
123+
* it read from the store it read it from. [R7-A] That loader still binds the
124+
* empty `package_id` column of the legacy row the item was read from, the
125+
* column only (`MetadataLoader.bindReadRowPackage`). Class-level, as
124126
* {@link MetadataUnregisterOptions} is.
125127
*/
126128
export interface MetadataRegisterOptions extends MetadataWriteOptions {
@@ -959,8 +961,12 @@ export class MetadataManager implements IMetadataService {
959961
// and because `save?` stays optional on the interface for the protocols
960962
// the gate does not cover. Mirrors the same guard in `unregister()`.
961963
if (typeof loader.save !== 'function') continue;
962-
// [#31699 R5-A] Never back into the loader this item was read from.
963-
if (options?.skipSourceLoader && data !== null && typeof data === 'object' && this.loadedFrom.get(data) === loader) continue;
964+
// [#31699 R5-A] Never back into the loader this item was read from; [R7-A] only the
965+
// column-only bind of the legacy row it was read from reaches that loader.
966+
if (options?.skipSourceLoader && data !== null && typeof data === 'object' && this.loadedFrom.get(data) === loader) {
967+
await loader.bindReadRowPackage?.(type, name, data);
968+
continue;
969+
}
964970
await loader.save(type, name, data);
965971
}
966972

‎packages/metadata/src/plugin.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1673,7 +1673,8 @@ export class MetadataPlugin implements Plugin {
16731673
// edits to these files reach watchers through the
16741674
// FileSystemRepository attached by onEnable.
16751675
// [#31699 R5-A] Never written back into the loader it was read from
1676-
// (a stored row stays as stored); every other loader still receives it,
1676+
// (a stored row stays as stored, but for a legacy row's empty package
1677+
// column, bound from its own stored body: R7-A); every other loader still receives it,
16771678
// so a file-system item still seeds the database loader.
16781679
await this.manager.register(entry.type, meta.name, item, { notify: false, skipSourceLoader: true });
16791680
}

0 commit comments

Comments
 (0)