From 30d2dbe6565efcbe11e230751fcf5f8655124186 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 08:46:31 +0000 Subject: [PATCH 01/19] wip(spec): retire SeedMode insert and replace (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- packages/spec/src/data/seed-loader.test.ts | 6 +-- packages/spec/src/data/seed-loader.zod.ts | 4 +- packages/spec/src/data/seed.test.ts | 23 ++++++-- packages/spec/src/data/seed.zod.ts | 52 +++++++++++++++---- .../18.seed-mode-insert-replace-retired.ts | 35 +++++++++++++ 5 files changed, 99 insertions(+), 21 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts diff --git a/packages/spec/src/data/seed-loader.test.ts b/packages/spec/src/data/seed-loader.test.ts index 81c0a72fee1..c7b07142c5f 100644 --- a/packages/spec/src/data/seed-loader.test.ts +++ b/packages/spec/src/data/seed-loader.test.ts @@ -261,7 +261,7 @@ describe('SeedLoaderConfigSchema', () => { }); it('should accept all valid dataset modes as default', () => { - const modes = ['insert', 'update', 'upsert', 'replace', 'ignore'] as const; + const modes = ['update', 'upsert', 'ignore'] as const; modes.forEach(mode => { const config = SeedLoaderConfigSchema.parse({ defaultMode: mode }); expect(config.defaultMode).toBe(mode); @@ -326,7 +326,7 @@ describe('SeedLoadResultSchema', () => { it('should accept a result with deferred references', () => { const result = SeedLoadResultSchema.parse({ object: 'task', - mode: 'insert', + mode: 'ignore', inserted: 10, updated: 0, skipped: 0, @@ -341,7 +341,7 @@ describe('SeedLoadResultSchema', () => { it('should default errors to empty array', () => { const result = SeedLoadResultSchema.parse({ object: 'product', - mode: 'insert', + mode: 'ignore', inserted: 1, updated: 0, skipped: 0, diff --git a/packages/spec/src/data/seed-loader.zod.ts b/packages/spec/src/data/seed-loader.zod.ts index 0cd7da1ec4c..855aff99898 100644 --- a/packages/spec/src/data/seed-loader.zod.ts +++ b/packages/spec/src/data/seed-loader.zod.ts @@ -418,8 +418,8 @@ export const SeedLoadResultSchema = lazySchema(() => z.object({ * and left as it was. Each id appears once, in record order. Empty on a * dry run, which writes nothing and matches nothing. * - * [#30348] Exactly what the loader fills, per mode: `insert` / `replace` — - * each row an insert created; `ignore` (the default since #30081) — each row + * [#30348] Exactly what the loader fills, per mode: `ignore` (the default + * since #30081; the unkeyed `insert` / `replace` modes are retired, #34613) — each row * an insert created AND each existing row a record's key matched, which the * mode then leaves as it was; `upsert` — created, updated, and matched-but- * unchanged rows; `update` — updated and matched-but-unchanged rows (an diff --git a/packages/spec/src/data/seed.test.ts b/packages/spec/src/data/seed.test.ts index 4760d92f3c5..eaee698b61b 100644 --- a/packages/spec/src/data/seed.test.ts +++ b/packages/spec/src/data/seed.test.ts @@ -5,13 +5,26 @@ import { FieldMappingEntrySchema } from '../api/export.zod'; describe('SeedMode', () => { it('should accept valid dataset modes', () => { - const validModes = ['insert', 'update', 'upsert', 'replace', 'ignore']; + const validModes = ['update', 'upsert', 'ignore']; validModes.forEach(mode => { expect(() => SeedMode.parse(mode)).not.toThrow(); }); }); + // [#34613] The two unkeyed modes are retired (ADR-0049 enforce-or-remove): + // each refusal names the mode, the version and the keyed fix. + it.each([ + ['insert', /`seed\.mode: 'insert'` was removed in @objectstack\/spec 18\.6\.0.*every replay.*inserted each record again.*`mode: 'ignore'`.*`externalId`/s], + ['replace', /`seed\.mode: 'replace'` was removed in @objectstack\/spec 18\.6\.0.*no load ever clears one.*`mode: 'ignore'`.*`externalId`/s], + ])('refuses the retired mode %s with its prescription', (mode, prescription) => { + expect(() => SeedMode.parse(mode)).toThrow(prescription); + const parsed = SeedSchema.safeParse({ object: 'task', mode, records: [{ name: 'a' }] }); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues[0]?.path).toEqual(['mode']); + expect(parsed.error?.issues[0]?.message).toMatch(prescription); + }); + it('should reject invalid modes', () => { expect(() => SeedMode.parse('merge')).toThrow(); expect(() => SeedMode.parse('delete')).toThrow(); @@ -61,7 +74,7 @@ describe('SeedSchema', () => { }); it('keeps every authored mode as written — only an omitted mode takes the default', () => { - for (const mode of ['insert', 'update', 'upsert', 'replace', 'ignore'] as const) { + for (const mode of ['update', 'upsert', 'ignore'] as const) { expect(SeedSchema.parse({ object: 'product', mode, records: [] }).mode).toBe(mode); } }); @@ -84,7 +97,7 @@ describe('SeedSchema', () => { }); it('should accept different modes', () => { - const modes: Array = ['insert', 'update', 'upsert', 'replace', 'ignore']; + const modes: Array = ['update', 'upsert', 'ignore']; modes.forEach(mode => { const dataset = SeedSchema.parse({ @@ -208,7 +221,7 @@ describe('SeedSchema', () => { const demoData = SeedSchema.parse({ object: 'project', externalId: 'name', - mode: 'replace', + mode: 'ignore', env: ['dev'], records: [ { name: 'Demo Project 1', status: 'active' }, @@ -217,7 +230,7 @@ describe('SeedSchema', () => { }); expect(demoData.env).toEqual(['dev']); - expect(demoData.mode).toBe('replace'); + expect(demoData.mode).toBe('ignore'); }); it('should handle test data use case', () => { diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index acfd2e15f12..bab224d383f 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -7,6 +7,7 @@ import { z } from 'zod'; * Defines how the engine handles existing records when a seed is applied. */ import { lazySchema } from '../shared/lazy-schema'; +import { enumWithRetiredValues } from '../shared/retired-key'; import { strictObject } from '../shared/strict-object'; import { MetadataProtectionFields } from '../kernel/metadata-protection.zod'; import { LocaleSchema } from '../system/translation.zod'; @@ -20,13 +21,42 @@ import { SeedFileReferenceSchema, isSeedFileReference, } from './seed-file.zod'; -export const SeedMode = z.enum([ - 'insert', // Insert every record, no match: each replay inserts them again (a row the database refuses is that row's error) +/** + * The fix both retired modes share: a seed row's identity is declared, never + * guessed by the loader (#34613, ruling 6942780880). + */ +const SEED_MODE_RETIRED_FIX = + 'Declare the rows\' identity instead: keep the default `mode: \'ignore\'` (or `\'upsert\'`) and set ' + + '`externalId` to the field that names a row, to a list of fields when no single field does (a junction ' + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids.'; + +/** + * The parse refusals an author meets for the two unkeyed modes (ADR-0049 + * enforce-or-remove; `enumWithRetiredValues`, `../shared/retired-key.ts`). + * A seed is replayed — every single-tenant boot, every package install or + * upgrade, every publish — and neither mode matched a row, so each replay + * inserted every record again: the table grew by the dataset on every restart, + * and a person reference the first load had to leave NULL stayed NULL on the + * first row while a later copy got it (#34613, measured 1 → 2 → 3 rows over + * three boots). `replace` promised a table "the caller cleared" and no load + * path ever cleared one. No D2 conversion: which field names a row is the + * author's to say. The D3 semantic entry `seed-mode-insert-replace-retired` + * carries that judgement. + */ +const SEED_MODE_INSERT_RETIRED = + "`seed.mode: 'insert'` was removed in @objectstack/spec 18.6.0 (ADR-0049 enforce-or-remove) — a seed is " + + 'replayed on every boot, package install and publish, and `insert` matched no existing row, so every replay ' + + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; +const SEED_MODE_REPLACE_RETIRED = + "`seed.mode: 'replace'` was removed in @objectstack/spec 18.6.0 (ADR-0049 enforce-or-remove) — it inserted " + + 'every record and left clearing the table to the caller, and no load ever clears one, so every replay ' + + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; + +export const SeedMode = enumWithRetiredValues([ 'update', // Only update found records, ignore new 'upsert', // Create new or update existing: every replay writes the declared columns back - 'replace', // Insert every record, no match, deleting nothing: for a cache table the caller cleared 'ignore' // Create-only (the default): insert missing rows, leave existing rows alone -]); +], { insert: SEED_MODE_INSERT_RETIRED, replace: SEED_MODE_REPLACE_RETIRED }); /** * Seed Column — the write policy a seed dataset declares for one of its @@ -46,8 +76,8 @@ export const SeedColumnSchema = lazySchema(() => strictObject({ * replay's no-op check, not written, and — a reference column — not * resolved and not deferred to pass 2, so nothing the load does afterwards * writes it back. A row the load creates gets it like any other column. - * `insert`, `ignore` and `replace` never update a matched row, so the policy - * changes nothing on those modes. + * `ignore` never updates a matched row, so the policy changes nothing on + * that mode. * * A column of the dataset's `externalId` is the key the row was matched by: * it stays in the matched row's update whatever it declares, as an import's @@ -154,8 +184,9 @@ export const SeedSchema = lazySchema(() => strictObject({ * — a list of field names — is required for objects with no single-field * natural key, most commonly a **join / junction table** keyed by both of its * foreign keys (e.g. `externalId: ['team', 'project']`). Without it such a - * dataset can only run `mode: 'insert'`, which re-inserts every row on each - * replay boot and duplicates the table (framework#3434). The reference fields + * dataset has no key to match a replay on (the unkeyed `insert` mode, which + * re-inserted every row on each replay boot and duplicated the table — + * framework#3434 — is retired, #34613). The reference fields * are matched by their RESOLVED ids, so a composite of foreign keys dedupes * correctly across restarts. */ @@ -214,9 +245,8 @@ export const SeedSchema = lazySchema(() => strictObject({ 'is create-only: a missing row is inserted and an existing row is left as it is, so a replay ' + '(every boot, a package install or upgrade, a publish) never writes a seeded value back over a ' + 'later edit. `upsert` also writes every declared column back onto the matched row on each replay; ' + - 'declare it for reference data the package keeps current. `update` writes matched rows only, ' + - '`insert` inserts every record with no match, so each replay inserts them again, and `replace` does the ' + - 'same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization ' + + 'declare it for reference data the package keeps current. `update` writes matched rows only. Every mode ' + + 'matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization ' + '(the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or ' + '`upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that ' + 'names no organization and finds no sole one, keeps no such record, and seed-replayer called with ' + diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts new file mode 100644 index 00000000000..954690f7561 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the two unkeyed seed modes, `insert` and +// `replace`, retired from `SeedSchema.mode` (ADR-0049 enforce-or-remove; +// maintainer ruling on #34613, option B). No D2 conversion: which field names +// a seed row is the author's to declare, and a rewrite to a keyed mode would +// guess it. +export const entry: SemanticMigration = { + id: 'seed-mode-insert-replace-retired', + surface: + 'data.Seed.mode (a seed dataset in `defineStack({ data })`, `defineSeed`, a `seed` metadata item, or a package ' + + 'body\'s seed): the values `insert` and `replace`', + replacement: + 'Keep the default `mode: \'ignore\'` (or declare `\'upsert\'` for reference data the package keeps current) and ' + + 'set `externalId` to the field that names a row, to a list of fields when no single field does (a junction ' + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids', + reason: + 'A seed is replayed, not applied once: on every single-tenant boot, every package install or upgrade, every ' + + 'publish. `insert` matched no existing row, so every replay inserted each record again, and `replace` did the ' + + 'same while promising a table the caller cleared, which no load path ever clears. Measured on an un-walled ' + + 'install over three boots: 1, then 2, then 3 rows; a person reference the first load had to leave NULL stayed ' + + 'NULL on the first row while only the newest copy named the person; with a unique field the replay insert was ' + + 'refused and the one row stayed NULL. Both values are now refused where a seed is parsed, with the ' + + 'prescription. A dataset already stored with either value is refused loudly by the loads that replay stored ' + + 'seeds (the boot seed, the per-organization replay, the dev hot reload, a package install or upgrade): that ' + + 'dataset writes nothing and the load logs its prescription at error, and every other dataset loads. There is no ' + + 'mechanical rewrite, because a keyed mode needs the field that identifies a row, and only the author knows it. ' + + 'Rows earlier replays duplicated are data, not metadata, and are left as they are', + acceptanceCriteria: + 'os validate reports no seed dataset whose `mode` is `insert` or `replace`; every dataset that declared one ' + + 'declares `ignore` or `upsert` with an `externalId` naming fields its object has; after two restarts over the ' + + 'same database the seeded object holds one row per record, and the boot log carries no seed-mode refusal.', +}; From 5267073711d595875be0a03c22faf59ee7c3b079 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:03:37 +0000 Subject: [PATCH 02/19] wip: loader refuses a stored retired-mode dataset alone; lint rule retired; fixtures keyed (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- packages/cli/src/commands/diff.ts | 8 +- packages/cli/test/diff-upgrade-plan.test.ts | 11 +- .../seed-record-values-load-parity.test.ts | 4 +- .../cloud-connection-auth-gate.pin.test.ts | 6 + .../marketplace-install-local-heal.test.ts | 6 + .../src/marketplace-install-local-plugin.ts | 10 +- .../marketplace-install-local-reseed.test.ts | 6 + ...stall-local-resolver-refusal-34432.test.ts | 2 + ...tplace-install-local-seed-replayer.test.ts | 6 + ...lace-install-local-tenancy-posture.test.ts | 6 + packages/lint/src/authoring-rules.ts | 17 +- packages/lint/src/index.ts | 6 - packages/lint/src/rule-explanations.ts | 23 +-- .../src/validate-seed-replay-safety.test.ts | 153 ------------------ .../lint/src/validate-seed-replay-safety.ts | 80 --------- .../metadata-core/src/package-upgrade-plan.ts | 8 +- ...ocol-publish-drafts-all-or-nothing.test.ts | 2 +- .../src/protocol-save-door-refusals.ts | 10 +- .../protocol.seed-external-id-refusal.test.ts | 15 +- .../seed-loader-composite-external-id.test.ts | 2 +- .../src/seed-loader-deferred-dropped.test.ts | 18 ++- .../src/seed-loader-deferred-failure.test.ts | 6 +- .../src/seed-loader-driver-text.test.ts | 4 +- .../seed-loader-organization-stamp.test.ts | 8 +- .../src/seed-loader-pointer-pair.test.ts | 7 +- .../seed-loader-retired-mode-34613.test.ts | 141 ++++++++++++++++ .../src/seed-loader-retry.test.ts | 10 +- ...der-sole-organization-read-failure.test.ts | 4 +- .../src/seed-loader-summary-scope.test.ts | 12 +- .../src/seed-loader-summary-stale.test.ts | 6 +- .../src/seed-loader-unresolved-drop.test.ts | 8 +- packages/metadata-protocol/src/seed-loader.ts | 109 +++++++++---- .../src/engine-seed-required-deferral.test.ts | 14 +- ...redicate-related-read-tenant-scope.test.ts | 2 +- ...grant-table-write-contract.dogfood.test.ts | 2 +- .../app-plugin.seed-stamped-additive.test.ts | 8 +- packages/runtime/src/app-plugin.seed.test.ts | 6 +- packages/runtime/src/app-plugin.ts | 18 +-- .../runtime/src/artifact-collections.test.ts | 8 +- ...bulk-write-real-driver.integration.test.ts | 6 +- packages/runtime/src/seed-datasets.test.ts | 6 + ...river-text-real-driver.integration.test.ts | 4 +- packages/runtime/src/seed-loader.test.ts | 10 +- .../src/harness.seed-temporal-form.test.ts | 6 +- 44 files changed, 394 insertions(+), 410 deletions(-) delete mode 100644 packages/lint/src/validate-seed-replay-safety.test.ts delete mode 100644 packages/lint/src/validate-seed-replay-safety.ts create mode 100644 packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index 36e7cb95eb1..fda3fd47177 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -78,8 +78,12 @@ function diffNamedArrays( function seedModeNote(mode: string): string { if (seedModeOverwritesMatchedRows(mode)) return '; a replay writes its columns over the rows it matches'; - if (mode === 'replace') return '; a replay deletes nothing and inserts these again, so rows already in the table stay'; - if (mode === 'insert') return "; a replay inserts these again, and a row the database refuses is that row's error"; + // [#34613] `insert` and `replace` are retired: a replay refuses such a + // dataset whole and writes none of it, so the note says what to declare. + if (mode === 'insert' || mode === 'replace') { + return `; \`${mode}\` is a retired seed mode: a replay refuses this dataset and writes none of it. ` + + "Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row"; + } return ''; } diff --git a/packages/cli/test/diff-upgrade-plan.test.ts b/packages/cli/test/diff-upgrade-plan.test.ts index 135d0c94408..f0a8b90306a 100644 --- a/packages/cli/test/diff-upgrade-plan.test.ts +++ b/packages/cli/test/diff-upgrade-plan.test.ts @@ -144,7 +144,8 @@ describe('os diff — what the upgrade plan adds', () => { { type: 'removed', category: 'data', name: 'acme_old', breaking: false, detail: 'seed dataset removed, mode insert' }, { type: 'added', category: 'data', name: 'acme_tier', breaking: false, - detail: 'seed dataset added: 1 record(s); mode replace; a replay deletes nothing and inserts these again, so rows already in the table stay', + detail: 'seed dataset added: 1 record(s); mode replace; `replace` is a retired seed mode: a replay refuses this ' + + "dataset and writes none of it. Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row", }, { type: 'modified', category: 'data', name: 'acme_stage', breaking: false, @@ -154,7 +155,10 @@ describe('os diff — what the upgrade plan adds', () => { ]); }); - it('an insert dataset, added or changed, says a replay inserts its records again; ignore stays silent', () => { + // [#34613] A stored artifact built before the retirement can still carry + // `insert`: the diff names the mode as retired and the fix, rather than + // describing a replay that no longer writes the dataset. + it('a retired insert dataset, added or changed, says a replay refuses it; ignore stays silent', () => { const before = lead({}, [ { object: 'acme_source', mode: 'insert', records: [{ name: 'web' }] }, { object: 'acme_region', mode: 'ignore', records: [{ name: 'emea' }] }, @@ -164,7 +168,8 @@ describe('os diff — what the upgrade plan adds', () => { { object: 'acme_region', mode: 'ignore', records: [{ name: 'apac' }] }, { object: 'acme_channel', mode: 'insert', records: [{ name: 'email' }] }, ]); - const insertNote = "a replay inserts these again, and a row the database refuses is that row's error"; + const insertNote = '`insert` is a retired seed mode: a replay refuses this dataset and writes none of it. ' + + "Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row"; expect(diffStacks(before, after)).toEqual([ { type: 'added', category: 'data', name: 'acme_channel', breaking: false, diff --git a/packages/cli/test/seed-record-values-load-parity.test.ts b/packages/cli/test/seed-record-values-load-parity.test.ts index 0d9c80ad21d..0802f2f0bd2 100644 --- a/packages/cli/test/seed-record-values-load-parity.test.ts +++ b/packages/cli/test/seed-record-values-load-parity.test.ts @@ -54,8 +54,8 @@ async function seedLoad(): Promise<{ written: string[]; refused: Map PROJECT, listObjects: async () => [PROJECT] }; const loader = new SeedLoaderService(engine as never, metadata as never, silent as never); const result = await loader.load({ - seeds: [{ object: 'proj_project', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: structuredClone(RECORDS) }], - config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1, transaction: false, organizationId: 'org_parity' }, + seeds: [{ object: 'proj_project', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: structuredClone(RECORDS) }], + config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1, transaction: false, organizationId: 'org_parity' }, } as never); const refused = new Map(); for (const e of result.errors as Array<{ recordIndex?: number; message: string }>) { diff --git a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts index 3505a368aab..16ceb028706 100644 --- a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts +++ b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts @@ -50,6 +50,12 @@ import { isAuthGateAllowlisted } from '@objectstack/core'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts index 7344130221e..f36cbaa5978 100644 --- a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts @@ -29,6 +29,12 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } // The purge reads the loader's dependency order; these objects // reference nothing, so the order is the order asked. diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index c81043840d2..203f0241d2c 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -7636,10 +7636,7 @@ export class MarketplaceInstallLocalPlugin implements Plugin { try { metadata = ctx.getService('metadata'); } catch { /* none */ } if (!ql || !metadata) throw new Error('objectql-or-metadata-missing'); - const [{ SeedLoaderService, appDefaultSeedLocale, describeSeedLocale, resolveSeedLocaleForLoad }, { SeedLoaderRequestSchema }] = await Promise.all([ - import('@objectstack/runtime'), - import('@objectstack/spec/data'), - ]); + const { SeedLoaderService, appDefaultSeedLocale, describeSeedLocale, resolveSeedLocaleForLoad } = await import('@objectstack/runtime'); const seedLocale = await resolveSeedLocaleForLoad(ctx, { seeds: datasets, organizationId, @@ -7648,7 +7645,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin { }); ctx.logger?.info?.(`[MarketplaceInstallLocal] seed locale${organizationId ? ` for org ${organizationId}` : ''}: ${describeSeedLocale(seedLocale)}`); const seedLoader = new (SeedLoaderService as any)(ql, metadata, ctx.logger, { landedKeys }); - const request = (SeedLoaderRequestSchema as any).parse({ + // [#34613] `loadStored`: a stored dataset declaring a retired `mode` + // is refused alone, as an error of the result; the rest load. + const result = await seedLoader.loadStored({ // ADR-0036 / seed rename: the field is `seeds` (was `datasets`). seeds: datasets, config: { @@ -7663,7 +7662,6 @@ export class MarketplaceInstallLocalPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale.locale } : {}), }, }); - const result = await seedLoader.load(request); // [#30324 · ruling 6670861426] The rows this load CREATED get the // person this door names as `owner_id` and `created_by`, then follow // the ordinary permission rules like any record they own. diff --git a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts index 77924fa7f97..6816530912c 100644 --- a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts @@ -33,6 +33,12 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, // [#30281] The seed-locale producer, answering "no locale": this suite's diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts index f5759aba534..a024a79ada6 100644 --- a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts @@ -30,6 +30,8 @@ import { tmpdir } from 'node:os'; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts index d6de3dba016..d62031cd70e 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts @@ -93,6 +93,12 @@ const appDefaultBodies: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts index 7789aa9f275..7e7db62d4cd 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts @@ -53,6 +53,12 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 55665132f78..2eb3d175e69 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -131,7 +131,6 @@ import { validateSemanticRoles } from './validate-semantic-roles.js'; import { validateFormLayout } from './validate-form-layout.js'; import { validatePublicFormFileFields } from './validate-public-form-file-fields.js'; import { validateThankYouRecordFields } from './validate-thank-you-record-fields.js'; -import { validateSeedReplaySafety } from './validate-seed-replay-safety.js'; import { validateAssignmentRules } from './validate-assignment-rules.js'; import { validateSeedStateMachine } from './validate-seed-state-machine.js'; import { validateVisibilityPredicates } from './validate-visibility-predicates.js'; @@ -1826,18 +1825,10 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateAssignmentRules(stack), }, - // framework#3434 — seeds replay on every boot, so a `mode: 'insert'` dataset - // duplicates its table on every restart. - { - name: 'validateSeedReplaySafety', - tier: 'advisory', - input: 'parsed', - commands: ALL, - source: 'packages/lint/src/validate-seed-replay-safety.ts', - surfaces: CLI_ONLY, - surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, - run: (stack) => validateSeedReplaySafety(stack), - }, + // [#34613] `validateSeedReplaySafety` (framework#3434, the `insert`-mode + // replay warning) is retired: `SeedMode` itself refuses `insert` and + // `replace` at parse (ruling 6942780880), so no stack this rule could flag + // gets past the schema. // framework#3433 follow-up — #3433 exempts seed writes from the // `state_machine` rule, so a seeded status the FSM does not declare is no // longer rejected at write time. Re-added at author time; advisory, because diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 31672a7c7f6..a1add7e25d7 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -349,12 +349,6 @@ export { } from './validate-assignment-rules.js'; export type { AssignmentRuleFinding, AssignmentRuleSeverity } from './validate-assignment-rules.js'; -export { - validateSeedReplaySafety, - SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, -} from './validate-seed-replay-safety.js'; -export type { SeedReplaySafetyFinding, SeedReplaySafetySeverity } from './validate-seed-replay-safety.js'; - export { validateSeedStateMachine, SEED_VALUE_OUTSIDE_STATE_MACHINE, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index ad337d8e42a..8d5ca9d2dd2 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -5624,7 +5624,7 @@ const PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION: RuleExplanation = { ], }; -// ── Seed datasets (`validate-seed-replay-safety.ts`, `validate-seed-state-machine.ts`) ── +// ── Seed datasets (`validate-seed-state-machine.ts`) ── // ── Assignment rules (`validate-assignment-rules.ts`) ── @@ -5662,26 +5662,6 @@ const ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION: RuleExplanation = { ], }; -const SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION: RuleExplanation = { - rule: 'seed-insert-mode-duplicates-on-replay', - covers: 'why a seed dataset must be safe to replay', - paragraphs: [ - 'Seeds are replayed, not applied once: every `data` dataset is loaded again on each dev-server ' + - 'boot and each package re-publish, so a dataset\'s mode must be idempotent. `mode: \'insert\'` ' + - 'is the one that is not: the loader\'s insert path writes every record unconditionally, with no ' + - 'existing-row check, so the table grows by the dataset\'s size on every restart (three rows, ' + - 'then six, then nine).', - // The modes are held to the rule by its test, each one silent. - 'The fix line names the idempotent modes, `ignore` (skip rows that already exist) and `upsert` ' + - '(create or update), each matching on the dataset\'s `externalId`: a single natural-key field ' + - '(`externalId: \'code\'`), ' + - 'or a composite list of fields for a join or junction table with no single natural key ' + - '(`[\'team\', \'project\']`).', - 'A warning, not a refusal: an insert seed loads and works on a fresh database, and the defect ' + - 'shows only from the second boot on.', - ], -}; - const SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION: RuleExplanation = { rule: 'seed-value-outside-state-machine', covers: 'which states a seeded value may name', @@ -6407,7 +6387,6 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION.rule]: PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION, [ASSIGNMENT_RULE_USER_TARGET_EXPLANATION.rule]: ASSIGNMENT_RULE_USER_TARGET_EXPLANATION, [ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION.rule]: ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION, - [SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION.rule]: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION, [SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION.rule]: SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION, [SEMANTIC_ROLE_FIELD_UNPROVISIONED_EXPLANATION.rule]: SEMANTIC_ROLE_FIELD_UNPROVISIONED_EXPLANATION, [ACTION_NO_PLACEMENT_EXPLANATION.rule]: ACTION_NO_PLACEMENT_EXPLANATION, diff --git a/packages/lint/src/validate-seed-replay-safety.test.ts b/packages/lint/src/validate-seed-replay-safety.test.ts deleted file mode 100644 index 6d2a9f55be5..00000000000 --- a/packages/lint/src/validate-seed-replay-safety.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - validateSeedReplaySafety as validateSeedReplaySafetyUnrecorded, - SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, -} from './validate-seed-replay-safety.js'; -import { explainRule } from './rule-explanations.js'; - -// [#22161] Each finding is one verdict sentence; the reasoning it used to -// carry is `os explain seed-insert-mode-duplicates-on-replay`. Every direct -// call below records what it fired, and the last cases in this file hold each -// recorded verdict to one line of at most 200 characters — every firing -// variant this suite exercises, not a chosen few. Run the whole file: those -// cases read what the cases above fired. -const fired: Array<{ rule: string; message: string; hint: string }> = []; -const validateSeedReplaySafety: typeof validateSeedReplaySafetyUnrecorded = (...args) => { - const findings = validateSeedReplaySafetyUnrecorded(...args); - fired.push(...findings); - return findings; -}; - -describe('validateSeedReplaySafety (framework#3434 replay-unsafe seed gate)', () => { - it('passes a stack with no seed data', () => { - expect(validateSeedReplaySafety({})).toHaveLength(0); - expect(validateSeedReplaySafety({ data: [] })).toHaveLength(0); - }); - - it('passes idempotent modes (ignore / upsert / update / replace) and the default (unset)', () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'a', mode: 'ignore', externalId: ['team', 'project'], records: [] }, - { object: 'b', mode: 'upsert', externalId: 'code', records: [] }, - { object: 'c', mode: 'update', records: [] }, - { object: 'd', mode: 'replace', records: [] }, - { object: 'e', records: [] }, // mode unset → defaults to upsert, safe - ], - }); - expect(findings).toHaveLength(0); - }); - - it("flags a mode: 'insert' seed with location + an actionable fix hint", () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'showcase_project_membership', mode: 'insert', records: [{ team: 'x', project: 'y' }] }, - ], - }); - expect(findings).toHaveLength(1); - expect(findings[0]).toMatchObject({ - severity: 'warning', - rule: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, - path: 'data[0].mode', - }); - expect(findings[0].where).toContain('showcase_project_membership'); - expect(findings[0].message).toContain('replay'); - // Hint steers to the idempotent modes and the composite externalId the fix - // added; [#22161] the composite example itself is the explanation's. - expect(findings[0].hint).toContain('ignore'); - expect(findings[0].hint).toContain('upsert'); - expect(findings[0].hint).toContain('externalId'); - expect(findings[0].hint).toContain('a list of fields for a junction table'); - }); - - it('flags each insert seed and reports its index in the path; leaves safe seeds alone', () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'safe', mode: 'upsert', records: [] }, - { object: 'bad_one', mode: 'insert', records: [] }, - { object: 'also_safe', mode: 'ignore', records: [] }, - { object: 'bad_two', mode: 'insert', records: [] }, - ], - }); - expect(findings).toHaveLength(2); - expect(findings.map((f) => f.path)).toEqual(['data[1].mode', 'data[3].mode']); - expect(findings.map((f) => f.where)).toEqual(['seed "bad_one"', 'seed "bad_two"']); - }); - - it('falls back to a data[i] location when a seed has no object name', () => { - const findings = validateSeedReplaySafety({ data: [{ mode: 'insert', records: [] }] }); - expect(findings).toHaveLength(1); - expect(findings[0].where).toBe('data[0]'); - }); - - it('ignores non-object entries defensively', () => { - const findings = validateSeedReplaySafety({ data: [null, 'insert', 42, { object: 'z', mode: 'insert', records: [] }] }); - expect(findings).toHaveLength(1); - expect(findings[0].where).toContain('z'); - }); -}); - -describe('[#22161] one-line verdicts — seed-insert-mode-duplicates-on-replay', () => { - it('reads as one sentence', () => { - const findings = validateSeedReplaySafety({ data: [{ object: 'z', mode: 'insert', records: [] }] }); - expect(findings.map((f) => f.message)).toEqual([ - "`mode: 'insert'` re-inserts every record on each replay boot (dev-server restart, package re-publish) " - + 'with no existing-row check, so every restart duplicates its rows', - ]); - }); - - it('`os explain` carries what the verdict no longer says', () => { - const entry = explainRule(SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - expect(entry, 'no `os explain seed-insert-mode-duplicates-on-replay` entry').toBeDefined(); - const text = entry!.paragraphs.join('\n'); - // The idempotent modes are held to the rule by the silent case above. - for (const fact of [ - 'Seeds are replayed, not applied once', - 'no existing-row check', - '`ignore` (skip rows that already exist)', - '`upsert` (create or update)', - '`externalId`', - '(`[\'team\', \'project\']`)', - 'only from the second boot on', - ]) { - expect(text, `explanation names ${fact}`).toContain(fact); - } - }); - - it('every verdict the cases in this file fired is one line of at most 200 characters', () => { - const converted = fired.filter((f) => f.rule === SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - // The coverage control first: the id fired, on more than one seed. - expect(converted.length).toBeGreaterThan(1); - for (const f of converted) { - expect(f.message, f.rule).not.toContain('\n'); - expect(f.message.length, `${f.rule}: ${f.message}`).toBeLessThanOrEqual(200); - } - }); -}); - -// [#22161] Slice 16: the `fix:` line names the two idempotent modes and the -// match key in one line; what each mode does and the examples are the -// explanation's (pinned above, and here for what moved). -describe('[#22161] one-line fix — seed-insert-mode-duplicates-on-replay', () => { - it('reads as one remedy', () => { - const [f] = validateSeedReplaySafety({ data: [{ object: 'z', mode: 'insert', records: [] }] }); - expect(f!.hint).toBe( - "Use `mode: 'ignore'` or `'upsert'` with an `externalId` to match on (a natural-key field, or a list of " + - 'fields for a junction table)', - ); - }); - - it('every `fix:` line the cases in this file fired is one line of at most 200 characters', () => { - const converted = fired.filter((f) => f.rule === SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - expect(converted.length).toBeGreaterThan(1); - for (const f of converted) { - expect(f.hint, f.rule).not.toContain('\n'); - expect(f.hint.length, `${f.rule}: ${f.hint}`).toBeLessThanOrEqual(200); - } - }); - - it('`os explain` carries the examples the `fix:` line dropped', () => { - const text = explainRule(SEED_INSERT_MODE_DUPLICATES_ON_REPLAY)!.paragraphs.join('\n'); - expect(text).toContain("(`externalId: 'code'`)"); - expect(text).toContain("(`['team', 'project']`)"); - }); -}); diff --git a/packages/lint/src/validate-seed-replay-safety.ts b/packages/lint/src/validate-seed-replay-safety.ts deleted file mode 100644 index 0316dc2e283..00000000000 --- a/packages/lint/src/validate-seed-replay-safety.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// Build-time guardrail for replay-unsafe seed datasets (framework#3434). -// -// A pure `(stack) => Finding[]` rule (ADR-0019), run from `os validate` and -// reusable by AI authoring. Seeds are REPLAYED — they re-load on every -// dev-server boot and every package re-publish, not applied once — so a -// dataset's mode has to be idempotent. `mode: 'insert'` is the one mode that -// is not: the loader's `insert` path writes every record unconditionally, with -// no existing-row check, so the table grows by the dataset's size on every -// restart (the showcase `showcase_project_membership` fixture went 3 → 6 → 9). -// -// This is the authoring-time nudge that would have caught #3434 before boot: -// flag `insert`, and point at the idempotent modes (`ignore` / `upsert`) plus -// the `externalId` — single field, or a COMPOSITE list of fields for a join / -// junction table that has no single natural key (`['team', 'project']`), the -// support for which #3434 added. -// -// Advisory (warning): an `insert` seed is not a schema error — it loads and -// "works" on a fresh DB; the defect only shows on the second boot. So it earns -// a located fix-it, not a hard `os compile` gate. - -export type SeedReplaySafetySeverity = 'error' | 'warning'; - -export interface SeedReplaySafetyFinding { - severity: SeedReplaySafetySeverity; - rule: string; - /** Human-readable location, e.g. `seed "showcase_project_membership"`. */ - where: string; - /** Config path, e.g. `data[12].mode`. */ - path: string; - message: string; - hint: string; -} - -// Rule id (registry entry). -export const SEED_INSERT_MODE_DUPLICATES_ON_REPLAY = 'seed-insert-mode-duplicates-on-replay'; - -type AnyRec = Record; - -/** - * Flag every seed dataset declared with `mode: 'insert'` — the one non-idempotent - * mode, which duplicates its rows on every replay boot (framework#3434). Returns - * the findings (empty = clean). The caller decides how to surface them / whether - * to fail the build; the CLI folds them in as advisory warnings. - * - * Reads `stack.data` (the `SeedSchema[]` fixtures). Safe on any shape — a stack - * with no `data` array yields no findings. - */ -export function validateSeedReplaySafety(stack: AnyRec): SeedReplaySafetyFinding[] { - const out: SeedReplaySafetyFinding[] = []; - const seeds = Array.isArray(stack.data) ? (stack.data as AnyRec[]) : []; - - seeds.forEach((seed, i) => { - if (!seed || typeof seed !== 'object') return; - if (seed.mode !== 'insert') return; - - const object = typeof seed.object === 'string' ? seed.object : undefined; - const where = object ? `seed "${object}"` : `data[${i}]`; - - out.push({ - severity: 'warning', - rule: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, - where, - path: `data[${i}].mode`, - // [#22161] One verdict sentence and one remedy line; why seeds are - // replayed, what each idempotent mode does and the composite - // `externalId` of a junction table are - // `os explain seed-insert-mode-duplicates-on-replay`. - message: - "`mode: 'insert'` re-inserts every record on each replay boot (dev-server restart, " + - 'package re-publish) with no existing-row check, so every restart duplicates its rows', - hint: - "Use `mode: 'ignore'` or `'upsert'` with an `externalId` to match on (a natural-key field, or a " + - 'list of fields for a junction table)', - }); - }); - - return out; -} diff --git a/packages/metadata-core/src/package-upgrade-plan.ts b/packages/metadata-core/src/package-upgrade-plan.ts index 8db2829d20c..185112e0c06 100644 --- a/packages/metadata-core/src/package-upgrade-plan.ts +++ b/packages/metadata-core/src/package-upgrade-plan.ts @@ -269,10 +269,10 @@ const DEFAULT_SEED_EXTERNAL_ID: string | string[] = SeedSchema.shape.externalId. /** * Does a replay of a dataset in this mode write its columns over a row it * MATCHED by `externalId`? `upsert` and `update` do (a column declaring - * `applyOn: 'create'` excepted); `insert` and `ignore` never touch a matched - * row, and `replace` deletes every row before it inserts, so it matches none. - * The rows a customer edited that an upgrade's replay would overwrite are - * counted for these modes only. + * `applyOn: 'create'` excepted); `ignore` never touches a matched row. The + * retired `insert` and `replace` (#34613) matched no row, and a replay now + * refuses a dataset that still declares one. The rows a customer edited that + * an upgrade's replay would overwrite are counted for these modes only. */ export function seedModeOverwritesMatchedRows(mode: string): boolean { return mode === 'upsert' || mode === 'update'; diff --git a/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts b/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts index 4dceab80a02..5ef20ff814b 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts @@ -282,7 +282,7 @@ function cardDrafts(autonumberFormat: string): Array<[string, string, Record 0 ? clashes.map((c) => c.message).join(' ') : null; } -/** The seed modes whose load matches incoming records to existing rows by the dataset's `externalId`. */ +/** + * The seed modes whose load matches incoming records to existing rows by the + * dataset's `externalId`: every live mode since the unkeyed `insert` and + * `replace` were retired (#34613). A retired mode is the schema's refusal, not + * this one's. + */ const KEYED_SEED_MODES: ReadonlySet = new Set(['upsert', 'update', 'ignore']); /** @@ -1055,7 +1060,8 @@ export async function seedExternalIdSaveRefusal( if (missing.length === 0) return undefined; const consequence = `so a load in \`${mode}\` mode could never match a row it wrote before: each publish and each ` + `replay would ${mode === 'update' ? 'skip every record' : 'insert every record again'}. Name a field the object ` - + "declares, or use `mode: 'insert'` for rows with no natural key."; + + "declares, a list of fields when no single field names a row, or `'id'` when the records carry " + + 'their own ids.'; const issues: MetadataIssueEntry[] = missing.map(({ member, index }) => ({ path: composite ? `externalId.${index}` : 'externalId', message: (declared diff --git a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts index d0b6149fed0..46b9a84dbd9 100644 --- a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts @@ -341,11 +341,14 @@ describe('[#28952] controls — an `externalId` the object has is not refused', expect(stored(rows, 'seed', 'r_ok')).toEqual([`active|${PKG}|${JSON.stringify(externalId ?? null)}`]); }); - it.each([['insert'], ['replace']])('mode `%s` never matches by `externalId`, so it is not judged', async (mode) => { + // [#34613] The unkeyed `insert` and `replace` modes, which this suite once + // held out as "never matches, so not judged", are retired: the save door + // refuses them with `SeedMode`'s prescription, whatever the key names. + it.each([['insert'], ['replace']])('the retired mode `%s` is refused with its prescription', async (mode) => { const { protocol, rows } = makeSession({ objects: OBJECTS }); - const res = await protocol.saveMetaItem({ type: 'seed', name: 'r_ins', item: seed('seedkey_other', 'no_such_field', mode), mode: 'draft' }); - expect(res.success).toBe(true); - expect(stored(rows, 'seed', 'r_ins')).toEqual(['draft|-|"no_such_field"']); + const attempt = protocol.saveMetaItem({ type: 'seed', name: 'r_ins', item: seed('seedkey_other', 'sku', mode), mode: 'draft' }); + await expect(attempt).rejects.toThrow(new RegExp(`seed\\.mode: '${mode}'\` was removed in @objectstack/spec 18\\.6\\.0`)); + expect(stored(rows, 'seed', 'r_ins')).toEqual([]); }); it('an object drafted in the same batch that declares the field publishes with the seed', async () => { @@ -368,10 +371,6 @@ describe('[#28952] controls — an `externalId` the object has is not refused', it('a `migrate-stored` re-save of a stored seed is not judged', async () => { const { protocol, rows } = makeSession({ objects: OBJECTS }); - const res = await protocol.saveMetaItem({ - type: 'seed', name: 'r_old', item: seed('seedkey_other', 'no_such_field', 'insert'), mode: 'draft', - }); - expect(res.success).toBe(true); const migrated = await protocol.saveMetaItem({ type: 'seed', name: 'r_old', item: seed('seedkey_other', 'no_such_field'), mode: 'draft', source: 'migrate-stored', }); diff --git a/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts b/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts index 840af8737f7..2206b9dadac 100644 --- a/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts +++ b/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts @@ -10,7 +10,7 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin * * A join / junction table has no single-field natural key — the PAIR of its * foreign keys is what's unique. Before composite externalId support, such a - * dataset could only run `mode: 'insert'`, which re-inserts every row on each + * dataset could only run `mode: 'insert'` (since retired, #34613), which re-inserts every row on each * replay boot and duplicates the table (the showcase memberships went 3→6→9). * * A composite `externalId: ['team', 'project']` + `mode: 'ignore'` dedupes the diff --git a/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts index 7114185ce00..952f4b887a4 100644 --- a/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts +++ b/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts @@ -124,7 +124,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -134,14 +134,14 @@ const compositeSeeds = (region: string) => [ { object: 'drop_department', externalId: ['name', 'region'], - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', region, head_id: 'Alice' }], }, { object: 'drop_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', department_id: 'Engineering' }], }, @@ -205,7 +205,13 @@ describe('pass 2 heals a row whose natural key evaluated empty (#5127 → #11674 }); expect(logger.error).not.toHaveBeenCalled(); - expect(logger.warn).not.toHaveBeenCalled(); + // [#34613] The dataset is keyed now (the unkeyed `insert` it ran in is + // retired), so the one `warn` is #28952's notice that every record keys + // empty — a fact about the declaration. Nothing at warn is about the + // deferral the load healed. + const warned = logger.warn.mock.calls.map((c: unknown[]) => String(c[0])); + expect(warned).toHaveLength(1); + expect(warned[0]).toMatch(/keys every record on externalId 'name\+region', and no record carries a value for it/); }); /** @@ -281,7 +287,7 @@ describe('pass 2 finds no id because the source row failed in pass 1 (#5127)', ( { object: 'drop_department', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', region: 'APAC', head_id: 'Alice' }], }, @@ -291,7 +297,7 @@ describe('pass 2 finds no id because the source row failed in pass 1 (#5127)', ( // deferred update that would muddy the assertions below. object: 'drop_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts index dfc72bee430..1753de45f02 100644 --- a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts @@ -107,7 +107,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -116,14 +116,14 @@ const SEEDS = [ { object: 'audit_department', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }], }, { object: 'audit_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', department_id: 'Engineering' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-driver-text.test.ts b/packages/metadata-protocol/src/seed-loader-driver-text.test.ts index 3a53f957a0d..07e081b7c36 100644 --- a/packages/metadata-protocol/src/seed-loader-driver-text.test.ts +++ b/packages/metadata-protocol/src/seed-loader-driver-text.test.ts @@ -247,8 +247,8 @@ describe('[#8442] raw driver text is withheld from the seed `errors[].message`', const logger = createLogger(); const result = await new SeedLoaderService(engine, metadata, logger as never).load({ seeds: [ - { object: 'dept', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }] }, - { object: 'worker', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', dept_id: 'Engineering' }] }, + { object: 'dept', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }] }, + { object: 'worker', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', dept_id: 'Engineering' }] }, ], config: CONFIG, } as never); diff --git a/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts b/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts index d268f58f12b..2197666d1c3 100644 --- a/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts +++ b/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts @@ -103,19 +103,19 @@ const silentLogger = () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debu function seeds(organizationId?: string) { return { seeds: [ - { object: 'sys_business_unit', externalId: 'code', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'sys_business_unit', externalId: 'code', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Head Office', code: 'HQ' }] }, - { object: 'my_app_widget', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'my_app_widget', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'Gizmo', sku: 'G-1' }, // Carries its own organization: that IS an explicit owner. { name: 'Pinned', sku: 'P-1', organization_id: 'org_named_by_author' }, ] }, - { object: 'billing_license', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'billing_license', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Site licence', sku: 'L-1' }] }, ], config: { - dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1000, + dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false, ...(organizationId ? { organizationId } : {}), }, } as never; diff --git a/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts b/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts index 66389d2073b..d87f569d140 100644 --- a/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts +++ b/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts @@ -520,10 +520,11 @@ const ADOPTER_SCHEMAS: Record = { }; /** A dataset for an object with no natural key of its own — every adopted - * object here is engine/append-only owned, so `mode: 'insert'` (no - * `externalId`) is how such rows would honestly be authored. */ + * object here is engine/append-only owned. The keyless `insert` mode such + * rows were once authored with is retired (#34613), so the dataset keys on + * `id`; these rows carry none, so each one is written as a new row. */ function insertSeed(object: string, records: Array>) { - return { object, mode: 'insert', env: ['prod', 'dev', 'test'], records }; + return { object, externalId: 'id', mode: 'ignore', env: ['prod', 'dev', 'test'], records }; } describe('pointer-pair adoption per object (#11386)', () => { diff --git a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts new file mode 100644 index 00000000000..3c38d49a486 --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts @@ -0,0 +1,141 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34613] `SeedLoaderService.loadStored`: a STORED seed dataset that still + * declares a retired `SeedMode` (`insert`, `replace`; ruling 6942780880) is + * refused alone, loudly, and every other dataset of the load lands. + * + * The request parse refuses a retired mode by name, so a load built straight + * through `SeedLoaderRequestSchema.parse` would refuse the WHOLE boot seed (or + * install, or replay) over one dataset a package carried from before the + * retirement. `loadStored` is the funnel the replaying loads go through: the + * refused dataset writes nothing, its error names the object and carries the + * schema's own prescription, and the result says `success: false`. + * + * Controls: a load with no retired dataset is `load()`'s answer unchanged, and + * a malformed dataset that is not a retired mode still throws from the parse, + * as it did before. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { SeedMode } from '@objectstack/spec/data'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { SeedLoaderService } from './seed-loader.js'; + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** An in-memory engine: equality `where`, ids minted on insert. */ +function createEngine(): { engine: IDataEngine; store: Record>> } { + const store: Record>> = {}; + let next = 0; + const find = async (object: string, query?: { where?: Record; limit?: number }) => { + let rows = store[object] ?? []; + if (query?.where) rows = rows.filter((r) => Object.entries(query.where!).every(([k, v]) => r[k] === v)); + return typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows; + }; + const engine = { + find: vi.fn(find), + findOne: vi.fn(async (object: string, query?: any) => (await find(object, { ...query, limit: 1 }))[0] ?? null), + insert: vi.fn(async (object: string, data: any) => { + const put = (d: Record) => { + const row = { id: `r${++next}`, ...d }; + (store[object] ??= []).push(row); + return row; + }; + return Array.isArray(data) ? data.map(put) : put(data); + }), + update: vi.fn(async (_object: string, data: any) => data), + delete: vi.fn(async () => ({ deleted: 0 })), + count: vi.fn(async (object: string) => (store[object] ?? []).length), + aggregate: vi.fn(async () => []), + } as unknown as IDataEngine; + return { engine, store }; +} + +function createMetadata(): IMetadataService { + const objects: Record = { + rm_region: { name: 'rm_region', fields: { name: { type: 'text' } } }, + rm_source: { name: 'rm_source', fields: { name: { type: 'text' } } }, + rm_tier: { name: 'rm_tier', fields: { name: { type: 'text' } } }, + }; + return { + getObject: vi.fn(async (name: string) => objects[name]), + listObjects: vi.fn(async () => Object.values(objects)), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => objects[name]), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; +} + +const prescriptionOf = (mode: string): string => { + const verdict = SeedMode.safeParse(mode); + if (verdict.success) throw new Error(`'${mode}' is a live mode — wrong fixture`); + return verdict.error.issues[0]!.message; +}; + +describe('loadStored — a stored dataset with a retired mode is refused alone (#34613)', () => { + it.each([['insert'], ['replace']])('`%s`: that dataset writes nothing, every other dataset lands, the result names the refusal', async (mode) => { + const { engine, store } = createEngine(); + const logger = createLogger(); + + const result = await new SeedLoaderService(engine, createMetadata(), logger).loadStored({ + seeds: [ + { object: 'rm_region', records: [{ name: 'emea' }] }, + { object: 'rm_source', mode, records: [{ name: 'web' }] }, + { object: 'rm_tier', mode: 'upsert', externalId: 'name', records: [{ name: 'gold' }] }, + ], + config: { multiPass: true }, + }); + + // The refused dataset wrote nothing; both others landed. + expect(store.rm_source).toBeUndefined(); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + expect(store.rm_tier?.map((r) => r.name)).toEqual(['gold']); + expect(result.results.map((r) => r.object).sort()).toEqual(['rm_region', 'rm_tier']); + + // Loud: the load failed, and its one error is the dataset's refusal with + // the schema's prescription, read from `SeedMode` rather than restated. + expect(result.success).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.errors[0]).toMatchObject({ sourceObject: 'rm_source', field: 'mode', attemptedValue: mode, recordIndex: 0 }); + expect(result.errors[0]!.message).toBe(`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf(mode)}`); + expect(result.errors[0]!.message).toMatch(/`mode: 'ignore'`.*`externalId`/s); + }); + + it('a load whose only dataset is retired writes nothing and still answers, failed', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [{ object: 'rm_source', mode: 'insert', records: [{ name: 'web' }] }], + }); + expect(store).toEqual({}); + expect(result.success).toBe(false); + expect(result.errors.map((e) => e.sourceObject)).toEqual(['rm_source']); + }); + + it('CONTROL: with no retired dataset the answer is the load’s own', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [{ object: 'rm_region', records: [{ name: 'emea' }] }], + }); + expect(result.success).toBe(true); + expect(result.errors).toEqual([]); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + }); + + it('CONTROL: a mode that was never a seed mode is still the parse’s refusal, for the whole load', async () => { + const { engine, store } = createEngine(); + const attempt = new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [ + { object: 'rm_region', records: [{ name: 'emea' }] }, + { object: 'rm_source', mode: 'merge', records: [{ name: 'web' }] }, + ], + }); + await expect(attempt).rejects.toThrow(); + expect(store).toEqual({}); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader-retry.test.ts b/packages/metadata-protocol/src/seed-loader-retry.test.ts index 8a49d691991..eaf55af4382 100644 --- a/packages/metadata-protocol/src/seed-loader-retry.test.ts +++ b/packages/metadata-protocol/src/seed-loader-retry.test.ts @@ -102,7 +102,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -111,7 +111,7 @@ const SEEDS = [ { object: 'my_app_employee', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }, { name: 'Bob' }], }, @@ -169,7 +169,7 @@ describe('seed batched path — idempotent retry after commit-then-lost-response seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Widget A', sku: 'W-A' }, { name: 'Widget B', sku: 'W-B' }], }] as any, @@ -211,7 +211,7 @@ describe('seed batched path — partial-success engine (framework#3172)', () => seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'Good A', sku: 'W-A' }, @@ -265,7 +265,7 @@ describe('seed batched path — a recompute failure is recovered, not re-written seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }], }] as any, diff --git a/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts b/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts index 0eacd844747..0da96e23af7 100644 --- a/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts @@ -169,7 +169,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as never; @@ -177,7 +177,7 @@ const CONFIG = { const seedOf = (records: Array>) => [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records, }] as never; diff --git a/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts b/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts index 40bbba4c5bd..0985ba1f5f0 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts @@ -154,7 +154,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -200,7 +200,7 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-001', owner_id: 'dev-admin' }], }, @@ -268,14 +268,14 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-002', owner_id: 'Ada' }], }, { object: 'claim_user', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ada', contract_id: 'ACME-002' }], }, @@ -318,14 +318,14 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-003', owner_id: 'Ada' }], }, { object: 'claim_user', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ada', contract_id: 'ACME-003' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index 9a083bbd8be..2104d167946 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -103,7 +103,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -111,7 +111,7 @@ const CONFIG = { const seedFor = (object: string, records: any[]) => ({ object, externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records, }); @@ -286,7 +286,7 @@ describe('the counter survives the contract, and the contract survives older pay // a pre-#4998 producer's output, and it must still parse. const legacyPerObject = { object: 'roll_invoice', - mode: 'insert', + mode: 'ignore', inserted: 2, updated: 0, skipped: 0, errored: 0, total: 2, referencesResolved: 0, referencesDeferred: 0, errors: [], diff --git a/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts b/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts index 7d478270072..6176c7e797c 100644 --- a/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts +++ b/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts @@ -120,7 +120,7 @@ const SINGLE_PASS = { dryRun: false, haltOnError: false, multiPass: false, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -130,7 +130,7 @@ const ORDERS = [ { object: 'drop_order', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'ORD-1' }, @@ -223,7 +223,7 @@ describe('a record dropped for an unresolvable reference is logged, not only cou { object: 'drop_customer', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ghost Inc' }], }, @@ -322,7 +322,7 @@ describe('a deferred reference still unresolved after pass 2 is logged too (fram { object: 'drop_team', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], // 'Nobody' is never seeded and is not in the database — pass 2 cannot // rescue it, so the deferred reference is permanently NULL. diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 95729c29a45..4cbc865114a 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -2,6 +2,7 @@ import type { IDataEngine, IFieldFileService, IMetadataService, ISeedLoaderService } from '@objectstack/spec/contracts'; import type { + SeedLoaderRequest, SeedLoaderRequestParsed, SeedLoaderResultParsed, SeedLoaderConfig, @@ -16,6 +17,8 @@ import type { } from '@objectstack/spec/data'; import { SeedLoaderConfigSchema, + SeedLoaderRequestSchema, + SeedMode, isMultiValueField, isTenancyDisabled, referenceTargetOf, @@ -401,6 +404,13 @@ function perOrganizationSeedRowId(authoredId: string, organizationId: string): s */ const SEED_LANDED_KEY_OBJECT = 'sys_seed_landed_key'; +/** + * [#34613] The `SeedMode` values retired by ruling 6942780880 that a stored + * seed can still carry. Only membership is read here: the prescription a + * refused dataset reports is `SeedMode`'s own refusal. + */ +const RETIRED_SEED_MODES: ReadonlySet = new Set(['insert', 'replace']); + /** * [#31021] The key a landed seed row is recorded under in * {@link SEED_LANDED_KEY_OBJECT}: the dataset's `externalId` field names, each @@ -458,8 +468,8 @@ interface LandedKeyLedger { * - Topological dependency ordering (parents before children) * - Multi-pass loading for circular references — pass 2 writes a deferred * reference back through the source row's INTERNAL id captured at insert - * time (commit 9a884c6e4), so it heals KEYLESS datasets (`mode: 'insert'`, no - * `externalId`) the same as keyed ones + * time (commit 9a884c6e4), so it heals a row whose key evaluates empty the + * same as a keyed one * - Dry-run validation mode * - Upsert support honoring SeedSchema mode * - Idempotent replay: an upsert/update whose declared fields already match @@ -1532,6 +1542,62 @@ export class SeedLoaderService implements ISeedLoaderService { return fromMetadata; } + /** + * [#34613] Load a request built from STORED seeds: the loads that replay a + * seed the author is not there to fix — the single-tenant boot seed, the + * per-organization replay, the dev hot reload, a package install, upgrade + * or sample-data reseed. + * + * `SeedMode` retired `insert` and `replace` (ruling 6942780880, ADR-0049): + * neither matched a row, so every replay inserted each record again. A + * package built or a seed stored before the retirement can still carry one, + * and the request parse would refuse the WHOLE load over it. Here that + * dataset alone is refused: it writes nothing, its prescription (the + * `SeedMode` refusal, read from the schema, never restated) becomes one + * error of the result with `success: false`, and every other dataset loads. + * No log line of its own: the refusal is handed to the caller, which + * reports a failed load's errors as it reports any other. + * + * The publish doors do not come here. A publish has its author present, so + * it parses the request itself and refuses the whole publish with the same + * prescription. + * + * Every other problem of the request is the parse's, as before: it throws. + */ + async loadStored(request: { + seeds: ReadonlyArray; + config?: SeedLoaderRequest['config']; + }): Promise { + const admitted: unknown[] = []; + const refusals: ReferenceResolutionError[] = []; + for (const seed of request.seeds) { + const mode = (seed as { mode?: unknown } | null)?.mode; + const verdict = typeof mode === 'string' && RETIRED_SEED_MODES.has(mode) ? SeedMode.safeParse(mode) : undefined; + if (!verdict || verdict.success) { + admitted.push(seed); + continue; + } + const objectName = String((seed as { object?: unknown }).object ?? '(unnamed)'); + refusals.push({ + sourceObject: objectName, + field: 'mode', + targetObject: objectName, + targetField: '(dataset)', + attemptedValue: mode, + // The mode is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: `Seed dataset for '${objectName}' was not loaded: ${verdict.error.issues[0]?.message ?? `mode '${mode}' is retired`}`, + }); + } + if (refusals.length === 0) return this.load(SeedLoaderRequestSchema.parse({ config: {}, ...request })); + // Every dataset refused: there is nothing to load (and the request schema + // asks for at least one dataset), so the answer is the empty load, failed. + const result = admitted.length === 0 + ? this.buildEmptyResult(SeedLoaderConfigSchema.parse(request.config ?? {}), 0) + : await this.load(SeedLoaderRequestSchema.parse({ config: {}, ...request, seeds: admitted })); + return { ...result, success: false, errors: [...refusals, ...result.errors] }; + } + async validate(datasets: Seed[], config?: SeedLoaderConfig): Promise { const parsedConfig = SeedLoaderConfigSchema.parse({ ...config, dryRun: true }); // `datasets` is the AUTHOR state (that is what `validate` takes); `load` @@ -1627,7 +1693,8 @@ export class SeedLoaderService implements ISeedLoaderService { `[SeedLoader] Seed dataset for '${objectName}' keys every record on externalId ` + `'${this.externalIdLabel(externalId)}', and no record carries a value for it, so this ${mode} load can ` + `match no existing row: ${mode === 'update' ? 'every record is skipped' : 'every record is written as a new row, on every load'}. ` + - `Set externalId to a field the object declares and each record carries, or use mode 'insert'.`, + `Set externalId to a field the object declares and each record carries, a list of fields when no ` + + `single field names a row, or 'id' when the records carry their own ids.`, { object: objectName, externalId: this.externalIdLabel(externalId), mode, records: dataset.records.length }, ); } @@ -1656,8 +1723,8 @@ export class SeedLoaderService implements ISeedLoaderService { // [#31021] The record of landed seed rows, for the datasets that insert a // keyed row they do not find (`upsert`, `ignore`): the modes the - // create-only rule reaches. `update` never inserts; `insert` / `replace` - // match no key. + // create-only rule reaches. `update` never inserts. (The unkeyed + // `insert` / `replace` modes are retired, #34613.) const recordedKeys = this.landedKeyLedger && (mode === 'upsert' || mode === 'ignore') ? await this.landedKeysOf(objectName) : undefined; @@ -1691,8 +1758,7 @@ export class SeedLoaderService implements ISeedLoaderService { // gets the batched path below. See framework#2678. const hasSelfRef = objectRefs.some(ref => ref.targetObject === objectName); - // Records resolved as inserts (mode 'insert'/'replace', or an unmatched - // upsert/ignore) are buffered here and flushed in batches through the + // Records resolved as inserts (an unmatched upsert/ignore) are buffered here and flushed in batches through the // engine's array-form insert() — one round-trip per batch instead of one // per record, with transient-error retry and per-row degradation on a // logical/validation failure. See framework#2678. @@ -1708,9 +1774,9 @@ export class SeedLoaderService implements ISeedLoaderService { // unlike the `insertedRecords` registrations, which need a non-empty // natural key. Once the dataset has fully written, the deferred updates it // pushed are annotated from this map (see the loop after the final flush), - // so pass 2 back-fills BY INTERNAL ID and a KEYLESS dataset (`mode: - // 'insert'`, no `externalId` — the honest authoring for an engine-owned - // object with no natural key) heals exactly like a keyed one. Before this, + // so pass 2 back-fills BY INTERNAL ID and a row whose key evaluates empty + // heals exactly like a keyed one (the keyless `insert` mode this was first + // written for is retired, #34613). Before this, // pass 2 re-resolved the source row through its externalId and a keyless // deferral was structurally unreachable: it resolved the target, then // dropped the link ("empty externalId, so no internal id"). @@ -2175,8 +2241,8 @@ export class SeedLoaderService implements ISeedLoaderService { * asks. The same lookup {@link SeedLoaderService.decideWriteAction} * makes: the record's natural key, as resolved so far, against the rows * pre-loaded for the modes that match one (`upsert`, `update`, - * `ignore`). A dry run and the `insert` / `replace` modes pre-load - * nothing, so every row they see is one they create. + * `ignore`). A dry run pre-loads nothing, so every row it sees is one + * it creates. */ const matchesExistingRow = (): boolean => existingRecords?.has(this.externalIdKey(record, externalId)) === true; @@ -3838,11 +3904,6 @@ export class SeedLoaderService implements ISeedLoaderService { const opts = this.writeOptionsFor(rowOrganization) as any; switch (mode) { - case 'insert': { - const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); - return { action: 'inserted', id: this.extractId(result) }; - } - case 'update': { if (!existing) { return { action: 'skipped' }; @@ -3877,12 +3938,8 @@ export class SeedLoaderService implements ISeedLoaderService { return { action: 'inserted', id: this.extractId(result) }; } - case 'replace': { - // Replace mode: just insert (caller should have cleared the table) - const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); - return { action: 'inserted', id: this.extractId(result) }; - } - + // The retired `insert` / `replace` (#34613) never reach here: the request + // parse refuses them, and `loadStored` refuses a stored one alone. default: { const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); return { action: 'inserted', id: this.extractId(result) }; @@ -3928,8 +3985,6 @@ export class SeedLoaderService implements ISeedLoaderService { : { action: 'update', id: this.extractId(existing)! }; case 'ignore': return existing ? { action: 'skip', id: this.extractId(existing) } : { action: 'insert' }; - case 'insert': - case 'replace': default: return { action: 'insert' }; } @@ -5180,8 +5235,8 @@ interface DeferredUpdate { * The source record's INTERNAL id, captured at the moment its pass-1 write * landed (commit 9a884c6e4). This is the handle pass 2 writes the resolved reference * back through: it exists for every row this load actually wrote — - * including rows of a KEYLESS dataset (`mode: 'insert'`, no `externalId`) - * and rows whose composite key evaluated to the empty string — so the + * including rows whose key (single or composite) evaluated to the empty + * string — so the * "pass 2 resolved the target and had nowhere to write it" loss (#5127) is * reduced to the one case where it is true: the source row never landed. * diff --git a/packages/objectql/src/engine-seed-required-deferral.test.ts b/packages/objectql/src/engine-seed-required-deferral.test.ts index a710be59110..f15c83cfa8c 100644 --- a/packages/objectql/src/engine-seed-required-deferral.test.ts +++ b/packages/objectql/src/engine-seed-required-deferral.test.ts @@ -154,7 +154,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -235,7 +235,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { // in pass 1, so the loader defers by DELETING required `record_id`. const result = await loader().load({ seeds: [ - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, LEAD_SEED, @@ -270,7 +270,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const result = await loader().load({ seeds: [ LEAD_SEED, - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, ] as any, @@ -287,7 +287,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { it('MEASURED: an OPTIONAL id half on a KEYLESS dataset heals out-of-order through the real engine (#11674 end-to-end)', async () => { const result = await loader().load({ seeds: [ - { object: 'rq_ledger', mode: 'insert', env: ENV, records: [ + { object: 'rq_ledger', mode: 'ignore', env: ENV, records: [ { action: 'read', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, @@ -314,7 +314,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { // signal moves when the author learns, it does not move the verdict. const result = await loader(logger).load({ seeds: [ - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, LEAD_SEED, @@ -343,7 +343,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const logger = silentLogger(); const result = await loader(logger).load({ seeds: [ - { object: 'rq_ledger', mode: 'insert', env: ENV, records: [ + { object: 'rq_ledger', mode: 'ignore', env: ENV, records: [ { action: 'read', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, @@ -416,7 +416,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const logger = silentLogger(); const result = await loader(logger).load({ seeds: [ - { object: 'rq_approval_ro', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval_ro', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, diff --git a/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts b/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts index 8236fe14cb5..1020fe13390 100644 --- a/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts +++ b/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts @@ -209,7 +209,7 @@ async function observe( .insert(object, { name: 'probe', [ref]: line }, { context: caller } as never) .then(() => null, (e: { code?: string; message?: string }) => ({ code: e.code, message: e.message })); const preview = await h.engine.validate( - object, { name: 'probe', [ref]: line }, { mode: 'insert', context: caller } as never, + object, { name: 'probe', [ref]: line }, { mode: 'ignore', context: caller } as never, ); // Given a posture, the by-id UPDATE door too: a seeded row the caller may edit, repointed at `line`. let update: unknown; diff --git a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts index 6fb3e39600b..2066c4e24ea 100644 --- a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts +++ b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts @@ -280,7 +280,7 @@ describe('an agent ceiling set reaches no person through a position or a seed', it('a published seed granting an agent ceiling set stores no grant, and a person-set seed does', async () => { const seed = (name: string, set: string) => stack.apiAs(admin, 'PUT', `/meta/seed/${name}?mode=draft&package=${PKG}`, { - object: 'sys_user_permission_set', mode: 'insert', records: [{ user_id: personId, permission_set: set }], + object: 'sys_user_permission_set', mode: 'ignore', records: [{ user_id: personId, permission_set: set }], }); expect((await seed('agent_ceiling_grant_seed', CEILING)).status).toBe(200); expect((await seed('person_set_grant_seed', SET)).status).toBe(200); diff --git a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts index ef33e93c8e6..45b9c3f2efe 100644 --- a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts +++ b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts @@ -17,7 +17,7 @@ * resolves its collections, and a dataset has no `name`, so it is claimed by * value. With the stamps counted as part of that value the body copy was a * second dataset: two entries in the shared `seed-datasets` registry, and a - * `mode: 'insert'` row written twice. + * `mode: 'insert'` row written twice (that mode is since retired, #34613). * * The fixtures elsewhere could not see this: they are `upsert`-only, which is * idempotent, and their additive fixture shares object REFERENCES between the @@ -40,7 +40,7 @@ const coreBody = () => ({ version: '1.0.0', type: 'app', objects: [{ name: 'stamped_account', label: 'Account', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }], - data: [{ object: 'stamped_account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'stamped_account', mode: 'ignore', records: [{ name: 'once' }] }], }); const ordersBody = (withOwnDataset = false) => ({ @@ -50,7 +50,7 @@ const ordersBody = (withOwnDataset = false) => ({ type: 'module', dependencies: { [CORE_ID]: '^1.0.0' }, objects: [{ name: 'stamped_order', label: 'Order', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }], - ...(withOwnDataset ? { data: [{ object: 'stamped_order', mode: 'insert', records: [{ name: 'second' }] }] } : {}), + ...(withOwnDataset ? { data: [{ object: 'stamped_order', mode: 'ignore', records: [{ name: 'second' }] }] } : {}), }); /** The compiled additive shape: both halves, round-tripped through JSON. */ @@ -90,7 +90,7 @@ describe('additive artifact — real registration, then the seed registry', () = expect(artifact.data[0]._packageId).toBeUndefined(); expect(seeds).toHaveLength(1); - expect(seeds).toEqual([expect.objectContaining({ object: 'stamped_account', mode: 'insert' })]); + expect(seeds).toEqual([expect.objectContaining({ object: 'stamped_account', mode: 'ignore' })]); }); it('still registers a second package\'s OWN dataset', async () => { diff --git a/packages/runtime/src/app-plugin.seed.test.ts b/packages/runtime/src/app-plugin.seed.test.ts index 4f3b56fe8ca..3007153070d 100644 --- a/packages/runtime/src/app-plugin.seed.test.ts +++ b/packages/runtime/src/app-plugin.seed.test.ts @@ -288,7 +288,7 @@ describe('AppPlugin flat-bundle seed collection (#15262)', () => { data: [ { object: 'sys_user', - mode: 'insert', + mode: 'ignore', records: [{ id: 'flat_u1', name: 'Flat One' }], }, ], @@ -332,9 +332,9 @@ describe('AppPlugin flat-bundle seed collection (#15262)', () => { const bundle = { manifest: { id: 'com.test.nested-seed', - data: [{ object: 'sys_user', mode: 'insert', records: [{ id: 'legacy_u1' }] }], + data: [{ object: 'sys_user', mode: 'ignore', records: [{ id: 'legacy_u1' }] }], }, - data: [{ object: 'sys_user', mode: 'insert', records: [{ id: 'top_u1' }] }], + data: [{ object: 'sys_user', mode: 'ignore', records: [{ id: 'top_u1' }] }], }; await new AppPlugin(bundle).start(ctx); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 44ea0f4593d..b8fe3a113b2 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -2061,8 +2061,9 @@ export class AppPlugin implements Plugin { const seedLoader = new SeedLoaderService( ql, md, loggerRef, seedLoaderOptionsFor(ctx, options?.reseed === true ? 'reseed' : 'honour'), ); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a + // retired `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds: datasetsNow, config: { // [#30081] No mode of its own: each dataset's @@ -2084,7 +2085,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale.locale } : {}), }, }); - const result = await seedLoader.load(request); // [#23354] The rows this replay landed on, for the // organization's owner-bind claim (`seededRecordIds` with // this organization): it hands over these rows and no @@ -2162,11 +2162,12 @@ export class AppPlugin implements Plugin { const metadata = ctx.getService('metadata') as IMetadataService | undefined; if (metadata) { const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour')); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); // [#16595] `Seed.locale`'s producer on the DEFAULT boot // path — see {@link resolveSeedLocale}. const seedLocale = this.resolveSeedLocale(); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a + // retired `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds: normalizedDatasets, config: { // [#30081] No mode of its own: a replay on a @@ -2179,7 +2180,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale } : {}), }, }); - const result = await seedLoader.load(request); // [#34458] A person the seed names who does not exist yet // (the first admin) left a NULL; the handoff below // resolves it once a `sys_user` row is inserted. @@ -2650,13 +2650,14 @@ export class AppPlugin implements Plugin { return; } const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour')); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); // [#16595] `Seed.locale`'s producer on the dev hot-reload // path. Resolved from the BOOT bundle, not from `payload`: a // reload re-parses the artifact's metadata collections, and // `i18n` is an envelope key that does not travel in it. const seedLocale = this.resolveSeedLocale(); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a retired + // `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds, config: { // [#30081] No mode of its own — the spec default applies. @@ -2664,7 +2665,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale } : {}), }, }); - const result = await seedLoader.load(request); const { totalInserted, totalUpdated, totalErrored } = result.summary; ctx.logger.info( `[Seeder] Hot-reload seeded new object(s) ${fresh.join(', ')}: ` + diff --git a/packages/runtime/src/artifact-collections.test.ts b/packages/runtime/src/artifact-collections.test.ts index d9ac2effe23..4d3e2d21c7e 100644 --- a/packages/runtime/src/artifact-collections.test.ts +++ b/packages/runtime/src/artifact-collections.test.ts @@ -192,10 +192,10 @@ describe('resolveArtifactCollections', () => { // resolves its collections after that. A nameless item is claimed by // value, so the stamps alone used to turn one definition into two. const additive = JSON.parse(JSON.stringify({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'once' }] }], datasourceMapping: [{ datasource: 'primary', default: true }], packages: packagesOf({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'once' }] }], datasourceMapping: [{ datasource: 'primary', default: true }], }), })); @@ -223,8 +223,8 @@ describe('resolveArtifactCollections', () => { // out of identity. A dataset whose records differ is a second // definition, and it still arrives. const additive = JSON.parse(JSON.stringify({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'top' }] }], - packages: packagesOf({ data: [{ object: 'account', mode: 'insert', records: [{ name: 'body' }] }] }), + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'top' }] }], + packages: packagesOf({ data: [{ object: 'account', mode: 'ignore', records: [{ name: 'body' }] }] }), })); applyProtection(additive.packages[1].manifest.data[0], { packageId: 'com.example.core' }); diff --git a/packages/runtime/src/bulk-write-real-driver.integration.test.ts b/packages/runtime/src/bulk-write-real-driver.integration.test.ts index 8902d067945..f8685c929b9 100644 --- a/packages/runtime/src/bulk-write-real-driver.integration.test.ts +++ b/packages/runtime/src/bulk-write-real-driver.integration.test.ts @@ -84,7 +84,7 @@ const TREENODE = { fields: { name: { type: 'text' }, parent: { type: 'lookup', reference: 'treenode' } }, }; -const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1000, transaction: false } as any; +const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false } as any; const logger = { info() {}, warn() {}, error() {}, debug() {} }; function metadataFor(objects: any[]) { @@ -183,7 +183,7 @@ describe('bulk-write hardening on a REAL SqlDriver (framework#3147–#3152, #317 }); const seeder = new SeedLoaderService(e as any, metadataFor([WIDGET]), logger as any); const result = await seeder.load({ - seeds: [{ object: 'widget', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + seeds: [{ object: 'widget', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }] }] as any, config: SEED_CONFIG, }); @@ -202,7 +202,7 @@ describe('bulk-write hardening on a REAL SqlDriver (framework#3147–#3152, #317 }); const seeder = new SeedLoaderService(e as any, metadataFor([TREENODE]), logger as any); const result = await seeder.load({ - seeds: [{ object: 'treenode', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], + seeds: [{ object: 'treenode', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }, { name: 'Bob' }] }] as any, config: SEED_CONFIG, }); diff --git a/packages/runtime/src/seed-datasets.test.ts b/packages/runtime/src/seed-datasets.test.ts index 937db858545..b84b3f2b4a1 100644 --- a/packages/runtime/src/seed-datasets.test.ts +++ b/packages/runtime/src/seed-datasets.test.ts @@ -42,6 +42,12 @@ let seedResult: any = loaderResult({ totalInserted: 0, totalUpdated: 0, totalSki vi.mock('./seed-loader.js', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } constructor(..._args: any[]) { /* ql / metadata / logger ignored — mocked */ } async load(request: any) { loadCalls.push(request); return seedResult; } }, diff --git a/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts b/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts index 597d68835b6..e8d48ca883a 100644 --- a/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts +++ b/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts @@ -72,7 +72,7 @@ const ACCT = { const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', batchSize: 1000, transaction: false, + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; function metadataFor(objects: any[]) { @@ -162,7 +162,7 @@ describe('[#8442] a REAL driver constraint violation is withheld from the seed r seeds: [{ object: 'dt_acct', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'first', email: 'dup@example.com' }, diff --git a/packages/runtime/src/seed-loader.test.ts b/packages/runtime/src/seed-loader.test.ts index c0f3ecf1a84..9ac48b7fd81 100644 --- a/packages/runtime/src/seed-loader.test.ts +++ b/packages/runtime/src/seed-loader.test.ts @@ -1117,7 +1117,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', author: cel('os.user.id') }], }, @@ -1150,7 +1150,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', author: cel('os.user.id') }], }, @@ -1185,7 +1185,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', org_label: cel('os.org.id') }], }, @@ -1220,12 +1220,12 @@ describe('SeedLoaderService', () => { { object: 'account', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Acme' }], }, ], - config: baseConfig({ defaultMode: 'insert' }), + config: baseConfig({ defaultMode: 'ignore' }), }); expect(result.success).toBe(false); diff --git a/packages/verify/src/harness.seed-temporal-form.test.ts b/packages/verify/src/harness.seed-temporal-form.test.ts index 7461ae63ab4..eb7b2be36d1 100644 --- a/packages/verify/src/harness.seed-temporal-form.test.ts +++ b/packages/verify/src/harness.seed-temporal-form.test.ts @@ -89,9 +89,9 @@ const app = defineStack({ }, ], data: [ - { object: 'stf_handler', mode: 'insert', records: rows('handler') }, - { object: 'stf_body', mode: 'insert', records: rows('body') }, - { object: 'stf_guarded', mode: 'insert', records: rows('guarded') }, + { object: 'stf_handler', mode: 'ignore', records: rows('handler') }, + { object: 'stf_body', mode: 'ignore', records: rows('body') }, + { object: 'stf_guarded', mode: 'ignore', records: rows('guarded') }, ], } as never); From d7bf0cdc1c1c32092a83b9443afccdac1745aaa6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:53:21 +0000 Subject: [PATCH 03/19] wip: docs conversion steps, changeset, remaining loader mocks (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- .../34613-seed-mode-insert-replace-retired.md | 32 ++++++++ content/docs/data-modeling/seed-data.mdx | 82 ++++++++++++------- ...-local-api-key-account-posture.pin.test.ts | 6 ++ ...stall-local-capability-enumeration.test.ts | 6 ++ ...nstall-local-composed-bundle-seeds.test.ts | 6 ++ ...all-local-composed-top-level-reads.test.ts | 2 + ...place-install-local-corrupt-ledger.test.ts | 2 + ...stall-local-no-active-organization.test.ts | 6 ++ ...rketplace-install-local-seed-owner.test.ts | 6 ++ ...ce-install-local-tenancy-admission.test.ts | 6 ++ 10 files changed, 125 insertions(+), 29 deletions(-) create mode 100644 .changeset/34613-seed-mode-insert-replace-retired.md diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md new file mode 100644 index 00000000000..3282a26b1c0 --- /dev/null +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -0,0 +1,32 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/runtime': patch +'@objectstack/cloud-connection': patch +'@objectstack/lint': minor +'@objectstack/cli': patch +--- + +fix(spec,metadata-protocol)!: retire the seed modes `insert` and `replace`, which inserted every record again on each replay + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up owed — skills/objectstack-data/references/seeds.md, skills/objectstack-platform/SKILL.md + + + +**BREAKING** for a seed dataset authored with `mode: 'insert'` or `mode: 'replace'`. A seed is replayed on every single-tenant boot, every package install or upgrade and every publish, and neither mode matched an existing row, so every replay inserted each record again: an un-walled install went from 1 to 2 to 3 rows over three boots, a person reference the first load had to leave empty stayed empty on the first row while only the newest copy named the person, and with a unique field the replay insert was refused and the one row stayed empty. `replace` expected the caller to clear the table first, and no load path ever clears one. + +What moves (each line FROM → TO): + +- `SeedSchema.mode` / `SeedMode` (`@objectstack/spec/data`; `defineSeed`, `defineStack({ data })`, a `seed` metadata item, a package body's seed): FROM `insert` / `update` / `upsert` / `replace` / `ignore` TO `update` / `upsert` / `ignore` (default `ignore`, unchanged). `mode: 'insert'` or `mode: 'replace'` fails parse with a prescription naming the fix; the save and publish doors refuse it with the same message. +- a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. +- `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. +- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. +- the save door's and the loader's hint for a key no record carries: FROM "or use mode 'insert' for rows with no natural key" TO a list of fields when no single field names a row, or `'id'` when the records carry their own ids. + +The fix: declare which field identifies a row and drop the mode (or declare `upsert` for reference data the package keeps current). Set `externalId` to the field that names a row, to a list of fields when no single field does (a junction table's `['team', 'project']`), or to `'id'` when the records carry their own ids. Rebuild the package, and reinstall it where it was installed with `os package install`, so the stored body carries the new declaration. + +No conversion is made, at load, at save or by a migration (ADR-0087 D3, entry `seed-mode-insert-replace-retired`): a keyed mode needs the field that identifies a row, and only the author knows it. Rows earlier replays duplicated are data and are left as they are. + +Unchanged: `ignore`, `upsert` and `update` datasets load byte-identically. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index ed2f7782631..24dda5c4f8d 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -73,9 +73,11 @@ customer has since edited. |:-----|:---------|:---------| | `ignore` | **Default.** Create-only: insert a record whose row is missing (a boot or organization replay skips one a person [deleted](#a-deleted-seed-row-stays-deleted)), leave an existing row exactly as it is | Business and starter data the customer owns once it is loaded | | `upsert` | Create if new (a boot or organization replay skips one a person [deleted](#a-deleted-seed-row-stays-deleted)), and on **every** replay write each declared column back onto the matched row | Reference data the package must keep current | -| `insert` | Insert **every** record unconditionally — no existing-row check, so it **duplicates the table on each replay boot** ([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). Rarely what you want | Append-only rows loaded exactly once (never re-run) | | `update` | Update only, skip if not found | Migration patches on existing rows | -| `replace` | Insert without checking for an existing match — the seed loader does **not** delete anything itself; the target table must already be empty (or cleared by the caller) | Cache / lookup tables rebuilt from an already-truncated table | + +Every mode matches on `externalId`, so a replay finds the row an earlier load wrote. +The unkeyed modes `insert` and `replace` are retired: see +[Moving off `insert` and `replace`](#moving-off-insert-and-replace). ### `ignore` — The Default (Create-Only) @@ -126,32 +128,53 @@ customer or a job owns, mark those columns create-only — see `mode: 'upsert'` on the datasets that must stay current. -### `replace` — Insert Into an Already-Cleared Table +### Moving off `insert` and `replace` + +`insert` and `replace` matched no existing row, so every replay inserted each +record again: a 3-row fixture became 6, then 9 +([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)), and a person +reference the first load had to leave empty stayed empty on the first row while +only a later copy named the person. `replace` expected the caller to clear the +table first, and no load ever clears one. Both were removed in +`@objectstack/spec` 18.6.0 ([#34613](https://github.com/objectstack-ai/objectstack/issues/34613)): + +- **Authoring refuses them.** `defineSeed`, `defineStack`, `os validate`, `os build` + and the metadata save and publish doors reject `mode: 'insert'` or + `mode: 'replace'` with a message that names the fix. +- **A stored dataset is refused alone.** A package built before the change, or a + seed already stored, can still carry one. The boot seed, the organization + replay, the dev hot reload and a package install or upgrade refuse that one + dataset: it writes nothing, the load reports it as an error with the same + message, and every other dataset loads. +- **Rows already duplicated stay.** Earlier replays wrote them as data; nothing + deletes them. Remove the extra copies yourself if they matter. + +To convert a dataset, declare which field identifies a row, then drop the mode +(or declare `upsert` for reference data the package keeps current): + +1. **A field names the row** (a code, a slug, an email): set `externalId` to it. +2. **No single field does** (a join table, a line item under a parent): set + `externalId` to the list of fields that together identify a row, for example + `['team', 'project']`. Reference fields are matched by their resolved ids. See + [Composite natural key](#composite-externalid--join--junction-tables). +3. **The records carry their own ids**: set `externalId: 'id'`. ```typescript -// ⚠️ The seed loader does NOT delete existing records for you — `replace` -// always inserts. Truncate/clear the table yourself before this seed runs, -// or every load will attempt to insert duplicate rows. -// Only use for cache or lookup tables with no user-generated data. -defineSeed(ExchangeRateCache, { - externalId: 'key', +// Before — refused since @objectstack/spec 18.6.0 +defineSeed(ExchangeRate, { mode: 'replace', - env: ['dev'], - records: [ - { key: 'USD_EUR', rate: 0.92 }, - { key: 'USD_GBP', rate: 0.79 }, - ], + records: [{ key: 'USD_EUR', rate: 0.92 }], }); -``` -### `insert` — Not Idempotent (Avoid for Replayed Seeds) +// After — one row per key, written once +defineSeed(ExchangeRate, { + externalId: 'key', + records: [{ key: 'USD_EUR', rate: 0.92 }], +}); +``` -Seeds are **replayed** — they re-load on every dev-server boot and every package -re-publish, not applied once. `insert` writes every record with **no existing-row -check**, so a replayed `insert` dataset duplicates its table on each restart -(a 3-row fixture becomes 6, then 9 — [#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). -It is almost never the right mode: leave `mode` unset (create-only), or declare -`upsert` for reference data, with a stable `externalId` instead. `os validate` warns on any `mode: 'insert'` seed. +Rebuild the package (and reinstall it where it was installed with +`os package install`) so the stored body carries the new declaration. ### A Deleted Seed Row Stays Deleted @@ -243,8 +266,8 @@ defineSeed(Instalment, { out of the write: the row keeps the values the jobs gave it, while `amount` (`applyOn: 'always'`, the default) is refreshed. A row whose only differences are create-only columns is not written at all. -- An `update` dataset never writes a create-only column. `insert`, `ignore` and - `replace` never update a matched row, so the policy changes nothing there. +- An `update` dataset never writes a create-only column. `ignore` never updates + a matched row, so the policy changes nothing there. - A create-only **reference** on a matched row is not resolved at all, so a replay neither re-points it nor reports it. - A column of the `externalId` is what the row was matched by, so it stays in @@ -541,8 +564,9 @@ const membershipsSeed = defineSeed(ProjectMembership, { }); ``` -Without a composite key such a table can only fall back to `mode: 'insert'`, which -duplicates on every replay boot ([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). +Without a composite key such a table has nothing to match a replay on. The +unkeyed `mode: 'insert'` it once fell back to duplicated on every replay boot +([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)) and is retired. --- @@ -807,8 +831,8 @@ behind already wrote — see [Locale Scoping](#locale-scoping). The default, `ignore`, is idempotent and never overwrites an edit. Declare a mode only when the use case requires it — `upsert` for reference data the package keeps current -(with `applyOn: 'create'` on the columns the customer or a job owns), or `replace` -for ephemeral cache tables. +(with `applyOn: 'create'` on the columns the customer or a job owns), or `update` +for a migration patch on rows that already exist. ### Declare a dependency no field expresses @@ -838,7 +862,7 @@ function defineSeed< objectDef: TObj, config: { externalId?: string | string[]; // single field, or a composite list (join tables); default: 'name' - mode?: 'insert' | 'update' | 'upsert' | 'replace' | 'ignore'; // default: 'ignore' + mode?: 'update' | 'upsert' | 'ignore'; // default: 'ignore' columns?: { [field: string]: { applyOn?: 'create' | 'always' } }; // per-column write policy; default: 'always' env?: Array<'prod' | 'dev' | 'test'>; // default: ['prod','dev','test'] locale?: string[]; // BCP-47 tags; omitted = every locale diff --git a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts index 5ac91550641..447062e87ef 100644 --- a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts @@ -37,6 +37,12 @@ import { currentCredentialUseClient, hashApiKey } from '@objectstack/core'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts index b9230733d01..b9ca68d2f01 100644 --- a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts @@ -69,6 +69,12 @@ import { tmpdir } from 'node:os'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts index 4d94fbc1a97..5b63ec6f3d6 100644 --- a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts @@ -30,6 +30,12 @@ let seedResult: any; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts index ac58b8aca88..9efb153e720 100644 --- a/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts @@ -47,6 +47,8 @@ const heldDatasources = vi.hoisted(() => new Map()); vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts b/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts index fb8211daf3f..87577277af3 100644 --- a/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts @@ -41,6 +41,8 @@ import { tmpdir } from 'node:os'; // does so these tests exercise rehydrate's reporting, not seeding. vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts index 11673d8454d..b0d616c159c 100644 --- a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts @@ -43,6 +43,12 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts index 4dedcc05f1d..3344390b1e3 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts @@ -30,6 +30,12 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts index 6a1cf3b288e..03fdaf48b41 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts @@ -61,6 +61,12 @@ import { tmpdir } from 'node:os'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; From 28c1361cd5fe9df45519448b9aab95083a9d9bf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:16:53 +0000 Subject: [PATCH 04/19] wip: regenerate references, transcript count 68, composite-key caveat, dogfood fixture keyed, revert plugin-security false positive (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- content/docs/data-modeling/seed-data.mdx | 5 ++++- content/docs/deployment/cli.mdx | 2 +- content/docs/deployment/validating-metadata.mdx | 2 +- .../getting-started/build-with-claude-code.mdx | 2 +- .../references/api/package-api-assembled.mdx | 6 +++--- content/docs/references/api/package-api.mdx | 16 ++++++++-------- content/docs/references/api/protocol.mdx | 2 +- content/docs/references/data/seed-loader.mdx | 16 ++++++++-------- content/docs/references/data/seed.mdx | 4 +--- content/docs/references/kernel/manifest.mdx | 4 ++-- .../docs/references/kernel/package-registry.mdx | 4 ++-- content/docs/ui/react-pages.mdx | 2 +- .../predicate-related-read-tenant-scope.test.ts | 2 +- .../grant-table-write-contract.dogfood.test.ts | 2 +- .../18.seed-mode-insert-replace-retired.ts | 2 +- 15 files changed, 36 insertions(+), 35 deletions(-) diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 24dda5c4f8d..84599911f1b 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -155,7 +155,10 @@ To convert a dataset, declare which field identifies a row, then drop the mode 1. **A field names the row** (a code, a slug, an email): set `externalId` to it. 2. **No single field does** (a join table, a line item under a parent): set `externalId` to the list of fields that together identify a row, for example - `['team', 'project']`. Reference fields are matched by their resolved ids. See + `['team', 'project']`. Reference fields are matched by their resolved ids, so + list only fields every load can fill: a reference the first load has to leave + empty (a person who has not signed up yet) makes each later load miss that row + and insert another. See [Composite natural key](#composite-externalid--join--junction-tables). 3. **The records carry their own ids**: set `externalId: 'id'`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 5a0c9142933..c005050575d 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -887,7 +887,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (69)... + → Running author-time rules (68)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index d0adea624a1..ff349ada78d 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -852,7 +852,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (68)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index e8fe83b2be9..0afbb85a249 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (68)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index ef4f4851700..cf5e7155426 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -99,7 +99,7 @@ Installed package row whose manifest is the assembled package body | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | | **capabilities** | `{ name: string; label?: string; description?: string; scope?: Enum<'platform' \| 'org'>; … }[]` | optional | [ADR-0066 D1] Authorization capabilities this package defines (seeded with package provenance) | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -285,7 +285,7 @@ This schema accepts one of the following structures: | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -349,7 +349,7 @@ This schema accepts one of the following structures: | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | | **capabilities** | `{ name: string; label?: string; description?: string; scope?: Enum<'platform' \| 'org'>; … }[]` | optional | [ADR-0066 D1] Authorization capabilities this package defines (seeded with package provenance) | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/api/package-api.mdx b/content/docs/references/api/package-api.mdx index 48ade0c36a5..bae5bca0373 100644 --- a/content/docs/references/api/package-api.mdx +++ b/content/docs/references/api/package-api.mdx @@ -155,7 +155,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -201,7 +201,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -243,7 +243,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | @@ -310,7 +310,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -352,7 +352,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | @@ -428,7 +428,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -570,7 +570,7 @@ Upgrade package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -664,7 +664,7 @@ Resolve dependencies request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 4027b6a360b..6f8718cca32 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2185,7 +2185,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index ac7c1bf2d34..bf232d2845c 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -153,7 +153,7 @@ Result of loading a single dataset | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Object that was loaded | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | ✅ | Import mode used | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | ✅ | Import mode used | | **inserted** | `integer` | ✅ | Records inserted | | **updated** | `integer` | ✅ | Records updated | | **skipped** | `integer` | ✅ | Records skipped | @@ -195,7 +195,7 @@ Seed data loader configuration | **dryRun** | `boolean` | optional (default: `false`) | Validate references without writing data | | **haltOnError** | `boolean` | optional (default: `false`) | Stop on first reference resolution error | | **multiPass** | `boolean` | optional (default: `true`) | Enable multi-pass loading for circular dependencies | -| **defaultMode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | +| **defaultMode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | | **batchSize** | `integer` | optional (default: `1000`) | Maximum records per batch insert/upsert | | **transaction** | `boolean` | optional (default: `false`) | Wrap entire load in a transaction (all-or-nothing) | | **env** | `Enum<'prod' \| 'dev' \| 'test'>` | optional | Only load datasets matching this environment | @@ -221,8 +221,8 @@ Seed loader request with datasets and configuration | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **seeds** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | ✅ | Seeds to load | -| **config** | `{ dryRun?: boolean; haltOnError?: boolean; multiPass?: boolean; defaultMode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; … }` | optional (has default) | Loader configuration | +| **seeds** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | ✅ | Seeds to load | +| **config** | `{ dryRun?: boolean; haltOnError?: boolean; multiPass?: boolean; defaultMode?: Enum<'update' \| 'upsert' \| 'ignore'>; … }` | optional (has default) | Loader configuration | ### Nested Shape: `SeedLoaderRequest.seeds[number]` @@ -230,7 +230,7 @@ Seed loader request with datasets and configuration | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | @@ -252,7 +252,7 @@ Seed loader request with datasets and configuration | **dryRun** | `boolean` | optional (default: `false`) | Validate references without writing data | | **haltOnError** | `boolean` | optional (default: `false`) | Stop on first reference resolution error | | **multiPass** | `boolean` | optional (default: `true`) | Enable multi-pass loading for circular dependencies | -| **defaultMode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | +| **defaultMode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | | **batchSize** | `integer` | optional (default: `1000`) | Maximum records per batch insert/upsert | | **transaction** | `boolean` | optional (default: `false`) | Wrap entire load in a transaction (all-or-nothing) | | **env** | `Enum<'prod' \| 'dev' \| 'test'>` | optional | Only load datasets matching this environment | @@ -274,7 +274,7 @@ Complete seed loader result | **success** | `boolean` | ✅ | Overall success status | | **dryRun** | `boolean` | ✅ | Whether this was a dry-run | | **dependencyGraph** | `{ nodes: object[]; insertOrder: string[]; circularDependencies?: string[][] }` | ✅ | Object dependency graph | -| **results** | `{ object: string; mode: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; inserted: integer; updated: integer; … }[]` | ✅ | Per-object load results | +| **results** | `{ object: string; mode: Enum<'update' \| 'upsert' \| 'ignore'>; inserted: integer; updated: integer; … }[]` | ✅ | Per-object load results | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | ✅ | All reference resolution errors | | **summary** | `{ objectsProcessed: integer; totalRecords: integer; totalInserted: integer; totalUpdated: integer; … }` | ✅ | Summary statistics | @@ -293,7 +293,7 @@ Result of loading a single dataset | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Object that was loaded | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | ✅ | Import mode used | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | ✅ | Import mode used | | **inserted** | `integer` | ✅ | Records inserted | | **updated** | `integer` | ✅ | Records updated | | **skipped** | `integer` | ✅ | Records skipped | diff --git a/content/docs/references/data/seed.mdx b/content/docs/references/data/seed.mdx index 85b470d265c..c113b1fb172 100644 --- a/content/docs/references/data/seed.mdx +++ b/content/docs/references/data/seed.mdx @@ -30,7 +30,7 @@ const result = SeedSchema.parse(data); | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | @@ -80,10 +80,8 @@ One bundled seed file: its bytes and what they must hash to ### Allowed Values -* `insert` * `update` * `upsert` -* `replace` * `ignore` diff --git a/content/docs/references/kernel/manifest.mdx b/content/docs/references/kernel/manifest.mdx index 0a6ae3cce51..31798189bd5 100644 --- a/content/docs/references/kernel/manifest.mdx +++ b/content/docs/references/kernel/manifest.mdx @@ -55,7 +55,7 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -97,7 +97,7 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | diff --git a/content/docs/references/kernel/package-registry.mdx b/content/docs/references/kernel/package-registry.mdx index b01891eb534..34d19a404cf 100644 --- a/content/docs/references/kernel/package-registry.mdx +++ b/content/docs/references/kernel/package-registry.mdx @@ -210,7 +210,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -308,7 +308,7 @@ Installed package with runtime lifecycle state | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index c39a14544a4..a2c91e9cff5 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (69)... + → Running author-time rules (68)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts b/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts index 1020fe13390..8236fe14cb5 100644 --- a/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts +++ b/packages/plugins/plugin-security/src/predicate-related-read-tenant-scope.test.ts @@ -209,7 +209,7 @@ async function observe( .insert(object, { name: 'probe', [ref]: line }, { context: caller } as never) .then(() => null, (e: { code?: string; message?: string }) => ({ code: e.code, message: e.message })); const preview = await h.engine.validate( - object, { name: 'probe', [ref]: line }, { mode: 'ignore', context: caller } as never, + object, { name: 'probe', [ref]: line }, { mode: 'insert', context: caller } as never, ); // Given a posture, the by-id UPDATE door too: a seeded row the caller may edit, repointed at `line`. let update: unknown; diff --git a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts index 2066c4e24ea..804c57f3523 100644 --- a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts +++ b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts @@ -280,7 +280,7 @@ describe('an agent ceiling set reaches no person through a position or a seed', it('a published seed granting an agent ceiling set stores no grant, and a person-set seed does', async () => { const seed = (name: string, set: string) => stack.apiAs(admin, 'PUT', `/meta/seed/${name}?mode=draft&package=${PKG}`, { - object: 'sys_user_permission_set', mode: 'ignore', records: [{ user_id: personId, permission_set: set }], + object: 'sys_user_permission_set', externalId: ['user_id', 'permission_set'], records: [{ user_id: personId, permission_set: set }], }); expect((await seed('agent_ceiling_grant_seed', CEILING)).status).toBe(200); expect((await seed('person_set_grant_seed', SET)).status).toBe(200); diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts index 954690f7561..27359230f90 100644 --- a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts +++ b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts @@ -25,7 +25,7 @@ export const entry: SemanticMigration = { + 'refused and the one row stayed NULL. Both values are now refused where a seed is parsed, with the ' + 'prescription. A dataset already stored with either value is refused loudly by the loads that replay stored ' + 'seeds (the boot seed, the per-organization replay, the dev hot reload, a package install or upgrade): that ' - + 'dataset writes nothing and the load logs its prescription at error, and every other dataset loads. There is no ' + + 'dataset writes nothing, the load result fails with its prescription and the boot log names it, and every other dataset loads. There is no ' + 'mechanical rewrite, because a keyed mode needs the field that identifies a row, and only the author knows it. ' + 'Rows earlier replays duplicated are data, not metadata, and are left as they are', acceptanceCriteria: From 336672e4f70ec9915ac95b60b62deca4a1201cda Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:59:27 +0000 Subject: [PATCH 05/19] test: pay seed-test module loads at collection; the retired-mode test's engine refuses WHERE combinators (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- .../src/cloud-connection-auth-gate.pin.test.ts | 2 +- ...ace-install-local-api-key-account-posture.pin.test.ts | 2 +- ...ketplace-install-local-capability-enumeration.test.ts | 2 +- ...rketplace-install-local-composed-bundle-seeds.test.ts | 2 +- .../src/marketplace-install-local-heal.test.ts | 2 +- ...ketplace-install-local-no-active-organization.test.ts | 2 +- .../src/marketplace-install-local-reseed.test.ts | 2 +- .../src/marketplace-install-local-seed-owner.test.ts | 2 +- .../src/marketplace-install-local-seed-replayer.test.ts | 2 +- .../marketplace-install-local-tenancy-admission.test.ts | 2 +- .../marketplace-install-local-tenancy-posture.test.ts | 2 +- .../src/seed-loader-retired-mode-34613.test.ts | 9 +++++++-- .../runtime/src/app-plugin.seed-stamped-additive.test.ts | 2 ++ packages/runtime/src/app-plugin.seed.test.ts | 2 ++ packages/runtime/src/seed-datasets.test.ts | 2 ++ packages/verify/src/harness.seed-temporal-form.test.ts | 3 +++ 16 files changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts index 16ceb028706..4f7ac3689ed 100644 --- a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts +++ b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts @@ -42,6 +42,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -53,7 +54,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: unknown) { diff --git a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts index 447062e87ef..8bcb5d2ada9 100644 --- a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts @@ -29,6 +29,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -40,7 +41,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: unknown) { diff --git a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts index b9ca68d2f01..75fcd6455ac 100644 --- a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts @@ -62,6 +62,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -72,7 +73,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: unknown) { diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts index 5b63ec6f3d6..cdca8081771 100644 --- a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts @@ -20,6 +20,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -33,7 +34,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts index f36cbaa5978..16505f407e8 100644 --- a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts @@ -18,6 +18,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -32,7 +33,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts index b0d616c159c..12339f78b27 100644 --- a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts @@ -35,6 +35,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -46,7 +47,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { diff --git a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts index 6816530912c..f8bdc6f2ab1 100644 --- a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts @@ -21,6 +21,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -36,7 +37,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts index 3344390b1e3..0e1b6ab3229 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts @@ -21,6 +21,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -33,7 +34,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts index d62031cd70e..6246746b3d4 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts @@ -39,6 +39,7 @@ // replayer IS the scenario. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -96,7 +97,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts index 03fdaf48b41..72a75fe1ed1 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts @@ -54,6 +54,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -64,7 +65,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: unknown) { diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts index 7e7db62d4cd..61d9f9723e6 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts @@ -44,6 +44,7 @@ // this package use) so the assertions can read what the seeder was ASKED to do. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -56,7 +57,6 @@ vi.mock('@objectstack/runtime', () => ({ // [#34613] The real `loadStored` parses the stored request and hands it to `load`; // the stand-in keeps that funnel, so the request `load` records is the parsed one. async loadStored(raw: any) { - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); return this.load(SeedLoaderRequestSchema.parse(raw)); } async load(request: any) { loadCalls.push(request); return seedResult; } diff --git a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts index 3c38d49a486..066c86b634b 100644 --- a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts +++ b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts @@ -26,13 +26,18 @@ function createLogger() { return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; } -/** An in-memory engine: equality `where`, ids minted on insert. */ +/** An in-memory engine: equality `where` (a combinator is refused, not read as a field), ids minted on insert. */ function createEngine(): { engine: IDataEngine; store: Record>> } { const store: Record>> = {}; let next = 0; const find = async (object: string, query?: { where?: Record; limit?: number }) => { let rows = store[object] ?? []; - if (query?.where) rows = rows.filter((r) => Object.entries(query.where!).every(([k, v]) => r[k] === v)); + if (query?.where) { + rows = rows.filter((r) => Object.entries(query.where!).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`in-memory engine: unsupported operator ${k}`); + return r[k] === v; + })); + } return typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows; }; const engine = { diff --git a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts index 45b9c3f2efe..f79e641e7f1 100644 --- a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts +++ b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts @@ -25,6 +25,8 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; import { LiteKernel, type PluginContext } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; import { applyProtection } from '@objectstack/spec/shared'; diff --git a/packages/runtime/src/app-plugin.seed.test.ts b/packages/runtime/src/app-plugin.seed.test.ts index 3007153070d..303c70ec9da 100644 --- a/packages/runtime/src/app-plugin.seed.test.ts +++ b/packages/runtime/src/app-plugin.seed.test.ts @@ -1,6 +1,8 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; import { AppPlugin } from './app-plugin'; import { readSeedDatasets } from './seed-datasets.js'; import { readSeedSettlement } from './seed-settlement.js'; diff --git a/packages/runtime/src/seed-datasets.test.ts b/packages/runtime/src/seed-datasets.test.ts index b84b3f2b4a1..f288f9df4e8 100644 --- a/packages/runtime/src/seed-datasets.test.ts +++ b/packages/runtime/src/seed-datasets.test.ts @@ -1,6 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; /** * #3453 — the multi-tenant seed-replay seam. diff --git a/packages/verify/src/harness.seed-temporal-form.test.ts b/packages/verify/src/harness.seed-temporal-form.test.ts index eb7b2be36d1..2ee48e74e02 100644 --- a/packages/verify/src/harness.seed-temporal-form.test.ts +++ b/packages/verify/src/harness.seed-temporal-form.test.ts @@ -24,6 +24,9 @@ */ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; import { cel, defineStack } from '@objectstack/spec'; import { Field, ObjectSchema } from '@objectstack/spec/data'; import { bootStack, type VerifyStack } from './harness.js'; From 07b6f2fe49dad741775a5681fad949da8115da9e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:49:54 +0000 Subject: [PATCH 06/19] fix(metadata,metadata-protocol): a compiled artifact with a retired seed mode still boots; the loader refuses the mode itself (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- .../34613-seed-mode-insert-replace-retired.md | 4 +- content/docs/data-modeling/seed-data.mdx | 9 +- .../src/seed-loader-empty-key-warn.test.ts | 5 +- ...ader-existing-records-read-failure.test.ts | 4 +- .../seed-loader-retired-mode-34613.test.ts | 44 +++++- packages/metadata-protocol/src/seed-loader.ts | 51 ++++++- .../src/artifact-retired-seed-modes.test.ts | 62 +++++++++ .../src/artifact-retired-seed-modes.ts | 127 ++++++++++++++++++ packages/metadata/src/plugin.ts | 30 ++++- packages/runtime/src/app-plugin.ts | 4 +- packages/runtime/src/seed-loader.test.ts | 2 +- ...k-artifact-retired-seed-mode-34613.test.ts | 93 +++++++++++++ packages/spec/api-surface/data.json | 1 + packages/spec/export-origins/data.json | 1 + packages/spec/src/data/seed.zod.ts | 24 +++- .../18.seed-mode-insert-replace-retired.ts | 11 +- scripts/check-skill-identifier-liveness.mjs | 4 +- scripts/engine-double-contract.pinned.json | 15 +++ 18 files changed, 460 insertions(+), 31 deletions(-) create mode 100644 packages/metadata/src/artifact-retired-seed-modes.test.ts create mode 100644 packages/metadata/src/artifact-retired-seed-modes.ts create mode 100644 packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md index 3282a26b1c0..baa533406df 100644 --- a/.changeset/34613-seed-mode-insert-replace-retired.md +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -5,6 +5,7 @@ '@objectstack/cloud-connection': patch '@objectstack/lint': minor '@objectstack/cli': patch +'@objectstack/metadata': patch --- fix(spec,metadata-protocol)!: retire the seed modes `insert` and `replace`, which inserted every record again on each replay @@ -20,7 +21,8 @@ Skills-docs: follow-up owed — skills/objectstack-data/references/seeds.md, ski What moves (each line FROM → TO): - `SeedSchema.mode` / `SeedMode` (`@objectstack/spec/data`; `defineSeed`, `defineStack({ data })`, a `seed` metadata item, a package body's seed): FROM `insert` / `update` / `upsert` / `replace` / `ignore` TO `update` / `upsert` / `ignore` (default `ignore`, unchanged). `mode: 'insert'` or `mode: 'replace'` fails parse with a prescription naming the fix; the save and publish doors refuse it with the same message. -- a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. +- a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. `SeedLoaderService.load()` and `validate()` refuse the dataset the same way when handed one unparsed, so a dry run reports what a real load does. +- a compiled artifact (`objectstack.json`) carrying such a dataset, booted by `os serve` / `os start` / `os dev` (the artifact door, `MetadataPlugin`, `@objectstack/metadata`): the door parses the artifact without that dataset and hands it back to the seed load, which refuses it alone; the door logs a warning naming the dataset and the fix. Everything else in the artifact registers and boots. - `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. - the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. - the save door's and the loader's hint for a key no record carries: FROM "or use mode 'insert' for rows with no natural key" TO a list of fields when no single field names a row, or `'id'` when the records carry their own ids. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 84599911f1b..e8fcb9d4f03 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -141,11 +141,12 @@ table first, and no load ever clears one. Both were removed in - **Authoring refuses them.** `defineSeed`, `defineStack`, `os validate`, `os build` and the metadata save and publish doors reject `mode: 'insert'` or `mode: 'replace'` with a message that names the fix. -- **A stored dataset is refused alone.** A package built before the change, or a - seed already stored, can still carry one. The boot seed, the organization +- **A stored dataset is refused alone.** A package or a compiled artifact + (`objectstack.json`) built before the change, or a seed already stored, can + still carry one. The environment still boots: the boot seed, the organization replay, the dev hot reload and a package install or upgrade refuse that one - dataset: it writes nothing, the load reports it as an error with the same - message, and every other dataset loads. + dataset. It writes nothing, the load reports it as an error with the same + message, and every other dataset and definition loads. - **Rows already duplicated stay.** Earlier replays wrote them as data; nothing deletes them. Remove the extra copies yourself if they matter. diff --git a/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts b/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts index 3abe76c0a10..c2450c57f29 100644 --- a/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts +++ b/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts @@ -159,12 +159,13 @@ describe('[#28952] the boot loader — a keyed dataset whose every record keys e expect(emptyKeyWarnings(logger)).toEqual([]); }); - it('control: an `insert` dataset never matches, so it is not warned about', async () => { + it('control: a retired `insert` dataset is refused before any key is read, so it is not warned about (#34613)', async () => { const { engine } = createFaithfulEngine(); const logger = createLogger(); - await new SeedLoaderService(engine, createMetadata(), logger).load({ + const result = await new SeedLoaderService(engine, createMetadata(), logger).load({ seeds: [dataset('no_such_field', 'insert')] as any[], config: CONFIG, }); + expect(result.results[0]).toMatchObject({ inserted: 0, errored: 1 }); expect(emptyKeyWarnings(logger)).toEqual([]); }); diff --git a/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts b/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts index d828c6821a1..91c9e4dc576 100644 --- a/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts @@ -180,7 +180,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as never; @@ -306,7 +306,7 @@ describe('[#8896] seed loader — an existing-records read that FAILED is not "n }); const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).load({ - seeds: seedOf('insert', [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }]), + seeds: seedOf('ignore', [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }]), config: CONFIG, }); diff --git a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts index 066c86b634b..128a7e6dc57 100644 --- a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts +++ b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts @@ -20,6 +20,7 @@ import { describe, it, expect, vi } from 'vitest'; import { SeedMode } from '@objectstack/spec/data'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { SeedLoaderService } from './seed-loader.js'; function createLogger() { @@ -42,7 +43,10 @@ function createEngine(): { engine: IDataEngine; store: Record (await find(object, { ...query, limit: 1 }))[0] ?? null), + findOne: vi.fn(async (object: string, query?: any) => { + assertEngineFindOnePredicate(object, query); + return (await find(object, { ...query, limit: 1 }))[0] ?? null; + }), insert: vi.fn(async (object: string, data: any) => { const put = (d: Record) => { const row = { id: `r${++next}`, ...d }; @@ -51,8 +55,14 @@ function createEngine(): { engine: IDataEngine; store: Record data), - delete: vi.fn(async () => ({ deleted: 0 })), + update: vi.fn(async (_object: string, data: any, options?: any) => { + assertEngineUpdateDispatch(data, options); + return data; + }), + delete: vi.fn(async (_object: string, options?: any) => { + assertEngineDeleteDispatch(options); + return { deleted: 0 }; + }), count: vi.fn(async (object: string) => (store[object] ?? []).length), aggregate: vi.fn(async () => []), } as unknown as IDataEngine; @@ -122,6 +132,34 @@ describe('loadStored — a stored dataset with a retired mode is refused alone ( expect(result.errors.map((e) => e.sourceObject)).toEqual(['rm_source']); }); + it.each([['insert'], ['replace']])('`load()` itself refuses a `%s` dataset it was handed unparsed: nothing written, every record errored (S1)', async (mode) => { + const { engine, store } = createEngine(); + const logger = createLogger(); + const result = await new SeedLoaderService(engine, createMetadata(), logger).load({ + seeds: [ + { object: 'rm_source', mode, externalId: 'name', records: [{ name: 'web' }, { name: 'mail' }] }, + { object: 'rm_region', mode: 'ignore', externalId: 'name', records: [{ name: 'emea' }] }, + ], + config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false }, + } as never); + expect(store.rm_source).toBeUndefined(); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + expect(result.success).toBe(false); + expect(result.results.find((r) => r.object === 'rm_source')).toMatchObject({ inserted: 0, updated: 0, errored: 2, total: 2 }); + expect(result.errors.map((e) => e.message)).toEqual([`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf(mode)}`]); + expect(logger.error).toHaveBeenCalledTimes(1); + }); + + it('`validate()` (the dry run) answers the same refusal a real load would, not a clean result (S1)', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).validate( + [{ object: 'rm_source', mode: 'insert', externalId: 'name', records: [{ name: 'web' }] }] as never, + ); + expect(store).toEqual({}); + expect(result.success).toBe(false); + expect(result.errors[0]!.message).toBe(`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf('insert')}`); + }); + it('CONTROL: with no retired dataset the answer is the load’s own', async () => { const { engine, store } = createEngine(); const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 4cbc865114a..59e66d0a6ff 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -19,6 +19,7 @@ import { SeedLoaderConfigSchema, SeedLoaderRequestSchema, SeedMode, + RETIRED_SEED_MODE_VALUES, isMultiValueField, isTenancyDisabled, referenceTargetOf, @@ -409,7 +410,7 @@ const SEED_LANDED_KEY_OBJECT = 'sys_seed_landed_key'; * seed can still carry. Only membership is read here: the prescription a * refused dataset reports is `SeedMode`'s own refusal. */ -const RETIRED_SEED_MODES: ReadonlySet = new Set(['insert', 'replace']); +const RETIRED_SEED_MODES: ReadonlySet = new Set(RETIRED_SEED_MODE_VALUES); /** * [#31021] The key a landed seed row is recorded under in @@ -1556,7 +1557,11 @@ export class SeedLoaderService implements ISeedLoaderService { * `SeedMode` refusal, read from the schema, never restated) becomes one * error of the result with `success: false`, and every other dataset loads. * No log line of its own: the refusal is handed to the caller, which - * reports a failed load's errors as it reports any other. + * reports a failed load's errors as it reports any other. (A compiled + * artifact reaches here too: the artifact door parses the rest of the + * artifact without such a dataset, see `@objectstack/metadata`'s + * `artifact-retired-seed-modes.ts`; and `loadDataset` refuses the mode again + * for a caller that skips this funnel.) * * The publish doors do not come here. A publish has its author present, so * it parses the request itself and refuses the whole publish with the same @@ -1622,6 +1627,44 @@ export class SeedLoaderService implements ISeedLoaderService { ): Promise { const objectName = dataset.object; const mode = dataset.mode || config.defaultMode; + // [#34613] A mode outside the live `SeedMode` set refuses the dataset HERE, + // whatever the caller parsed: `load()` and `validate()` take requests they + // do not parse, and the retired `insert` / `replace` would otherwise fall to + // the default arm below and insert every record again on each replay. The + // refusal writes nothing, counts every record errored, and carries the + // schema's own prescription. (No mode at all, a request built without the + // parse's defaults, keeps its old path below.) + const modeVerdict = mode === undefined ? undefined : SeedMode.safeParse(mode); + if (modeVerdict && !modeVerdict.success) { + const error: ReferenceResolutionError = { + sourceObject: objectName, + field: 'mode', + targetObject: objectName, + targetField: '(dataset)', + attemptedValue: mode, + // The mode is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: `Seed dataset for '${objectName}' was not loaded: ${modeVerdict.error.issues[0]?.message ?? `mode '${String(mode)}' is not a seed mode`}`, + }; + allErrors.push(error); + this.logger.error(`[SeedLoader] ${error.message}`, undefined, { object: objectName, mode }); + return { + object: objectName, + mode, + inserted: 0, + updated: 0, + skipped: 0, + errored: dataset.records.length, + total: dataset.records.length, + referencesResolved: 0, + referencesDeferred: 0, + referencesDropped: 0, + summariesStale: 0, + landedIds: [], + insertedIds: [], + errors: [error], + }; + } const externalId = dataset.externalId || 'name'; // [#25761] Left out of every write to a row this dataset MATCHED — see // `matchesExistingRow` in the record loop below. @@ -3938,8 +3981,8 @@ export class SeedLoaderService implements ISeedLoaderService { return { action: 'inserted', id: this.extractId(result) }; } - // The retired `insert` / `replace` (#34613) never reach here: the request - // parse refuses them, and `loadStored` refuses a stored one alone. + // The retired `insert` / `replace` (#34613) never reach here: + // `loadDataset` refuses a mode outside the live set before any write. default: { const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); return { action: 'inserted', id: this.extractId(result) }; diff --git a/packages/metadata/src/artifact-retired-seed-modes.test.ts b/packages/metadata/src/artifact-retired-seed-modes.test.ts new file mode 100644 index 00000000000..3a3ef830a8c --- /dev/null +++ b/packages/metadata/src/artifact-retired-seed-modes.test.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34613] The artifact door takes a retired-mode seed dataset out of every + * seed collection an artifact can hold (top-level `data`, `manifest.data`, each + * assembled package body's `data` and `manifest.data`) before its strict parse, + * and hands it back to the same collection after. The boot over a real artifact + * is pinned in `@objectstack/runtime` + * (`standalone-stack-artifact-retired-seed-mode-34613.test.ts`). + */ + +import { describe, it, expect } from 'vitest'; +import { SeedMode } from '@objectstack/spec/data'; +import { restoreWithheldSeedDatasets, withholdRetiredSeedModes } from './artifact-retired-seed-modes.js'; + +const live = { object: 'a_region', externalId: 'name', records: [{ name: 'emea' }] }; +const stale = (mode: string, object = 'a_source') => ({ object, mode, records: [{ name: 'web' }] }); + +describe('withholdRetiredSeedModes', () => { + it('takes a retired-mode dataset out of every seed collection, without mutating the input', () => { + const input = { + data: [live, stale('insert')], + manifest: { id: 'x', data: [stale('replace', 'm_source')] }, + packages: [{ id: 'p', data: [stale('insert', 'p_source'), live], manifest: { data: [live] } }], + }; + const before = JSON.stringify(input); + const { definition, withheld } = withholdRetiredSeedModes(input) as { definition: any; withheld: any[] }; + + expect(JSON.stringify(input)).toBe(before); + expect(definition.data).toEqual([live]); + expect(definition.manifest.data).toEqual([]); + expect(definition.packages[0].data).toEqual([live]); + expect(definition.packages[0].manifest.data).toEqual([live]); + expect(withheld.map((w) => [w.path.join('.'), w.object, w.mode])).toEqual([ + ['', 'a_source', 'insert'], + ['manifest', 'm_source', 'replace'], + ['packages.0', 'p_source', 'insert'], + ]); + // The prescription is SeedMode's own refusal, not restated. + const verdict = SeedMode.safeParse('insert'); + expect(verdict.success).toBe(false); + expect(withheld[0].prescription).toBe(verdict.success ? '' : verdict.error.issues[0]!.message); + }); + + it('hands each withheld dataset back to the collection it came from', () => { + const { definition, withheld } = withholdRetiredSeedModes({ + data: [live, stale('insert')], + packages: [{ id: 'p', data: [stale('replace', 'p_source')] }], + }) as { definition: any; withheld: any[] }; + const parsed = structuredClone(definition); + restoreWithheldSeedDatasets(parsed, withheld); + expect(parsed.data).toEqual([live, stale('insert')]); + expect(parsed.packages[0].data).toEqual([stale('replace', 'p_source')]); + }); + + it('CONTROL: a never-valid mode and a definition with nothing retired are left for the parse, untouched', () => { + const input = { data: [live, stale('merge')] }; + const { definition, withheld } = withholdRetiredSeedModes(input); + expect(definition).toBe(input); + expect(withheld).toEqual([]); + }); +}); diff --git a/packages/metadata/src/artifact-retired-seed-modes.ts b/packages/metadata/src/artifact-retired-seed-modes.ts new file mode 100644 index 00000000000..16887adb3a8 --- /dev/null +++ b/packages/metadata/src/artifact-retired-seed-modes.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { RETIRED_SEED_MODE_VALUES, SeedMode } from '@objectstack/spec/data'; + +/** + * [#34613] A compiled artifact built before the seed modes `insert` and + * `replace` were retired can still carry a dataset declaring one. The artifact + * door strict-parses the whole definition, and `SeedSchema.mode` refuses both + * values, so without this the boot would abort over one seed dataset: no + * object, view or flow of the artifact would register either. Ruling + * 6942780880 asks for the opposite: that dataset is refused, loudly, and the + * rest of the environment loads. + * + * So the door parses the definition WITHOUT such datasets and hands them back + * afterwards, unparsed, to the collection they came from. Seeds are never + * registered as metadata items (they are applied by the seed loader off the + * bundle), so the only reader of the handed-back dataset is a seed load, and + * every seed load refuses it alone with `SeedMode`'s prescription + * (`SeedLoaderService.loadStored`, and `loadDataset` beneath it). + * + * Only a RETIRED value is withheld. A mode that was never a seed mode, or any + * other malformed dataset, is still the parse's refusal, as before. + */ + +/** Where a seed collection sits in an artifact definition, as a key path. */ +type SeedCollectionPath = ReadonlyArray; + +export interface WithheldSeedDataset { + /** The path of the `data` collection the dataset was taken from. */ + readonly path: SeedCollectionPath; + readonly dataset: unknown; + readonly object: string; + readonly mode: string; + /** `SeedMode`'s own refusal of the mode: the prescription, never restated. */ + readonly prescription: string; +} + +const RETIRED = new Set(RETIRED_SEED_MODE_VALUES); + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Every container that can hold a seed `data` collection, by path. */ +function seedCollectionPaths(definition: Record): SeedCollectionPath[] { + const paths: SeedCollectionPath[] = [[], ['manifest']]; + const packages = definition.packages; + if (Array.isArray(packages)) { + packages.forEach((_body, index) => { + paths.push(['packages', index], ['packages', index, 'manifest']); + }); + } + return paths; +} + +function at(root: unknown, path: SeedCollectionPath): unknown { + let node: unknown = root; + for (const key of path) { + if (Array.isArray(node) && typeof key === 'number') node = node[key]; + else if (isRecord(node) && typeof key === 'string') node = node[key]; + else return undefined; + } + return node; +} + +/** + * The definition with every retired-mode seed dataset taken out of its `data` + * collection (the input is not mutated: each container on the way is copied), + * and the datasets taken out. With none, the definition is returned as is. + */ +export function withholdRetiredSeedModes(definition: unknown): { + definition: unknown; + withheld: WithheldSeedDataset[]; +} { + if (!isRecord(definition)) return { definition, withheld: [] }; + const withheld: WithheldSeedDataset[] = []; + let copy: Record | undefined; + + for (const path of seedCollectionPaths(definition)) { + const container = at(copy ?? definition, path); + if (!isRecord(container) || !Array.isArray(container.data)) continue; + const kept: unknown[] = []; + const taken: WithheldSeedDataset[] = []; + for (const dataset of container.data) { + const mode = isRecord(dataset) ? dataset.mode : undefined; + if (typeof mode === 'string' && RETIRED.has(mode)) { + const verdict = SeedMode.safeParse(mode); + taken.push({ + path, + dataset, + object: String((dataset as Record).object ?? '(unnamed)'), + mode, + prescription: verdict.success ? '' : verdict.error.issues[0]?.message ?? '', + }); + } else { + kept.push(dataset); + } + } + if (taken.length === 0) continue; + withheld.push(...taken); + // Copy the containers along the path, then replace the collection. + copy ??= { ...definition }; + let parent: Record | unknown[] = copy; + for (const key of path) { + const child: unknown = (parent as Record)[key as never]; + const cloned: Record | unknown[] = Array.isArray(child) ? [...child] : { ...(child as Record) }; + (parent as Record)[key as never] = cloned; + parent = cloned; + } + (parent as Record).data = kept; + } + return { definition: copy ?? definition, withheld }; +} + +/** + * Hand the withheld datasets back to the collection each came from in the + * PARSED definition, after its own datasets, so a seed load that reads the + * parsed definition (the dev hot reload reads the top-level `data`) still meets + * them and refuses them. Mutates `parsed`, which the caller owns. + */ +export function restoreWithheldSeedDatasets(parsed: unknown, withheld: readonly WithheldSeedDataset[]): void { + for (const entry of withheld) { + const container = at(parsed, entry.path); + if (!isRecord(container)) continue; + container.data = [...(Array.isArray(container.data) ? container.data : []), entry.dataset]; + } +} diff --git a/packages/metadata/src/plugin.ts b/packages/metadata/src/plugin.ts index c42d084bd1e..85eedd30463 100644 --- a/packages/metadata/src/plugin.ts +++ b/packages/metadata/src/plugin.ts @@ -14,6 +14,7 @@ import { Plugin, PluginContext } from '@objectstack/core'; import { resolveArtifactPackageOrder, artifactPackageId } from '@objectstack/core'; import { NodeMetadataManager } from './node-metadata-manager.js'; import { MemoryLoader } from './loaders/memory-loader.js'; +import { restoreWithheldSeedDatasets, withholdRetiredSeedModes, type WithheldSeedDataset } from './artifact-retired-seed-modes.js'; import { PACKAGE_SLOTTED_STORE_TYPES, bundleEntryKey, isBundledStoreType, storedItemPackageId } from './package-slotted-store.js'; import { DEFAULT_METADATA_TYPE_REGISTRY, judgeCollectionItemOwnerStamp, OWNER_STAMP_JUDGED_COLLECTIONS } from '@objectstack/spec/kernel'; import type { MetadataPluginConfig } from '@objectstack/spec/kernel'; @@ -1380,22 +1381,33 @@ export class MetadataPlugin implements Plugin { let metadata: Record; + // [#34613] A seed dataset declaring a retired mode is taken out before + // the strict parse and handed back after it, so the seed load refuses + // that dataset alone instead of this parse refusing the whole artifact + // (see `artifact-retired-seed-modes.ts`). + let withheld: WithheldSeedDataset[] = []; + const prepare = (definition: unknown): unknown => { + const split = withholdRetiredSeedModes(this._convertArtifactForward(ctx, definition, label)); + withheld = split.withheld; + return split.definition; + }; + const obj = raw as any; if (obj?.schemaVersion && obj?.commitId && obj?.metadata !== undefined) { const artifact = EnvironmentArtifactSchema.parse({ ...obj, - metadata: this._convertArtifactForward(ctx, obj.metadata, label), + metadata: prepare(obj.metadata), }); metadata = artifact.metadata as Record; } else if (obj?.success && obj?.data?.metadata) { // Unwrap cloud API envelope: { success: true, data: { metadata: {...} } } const artifact = EnvironmentArtifactSchema.parse({ ...obj.data, - metadata: this._convertArtifactForward(ctx, obj.data.metadata, label), + metadata: prepare(obj.data.metadata), }); metadata = artifact.metadata as Record; } else { - const def = ObjectStackDefinitionSchema.parse(this._convertArtifactForward(ctx, obj, label)); + const def = ObjectStackDefinitionSchema.parse(prepare(obj)); const canonical = JSON.stringify(def, Object.keys(def).sort()); const checksum = createHash('sha256').update(canonical).digest('hex'); const environmentId = this.options.environmentId ?? 'env_local'; @@ -1409,6 +1421,18 @@ export class MetadataPlugin implements Plugin { metadata = def as Record; } + if (withheld.length > 0) { + restoreWithheldSeedDatasets(metadata, withheld); + for (const entry of withheld) { + ctx.logger.warn( + `[MetadataPlugin] artifact '${label}': the seed dataset for '${entry.object}' declares the retired ` + + `mode '${entry.mode}'. Everything else in the artifact loads; the seed load refuses that dataset ` + + `and writes none of it. ${entry.prescription} Rebuild the artifact after the fix.`, + { object: entry.object, mode: entry.mode }, + ); + } + } + this.lastParsedMetadata = metadata; const memLoader = new MemoryLoader(); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index b8fe3a113b2..ed42c4bc071 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -1959,8 +1959,8 @@ export class AppPlugin implements Plugin { // just contributed and every dataset lands twice. `mergeSeedDatasets` // is a plain `push` with no de-duplication, so both copies reach the // shared registry, the inline loader and every later per-org replay: - // for a `mode: 'insert'` dataset that is the row applied twice per - // boot, not merely doubled work. + // for a dataset whose key matches no row yet, that is the row applied + // twice per boot, not merely doubled work. const manifest = this.bundle.manifest || this.bundle; if (manifest && Array.isArray(manifest.data) && manifest.data !== this.collections.data) { seedDatasets.push(...manifest.data); diff --git a/packages/runtime/src/seed-loader.test.ts b/packages/runtime/src/seed-loader.test.ts index 9ac48b7fd81..8ee4ceab9d3 100644 --- a/packages/runtime/src/seed-loader.test.ts +++ b/packages/runtime/src/seed-loader.test.ts @@ -1194,7 +1194,7 @@ describe('SeedLoaderService', () => { }); expect(result.success).toBe(true); - // One record, mode 'insert' ⇒ exactly ONE engine write. Seed application is + // One record ⇒ exactly ONE engine write. Seed application is // the very path where a doubled collect writes twice and stays green under // `toHaveBeenCalledWith` (#15607). expect(engine.insert).toHaveBeenCalledTimes(1); diff --git a/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts b/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts new file mode 100644 index 00000000000..700da3be77d --- /dev/null +++ b/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34613] A compiled artifact built before the seed modes `insert` and +// `replace` were retired still boots, and only that dataset is refused. +// +// The composition is the one `os serve` / `os start` / `os dev` boot +// (`createStandaloneStack`): the artifact door (`MetadataPlugin`), which +// strict-parses the definition, and the `AppPlugin` that seeds from the same +// bytes. `SeedSchema.mode` refuses both retired values, so before the door +// withheld such a dataset from its parse, one stale seed dataset aborted the +// whole boot: no object registered, no other dataset loaded (L2 review M1 on +// PR #34791). Ruling 6942780880 item 2 asks for the opposite, and this file +// drives the real boot to the seeder: +// +// - the artifact's object registers and its keyed dataset lands, once; +// - the retired dataset writes nothing, with `insert` and with `replace`; +// - CONTROL: a mode that was never a seed mode is still the door's parse +// refusal, for the whole boot, exactly as before. + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ObjectQL } from '@objectstack/objectql'; +import { Runtime } from './runtime.js'; +import { createStandaloneStack } from './standalone-stack.js'; + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; +import '@objectstack/objectql'; +import '@objectstack/service-datasource'; + +const BOOT_TIMEOUT = 90_000; +const SYSTEM = { context: { isSystem: true } } as const; + +const artifact = (staleMode: string) => ({ + manifest: { id: 'com.test.retired-seed-mode', name: 'retired_seed_mode', type: 'app', version: '1.0.0', namespace: 'rsm' }, + objects: [ + { name: 'rsm_region', label: 'Region', tenancy: { enabled: false }, fields: { name: { type: 'text', label: 'Name' } } }, + { name: 'rsm_source', label: 'Source', tenancy: { enabled: false }, fields: { name: { type: 'text', label: 'Name' } } }, + ], + data: [ + { object: 'rsm_region', externalId: 'name', records: [{ name: 'emea' }, { name: 'apac' }] }, + { object: 'rsm_source', mode: staleMode, records: [{ name: 'web' }] }, + ], +}); + +describe('#34613 — a compiled artifact carrying a retired seed mode boots; only that dataset is refused', () => { + const dirs: string[] = []; + const kernels: any[] = []; + + afterEach(async () => { + for (const k of kernels.splice(0)) { + try { await k.shutdown(); } catch { /* noop */ } + } + for (const d of dirs.splice(0)) { + try { rmSync(d, { recursive: true, force: true }); } catch { /* noop */ } + } + }); + + async function bootOverArtifact(staleMode: string) { + const dir = mkdtempSync(join(tmpdir(), 'os-retired-seed-mode-')); + dirs.push(dir); + const artifactPath = join(dir, 'objectstack.json'); + writeFileSync(artifactPath, JSON.stringify(artifact(staleMode)), 'utf-8'); + const stack = await createStandaloneStack({ + artifactPath, + projectRoot: dir, + databaseUrl: ':memory:', + runPlatformMigrations: false, + }); + const runtime = new Runtime({ cluster: false }); + const kernel = runtime.getKernel(); + kernels.push(kernel); + for (const p of stack.plugins) await kernel.use(p as any); + await kernel.bootstrap(); + return kernel; + } + + it.each([['insert'], ['replace']])('`%s`: the boot completes, the object registers, the keyed dataset lands, the stale one writes nothing', async (staleMode) => { + const kernel = await bootOverArtifact(staleMode); + const ql = kernel.getService('objectql'); + + expect(ql.registry.getObject('rsm_source'), 'the object of the refused dataset still registers').toBeDefined(); + const regions = await ql.find('rsm_region', { where: {}, ...SYSTEM } as never); + expect((regions as Array<{ name: string }>).map((r) => r.name).sort()).toEqual(['apac', 'emea']); + expect(await ql.find('rsm_source', { where: {}, ...SYSTEM } as never)).toEqual([]); + }, BOOT_TIMEOUT); + + it('CONTROL: a mode that was never a seed mode is still the artifact door’s parse refusal', async () => { + await expect(bootOverArtifact('merge')).rejects.toThrow(/mode/); + }, BOOT_TIMEOUT); +}); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 3b54be1ad3f..9770d320ca6 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -670,6 +670,7 @@ "REFERENCE_VALUE_TYPES (const)", "RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS (const)", + "RETIRED_SEED_MODE_VALUES (const)", "RETIRED_SUB_DAY_INTERVALS (const)", "RLS_DENY_FILTER (const)", "ROUTE_SHADOWED_DATASOURCE_NAMES (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 62b3c71f639..cda828eb638 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -659,6 +659,7 @@ "REFERENCE_VALUE_TYPES": "src/data/field-value.zod.ts#REFERENCE_VALUE_TYPES (const)", "RETIRED_DRIVER_ID_GUIDANCE": "src/data/driver/config-registry.zod.ts#RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS": "src/data/filter.zod.ts#RETIRED_FILTER_OPERATORS (const)", + "RETIRED_SEED_MODE_VALUES": "src/data/seed.zod.ts#RETIRED_SEED_MODE_VALUES (const)", "RETIRED_SUB_DAY_INTERVALS": "src/data/analytics.zod.ts#RETIRED_SUB_DAY_INTERVALS (const)", "RLS_DENY_FILTER": "src/data/readable-ids.ts#RLS_DENY_FILTER (const)", "ROUTE_SHADOWED_DATASOURCE_NAMES": "src/data/datasource.zod.ts#ROUTE_SHADOWED_DATASOURCE_NAMES (const)", diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index bab224d383f..12f2237dd2e 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -28,7 +28,8 @@ import { const SEED_MODE_RETIRED_FIX = 'Declare the rows\' identity instead: keep the default `mode: \'ignore\'` (or `\'upsert\'`) and set ' + '`externalId` to the field that names a row, to a list of fields when no single field does (a junction ' - + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids.'; + + 'table\'s `[\'team\', \'project\']`, listing only fields every load can fill), or to `\'id\'` when the ' + + 'records carry their own ids.'; /** * The parse refusals an author meets for the two unkeyed modes (ADR-0049 @@ -52,11 +53,26 @@ const SEED_MODE_REPLACE_RETIRED = + 'every record and left clearing the table to the caller, and no load ever clears one, so every replay ' + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; -export const SeedMode = enumWithRetiredValues([ +/** The live seed modes, in the order the reference documents them. */ +const SEED_MODE_VALUES = [ 'update', // Only update found records, ignore new 'upsert', // Create new or update existing: every replay writes the declared columns back - 'ignore' // Create-only (the default): insert missing rows, leave existing rows alone -], { insert: SEED_MODE_INSERT_RETIRED, replace: SEED_MODE_REPLACE_RETIRED }); + 'ignore', // Create-only (the default): insert missing rows, leave existing rows alone +] as const; + +const SEED_MODE_RETIRED = { insert: SEED_MODE_INSERT_RETIRED, replace: SEED_MODE_REPLACE_RETIRED }; + +/** + * [#34613] The retired `SeedMode` values, for the doors that hold a STORED + * seed (a compiled artifact, an installed package body, a stored seed item): + * such a door hands a dataset declaring one to the seed load, which refuses + * that dataset alone with `SeedMode`'s own prescription, instead of failing + * every other dataset and definition with it. Membership only: the + * prescription is always read from `SeedMode`, never restated. + */ +export const RETIRED_SEED_MODE_VALUES: readonly string[] = Object.freeze(Object.keys(SEED_MODE_RETIRED)); + +export const SeedMode = enumWithRetiredValues(SEED_MODE_VALUES, SEED_MODE_RETIRED); /** * Seed Column — the write policy a seed dataset declares for one of its diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts index 27359230f90..f7c7eb663df 100644 --- a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts +++ b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts @@ -15,7 +15,8 @@ export const entry: SemanticMigration = { replacement: 'Keep the default `mode: \'ignore\'` (or declare `\'upsert\'` for reference data the package keeps current) and ' + 'set `externalId` to the field that names a row, to a list of fields when no single field does (a junction ' - + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids', + + 'table\'s `[\'team\', \'project\']`; list only fields every load can fill, since a reference the first ' + + 'load leaves empty makes each later load miss that row), or to `\'id\'` when the records carry their own ids', reason: 'A seed is replayed, not applied once: on every single-tenant boot, every package install or upgrade, every ' + 'publish. `insert` matched no existing row, so every replay inserted each record again, and `replace` did the ' @@ -23,9 +24,11 @@ export const entry: SemanticMigration = { + 'install over three boots: 1, then 2, then 3 rows; a person reference the first load had to leave NULL stayed ' + 'NULL on the first row while only the newest copy named the person; with a unique field the replay insert was ' + 'refused and the one row stayed NULL. Both values are now refused where a seed is parsed, with the ' - + 'prescription. A dataset already stored with either value is refused loudly by the loads that replay stored ' - + 'seeds (the boot seed, the per-organization replay, the dev hot reload, a package install or upgrade): that ' - + 'dataset writes nothing, the load result fails with its prescription and the boot log names it, and every other dataset loads. There is no ' + + 'prescription. A dataset already stored with either value (a compiled artifact, an installed package body, a ' + + 'stored seed item) is refused loudly by the seed load itself (the boot seed, the per-organization replay, the ' + + 'dev hot reload, a package install or upgrade; the artifact door parses the rest of an artifact without it, so ' + + 'the environment still boots): that dataset writes nothing, the load result fails with its prescription and ' + + 'the boot log names it, and every other dataset loads. There is no ' + 'mechanical rewrite, because a keyed mode needs the field that identifies a row, and only the author knows it. ' + 'Rows earlier replays duplicated are data, not metadata, and are left as they are', acceptanceCriteria: diff --git a/scripts/check-skill-identifier-liveness.mjs b/scripts/check-skill-identifier-liveness.mjs index 746cd36ad3b..ad5315e1204 100644 --- a/scripts/check-skill-identifier-liveness.mjs +++ b/scripts/check-skill-identifier-liveness.mjs @@ -367,7 +367,9 @@ const BINDINGS = [ id: 'seed-modes', file: 'skills/objectstack-platform/SKILL.md', heading: '## Seed Data', - symbol: 'SeedMode', + // [#34613] `SeedMode` is an `enumWithRetiredValues` call this gate does not + // read whole; its live members are the `SEED_MODE_VALUES` array it wraps. + symbol: 'SEED_MODE_VALUES', source: 'packages/spec/src/data/seed.zod.ts', why: 'The mode table is the only place an author learns what `mode` accepts.', }, diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index cd593c9c3ea..8b181b93a0b 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2641,6 +2641,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/seed-loader-retry.test.ts", "verb": "delete", From ef48f915c84c2351059d49b6187b4abb58df8c44 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:54:22 +0000 Subject: [PATCH 07/19] docs(references): regenerate from the merged tree (#34613) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQWxrh3KzUvuZWTy7H --- content/docs/references/api/protocol.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 6f8718cca32..c06740cdbd0 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -3004,7 +3004,7 @@ Answer to a device registration: the device id the client keeps | **actor** | `string` | optional | Identity recorded on the write's history event (`recorded_by`, a lookup into `sys_user`) and audit row. On the REST door this is the request's authenticated identity (one producer) — never a caller-supplied header. Absent, the event is recorded actor-less (null), deliberately not attributed to "system". | | **force** | `boolean` | optional | Destructive-change acknowledgement (`?force=true` on the REST door): skips the safety diff that refuses an `object` save whose body drops fields or narrows types the stored item still carries (409 with the findings otherwise). Only `object` saves reach that diff, so the flag is inert for every other type. Absent = the guard runs. | | **mode** | `Enum<'draft' \| 'publish'>` | optional | Per-item lifecycle (ADR-0005 drafts): `draft` stages the body as a pending draft overlay (`?mode=draft` on the REST door; the publish door promotes it later); `publish` or ABSENT writes straight to the live `active` row — the legacy default, kept so callers that predate the draft/publish split keep working. Any value other than `draft` is read as `publish`. | -| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | +| **packageId** | `string \| null` | optional | ADR-0048 — the software package to bind the saved row to (`sys_metadata.package_id`; `?package=` on the REST door, where `all` and an empty value name no package). Set when authoring inside a Studio package workspace; a named read-only base package is refused. On create the row is stamped with this id; on update an existing binding is preserved, never silently re-bound. Absent or `null` names no package. An `active` save then writes the row of the one package the item's active rows are bound to, as a save naming that package does, is refused `409 RESOURCE_CONFLICT` when they are bound to two or more, and with none writes the env-local overlay (no package stamp); a `draft` save writes the draft of the one package the item's active rows are bound to (a pending change stays in the package it edits), else its package-unbound draft, adopted into that package — the draft the per-item publish naming no package promotes. For an item never published into a package it is the package-unbound draft, else the one package's draft, and with no draft at all the save creates the package-unbound draft. It is refused `409 RESOURCE_CONFLICT` when the active rows (or, with none and no package-unbound draft, the drafts) are bound to two or more packages, as that publish is (see `PublishMetaItemRequestSchema.packageId`). An `action` is keyed by the object it binds (ADR-0150 D4): when one or more packages' active rows hold the name and none of those rows binds the object the body binds (object-less is its own key), the save writes the environment's own package-unbound row (`active`) or draft (`draft`), never a package's item. The environment keeps one package-unbound row and one package-unbound draft per action name: such a save over the environment's own row or draft bound to another object rewrites it onto the body's object, and over one bound to an object a package's active row binds (that package's customization) it is refused `409 RESOURCE_CONFLICT`; a `draft` save is refused the same way when the package-unbound row its publish would rewrite is that customization. Otherwise the address above stands, judged over every holder of the name (every enabled holder, for an `active` save), except that an `active` save is judged over the holders at the body's object only when a disabled package is one of them and another holder binds another object. The per-item publish and the draft discard naming no package act on the environment's draft so written, except that with one package holding the name, that package's own draft, when one is stored, comes first; that publish is refused `409 RESOURCE_CONFLICT` when the package-unbound row it would rewrite is a package's customization. Until the read naming no package keys an action by object, the version it serves is the package's item's, so a save carrying it as the parent is refused as a version conflict. The row written is also the one the parent-version resolution reads: an unpinned save takes its version as the parent (last-write-wins), a pinned one is judged against it, and the item read at the same scope serves it as `version`. | | **writeFace** | `Enum<'package-duplicate' \| 'meta-envelope' \| 'meta-dispatch' \| 'external-import'>` | optional | Which write door a refusal is being rendered FOR — stated by the SERVER, never by a remote caller: every door builds this request field by field and never spreads a request body into it, so there is no path for a client to smuggle a face in, and a face arriving in a wire body is simply never read. Two refusals branch on it, for different questions: the 409 destructive-change remedy names the acknowledgement mechanism that actually exists on the refusing door (`?force=true` on the REST doors; the dispatcher, the duplicate-package door and the external-table import have none), and the 422 invalid-metadata message adapts to whether a structured `issues[]` channel reaches the consumer beside it. Absent = the conservative default wording. | | **surface** | `Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>` | optional | The authoring surface this save is made through (see `MetadataAuthoringSurfaceSchema`). A draft save (`mode: 'draft'`) stamps it as `by` on every key path it changes, the entries the strict draft read serves as `draftChanges`; an active save records no per-key provenance. ABSENT stamps `api`. On the REST door and the runtime dispatcher it is the `?surface=` query parameter, which takes `studio` or `api` and refuses every other value `400 VALIDATION_ERROR`, `copilot` and `mcp` included: `copilot` is stated only by an in-process AI tool calling the save and `mcp` only by the MCP build door after it verified the client's token, never by a remote caller, so an HTTP request cannot mark its own write as the copilot's or an MCP agent's. A value outside the set in-process is refused `400 INVALID_REQUEST`, before anything is written. | | **client** | `{ id: string; name?: string }` | optional | The OAuth client this save is made by (see `MetadataAuthoringClientSchema`), stated only by the MCP build door, in-process, from the token it verified. Only with `surface: 'mcp'`: a `client` beside any other surface, or a malformed one, is refused `400 INVALID_REQUEST` before anything is written. A draft save stamps it as `client` beside `by: 'mcp'` on every key path it changes; an active save records it nowhere. No HTTP door reads it: the REST door and the dispatcher build this request member by member, so a `client` in a wire body or query is never read. | From c6753173052d2d73d24fdc01fe0834985f74ee91 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:47:30 +0000 Subject: [PATCH 08/19] docs(references): regenerate protocol reference after main merge Regenerated content/docs/references/api/protocol.mdx from the merged tree (gen:migration-registry, gen:schema, gen:docs). The references now differ from main by exactly this branch's own seven pages. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- content/docs/references/api/protocol.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index c06740cdbd0..a73c61b15a9 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1504,6 +1504,7 @@ This schema accepts one of the following structures: | **member** | `string` | optional | Bundle member selector, for a metadata type whose identity is a pair (today only `email_template`, identified by `(name, locale)`): the member this request addresses, spelled as its discriminator value (`zh-CN`). Absent, the canonical member (`en-US` for `email_template`), which is what a bare-name read answers; naming the canonical value is the same request. It is not the response translation locale, which `?locale=` and `Accept-Language` choose. Refused with 400 `VALIDATION_ERROR` on a type that has no members, and for a blank value or one longer than a stored member can be (100 characters). A well-formed member with nothing stored or shipped answers as that door answers an absent item. | | **state** | `Enum<'active' \| 'draft'>` | optional | Draft-visibility switch — which lifecycle row to read (strict mode): `'draft'` opens the pending draft buffer (Studio's editor read) and fails when no draft exists; absent or `'active'` reads the live published row. Distinct from `previewDrafts`, which FALLS BACK to the active row when no draft exists. Declaration ≠ authorization: this member only selects which stored row is read — ADR-0106 masking is unaffected, and draft access is gated upstream, not by this schema. | | **previewDrafts** | `boolean` | optional | Draft-visibility switch (ADR-0033 draft-overlay preview, non-strict): when true and `state` is not `'draft'`, a pending draft row is preferred if one exists, else the read falls back to the active row — the render path degrades to the published value instead of erroring. A served draft is tagged `_draft: true` so UIs can badge it. Declaration ≠ authorization: this member only switches which row is read, and ADR-0106 masking is unaffected — draft preview is admin-gated upstream, not by this schema. | +| **userTextLocales** | `string[]` | optional | The locales the user-facing sentences of a served DRAFT's check findings are composed in, in ladder order: the locale the request names, then the workspace default — the save request's member of the same name, read the same way (each value against the platform locale table, whole and then one subtag shorter at a time; a value that names no table language is passed over; `en` is the last rung). Read only by the `state: 'draft'` read, which folds what publishing the draft would say into its `_diagnostics`: an advisory finding that carries a user sentence becomes a `_diagnostics.warnings[]` entry in that sentence. Stated by the door that holds the request (the REST door and the dispatcher state `[ExecutionContext.locale, ExecutionContext.workspaceLocale]`), never read from a query string. ABSENT ⇒ the sentences are composed in `en`. It selects a language only: which row is read, and what the verdict is, do not depend on it. | --- @@ -1711,7 +1712,7 @@ One changed key path of the pending draft, and the last write that changed it. | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Object name | | **permissions** | `{ allowCreate?: boolean; allowRead?: boolean; allowEdit?: boolean; allowDelete?: boolean; … }` | ✅ | Object-level permissions | -| **fieldPermissions** | `Record` | optional | Field-level permissions keyed by field name | +| **fieldPermissions** | `Record` | optional | Field-level permissions keyed by field name | ### Nested Shape: `GetObjectPermissionsResponse.permissions` @@ -1739,6 +1740,7 @@ One changed key path of the pending draft, and the last write that changed it. | **readable** | `boolean` | optional (default: `true`) | Field read access | | **editable** | `boolean` | optional (default: `false`) | Field edit access | | **when** | `string` | optional | Row condition narrowing where this entry votes, authored in canonical CEL like `rowLevelSecurity[].using` (a field of this object compared with a literal or a `current_user.*` value using `==`, `!=`, `<`, `<=`, `>`, `>=` or `in`, combined with `&&` / `\|\|`; e.g. status in ["approved", "signing", "active"]). Absent, the entry votes on every row. Present, the entry votes as declared on the rows the condition matches and is ABSENT on every other row, so the most-permissive merge across the caller's sets is unchanged: a set that locks a field only from a stage onward does not lock the rows before it, and a co-held set that says nothing about the field still lifts nothing, unless it holds the super-user bypass on the object (its own entry for the object, otherwise its `'*'` wildcard). Such a set votes on every field of the object, on every row, whatever `when` says: `viewAllRecords` votes `readable: true`, and `modifyAllRecords` votes `readable: true` and `editable: true`, so a row-conditioned lock never binds a Modify All holder. View All never grants an edit. Otherwise union without deny is unchanged. The write gate judges the condition on the stored row BEFORE an update (so a lock on `status in [...]` holds on an approved row even when the write changes `status`) and on the incoming row of an insert, as the caller sent it. It reaches the EDIT vote only — reads are judged row-blind — so `readable: false` beside a `when` is refused at parse time: keep `readable: true` (the default) on a row-conditioned entry. Where no row can be judged (a predicate update with no row address, a stored row the caller cannot read, a condition that does not resolve for the request) the entry is judged as its lock: it contributes no edit grant on that write. Validated like an RLS predicate at authoring and publish time: the fields it names must exist on the entry's object and it may not reach across a relation; a condition that cannot be lowered is refused there, never dropped at runtime. Readers that hold no row (`/auth/me/permissions`, the object-wide field projections, the write preview on an update) report a row-conditioned entry as its lock, so a client never advertises an edit the gate refuses. The record-scoped field projection (`GET /data/{object}/{id}/field-access`, the answer a record's edit form reads) holds the row: it judges the condition on the stored row exactly as the write gate does on an update of that row, so a lock that applies only from a stage onward disables the field only on the rows it names. | +| **rollupSourceUnreadableReason** | `string` | optional | Authoring-time acknowledgement, read only by `os lint` (the runtime does not read it): why holders of this set are meant to read this roll-up `summary` column although the set cannot read the child object, the aggregated child field or a child field the roll-up's `filter` tests (e.g. 'Service staff read account totals but not invoice rows'). Declared on the set's entry for the summary column, it turns that set's `security-rollup-source-unreadable` warning for the column into an `info` note quoting the reason, so `os lint --strict` passes; every other finding is unchanged. The runtime does not read the key, but the entry that carries it is an ordinary declaring entry: it votes `readable: true` in the field merge (only declaring sets vote, and the most permissive vote wins), so on a set that had no entry for the column, adding one to carry the reason restores the column for holders whose other sets mask it. A blank reason is refused, and so is a reason beside `readable: false`, an entry that declares no read to acknowledge. | --- From 09901d0ae23fca4455c5cc32ba978ffd20ebee27 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:56:44 +0000 Subject: [PATCH 09/19] docs(changeset): name follow-up #34798 and RETIRED_SEED_MODE_VALUES L1 S1: the Skills-docs line names the filed card instead of "follow-up owed". L1 N1 / seat N7: the changeset names the exported RETIRED_SEED_MODE_VALUES list. Changeset text only. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .changeset/34613-seed-mode-insert-replace-retired.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md index baa533406df..5f62575ea24 100644 --- a/.changeset/34613-seed-mode-insert-replace-retired.md +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -12,7 +12,7 @@ fix(spec,metadata-protocol)!: retire the seed modes `insert` and `replace`, whic Clause-②: no (narrowing) Metadata-protocol: narrowed -Skills-docs: follow-up owed — skills/objectstack-data/references/seeds.md, skills/objectstack-platform/SKILL.md +Skills-docs: follow-up #34798 @@ -20,7 +20,7 @@ Skills-docs: follow-up owed — skills/objectstack-data/references/seeds.md, ski What moves (each line FROM → TO): -- `SeedSchema.mode` / `SeedMode` (`@objectstack/spec/data`; `defineSeed`, `defineStack({ data })`, a `seed` metadata item, a package body's seed): FROM `insert` / `update` / `upsert` / `replace` / `ignore` TO `update` / `upsert` / `ignore` (default `ignore`, unchanged). `mode: 'insert'` or `mode: 'replace'` fails parse with a prescription naming the fix; the save and publish doors refuse it with the same message. +- `SeedSchema.mode` / `SeedMode` (`@objectstack/spec/data`; `defineSeed`, `defineStack({ data })`, a `seed` metadata item, a package body's seed): FROM `insert` / `update` / `upsert` / `replace` / `ignore` TO `update` / `upsert` / `ignore` (default `ignore`, unchanged). `mode: 'insert'` or `mode: 'replace'` fails parse with a prescription naming the fix; the save and publish doors refuse it with the same message. The retired pair is exported as `RETIRED_SEED_MODE_VALUES` (`@objectstack/spec/data`): it is derived from the parse refusal's own table, and the loader and the artifact door read it. - a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. `SeedLoaderService.load()` and `validate()` refuse the dataset the same way when handed one unparsed, so a dry run reports what a real load does. - a compiled artifact (`objectstack.json`) carrying such a dataset, booted by `os serve` / `os start` / `os dev` (the artifact door, `MetadataPlugin`, `@objectstack/metadata`): the door parses the artifact without that dataset and hands it back to the seed load, which refuses it alone; the door logs a warning naming the dataset and the fix. Everything else in the artifact registers and boots. - `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. From f596517c0cfa759935bad5092f825b53dd2eeff9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 18:39:42 +0000 Subject: [PATCH 10/19] docs(spec): drop the stale "fields every load can fill" advice for seed keys Seat S2: since #34854 a composite-key row whose reference the first load leaves empty is found again by its authored key and filled later, so the advice to key only on fields every load can fill is false. Dropped from the migration entry replacement and SEED_MODE_RETIRED_FIX; seed-data.mdx step 2 now says what the loader does. N12: the changeset states the rule count 70 to 69. Text only. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .changeset/34613-seed-mode-insert-replace-retired.md | 2 +- content/docs/data-modeling/seed-data.mdx | 8 ++++---- packages/spec/src/data/seed.zod.ts | 2 +- .../semantic/18.seed-mode-insert-replace-retired.ts | 3 +-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md index 5f62575ea24..4574f823f26 100644 --- a/.changeset/34613-seed-mode-insert-replace-retired.md +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -24,7 +24,7 @@ What moves (each line FROM → TO): - a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. `SeedLoaderService.load()` and `validate()` refuse the dataset the same way when handed one unparsed, so a dry run reports what a real load does. - a compiled artifact (`objectstack.json`) carrying such a dataset, booted by `os serve` / `os start` / `os dev` (the artifact door, `MetadataPlugin`, `@objectstack/metadata`): the door parses the artifact without that dataset and hands it back to the seed load, which refuses it alone; the door logs a warning naming the dataset and the fix. Everything else in the artifact registers and boots. - `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. -- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. +- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. The author-time rule count `os validate` / `os build` print goes from 70 to 69. - the save door's and the loader's hint for a key no record carries: FROM "or use mode 'insert' for rows with no natural key" TO a list of fields when no single field names a row, or `'id'` when the records carry their own ids. The fix: declare which field identifies a row and drop the mode (or declare `upsert` for reference data the package keeps current). Set `externalId` to the field that names a row, to a list of fields when no single field does (a junction table's `['team', 'project']`), or to `'id'` when the records carry their own ids. Rebuild the package, and reinstall it where it was installed with `os package install`, so the stored body carries the new declaration. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index e8fcb9d4f03..7a736363e0f 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -156,10 +156,10 @@ To convert a dataset, declare which field identifies a row, then drop the mode 1. **A field names the row** (a code, a slug, an email): set `externalId` to it. 2. **No single field does** (a join table, a line item under a parent): set `externalId` to the list of fields that together identify a row, for example - `['team', 'project']`. Reference fields are matched by their resolved ids, so - list only fields every load can fill: a reference the first load has to leave - empty (a person who has not signed up yet) makes each later load miss that row - and insert another. See + `['team', 'project']`. Reference fields are matched by their resolved ids. A + reference the first load has to leave empty (a person who has not signed up + yet) still belongs in the key: each later load finds that row again by the + key as authored, and the load that can resolve the person fills it in. See [Composite natural key](#composite-externalid--join--junction-tables). 3. **The records carry their own ids**: set `externalId: 'id'`. diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index 12f2237dd2e..81410539784 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -28,7 +28,7 @@ import { const SEED_MODE_RETIRED_FIX = 'Declare the rows\' identity instead: keep the default `mode: \'ignore\'` (or `\'upsert\'`) and set ' + '`externalId` to the field that names a row, to a list of fields when no single field does (a junction ' - + 'table\'s `[\'team\', \'project\']`, listing only fields every load can fill), or to `\'id\'` when the ' + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the ' + 'records carry their own ids.'; /** diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts index f7c7eb663df..cb0852a104b 100644 --- a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts +++ b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts @@ -15,8 +15,7 @@ export const entry: SemanticMigration = { replacement: 'Keep the default `mode: \'ignore\'` (or declare `\'upsert\'` for reference data the package keeps current) and ' + 'set `externalId` to the field that names a row, to a list of fields when no single field does (a junction ' - + 'table\'s `[\'team\', \'project\']`; list only fields every load can fill, since a reference the first ' - + 'load leaves empty makes each later load miss that row), or to `\'id\'` when the records carry their own ids', + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids', reason: 'A seed is replayed, not applied once: on every single-tenant boot, every package install or upgrade, every ' + 'publish. `insert` matched no existing row, so every replay inserted each record again, and `replace` did the ' From 4932db391b27e71354fe031fd7d3c927c99d9c29 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:55:28 +0000 Subject: [PATCH 11/19] test(dogfood): the insert-seed control now expects the mode retirement refusal The battery on f596517c found one red: the #28952 dogfood control saved an insert-mode seed and expected 200. This PR retires insert, so the save door now refuses it with 422 for its mode; the control pins that the refusal names the retired mode and never reaches the externalId key judgment. Forced test edit; the comment header follows. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .../test/seed-external-id-refusal.dogfood.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts b/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts index 809d2c792fc..34198df0ed6 100644 --- a/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts @@ -22,7 +22,8 @@ // nothing is stored, so `publish-drafts` has nothing of it to publish. // Controls: the same seed keyed on `name` saves, publishes and converges on // replay (`inserted: 1`, then `inserted: 0, updated: 0`, one row served); an -// `insert` seed is not judged. The publish door's refusal of a draft stored +// `insert` seed, a mode #34613 retired, is refused for its mode and never +// reaches the key judgment. The publish door's refusal of a draft stored // before this rule, and of a seed whose object is drafted in the same batch, // is pinned in-process // (`packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts`): @@ -114,8 +115,11 @@ describe('dogfood: a seed whose externalId names no field of its object is refus expect(JSON.stringify(listed.json).match(/"G1"/g) ?? []).toHaveLength(1); }); - it('control: an `insert` seed never matches by its key, so it is not judged', async () => { + it('control: an `insert` seed is refused for its retired mode, not judged on its key (#34613)', async () => { const saved = await call('PUT', `/meta/seed/r_insert?mode=draft&package=${PKG}`, seed('no_such_field', 'insert')); - expect(saved.status, JSON.stringify(saved.json)).toBe(200); + expect(saved.status, JSON.stringify(saved.json)).toBe(422); + const wire = JSON.stringify(saved.json); + expect(wire).toContain("`seed.mode: 'insert'` was removed"); + expect(wire).not.toContain('which is not a field of object'); }); }); From b398503c7d2ee6492d4c503e60badb7b911991d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:50:13 +0000 Subject: [PATCH 12/19] chore(spec): regenerate protocol reference, api-surface and export-origins over the main merge Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- content/docs/references/api/protocol.mdx | 3 ++- packages/spec/api-surface/data.json | 6 ++++++ packages/spec/export-origins/data.json | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index a73c61b15a9..c7948c4b01c 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1531,7 +1531,7 @@ This schema accepts one of the following structures: | **resettable** | `boolean` | optional | Whether the item can be reset to its packaged default — true iff it is artifact-backed, i.e. there is a baseline to reset TO. | | **version** | `string \| null` | optional | ADR-0008 version token of the STORED row a save to this item compares against, at this read's scope (the environment's partition and `?package=`) and lifecycle (`?state=draft` reads the draft row, the plain read the active row). The same keyed token a save receipt's `version` serves for that row: send it back as the `If-Match` request header on `PUT /meta/:type/:name` (with `?mode=draft` for the draft) and a concurrent edit is refused 409 `METADATA_CONFLICT` instead of overwritten. `null` when no stored row is there — an item served from code or a package artifact, or from a row in another scope (a package-less row a package read falls back to) — so the next save creates one: pin it with `If-None-Match: *`. A `null` beside `editable: false` is no such invitation: that item takes no save at this address, so no pin is prescribed for it. ABSENT on the cached published-value branch and on a `?preview=draft` read, which publish no version: absence means "not published here", never "no row". Opaque — echo it verbatim, never parse it. | | **registration** | `{ state: 'registered' } \| { state: 'refused'; reason: object } \| { state: 'unregistered' }` | optional | The automation engine's verdict on this flow (see `FlowRegistrationSchema`): `registered`, or `refused` with the engine's `reason` verbatim, or `unregistered`. Present only on a `flow` read answered by a process that runs an automation service; absent otherwise, and absence means no engine judged it, never `registered`. Unlike the protection keys it is published by the cached branch too, read live and never part of the ETag, so a cached read that carries it is never answered 304; it is absent on a draft read, whose pending body no engine holds. The verdict is the answering process's engine. Beside `item`, never inside it: the item's `status` stays what its author declared. | -| **disabledActions** | `string[]` | optional | The names in `item.actions` that this deployment's activation ledger switches off (an administrator turned them off under Setup › Packaged Actions): a call to any of them is refused 409 `ACTION_DISABLED`. Present only on an `object` read answered by a process whose data engine has an activation ledger attached, and then `[]` when none of this object's actions is switched off. Absent otherwise, and absence means no ledger answered, never that nothing is switched off. Unlike the protection keys it is published by the cached branch too, read live and folded into the ETag, so a cached read revalidates to 304 only while the switched-off set is unchanged; it is absent on a draft read. The ledger is the answering process's engine's. Beside `item`, never inside it: `item.actions` is served as declared, a switched-off action included. | +| **disabledActions** | `string[]` | optional | The names in `item.actions` that this deployment's activation ledger switches off (an administrator turned them off through the activation door, for example on the action in Studio): a call to any of them is refused 409 `ACTION_DISABLED`. Present only on an `object` read answered by a process whose data engine has an activation ledger attached, and then `[]` when none of this object's actions is switched off. Absent otherwise, and absence means no ledger answered, never that nothing is switched off. Unlike the protection keys it is published by the cached branch too, read live and folded into the ETag, so a cached read revalidates to 304 only while the switched-off set is unchanged; it is absent on a draft read. The ledger is the answering process's engine's. Beside `item`, never inside it: `item.actions` is served as declared, a switched-off action included. | | **cascadeDeleteObjects** | `string[]` | optional | The objects, by name, that deleting a record of this object can also delete: every object whose relation into it cascades (a `master_detail` by default, a `lookup`, `tree` or `user` field that declares `deleteBehavior: 'cascade'`), and the objects that cascade into those in turn, each once, in the order the delete reaches them. This object itself is named only when a cascading relation leads back to it. A `restrict` or `set_null` relation removes nothing and is not named. Read from the rule the delete runs, and object-level: it never says which records or how many. Present only on an `object` read answered by a process whose data engine answers it, and then `[]` when nothing cascades. Absent otherwise, and absence means no engine answered, never that nothing cascades. Unlike the protection keys it is published by the cached branch too, read live and folded into the ETag; it is absent on a draft read. Beside `item`, never inside it: it is derived from other objects' definitions and is not authorable. | | **draftChanges** | `{ path: string[]; by: Enum<'copilot' \| 'mcp' \| 'studio' \| 'api'>; actor: string \| null; client?: object; … }[]` | optional | Per-key provenance of the pending draft: which authoring surface last changed each key path of `item`, under which actor, and when. The draft save records it: each draft save is compared with the body that save replaced (the previous draft, or the stored published row for the draft's first save; a draft of an item with no stored published row is recorded as `[]`, the whole body). A `migrate-stored` rewrite of a draft row records nothing, since it is not authoring. The entries are kept from the first recorded save until the draft is published or discarded, which remove the draft row and the entries with it; and no two entries share a path: a save replaces every entry at or under each path it changes, so the last write to change a key is the entry whose `path` is the longest prefix of that key's path, and entries under a key's path are changes inside it. The entries name which writes changed what; they are not a list of every difference from the published body (compare the two bodies for that). Served only on a `?state=draft` read that answers a stored draft row. ABSENT on the active read, the cached branch and a `?preview=draft` read, and for a draft row whose saves recorded none: absence means "not recorded", never "no changes". | @@ -1882,6 +1882,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | +| **mappings** | `Record` | optional | Import-mapping translations keyed by mapping name | | **settingsCommon** | `{ sourceLabels?: object }` | optional | Cross-namespace Settings UI strings | | **settings** | `Record; keys?: Record; … }>` | optional | Settings manifest translations keyed by namespace | diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 9770d320ca6..3e37980bceb 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -4,6 +4,7 @@ "exports": [ "ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", + "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES (const)", "AGGREGATION_ROWS (const)", @@ -912,6 +913,7 @@ "ValueRoundTripColumn (type)", "ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase (interface)", + "actionRefusalsWithoutSandboxedBody (function)", "aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason (function)", @@ -1121,6 +1123,10 @@ "summaryFunctionReadsField (function)", "textComparandRefusalReason (function)", "textOperatorDoorVerdict (function)", + "undeclaredActionRefusalAtRun (function)", + "undeclaredActionRefusalCodeAtSave (function)", + "undeclaredActionRefusalReasonAtRun (function)", + "undeclaredActionRefusalReasonAtSave (function)", "undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index cda828eb638..6534a63ccdb 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -4,6 +4,7 @@ "exports": { "ACCEPTED_FILTER_COMPARAND_TYPES": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES (const)", "ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE": "src/data/filter-comparand-type.ts#ACCEPTED_FILTER_COMPARAND_TYPES_SENTENCE (const)", + "ACTION_REFUSAL_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#ACTION_REFUSAL_MESSAGE_HOLE_REFUSED (const)", "AGGREGATE_FIELD_TYPE_COMPATIBILITY": "src/data/aggregate-field-type-compatibility.ts#AGGREGATE_FIELD_TYPE_COMPATIBILITY (const)", "AGGREGATION_CASES": "src/data/aggregation-conformance.ts#AGGREGATION_CASES (const)", "AGGREGATION_ROWS": "src/data/aggregation-conformance.ts#AGGREGATION_ROWS (const)", @@ -898,6 +899,7 @@ "ValueRoundTripColumn": "src/data/value-roundtrip-conformance.ts#ValueRoundTripColumn (type)", "ValueShapeFieldDef": "src/data/field-value.zod.ts#ValueShapeFieldDef (interface)", "ZeroLimitConformanceCase": "src/data/pagination-conformance.ts#ZeroLimitConformanceCase (interface)", + "actionRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#actionRefusalsWithoutSandboxedBody (function)", "aiReadExposureRefusal": "src/data/ai-read-exposure.ts#aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage": "src/data/analytics.zod.ts#analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason": "src/data/api-derivation.ts#apiExposureDenialReason (function)", @@ -1107,6 +1109,10 @@ "summaryFunctionReadsField": "src/data/field.zod.ts#summaryFunctionReadsField (function)", "textComparandRefusalReason": "src/data/filter-text-comparand.ts#textComparandRefusalReason (function)", "textOperatorDoorVerdict": "src/data/filter-text-operator-declared-type.ts#textOperatorDoorVerdict (function)", + "undeclaredActionRefusalAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalAtRun (function)", + "undeclaredActionRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalCodeAtSave (function)", + "undeclaredActionRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtRun (function)", + "undeclaredActionRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredActionRefusalReasonAtSave (function)", "undeclaredHookRefusalAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalAtRun (function)", "undeclaredHookRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtRun (function)", From b5e8fd0f4520e068db972e901ce905055b41ce72 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:51:02 +0000 Subject: [PATCH 13/19] chore(changeset): the rule-count line drops by one, 71 to 70 at this release Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .changeset/34613-seed-mode-insert-replace-retired.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md index 4574f823f26..cbc2872ef90 100644 --- a/.changeset/34613-seed-mode-insert-replace-retired.md +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -24,7 +24,7 @@ What moves (each line FROM → TO): - a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. `SeedLoaderService.load()` and `validate()` refuse the dataset the same way when handed one unparsed, so a dry run reports what a real load does. - a compiled artifact (`objectstack.json`) carrying such a dataset, booted by `os serve` / `os start` / `os dev` (the artifact door, `MetadataPlugin`, `@objectstack/metadata`): the door parses the artifact without that dataset and hands it back to the seed load, which refuses it alone; the door logs a warning naming the dataset and the fix. Everything else in the artifact registers and boots. - `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. -- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. The author-time rule count `os validate` / `os build` print goes from 70 to 69. +- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. The author-time rule count `os validate` / `os build` print drops by one (71 to 70 at this release). - the save door's and the loader's hint for a key no record carries: FROM "or use mode 'insert' for rows with no natural key" TO a list of fields when no single field names a row, or `'id'` when the records carry their own ids. The fix: declare which field identifies a row and drop the mode (or declare `upsert` for reference data the package keeps current). Set `externalId` to the field that names a row, to a list of fields when no single field does (a junction table's `['team', 'project']`), or to `'id'` when the records carry their own ids. Rebuild the package, and reinstall it where it was installed with `os package install`, so the stored body carries the new declaration. From 863908f4f05a3f8a2bd962309e6ba5095d9bbbda Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:09:10 +0000 Subject: [PATCH 14/19] fix(scenarios): runner seed and restore name no retired seed mode main's #34985 brought in loadSeedRows, which declared `mode: 'insert'` on every card dataset. This PR retires that mode, and the install door refuses a dataset declaring it, so no card seed (and no restore) would load. Drop the mode so the default `ignore` loads them, make the test seed door judge `mode` with SeedMode as the real door does, and pin that the seed and restore packages carry no retired mode. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .../34613-scenario-seed-no-retired-mode.md | 7 ++++ .../qa/scenarios/src/runner/orchestrate.ts | 11 ++++-- .../scenarios/test/runner/orchestrate.test.ts | 37 +++++++++++++++++++ .../qa/scenarios/test/runner/seed-door.ts | 16 +++++++- 4 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 .changeset/34613-scenario-seed-no-retired-mode.md diff --git a/.changeset/34613-scenario-seed-no-retired-mode.md b/.changeset/34613-scenario-seed-no-retired-mode.md new file mode 100644 index 00000000000..d01c325c26f --- /dev/null +++ b/.changeset/34613-scenario-seed-no-retired-mode.md @@ -0,0 +1,7 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): the runner's card seed and restore load under the default seed mode, not the retired `insert` + +The scenario runner wrote every card seed (and every restore of a removed seeded row) as a data-only package whose datasets declared `mode: 'insert'`. That mode is retired (#34613), and the managed install door refuses a dataset declaring it, every row of it, so no card seed loaded. The datasets now name no `mode`: the default, `ignore`, creates each row whose `id` the object does not hold and leaves one it holds as it is, which is what a fresh seed and a restore need. The test double's seed door now judges `mode` with `SeedMode`, as the real door does, and a pin holds that the seed and restore packages carry no retired mode. diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 004bb0c7c0f..ef7e8a4b930 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -1250,9 +1250,12 @@ function seedLoadLetters(n: number): string { /** * Write rows through the platform's own seed path: one data-only package * whose `data[]` carries them, each object a dataset keyed on `id` - * (`externalId: 'id'`, `mode: 'insert'`), installed through the managed - * install door (`installManaged`). The platform's seed loader writes a - * package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in + * (`externalId: 'id'`) under the default seed mode (`ignore`: a row whose `id` + * the object does not hold yet is created, one it holds is left as it is), + * installed through the managed install door (`installManaged`). The dataset + * names no `mode`: `insert` and `replace` are retired (#34613), and the door + * refuses a dataset declaring either, every row of it. The platform's seed + * loader writes a package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in * `@objectstack/spec/kernel`): the object's `state_machine` rule is skipped, * every other validation rule and hook still runs, and record-triggered flows * do not fire. A row keeps the card's own `id`, and a lookup value naming a @@ -1284,7 +1287,7 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): type: 'app', scope: 'project', name: 'Scenario seed', - data: datasets.map((d) => ({ object: d.object, mode: 'insert', externalId: 'id', records: d.records })), + data: datasets.map((d) => ({ object: d.object, externalId: 'id', records: d.records })), }; const answer = await app.installManaged(manifest); if (!answer.ok) return all(`the seed package was refused: ${answer.status}${answer.code ? ` ${answer.code}` : ''}${answer.message ? ` ${answer.message}` : ''}`); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 82b26ea888d..9c9be471103 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -22,6 +22,7 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; import { validateRollupSourceVisibility } from '@objectstack/lint'; +import { RETIRED_SEED_MODE_VALUES } from '@objectstack/spec/data'; import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../../src/loader.js'; import { buildDeniesWrite, gradeCardAnswer, truthFigures } from '../../src/score/index.js'; @@ -968,6 +969,42 @@ describe('seedApp — a card row already past its entry state loads through the expect(app.rows.demotravel_expense_claim!.find((r) => r.id === 'c001')).toMatchObject({ status: 'paid' }); }); + it('[#34613] the seed and restore packages declare no retired seed mode: each dataset names no `mode`, so the default (`ignore`) loads it', async () => { + /** Records every data-only package the runner sends the managed door. */ + class ManifestTap extends TravelRulesApp { + readonly seedPackages: Array> = []; + override async installManaged(manifest: Record): Promise { + if (Array.isArray(manifest.data)) this.seedPackages.push(manifest); + return super.installManaged(manifest); + } + } + const scenario = travel(); + const app = new ManifestTap(); + expect((await seedApp(scenario, app, [])).refused).toEqual([]); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + await restoreSeededRows(scenario, app, [], seeded); + expect(app.seedPackages.length).toBeGreaterThanOrEqual(2); // the seed, then the restore + const datasets = app.seedPackages.flatMap((m) => m.data as Array>); + expect(datasets.filter((d) => 'mode' in d)).toEqual([]); + for (const d of datasets) expect(d.externalId).toBe('id'); + }); + + it('[#34613] control: the test door refuses a dataset declaring a retired mode whole, with SeedMode\'s own message, as the real door does', async () => { + for (const mode of RETIRED_SEED_MODE_VALUES) { + const written: string[] = []; + const answer = await seedDoorAnswer(async (_o, row) => (written.push(String(row.id)), { ok: true, status: 200, body: {} }), { + id: 'com.scenario.seed.x', + data: [{ object: 'demotravel_department', mode, externalId: 'id', records: [{ id: 'dep_a' }, { id: 'dep_b' }] }], + }); + const seeded = (answer.body as { data: { seeded: { inserted: number; errorList: Array<{ field: string; message: string }> } } }).data.seeded; + expect(written).toEqual([]); + expect(seeded.inserted).toBe(0); + expect(seeded.errorList.map((e) => e.field)).toEqual(['(write)', '(write)']); + expect(seeded.errorList[0]!.message).toContain(`seed.mode: '${mode}'\` was removed`); + } + }); + it('a reference the loader drops from a row it wrote refuses that row with the field and keeps its second-pass patch; a row also refused on write counts once; a restore counts the written row as reinserted', async () => { /** Departments under a self-lookup `parent`. Finance breaks a budget floor, so its write is refused; a `parent` naming a department not in is dropped, as an optional lookup the loader cannot resolve. */ class DroppedParentApp extends TravelRulesApp { diff --git a/packages/qa/scenarios/test/runner/seed-door.ts b/packages/qa/scenarios/test/runner/seed-door.ts index 941f7c042e1..de2de51256d 100644 --- a/packages/qa/scenarios/test/runner/seed-door.ts +++ b/packages/qa/scenarios/test/runner/seed-door.ts @@ -14,8 +14,13 @@ * it, and the answer carries one entry with `field` set to that lookup, as the * real loader reports a reference it could not resolve (`referencesDropped`). * A row whose write then fails carries both entries. + * + * A dataset whose `mode` `SeedMode` does not accept (a retired `insert` or + * `replace`, #34613) is refused whole, as the real door refuses it: every row + * carries a `(write)` entry with `SeedMode`'s own message, and none is written. */ +import { SeedMode } from '@objectstack/spec/data'; import type { HttpAnswer } from '../../src/runner/app.js'; export async function seedDoorAnswer( @@ -23,10 +28,17 @@ export async function seedDoorAnswer( manifest: Record, drops: (object: string, row: Record) => Record = () => ({}), ): Promise { - const datasets = manifest.data as Array<{ object: string; records: Array> }>; + const datasets = manifest.data as Array<{ object: string; mode?: unknown; records: Array> }>; let inserted = 0; const errorList: Array> = []; - for (const { object, records } of datasets) { + for (const { object, mode, records } of datasets) { + const judged = mode === undefined ? undefined : SeedMode.safeParse(mode); + if (judged && !judged.success) { + const said = judged.error.issues[0]?.message ?? `seed mode ${String(mode)} refused`; + for (const [recordIndex, sent] of records.entries()) + errorList.push({ sourceObject: object, field: '(write)', targetObject: object, targetField: 'id', attemptedValue: sent.id, recordIndex, message: said }); + continue; + } for (const [recordIndex, sent] of records.entries()) { const row = { ...sent }; for (const [field, targetObject] of Object.entries(drops(object, sent))) { From d56fedc24b320f6a821ed01826d728ff4727ddf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 03:55:34 +0000 Subject: [PATCH 15/19] chore(docs): regenerate protocol.mdx over the main merge The os-regen driver kept the branch side of protocol.mdx in 3f01444347, dropping main's view.timesheet rows; gen:schema + gen:docs on the merged tree restores them beside this PR's narrowed seed mode enum. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL --- content/docs/references/api/protocol.mdx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index c7948c4b01c..feee8113694 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1910,9 +1910,9 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **name** | `string` | optional | Item name — supplied by the metadata door; for an object-scoped container it is the object name. | | **label** | `string \| Record` | optional | Human-readable label shown in metadata lists. | | **object** | `string` | optional | Object this container binds to — how a stack-level `views: [...]` entry says which object its views belong to; read by `getViewsByObject()` / `GET /meta/view?object=`. | -| **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>; data?: object \| object \| object; … }` | optional | | +| **list** | `{ name?: string; label?: string \| Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }` | optional | | | **form** | `{ type?: Enum<'simple' \| 'tabbed' \| 'wizard'>; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }` | optional | | -| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | +| **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Additional named list views (views mode — dropdown userFilters allowed, no tabs; ADR-0047) | | **formViews** | `Record; layout?: Enum<'vertical' \| 'horizontal'>; columns?: integer; title?: string; … }>` | optional | Additional named form views | | **protection** | `{ lock: Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>; reason: string; docsUrl?: string }` | optional | Package author protection block — lock policy for this view. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | @@ -1929,7 +1929,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | :--- | :--- | :--- | :--- | | **name** | `string` | optional | Internal view name (lowercase snake_case) | | **label** | `string \| Record` | optional | Display label — the default-language string, or an inline locale map (`{ en, "zh-CN" }`) resolved at render time | -| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>` | optional (default: `"grid"`) | | +| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>` | optional (default: `"grid"`) | | | **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | | **columns** | `string[] \| { field: string; label?: string \| Record; width?: number; align?: Enum<'left' \| 'center' \| 'right'>; … }[]` | ✅ | Fields to display as columns — the PROJECTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: this list is the candidate set AND the baseline order; `hiddenFields` subtracts from it and `fieldOrder` orders what survives. `hiddenFields` and `fieldOrder` cannot add a field omitted here. An empty list declares no projection, so neither of them applies: which columns show is then left to the renderer (objectui's `ListView` grid derives the object's default columns). | | **filter** | `({ field: string; operator: Enum<'equals' \| 'not_equals' \| 'contains' \| 'not_contains' \| 'icontains' \| …>; value?: string \| number \| boolean \| null \| (string \| number)[] } \| { or: object[] })[]` | optional | Filter criteria (JSON Rules) | @@ -1949,6 +1949,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **chart** | `{ chartType?: Enum<'bar' \| 'line' \| 'pie' \| 'area' \| 'scatter'>; dataset: string; dimensions?: string[]; values: string[] }` | optional | Chart binding — applies when the view renders as a chart. A `type: 'chart'` view must bind one: it names the ADR-0021 `dataset` and the measures (`values`) the chart plots, and there is no default binding | | **map** | `{ latitudeField?: string; longitudeField?: string; locationField?: string; titleField?: string; … }` | optional | Map configuration — applies when the view renders as a map layout | | **tree** | `{ parentField?: string; labelField?: string; fields?: string[]; defaultExpandedDepth?: integer }` | optional | Tree/hierarchy configuration — applies when the view renders as a tree layout | +| **timesheet** | `{ rowFields: string[]; dateField: string; valueField: string }` | optional | Timesheet binding — applies when the view renders as a timesheet. A `type: 'timesheet'` view must bind one: the row fields, the date field and the numeric value field the weekly grid pivots and edits | | **pageName** | `never` | optional | [REMOVED] `view.pageName` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the page a `type: 'page'` view was to mount, and that mount was never built: no renderer read the key, so the named page was never reached and the view drew an empty grid. Delete the key; to put a published page in front of users, give the app a navigation item — `{ type: 'page', pageName: '' }` under the app's `navigation` — which is a different key on a different surface and is the page mount that has always rendered. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **description** | `string \| Record` | optional | View description for documentation/tooltips | | **sharing** | `{ lockedBy?: string }` | optional | View sharing configuration: who locked the view configuration | @@ -1965,7 +1966,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | | **userActions** | `{ sort?: boolean; search?: boolean; filter?: boolean; refresh?: boolean; … }` | optional | User action toggles for the view toolbar | -| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>[] }` | optional | Appearance and visualization configuration | +| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>[] }` | optional | Appearance and visualization configuration | | **tabs** | `never` | optional | [REMOVED] `view.list.tabs` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — no renderer ever mounted a tab bar for it, so authoring it drew nothing: the tab strip above an object's records is the saved-view switcher (ViewTabBar), which renders one tab per named list view and never read this key. Delete the key, and move each tab you want to a named list view under the object's `listViews` instead: the tab's `name` becomes the entry's key, its `label` the entry's `label`, and its `filter` rules join the view's own `filter` on that entry (copy the view's `columns` too); a tab whose `view` already named a list view needs nothing more. Every `listViews` entry renders as a tab in the switcher. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **addRecord** | `{ enabled: boolean; position?: Enum<'top' \| 'bottom' \| 'both'> }` | optional | Add record entry point configuration | | **showRecordCount** | `boolean` | optional | Show record count at the bottom of the list | @@ -2008,7 +2009,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | :--- | :--- | :--- | :--- | | **name** | `string` | optional | Internal view name (lowercase snake_case) | | **label** | `string \| Record` | optional | Display label — the default-language string, or an inline locale map (`{ en, "zh-CN" }`) resolved at render time | -| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>` | optional (default: `"grid"`) | | +| **type** | `Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>` | optional (default: `"grid"`) | | | **data** | `{ provider: 'object'; object: string } \| { provider: 'value'; items: any[] } \| { provider: 'schema'; schemaId: string; schema?: Record }` | optional | Data source configuration (defaults to "object" provider) | | **columns** | `string[] \| { field: string; label?: string \| Record; width?: number; align?: Enum<'left' \| 'center' \| 'right'>; … }[]` | ✅ | Fields to display as columns — the PROJECTION of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: this list is the candidate set AND the baseline order; `hiddenFields` subtracts from it and `fieldOrder` orders what survives. `hiddenFields` and `fieldOrder` cannot add a field omitted here. An empty list declares no projection, so neither of them applies: which columns show is then left to the renderer (objectui's `ListView` grid derives the object's default columns). | | **filter** | `({ field: string; operator: Enum<'equals' \| 'not_equals' \| 'contains' \| 'not_contains' \| 'icontains' \| …>; value?: string \| number \| boolean \| null \| (string \| number)[] } \| { or: object[] })[]` | optional | Filter criteria (JSON Rules) | @@ -2028,6 +2029,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **chart** | `{ chartType?: Enum<'bar' \| 'line' \| 'pie' \| 'area' \| 'scatter'>; dataset: string; dimensions?: string[]; values: string[] }` | optional | Chart binding — applies when the view renders as a chart. A `type: 'chart'` view must bind one: it names the ADR-0021 `dataset` and the measures (`values`) the chart plots, and there is no default binding | | **map** | `{ latitudeField?: string; longitudeField?: string; locationField?: string; titleField?: string; … }` | optional | Map configuration — applies when the view renders as a map layout | | **tree** | `{ parentField?: string; labelField?: string; fields?: string[]; defaultExpandedDepth?: integer }` | optional | Tree/hierarchy configuration — applies when the view renders as a tree layout | +| **timesheet** | `{ rowFields: string[]; dateField: string; valueField: string }` | optional | Timesheet binding — applies when the view renders as a timesheet. A `type: 'timesheet'` view must bind one: the row fields, the date field and the numeric value field the weekly grid pivots and edits | | **pageName** | `never` | optional | [REMOVED] `view.pageName` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — it named the page a `type: 'page'` view was to mount, and that mount was never built: no renderer read the key, so the named page was never reached and the view drew an empty grid. Delete the key; to put a published page in front of users, give the app a navigation item — `{ type: 'page', pageName: '' }` under the app's `navigation` — which is a different key on a different surface and is the page mount that has always rendered. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **description** | `string \| Record` | optional | View description for documentation/tooltips | | **sharing** | `{ lockedBy?: string }` | optional | View sharing configuration: who locked the view configuration | @@ -2044,7 +2046,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | | **userActions** | `{ sort?: boolean; search?: boolean; filter?: boolean; refresh?: boolean; … }` | optional | User action toggles for the view toolbar | -| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| 'chart' \| 'tree'>[] }` | optional | Appearance and visualization configuration | +| **appearance** | `{ showDescription?: boolean; allowedVisualizations?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>[] }` | optional | Appearance and visualization configuration | | **tabs** | `never` | optional | [REMOVED] `view.list.tabs` was removed in @objectstack/spec 17.5.0 (ADR-0049 enforce-or-remove) — no renderer ever mounted a tab bar for it, so authoring it drew nothing: the tab strip above an object's records is the saved-view switcher (ViewTabBar), which renders one tab per named list view and never read this key. Delete the key, and move each tab you want to a named list view under the object's `listViews` instead: the tab's `name` becomes the entry's key, its `label` the entry's `label`, and its `filter` rules join the view's own `filter` on that entry (copy the view's `columns` too); a tab whose `view` already named a list view needs nothing more. Every `listViews` entry renders as a tab in the switcher. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **addRecord** | `{ enabled: boolean; position?: Enum<'top' \| 'bottom' \| 'both'> }` | optional | Add record entry point configuration | | **showRecordCount** | `boolean` | optional | Show record count at the bottom of the list | From 2215056c076e3de710b00c75de4ce3573e3b1f52 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:12:26 +0000 Subject: [PATCH 16/19] test(cloud-connection): pin the landed-key record across data-only packages keyed on id The record (`sys_seed_landed_key`) has no package component, so a second data-only package carrying a recorded row that is gone does not insert it (withheld, counted in `skipped`, no error), and that package's reseed does. This is the door the scenario runner's restore loads through. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL --- ...ketplace-install-local-landed-keys.test.ts | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts b/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts index dc83594492f..fcae6d05ad8 100644 --- a/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts @@ -433,3 +433,52 @@ describe('an unmanaged copy\'s sample data: the install honours the record, the expect(names('lk_account')).toEqual(['Acme', 'Globex']); }); }); + +/** + * The record has no package component (`(organization_id, object_name, + * seed_key)`), so it is the organization's, not the installing package's. The + * scenario runner loads its seed, and puts a removed seed row back, as data-only + * packages keyed on `id`, each under a namespace of its own + * (`loadSeedRows` in `packages/qa/scenarios/src/runner/orchestrate.ts`). This + * pins what such a load meets at this door: a second package carrying a + * recorded row that is gone does not insert it (withheld, counted in + * `skipped`, no error), and that package's reseed does. + */ +describe('a data-only package keyed on `id`: the record is the organization\'s, whichever package carries the row', () => { + const dataOnly = (namespace: string, records: Row[]) => ({ + id: `com.scenario.seed.${namespace}`, + namespace, + version: '0.0.1', + type: 'app', + scope: 'project', + name: 'Scenario seed', + data: [{ object: 'lk_account', externalId: 'id', records }], + }); + const ids = (object: string) => (store[object] ?? []).filter((r) => r.organization_id === ORG).map((r) => r.id).sort(); + + it('a row deleted after one package seeded it is withheld from a second package\'s install; the second package\'s reseed brings it back', async () => { + const rt = await boot(); + const first = await rt.install(dataOnly('scenarioseeda', [{ id: 'ct1', name: 'Ann' }, { id: 'ct2', name: 'Ben' }])); + expect(first.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 2, skipped: 0, errors: 0 }); + expect(landed()).toEqual(['lk_account:ct1', 'lk_account:ct2']); + store.lk_account = store.lk_account!.filter((r) => r.id !== 'ct2'); + + const second = await rt.install(dataOnly('scenarioseedb', [{ id: 'ct2', name: 'Ben' }])); + expect(second.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 0, skipped: 1, errors: 0, errorList: [] }); + expect(ids('lk_account')).toEqual(['ct1']); + + const reseed = await rt.reseed('com.scenario.seed.scenarioseedb'); + expect(reseed.status, JSON.stringify(reseed.payload)).toBe(200); + expect(reseed.payload.data).toMatchObject({ inserted: 1, skipped: 0, errors: 0 }); + expect(ids('lk_account')).toEqual(['ct1', 'ct2']); + expect(landed()).toEqual(['lk_account:ct1', 'lk_account:ct2']); + }); + + it('control: a row no load recorded is inserted by a second package\'s install', async () => { + const rt = await boot(); + await rt.install(dataOnly('scenarioseeda', [{ id: 'ct1', name: 'Ann' }])); + const second = await rt.install(dataOnly('scenarioseedb', [{ id: 'ct2', name: 'Ben' }])); + expect(second.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 1, skipped: 0, errors: 0 }); + expect(ids('lk_account')).toEqual(['ct1', 'ct2']); + }); +}); From 1f74fbc7f3678b66c1419ebf5791c60ca2233d90 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:12:26 +0000 Subject: [PATCH 17/19] fix(scenarios): a restore puts back a withheld seeded row through the package's reseed The install door keeps the organization's record of landed seed rows (`sys_seed_landed_key`, no package in the key) and, under its `honour` posture, withholds a recorded row that is gone: `skipped`, no error. Every row a restore sends is such a row, so since the seed datasets moved to the default `ignore` the restore installed nothing, booked the row as reinserted, and failed after three rounds, leaving the later operations of template mode's iterate-run half unmeasured. `loadSeedRows` now reads the door's `skipped`. The restore goes on through the restore package's sample-data reseed (the deliberate re-seed, which inserts every missing row), and whenever the door skipped a row the objects are read back and each row still not there is refused by name with the reason, never counted as written or reinserted. A dataset refused whole (`field: 'mode'`) refuses each of its rows instead of filing a missing reference. The test double's door keeps the landed-row record and answers a retired mode with one dataset entry, as the real door does; `AppHarness` gains the optional `reseedManaged`. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL --- .../34613-scenario-seed-no-retired-mode.md | 2 +- packages/qa/scenarios/src/runner/app.ts | 15 +++ .../qa/scenarios/src/runner/orchestrate.ts | 116 ++++++++++++++---- .../scenarios/test/runner/orchestrate.test.ts | 85 ++++++++++++- .../qa/scenarios/test/runner/seed-door.ts | 77 ++++++++++-- 5 files changed, 261 insertions(+), 34 deletions(-) diff --git a/.changeset/34613-scenario-seed-no-retired-mode.md b/.changeset/34613-scenario-seed-no-retired-mode.md index d01c325c26f..d8ffef05342 100644 --- a/.changeset/34613-scenario-seed-no-retired-mode.md +++ b/.changeset/34613-scenario-seed-no-retired-mode.md @@ -4,4 +4,4 @@ fix(scenarios): the runner's card seed and restore load under the default seed mode, not the retired `insert` -The scenario runner wrote every card seed (and every restore of a removed seeded row) as a data-only package whose datasets declared `mode: 'insert'`. That mode is retired (#34613), and the managed install door refuses a dataset declaring it, every row of it, so no card seed loaded. The datasets now name no `mode`: the default, `ignore`, creates each row whose `id` the object does not hold and leaves one it holds as it is, which is what a fresh seed and a restore need. The test double's seed door now judges `mode` with `SeedMode`, as the real door does, and a pin holds that the seed and restore packages carry no retired mode. +The scenario runner wrote every card seed (and every restore of a removed seeded row) as a data-only package whose datasets declared `mode: 'insert'`. That mode is retired (#34613), and the managed install door refuses a dataset declaring it, every row of it, so no card seed loaded. The datasets now name no `mode`: the default, `ignore`, creates each row whose `id` the object does not hold and leaves one it holds as it is, which is what a fresh seed needs. A restore needs more: the install door keeps the organization's record of landed seed rows (`sys_seed_landed_key`) and withholds a recorded row that is gone, as a person's removal, so an install does not put back a seeded row a turn deleted. The restore therefore goes on through that package's sample-data reseed (`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`), the platform's deliberate re-seed, which inserts every missing row; and whenever the door skipped a row, the runner reads the objects back and refuses each row still not there by name, with the reason, instead of counting it as written or reinserted. The test double's seed door now judges `mode` with `SeedMode` and keeps the landed-row record, as the real door does, and pins hold that the seed and restore packages carry no retired mode and that a restore brings back a recorded row. diff --git a/packages/qa/scenarios/src/runner/app.ts b/packages/qa/scenarios/src/runner/app.ts index ead42d2af23..b1ba8ad8f4c 100644 --- a/packages/qa/scenarios/src/runner/app.ts +++ b/packages/qa/scenarios/src/runner/app.ts @@ -164,6 +164,17 @@ export interface AppHarness { * it that refusal stays the mode's finding, and every seed row is refused. */ installManaged?(manifest: Record): Promise; + /** + * The sample-data reseed of a package the managed door installed + * (`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`): + * its `data[]` loaded again under the deliberate re-seed posture, which + * inserts every missing row whatever the organization's record of landed + * seed rows says. It is how a restore puts back a seeded row a turn removed, + * which an install withholds (`loadSeedRows` in `orchestrate.ts`). Optional, + * so a harness written before it keeps compiling; without it such a row is + * refused, named, and the operation is not measured. + */ + reseedManaged?(manifestId: string): Promise; /** The environment's metadata of every collection the template carries, as an artifact. */ metadataAsArtifact(collections: readonly string[]): Promise>; /** One MCP tool call as the owner of `apiKey`, through the door the agent uses (`mcpUrl`). */ @@ -337,6 +348,10 @@ export class HttpApp implements AppHarness { return this.call('POST', '/api/v1/marketplace/install-local', { packageId, manifest, installMode: 'managed' }, { session: this.admin }); } + reseedManaged(manifestId: string): Promise { + return this.call('POST', `/api/v1/marketplace/install-local/${encodeURIComponent(manifestId)}/reseed-sample-data`, {}, { session: this.admin }); + } + async callTool(apiKey: string, tool: string, args: Record): Promise { const res = await fetch(this.mcpUrl, { method: 'POST', diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 43b93676c86..902855e249e 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -1234,7 +1234,8 @@ interface SeedLoaderAnswer { mode?: string; reason?: string; inserted?: number; - errorList?: Array<{ sourceObject?: string; field?: string; recordIndex?: number; attemptedValue?: unknown; code?: string; message?: string }>; + skipped?: number; + errorList?: Array<{ sourceObject?: string; field?: string; targetField?: string; recordIndex?: number; attemptedValue?: unknown; code?: string; message?: string }>; } /** The seed loads made in this process, which name each load's package apart (one namespace per installed package). */ @@ -1247,15 +1248,22 @@ function seedLoadLetters(n: number): string { return out; } +/** + * Why the install door skipped a row of a load and the object does not hold it + * ({@link loadSeedRows}): an install reads a recorded row that is gone as a + * person's removal, which it must not undo. Short, so the restore's refusal + * line ({@link restoreSeededRows}) keeps the reason after it. + */ +const WITHHELD = 'withheld by the install door: its key is recorded as landed (`sys_seed_landed_key`), the row gone'; + /** * Write rows through the platform's own seed path: one data-only package * whose `data[]` carries them, each object a dataset keyed on `id` - * (`externalId: 'id'`) under the default seed mode (`ignore`: a row whose `id` - * the object does not hold yet is created, one it holds is left as it is), - * installed through the managed install door (`installManaged`). The dataset - * names no `mode`: `insert` and `replace` are retired (#34613), and the door - * refuses a dataset declaring either, every row of it. The platform's seed - * loader writes a package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in + * (`externalId: 'id'`) under the default seed mode (`ignore`), installed + * through the managed install door (`installManaged`). The dataset names no + * `mode`: `insert` and `replace` are retired (#34613), and the door refuses a + * dataset declaring either, every row of it. The platform's seed loader writes + * a package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in * `@objectstack/spec/kernel`): the object's `state_machine` rule is skipped, * every other validation rule and hook still runs, and record-triggered flows * do not fire. A row keeps the card's own `id`, and a lookup value naming a @@ -1263,18 +1271,42 @@ function seedLoadLetters(n: number): string { * holds the claim seeded as `c001`. A user id in a row (`owner_id`, a `user` * field, a rewritten handle) is written as sent. * + * `ignore` at the install door is not "create every row the object does not + * hold". The door keeps the organization's record of landed seed rows + * (`sys_seed_landed_key`, keyed on the organization, the object and the row's + * key, with no package in it) and installs under its `honour` posture: a row + * the object holds is left as it is, and a row it does not hold whose key is + * recorded is withheld, as a person's removal, counted in `skipped` with no + * error. A fresh seed meets no record. A restore does: every row it sends is a + * seeded row a turn removed, recorded when the seed landed it. So with + * `reseedWithheld` (the restore, {@link restoreSeededRows}) a load the door + * skipped rows of goes on through that package's sample-data reseed + * (`reseedManaged`), the platform's deliberate re-seed, which inserts every + * missing row whatever the record says. Whenever the door skipped a row, each + * object of the load is read back, and every row sent that the door did not + * refuse and the object does not hold is refused by name with the reason + * ({@link WITHHELD}, and why the reseed did not bring it back), never counted + * as written. A read refused there leaves the rows of that object unconfirmed: + * each is refused with the read's answer. + * * Each package takes a namespace of its own, because one environment refuses * a second package claiming a namespace another already holds. * * The answer's `errorList` names each row the loader could not write - * (`field: '(write)'`), which is refused, and each reference it could not - * resolve on a row it did write, which is refused with the `fields` the row - * does not hold. An entry carries the loader's message and no error code. A - * door that refuses the package, a harness with no managed door, or a load - * that did not run inline (`seeded.mode` other than `inline`) refuses every - * row, with that reason in its message (the door's status and code included). + * (`field: '(write)'`), which is refused; each dataset it refused whole + * (`field: 'mode'`, `targetField: '(dataset)'`, a retired mode), every row of + * which is refused; and each reference it could not resolve on a row it did + * write, which is refused with the `fields` the row does not hold. An entry + * carries the loader's message and no error code. A door that refuses the + * package, a harness with no managed door, or a load that did not run inline + * (`seeded.mode` other than `inline`) refuses every row, with that reason in + * its message (the door's status and code included). */ -async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): Promise<{ inserted: number; refused: RunHalf['seed']['refused'] }> { +async function loadSeedRows( + app: AppHarness, + datasets: readonly SeedDataset[], + opts: { reseedWithheld?: boolean } = {}, +): Promise<{ inserted: number; refused: RunHalf['seed']['refused'] }> { const sent = datasets.flatMap((d) => d.records.map((r) => ({ object: d.object, id: String(r.id) }))); if (sent.length === 0) return { inserted: 0, refused: [] }; const all = (message: string) => ({ inserted: 0, refused: sent.map((r) => ({ ...r, message: message.slice(0, 300) })) }); @@ -1300,10 +1332,18 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): const unheld = new Map(); for (const e of seeded.errorList ?? []) { const object = String(e.sourceObject ?? ''); + const said = { ...(typeof e.code === 'string' ? { code: e.code } : {}), ...(e.message ? { message: e.message.slice(0, 300) } : {}) }; + if (e.field === 'mode' && e.targetField === '(dataset)') { + // The dataset refused whole: no row of it was attempted. + for (const row of records.get(object) ?? []) { + const id = String(row.id); + if (!unwritten.has(`${object}/${id}`)) unwritten.set(`${object}/${id}`, { object, id, ...said }); + } + continue; + } const row = typeof e.recordIndex === 'number' ? records.get(object)?.[e.recordIndex] : undefined; const id = String(row?.id ?? e.attemptedValue ?? ''); const key = `${object}/${id}`; - const said = { ...(typeof e.code === 'string' ? { code: e.code } : {}), ...(e.message ? { message: e.message.slice(0, 300) } : {}) }; if (e.field === '(write)') { if (!unwritten.has(key)) unwritten.set(key, { object, id, ...said }); } else { @@ -1313,10 +1353,40 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): } } for (const key of unwritten.keys()) unheld.delete(key); + let written = typeof seeded.inserted === 'number' ? seeded.inserted : sent.length - unwritten.size; + + // Rows the door skipped: brought back through the reseed when asked, then named if still not held. + const notBack = new Map(); + if (typeof seeded.skipped === 'number' && seeded.skipped > 0) { + let why: string | undefined; + if (opts.reseedWithheld) { + if (!app.reseedManaged) why = 'no reseed door'; + else { + const r = await app.reseedManaged(manifest.id); + const again = (r.body as { data?: { inserted?: unknown } } | null)?.data?.inserted; + if (r.ok && typeof again === 'number') written += again; + else why = `reseed refused: ${r.status}${r.code ? ` ${r.code}` : ''}${r.message ? ` ${r.message}` : ''}`; + } + why ??= 'the reseed left it out'; + } + for (const [object, rows] of records) { + const asked = rows.map((row) => String(row.id)).filter((id) => !unwritten.has(`${object}/${id}`)); + if (!asked.length) continue; + const read = await app.listRows(object); + const holds = new Set(read.ok ? read.rows.map((row) => String(row.id)) : []); + for (const id of asked) { + if (holds.has(id)) continue; + const message = read.ok + ? `${WITHHELD}${why ? `; ${why}` : ''}` + : `the door skipped ${seeded.skipped} row(s) of this load, and the read that would say whether this one is in was refused: ${read.status}${read.code ? ` ${read.code}` : ''}`; + notBack.set(`${object}/${id}`, { object, id, message: message.slice(0, 300) }); + } + } + for (const key of notBack.keys()) unheld.delete(key); + } const order = (r: { object: string; id: string }) => position.get(`${r.object}/${r.id}`) ?? sent.length; - const refused = [...unwritten.values(), ...unheld.values()].sort((a, b) => order(a) - order(b)); - const inserted = (typeof seeded.inserted === 'number' ? seeded.inserted : sent.length - unwritten.size) - unheld.size; - return { inserted, refused }; + const refused = [...unwritten.values(), ...notBack.values(), ...unheld.values()].sort((a, b) => order(a) - order(b)); + return { inserted: written - unheld.size, refused }; } /** @@ -1411,7 +1481,10 @@ async function seedDrift(card: Card, app: AppHarness, seeded: SeededRows, built? * 1. a row a turn added is deleted; * 2. a seeded row a turn removed is inserted again through the seed path * ({@link loadSeedRows}, the posture the seed loaded it under, so a row - * already `paid` is not refused as a new record) — the very body the + * already `paid` is not refused as a new record; the install withholds a + * row the seed recorded as landed, so the load goes on through that + * package's reseed, and a row still not back is refused by name, never + * counted as reinserted) — the very body the * seed sent ({@link seedRowBody}), or, for a row the app made itself * while seeding, the row as it was read, less the columns the platform * stamps ({@link RESTORE_UNWRITTEN}); the round's rows go in as one @@ -1479,7 +1552,8 @@ export async function restoreSeededRows( else refused(`delete ${d.object} ${id}`, r); } } - // 2. The seeded rows a turn removed, through the seed path ({@link loadSeedRows}), in its load order, one load a round. + // 2. The seeded rows a turn removed, through the seed path ({@link loadSeedRows}), in its load order, one load a round; + // the install withholds the ones the seed recorded as landed, which the package's reseed puts back. const back: Array<{ object: string; records: Array> }> = []; for (const d of [...drifts].sort((a, b) => order.indexOf(a.object) - order.indexOf(b.object))) { const records: Array> = []; @@ -1496,7 +1570,7 @@ export async function restoreSeededRows( } if (records.length) back.push({ object: d.object, records }); } - const load = await loadSeedRows(app, back); + const load = await loadSeedRows(app, back, { reseedWithheld: true }); const notBack = new Set(load.refused.filter((r) => !r.fields).map((r) => `${r.object}/${r.id}`)); for (const r of load.refused) refusals.add(`insert ${r.object} ${r.id}: ${r.code ? `${r.code} ` : ''}${r.fields ? `[${r.fields.join(', ')}] ` : ''}${(r.message ?? '').slice(0, 120)}`.trim()); for (const d of back) for (const row of d.records) if (!notBack.has(`${d.object}/${String(row.id)}`)) reinserted.add(`${d.object}/${String(row.id)}`); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 2e12cab3bb9..73c34d2cc8f 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -27,7 +27,7 @@ import { RETIRED_SEED_MODE_VALUES } from '@objectstack/spec/data'; import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../../src/loader.js'; import { buildDeniesWrite, gradeCardAnswer, truthFigures } from '../../src/score/index.js'; import type { AppHarness, HttpAnswer, PersonaAccount, ToolAnswer } from '../../src/runner/app.js'; -import { seedDoorAnswer } from './seed-door.js'; +import { reseedDoorAnswer, seedDoorAnswer, type SeedDoorRecord } from './seed-door.js'; import { RecordedDriver, RecordingDriver, ReplayNotFaithfulError, stepKey, type AgentDriver, type AskTask, type AuthorTask, type DriverInfo, type Recording } from '../../src/runner/driver.js'; import { loadedCardStamp, main as runScenarios, makeDriver, parseArgs, promptChoiceOf } from '../../src/runner/cli.js'; import { citationLabels, namespacedScenario } from '../../src/runner/namespace.js'; @@ -194,15 +194,32 @@ class FakeApp implements AppHarness { seedDrops(_object: string, _row: Record): Record { return {}; } - /** The managed door: a data-only package's `data[]` is the seed ({@link seedDoorAnswer}); any other manifest is a build. */ + /** The organization's record of landed seed rows (`sys_seed_landed_key`), `object/id`, kept across every package the door loads ({@link seedDoorAnswer}). */ + landed = new Set(); + /** The data-only packages the managed door installed, by id: what the reseed door loads again. */ + seedPackageById = new Map>(); + private seedRecord(): SeedDoorRecord { + return { landed: this.landed, holds: (object, id) => (this.rows[object] ?? []).some((r) => String(r.id) === id) }; + } + /** The managed door: a data-only package's `data[]` is the seed ({@link seedDoorAnswer}), under the install's `honour` posture; any other manifest is a build. */ async installManaged(manifest: Record): Promise { if (!Array.isArray(manifest.data)) { this.installed = manifest; return this.installAnswer; } + this.seedPackageById.set(String(manifest.id), manifest); + this.seeding = true; + try { + return await seedDoorAnswer((object, row) => this.insertRow(object, row), manifest, (object, row) => this.seedDrops(object, row), this.seedRecord()); + } finally { + this.seeding = false; + } + } + /** The sample-data reseed door of an installed data-only package ({@link reseedDoorAnswer}): every missing row, whatever the record says. */ + async reseedManaged(manifestId: string): Promise { this.seeding = true; try { - return await seedDoorAnswer((object, row) => this.insertRow(object, row), manifest, (object, row) => this.seedDrops(object, row)); + return await reseedDoorAnswer((object, row) => this.insertRow(object, row), this.seedPackageById.get(manifestId), manifestId, this.seedRecord(), (object, row) => this.seedDrops(object, row)); } finally { this.seeding = false; } @@ -997,14 +1014,72 @@ describe('seedApp — a card row already past its entry state loads through the id: 'com.scenario.seed.x', data: [{ object: 'demotravel_department', mode, externalId: 'id', records: [{ id: 'dep_a' }, { id: 'dep_b' }] }], }); - const seeded = (answer.body as { data: { seeded: { inserted: number; errorList: Array<{ field: string; message: string }> } } }).data.seeded; + const seeded = (answer.body as { data: { seeded: { inserted: number; errorList: Array<{ field: string; targetField: string; recordIndex: number; message: string }> } } }).data.seeded; expect(written).toEqual([]); expect(seeded.inserted).toBe(0); - expect(seeded.errorList.map((e) => e.field)).toEqual(['(write)', '(write)']); + // One entry for the dataset, as `loadStored` answers it: the mode is the dataset's, no row was attempted. + expect(seeded.errorList.map(({ field, targetField, recordIndex }) => ({ field, targetField, recordIndex }))).toEqual([{ field: 'mode', targetField: '(dataset)', recordIndex: 0 }]); expect(seeded.errorList[0]!.message).toContain(`seed.mode: '${mode}'\` was removed`); } }); + it('[#34613] control: the test door keeps the landed-row record as the real door does — an install withholds a recorded row that is gone, the package\'s reseed brings it back, an unrecorded row lands', async () => { + const app = new FakeApp(); + const pkg = (id: string, rows: Array>) => ({ id, data: [{ object: 'x', externalId: 'id', records: rows }] }); + const seededOf = (a: HttpAnswer) => (a.body as { data: { seeded: { inserted: number; skipped: number; errors: number } } }).data.seeded; + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.a', [{ id: 'r1' }, { id: 'r2' }])))).toMatchObject({ inserted: 2, skipped: 0, errors: 0 }); + app.rows.x = app.rows.x!.filter((r) => r.id !== 'r2'); + // A second package carrying the recorded, removed row: withheld, `skipped`, no error. + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.b', [{ id: 'r2' }])))).toMatchObject({ inserted: 0, skipped: 1, errors: 0 }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1']); + // That package's reseed inserts it, whatever the record says. + const reseed = await app.reseedManaged('com.scenario.seed.b'); + expect(reseed).toMatchObject({ ok: true, body: { data: { inserted: 1, skipped: 0, errors: 0 } } }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1', 'r2']); + // A row the object holds is left as it is; a row no load recorded lands. + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.c', [{ id: 'r1' }, { id: 'r3' }])))).toMatchObject({ inserted: 1, skipped: 1, errors: 0 }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1', 'r2', 'r3']); + expect(await app.reseedManaged('com.scenario.seed.none')).toMatchObject({ ok: false, status: 404 }); + }); + + it('[#34613] a restore puts back a seeded row the install withholds: the restore package\'s reseed brings it in, and is the only reseed asked', async () => { + class ReseedTap extends TravelRulesApp { + readonly reseeds: string[] = []; + override async reseedManaged(manifestId: string): Promise { + this.reseeds.push(manifestId); + return super.reseedManaged(manifestId); + } + } + const scenario = travel(); + const app = new ReseedTap(); + expect((await seedApp(scenario, app, [])).refused).toEqual([]); + expect(app.reseeds).toEqual([]); // a fresh seed meets no record + expect(app.landed.has('demotravel_expense_claim/c001')).toBe(true); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + expect(await restoreSeededRows(scenario, app, [], seeded)).toEqual({ restored: { reinserted: ['demotravel_expense_claim/c001'] } }); + expect(app.reseeds).toHaveLength(1); + expect(app.reseeds[0]).toMatch(/^com\.scenario\.seed\.scenarioseed[a-z]+$/); + expect(app.rows.demotravel_expense_claim!.filter((r) => r.id === 'c001')).toEqual([expect.objectContaining({ status: 'paid' })]); + }); + + it('[#34613] a withheld row a restore cannot put back is refused by name with the reason, never booked as reinserted', async () => { + const scenario = travel(); + const app = Object.assign(new TravelRulesApp(), { reseedManaged: undefined }); + await seedApp(scenario, app, []); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + const out = await restoreSeededRows(scenario, app, [], seeded); + expect(out.restored).toBeUndefined(); + expect(out.failed).toContain('the rows could not be restored to the seeded state: demotravel_expense_claim: 1 missing (c001)'); + // The refusal names the row, the record that withheld it, and why the reseed did not run. + const refusal = /\(refused: (.*)\)$/.exec(out.failed!)?.[1] ?? ''; + expect(refusal).toMatch(/^insert demotravel_expense_claim c001: /); + expect(refusal).toContain('sys_seed_landed_key'); + expect(refusal).toContain('no reseed door'); + expect(app.rows.demotravel_expense_claim!.some((r) => r.id === 'c001')).toBe(false); + }); + it('a reference the loader drops from a row it wrote refuses that row with the field and keeps its second-pass patch; a row also refused on write counts once; a restore counts the written row as reinserted', async () => { /** Departments under a self-lookup `parent`. Finance breaks a budget floor, so its write is refused; a `parent` naming a department not in is dropped, as an optional lookup the loader cannot resolve. */ class DroppedParentApp extends TravelRulesApp { diff --git a/packages/qa/scenarios/test/runner/seed-door.ts b/packages/qa/scenarios/test/runner/seed-door.ts index de2de51256d..1a10cea40f8 100644 --- a/packages/qa/scenarios/test/runner/seed-door.ts +++ b/packages/qa/scenarios/test/runner/seed-door.ts @@ -16,30 +16,66 @@ * A row whose write then fails carries both entries. * * A dataset whose `mode` `SeedMode` does not accept (a retired `insert` or - * `replace`, #34613) is refused whole, as the real door refuses it: every row - * carries a `(write)` entry with `SeedMode`'s own message, and none is written. + * `replace`, #34613) is refused whole, as the real door refuses it + * (`loadStored`): one entry for the dataset, `field: 'mode'`, + * `targetField: '(dataset)'`, `recordIndex: 0`, with `SeedMode`'s own message, + * and no row written. + * + * `record` is the organization's record of landed seed rows + * (`sys_seed_landed_key`), as the real door keeps it: keyed on the object and + * the row's `id` (every runner dataset is keyed on `id`), with no package in + * the key, so every package the door loads shares it. With it, each row of an + * (`ignore`) dataset is read first (`record.holds`): a row the object holds is + * left as it is (`skipped`); a row it does not hold whose key is recorded is + * withheld under the install's `honour` posture (`skipped`, not written, no + * error, as `isWithdrawnRow` in the real loader) and written under the + * reseed's `reseed` posture; every row written is recorded. Without `record` + * the door keeps no record and writes every row, the shape before the record + * was modelled. */ import { SeedMode } from '@objectstack/spec/data'; import type { HttpAnswer } from '../../src/runner/app.js'; +/** The landed-seed-row record a double's door keeps ({@link seedDoorAnswer}), and the read it judges a row by. */ +export interface SeedDoorRecord { + /** `object/id` of every seed row the door has landed, across every package it loaded. */ + landed: Set; + /** Whether the object holds a row with this `id` now. */ + holds(object: string, id: string): boolean | Promise; + /** `honour` for an install (the default), `reseed` for the package's sample-data reseed. */ + posture?: 'honour' | 'reseed'; +} + export async function seedDoorAnswer( write: (object: string, row: Record) => Promise, manifest: Record, drops: (object: string, row: Record) => Record = () => ({}), + record?: SeedDoorRecord, ): Promise { const datasets = manifest.data as Array<{ object: string; mode?: unknown; records: Array> }>; let inserted = 0; + let skipped = 0; const errorList: Array> = []; for (const { object, mode, records } of datasets) { const judged = mode === undefined ? undefined : SeedMode.safeParse(mode); if (judged && !judged.success) { const said = judged.error.issues[0]?.message ?? `seed mode ${String(mode)} refused`; - for (const [recordIndex, sent] of records.entries()) - errorList.push({ sourceObject: object, field: '(write)', targetObject: object, targetField: 'id', attemptedValue: sent.id, recordIndex, message: said }); + errorList.push({ sourceObject: object, field: 'mode', targetObject: object, targetField: '(dataset)', attemptedValue: mode, recordIndex: 0, message: `Seed dataset for '${object}' was not loaded: ${said}` }); continue; } for (const [recordIndex, sent] of records.entries()) { + const key = `${object}/${String(sent.id)}`; + if (record) { + if (await record.holds(object, String(sent.id))) { + skipped++; + continue; + } + if ((record.posture ?? 'honour') === 'honour' && record.landed.has(key)) { + skipped++; + continue; + } + } const row = { ...sent }; for (const [field, targetObject] of Object.entries(drops(object, sent))) { errorList.push({ @@ -54,8 +90,10 @@ export async function seedDoorAnswer( delete row[field]; } const r = await write(object, row); - if (r.ok) inserted++; - else + if (r.ok) { + inserted++; + record?.landed.add(key); + } else errorList.push({ sourceObject: object, field: '(write)', @@ -67,6 +105,31 @@ export async function seedDoorAnswer( }); } } - const seeded = { mode: 'inline', inserted, updated: 0, skipped: 0, errors: errorList.length, errorList, droppedRefs: 0 }; + const seeded = { mode: 'inline', inserted, updated: 0, skipped, errors: errorList.length, errorList, droppedRefs: 0 }; return { ok: true, status: 200, body: { success: true, data: { manifestId: manifest.id, seeded } } }; } + +/** + * The sample-data reseed door's answer for an installed data-only package + * (`POST …/install-local/:manifestId/reseed-sample-data`), as the real door + * gives it: the package's datasets loaded again under the `reseed` posture + * ({@link seedDoorAnswer}), answered with the loader's four counts and no + * error list; a run that wrote nothing and found nothing already there is + * `422 RESEED_NO_ROWS`, and a package the door never installed is `404`. + */ +export async function reseedDoorAnswer( + write: (object: string, row: Record) => Promise, + manifest: Record | undefined, + manifestId: string, + record: SeedDoorRecord, + drops?: (object: string, row: Record) => Record, +): Promise { + if (!manifest) return { ok: false, status: 404, body: {}, code: 'RESOURCE_NOT_FOUND', message: `No marketplace install for ${manifestId}.` }; + const answer = await seedDoorAnswer(write, manifest, drops, { ...record, posture: 'reseed' }); + const { inserted, updated, skipped, errors, errorList } = (answer.body as { data: { seeded: { inserted: number; updated: number; skipped: number; errors: number; errorList: Array<{ message?: string }> } } }).data.seeded; + if (inserted + updated === 0 && !(errors === 0 && skipped > 0)) { + const message = errors > 0 ? `Reseed wrote no rows (${errors} error${errors === 1 ? '' : 's'}).${errorList[0]?.message ? ` First error: ${errorList[0].message}` : ''}` : 'Reseed wrote no rows. The package declares no seedable records for this runtime.'; + return { ok: false, status: 422, body: {}, code: 'RESEED_NO_ROWS', message }; + } + return { ok: true, status: 200, body: { success: true, data: { manifestId, inserted, updated, skipped, errors, withSampleData: true } } }; +} From 0dd0e0af8addc4c044342d782cfa33200f6d4999 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:19:35 +0000 Subject: [PATCH 18/19] docs(spec): name 18.7.0 as the release that retires seed.mode insert/replace The 18.6.0 version cut landed without this change, so the first @objectstack/spec release that refuses the two modes is the next one: this PR's spec changeset is a minor bump over 18.6.0 and no pending changeset in the fixed group bumps major. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL --- content/docs/data-modeling/seed-data.mdx | 4 ++-- packages/spec/src/data/seed.zod.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 7a736363e0f..25df2611c2f 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -136,7 +136,7 @@ record again: a 3-row fixture became 6, then 9 reference the first load had to leave empty stayed empty on the first row while only a later copy named the person. `replace` expected the caller to clear the table first, and no load ever clears one. Both were removed in -`@objectstack/spec` 18.6.0 ([#34613](https://github.com/objectstack-ai/objectstack/issues/34613)): +`@objectstack/spec` 18.7.0 ([#34613](https://github.com/objectstack-ai/objectstack/issues/34613)): - **Authoring refuses them.** `defineSeed`, `defineStack`, `os validate`, `os build` and the metadata save and publish doors reject `mode: 'insert'` or @@ -164,7 +164,7 @@ To convert a dataset, declare which field identifies a row, then drop the mode 3. **The records carry their own ids**: set `externalId: 'id'`. ```typescript -// Before — refused since @objectstack/spec 18.6.0 +// Before — refused since @objectstack/spec 18.7.0 defineSeed(ExchangeRate, { mode: 'replace', records: [{ key: 'USD_EUR', rate: 0.92 }], diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index 81410539784..c3a5e157711 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -45,11 +45,11 @@ const SEED_MODE_RETIRED_FIX = * carries that judgement. */ const SEED_MODE_INSERT_RETIRED = - "`seed.mode: 'insert'` was removed in @objectstack/spec 18.6.0 (ADR-0049 enforce-or-remove) — a seed is " + "`seed.mode: 'insert'` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — a seed is " + 'replayed on every boot, package install and publish, and `insert` matched no existing row, so every replay ' + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; const SEED_MODE_REPLACE_RETIRED = - "`seed.mode: 'replace'` was removed in @objectstack/spec 18.6.0 (ADR-0049 enforce-or-remove) — it inserted " + "`seed.mode: 'replace'` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it inserted " + 'every record and left clearing the table to the caller, and no load ever clears one, so every replay ' + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; From fdaf62130fe0b222ff50465d08718f01f7ee957e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 05:25:11 +0000 Subject: [PATCH 19/19] test: pin 18.7.0 in the retired seed-mode prescriptions; type the no-reseed harness The two spec pins and the protocol save-door pin match the prescription's release by regex; they follow the 18.7.0 wording. The restore pin that runs a harness without a reseed door now clears the method on the instance instead of narrowing the app's type to `never`. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL --- .../src/protocol.seed-external-id-refusal.test.ts | 2 +- packages/qa/scenarios/test/runner/orchestrate.test.ts | 3 ++- packages/spec/src/data/seed.test.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts index 46b9a84dbd9..778797ca31d 100644 --- a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts @@ -347,7 +347,7 @@ describe('[#28952] controls — an `externalId` the object has is not refused', it.each([['insert'], ['replace']])('the retired mode `%s` is refused with its prescription', async (mode) => { const { protocol, rows } = makeSession({ objects: OBJECTS }); const attempt = protocol.saveMetaItem({ type: 'seed', name: 'r_ins', item: seed('seedkey_other', 'sku', mode), mode: 'draft' }); - await expect(attempt).rejects.toThrow(new RegExp(`seed\\.mode: '${mode}'\` was removed in @objectstack/spec 18\\.6\\.0`)); + await expect(attempt).rejects.toThrow(new RegExp(`seed\\.mode: '${mode}'\` was removed in @objectstack/spec 18\\.7\\.0`)); expect(stored(rows, 'seed', 'r_ins')).toEqual([]); }); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index 73c34d2cc8f..17de0b23ece 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -1065,7 +1065,8 @@ describe('seedApp — a card row already past its entry state loads through the it('[#34613] a withheld row a restore cannot put back is refused by name with the reason, never booked as reinserted', async () => { const scenario = travel(); - const app = Object.assign(new TravelRulesApp(), { reseedManaged: undefined }); + const app = new TravelRulesApp(); + Object.assign(app, { reseedManaged: undefined }); // a harness with no reseed door await seedApp(scenario, app, []); const seeded = await seededRows(app, restoreObjects(scenario.card)); app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); diff --git a/packages/spec/src/data/seed.test.ts b/packages/spec/src/data/seed.test.ts index eaee698b61b..42a5dfdbf8d 100644 --- a/packages/spec/src/data/seed.test.ts +++ b/packages/spec/src/data/seed.test.ts @@ -15,8 +15,8 @@ describe('SeedMode', () => { // [#34613] The two unkeyed modes are retired (ADR-0049 enforce-or-remove): // each refusal names the mode, the version and the keyed fix. it.each([ - ['insert', /`seed\.mode: 'insert'` was removed in @objectstack\/spec 18\.6\.0.*every replay.*inserted each record again.*`mode: 'ignore'`.*`externalId`/s], - ['replace', /`seed\.mode: 'replace'` was removed in @objectstack\/spec 18\.6\.0.*no load ever clears one.*`mode: 'ignore'`.*`externalId`/s], + ['insert', /`seed\.mode: 'insert'` was removed in @objectstack\/spec 18\.7\.0.*every replay.*inserted each record again.*`mode: 'ignore'`.*`externalId`/s], + ['replace', /`seed\.mode: 'replace'` was removed in @objectstack\/spec 18\.7\.0.*no load ever clears one.*`mode: 'ignore'`.*`externalId`/s], ])('refuses the retired mode %s with its prescription', (mode, prescription) => { expect(() => SeedMode.parse(mode)).toThrow(prescription); const parsed = SeedSchema.safeParse({ object: 'task', mode, records: [{ name: 'a' }] });