From b802de30125f7a815f310a434c7a32b21590d0f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:21:55 +0000 Subject: [PATCH 1/6] test(metadata-protocol): pin the seed save door's refusal of an unknown object (red) Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .../protocol.seed-external-id-refusal.test.ts | 100 ++++++++++++++++-- 1 file changed, 91 insertions(+), 9 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 778797ca31d..76a822a17b3 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 @@ -25,8 +25,12 @@ * published; * - controls: a declared field, an injected column (`id`), every member of * a composite declared, `insert` and `replace` (they never match), a - * draft seed whose object is itself still a draft, an object neither - * registered nor drafted, and a `migrate-stored` re-save. + * draft seed whose object is itself still a draft, and a `migrate-stored` + * re-save. + * + * [#34864] And, in its own `describe` below, a seed whose `object` names no + * object at all: refused by the save door, naming the object; left to the + * load by the publish promotion and the restore doors. * * Each refusal is asserted by its code, its status, its path and its * finding's first clause, spelled out here. @@ -362,13 +366,6 @@ describe('[#28952] controls — an `externalId` the object has is not refused', expect(stored(rows, 'seed', 'r_new')).toEqual([`active|${PKG}|"sku"`]); }); - it('an object neither registered nor drafted is not judged here (the load reports it)', async () => { - const { protocol, rows } = makeSession(); - const res = await protocol.saveMetaItem({ type: 'seed', name: 'r_far', item: seed('seedkey_elsewhere', 'no_such_field'), mode: 'draft' }); - expect(res.success).toBe(true); - expect(stored(rows, 'seed', 'r_far')).toEqual(['draft|-|"no_such_field"']); - }); - it('a `migrate-stored` re-save of a stored seed is not judged', async () => { const { protocol, rows } = makeSession({ objects: OBJECTS }); const migrated = await protocol.saveMetaItem({ @@ -378,3 +375,88 @@ describe('[#28952] controls — an `externalId` the object has is not refused', expect(stored(rows, 'seed', 'r_old')).toEqual(['draft|-|"no_such_field"']); }); }); + +describe('[#34864] the seed save door — an `object` that names no object', () => { + /** The finding's first clause, spelled out: the seed, then the object it names. */ + const unknownObjectFinding = (seedName: string, objectName: string) => + `Seed '${seedName}' loads its records into object '${objectName}', which is not defined: `; + + const expectUnknownObject = (err: any, seedName: string, objectName: string, fix: string) => { + expect({ code: err?.code, status: err?.status }, String(err?.message)).toEqual({ code: 'INVALID_METADATA', status: 422 }); + expect(String(err.message).startsWith(`seed/${seedName} failed spec validation: `), String(err.message)).toBe(true); + expect(err.issues.map((i: any) => ({ path: i.path, code: i.code }))).toEqual([{ path: 'object', code: 'custom' }]); + const message = String(err.issues[0].message); + expect(message.startsWith(unknownObjectFinding(seedName, objectName)), message).toBe(true); + expect(message.endsWith(fix), message).toBe(true); + expect(message.length).toBeLessThanOrEqual(500); + }; + + it.each([ + ['a draft save into a package', { mode: 'draft', packageId: PKG }, 'or create the object first: a draft of it is enough for this draft.'], + ['a draft save naming no package', { mode: 'draft' }, 'or create the object first: a draft of it is enough for this draft.'], + ['a publish save', {}, 'or create and publish the object first.'], + ])('%s is refused 422 at `object`, naming the object, and nothing is stored or loaded', async (_label, saveOpts, fix) => { + const { protocol, rows, dataInserts } = makeSession({ objects: OBJECTS }); + + const err = await refusalOf(protocol.saveMetaItem({ + type: 'seed', name: 'r_nope', item: seed('seedkey_nope', 'name'), ...saveOpts, + })); + + expectUnknownObject(err, 'r_nope', 'seedkey_nope', fix); + expect(stored(rows, 'seed', 'r_nope')).toEqual([]); + expect(dataInserts).toEqual([]); + }); + + it('a publish save whose object is only a draft is refused: the load it runs has no object to write to', async () => { + const { protocol, rows } = makeSession(); + await protocol.saveMetaItem({ type: 'object', name: 'seedkey_new', item: object('seedkey_new'), mode: 'draft', packageId: PKG }); + + const err = await refusalOf(protocol.saveMetaItem({ type: 'seed', name: 'r_live', item: seed('seedkey_new', 'sku'), packageId: PKG })); + + expectUnknownObject(err, 'r_live', 'seedkey_new', 'or create and publish the object first.'); + expect(stored(rows, 'seed', 'r_live')).toEqual([]); + }); + + describe('controls — an object something resolves is not refused for its existence', () => { + it('a registered object (a dependency package\'s object answers the same registry read): saves as a draft and live', async () => { + const { protocol, rows } = makeSession({ objects: OBJECTS }); + expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_reg', item: seed('seedkey_other', 'sku'), mode: 'draft', packageId: PKG })).success).toBe(true); + expect((await protocol.saveMetaItem({ type: 'seed', name: 'r_reg_live', item: seed('seedkey_other', 'sku') })).success).toBe(true); + expect(stored(rows, 'seed', 'r_reg')).toEqual([`draft|${PKG}|"sku"`]); + }); + + it('an object drafted in the same package: the draft seed saves and is judged at its publish', async () => { + const { protocol, rows } = makeSession(); + await protocol.saveMetaItem({ type: 'object', name: 'seedkey_new', item: object('seedkey_new'), mode: 'draft', packageId: PKG }); + const saved = await protocol.saveMetaItem({ type: 'seed', name: 'r_new', item: seed('seedkey_new', 'sku'), mode: 'draft', packageId: PKG }); + expect(saved.success).toBe(true); + expect(stored(rows, 'seed', 'r_new')).toEqual([`draft|${PKG}|"sku"`]); + }); + + it('a `migrate-stored` re-save of a stored seed naming no object is not judged', async () => { + const { protocol, rows } = makeSession(); + const migrated = await protocol.saveMetaItem({ + type: 'seed', name: 'r_old', item: seed('seedkey_nope', 'name'), mode: 'draft', source: 'migrate-stored', + }); + expect(migrated.success).toBe(true); + expect(stored(rows, 'seed', 'r_old')).toEqual(['draft|-|"name"']); + }); + + it('the publish promotion leaves it to the load, as before: a seed draft stored before the rule publishes', async () => { + const { protocol, rows } = makeSession(); + plantSeedDraft(rows, 'r_far', seed('seedkey_nope', 'name')); + + const res = await protocol.publishPackageDrafts({ packageId: PKG }); + + expect(res.failed, JSON.stringify(res.failed)).toEqual([]); + expect(stored(rows, 'seed', 'r_far')).toEqual([`active|${PKG}|"name"`]); + }); + + it('the restore door leaves it to the load too', async () => { + const { protocol } = makeSession(); + await expect(protocol.refuseRestoredBodyTheSaveDoorRefuses( + 'seed', 'r_far', seed('seedkey_nope', 'name'), null, 'protocol.restoreMetaItem', + )).resolves.toBeUndefined(); + }); + }); +}); From 727228b5c9359440293ac25ec2554890e7622523 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:30:42 +0000 Subject: [PATCH 2/6] fix(metadata-protocol): the seed save door refuses a seed whose object is unknown; the probe names a missing object Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .../src/build-probes-user-message.test.ts | 50 ++++++++++ .../metadata-protocol/src/build-probes.ts | 33 +++++++ .../src/build-probes.user-text.ts | 61 +++++++++--- .../src/protocol-save-door-refusals.ts | 98 +++++++++++++++---- .../metadata-protocol/src/protocol-save.ts | 6 +- packages/metadata-protocol/src/protocol.ts | 22 ++++- 6 files changed, 233 insertions(+), 37 deletions(-) diff --git a/packages/metadata-protocol/src/build-probes-user-message.test.ts b/packages/metadata-protocol/src/build-probes-user-message.test.ts index e7a5b165b3c..1231e15bbf8 100644 --- a/packages/metadata-protocol/src/build-probes-user-message.test.ts +++ b/packages/metadata-protocol/src/build-probes-user-message.test.ts @@ -82,6 +82,8 @@ const ITEMS: Record = { }, 'object crm_project': { name: 'crm_project', label: PROJECTS, fields: { title: { type: 'text', label: 'Title' } } }, 'seed crm_task_seed': { object: 'crm_task', records: [] }, + // [#34864] A seed naming an object that does not exist. + 'seed crm_nope_seed': { object: 'crm_nope', records: [] }, 'view crm_task_list': { name: 'crm_task_list', label: VIEW, object: 'crm_task' }, 'dashboard crm_board': { name: 'crm_board', @@ -143,6 +145,13 @@ const engineThrowing: ProbeEngine = { throw new Error('no such table: crm_task'); }, }; +/** [#34864] An engine that answers its registered objects, and registers none: every read is refused. */ +const engineWithoutObjects: ProbeEngine = { + find: async (object) => { + throw new Error(`Object '${object}' not found`); + }, + getSchema: () => undefined, +}; /** One `where` on one row: equality and `{ $in: [...] }`; any other operator or combinator is refused. */ const matches = (row: Record, where: Record | undefined): boolean => @@ -266,6 +275,13 @@ const CASES: readonly ProbeCase[] = [ params: () => ({ object: TASKS, cause: 'unreadable' }), hidden: ['crm_task'], }, + { + title: 'a seed whose object does not exist', + code: 'seed_not_applied', // adr0112-ok: D6c build-probe diagnostics code + run: probe({ engine: engineWithoutObjects, published: [{ type: 'seed', name: 'crm_nope_seed' }] }), + params: () => ({ object: 'crm_nope', cause: 'missing' }), + hidden: [], + }, { title: 'a view whose read throws', code: 'view_read_failed', // adr0112-ok: D6c build-probe diagnostics code @@ -550,6 +566,16 @@ describe('every probe finding carries the person\'s sentence, in the request\'s '“Tasks”的示例数据没有加载成功,所以“Tasks”中还没有任何记录。请检查示例数据,然后重新发布。', ); + // [#34864] An object that does not exist: the sentence names it and the fix, not "publish again" alone. + const missing = byTitle('a seed whose object does not exist'); + expect(onlyIssue(await missing.run(['en-US'])).userMessage).toBe( + 'The sample data could not load, because "crm_nope" does not exist. Correct the object the sample data ' + + 'names, or create and publish "crm_nope", then publish again.', + ); + expect(onlyIssue(await missing.run(['zh-CN'])).userMessage).toBe( + '示例数据无法加载,因为“crm_nope”不存在。请更正示例数据所指的对象,或先创建并发布“crm_nope”,然后重新发布。', + ); + const empty = byTitle('a widget whose query returns nothing over an object that has rows'); expect(onlyIssue(await empty.run(['en-US'])).userMessage).toBe( 'The widget "Open tasks" on dashboard "Team board" shows no data, although "Tasks" has records. ' @@ -773,3 +799,27 @@ describe('the catalog holds exactly the probe\'s codes, each in every platform l ); }); }); + +describe('[#34864] a seed\'s object that does not exist is not a read that failed', () => { + const SEED = [{ type: 'seed', name: 'crm_nope_seed' }]; + + it('names the missing object to the agent, with the fix, and says "missing" to the person', async () => { + const issue = onlyIssue(await runBuildProbes({ engine: engineWithoutObjects, getItem: readItems, published: SEED })); + expect(issue).toMatchObject({ code: 'seed_not_applied', ref: { type: 'object', name: 'crm_nope' } }); // adr0112-ok: D6c build-probe diagnostics code + expect(issue.message).toBe('Seed "crm_nope_seed" was published but loads into object "crm_nope", which does not exist — no record was loaded.'); + expect(issue.fix).toBe("Correct the seed's `object` to the object's full name, or create and publish object \"crm_nope\", then republish the seed."); + expect(issue.userMessage).toBe(BUILD_PROBE_USER_TEXT.seed_not_applied.en({ object: 'crm_nope', cause: 'missing' })); + }); + + it.each<[string, ProbeEngine, GetItem]>([ + ['the engine registers the object, and its read fails', { ...engineWithoutObjects, getSchema: () => ({ name: 'crm_nope' }) }, readItems], + ['the engine cannot answer for its objects (no `getSchema`)', engineThrowing, readItems], + ['the engine answers none, but a published object of the name is held', engineWithoutObjects, + async (type, name) => (type === 'object' && name === 'crm_nope' ? { name: 'crm_nope', label: 'Nope' } : readItems(type, name))], + ])('CONTROL: %s — still `unreadable`', async (_label, engine, getItem) => { + const issue = onlyIssue(await runBuildProbes({ engine, getItem, published: SEED })); + expect(issue.code).toBe('seed_not_applied'); // adr0112-ok: D6c build-probe diagnostics code + expect(issue.message.startsWith('Seed "crm_nope_seed" probe could not read object "crm_nope": ')).toBe(true); + expect(issue.userMessage).toContain('could not be read after publishing'); + }); +}); diff --git a/packages/metadata-protocol/src/build-probes.ts b/packages/metadata-protocol/src/build-probes.ts index 266521d3718..c00b4f00808 100644 --- a/packages/metadata-protocol/src/build-probes.ts +++ b/packages/metadata-protocol/src/build-probes.ts @@ -276,6 +276,20 @@ async function hasRows( return Array.isArray(rows) && rows.length > 0; } +/** + * [#34864] The engine registers no object of this name: it answers its + * registered objects (`getSchema`) and answers none for this one. An engine + * without the read, or whose read throws, cannot say so, and answers `false`. + */ +function objectIsMissing(engine: ProbeEngine, objectName: string): boolean { + if (typeof engine.getSchema !== 'function') return false; + try { + return !engine.getSchema(objectName); + } catch { + return false; + } +} + /** Rows sampled from an object by the data probes, and distinct values probed per column. */ const PROBE_SAMPLE_ROWS = 50; @@ -545,6 +559,25 @@ export async function runBuildProbes(opts: RunBuildProbesOptions): Promise `대시보드 "${p.dashboard}"의 위젯 "${p.widget}"`, }; -/** `seed_not_applied`: the sample data did not land (`no-rows`), or the probe could not look (`unreadable`). */ +/** + * `seed_not_applied`: the sample data did not land (`no-rows`), the probe could not look (`unreadable`), or + * [#34864] the object the seed names does not exist (`missing`), so publishing again cannot help. + */ const SEED_NOT_APPLIED: UserTextEntry = { en: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `The sample data could not load, because "${p.object}" does not exist. Correct the object the sample ` + + `data names, or create and publish "${p.object}", then publish again.` + : p.cause === 'unreadable' ? `The sample data for "${p.object}" could not be checked, because "${p.object}" could not be read after ` + `publishing. Publish again, and contact your administrator if it happens again.` : `The sample data for "${p.object}" did not load, so "${p.object}" has no records yet. Check the sample ` + `data, then publish again.`, 'zh-Hans': (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `示例数据无法加载,因为“${p.object}”不存在。请更正示例数据所指的对象,或先创建并发布“${p.object}”,然后重新发布。` + : p.cause === 'unreadable' ? `无法检查“${p.object}”的示例数据,因为发布后无法读取“${p.object}”。请重新发布;如果问题再次出现,请联系管理员。` : `“${p.object}”的示例数据没有加载成功,所以“${p.object}”中还没有任何记录。请检查示例数据,然后重新发布。`, 'zh-Hant': (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `示例資料無法載入,因為「${p.object}」不存在。請更正示例資料所指的物件,或先建立並發布「${p.object}」,然後重新發布。` + : p.cause === 'unreadable' ? `無法檢查「${p.object}」的示例資料,因為發布後無法讀取「${p.object}」。請重新發布;如果問題再次出現,請聯絡管理員。` : `「${p.object}」的示例資料沒有載入成功,所以「${p.object}」中還沒有任何記錄。請檢查示例資料,然後重新發布。`, es: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `Los datos de ejemplo no se pudieron cargar, porque "${p.object}" no existe. Corrija el objeto que indican ` + + `los datos de ejemplo, o cree y publique "${p.object}", y vuelva a publicar.` + : p.cause === 'unreadable' ? `No se pudieron comprobar los datos de ejemplo de "${p.object}", porque no se pudo leer "${p.object}" ` + `después de publicar. Vuelva a publicar y, si ocurre de nuevo, póngase en contacto con su administrador.` : `Los datos de ejemplo de "${p.object}" no se cargaron, por lo que "${p.object}" aún no tiene registros. ` + `Revise los datos de ejemplo y vuelva a publicar.`, ar: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `تعذّر تحميل البيانات التجريبية، لأن "${p.object}" غير موجود. صحّح الكائن الذي تشير إليه البيانات التجريبية، ` + + `أو أنشئ "${p.object}" وانشره، ثم أعد النشر.` + : p.cause === 'unreadable' ? `تعذّر التحقق من البيانات التجريبية لـ "${p.object}"، لأنه تعذّرت قراءة "${p.object}" بعد النشر. ` + `أعد النشر، وإذا تكرر ذلك فتواصل مع المسؤول.` : `لم يتم تحميل البيانات التجريبية لـ "${p.object}"، لذلك لا يحتوي "${p.object}" على أي سجلات بعد. ` + `راجع البيانات التجريبية ثم أعد النشر.`, fr: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `Les données d’exemple n’ont pas pu être chargées, car « ${p.object} » n’existe pas. Corrigez l’objet ` + + `indiqué par les données d’exemple, ou créez et publiez « ${p.object} », puis publiez à nouveau.` + : p.cause === 'unreadable' ? `Les données d’exemple de « ${p.object} » n’ont pas pu être vérifiées, car « ${p.object} » n’a pas pu ` + `être lu après la publication. Publiez à nouveau et, si cela se reproduit, contactez votre administrateur.` : `Les données d’exemple de « ${p.object} » n’ont pas été chargées ; « ${p.object} » ne contient donc ` + `encore aucun enregistrement. Vérifiez les données d’exemple, puis publiez à nouveau.`, 'pt-BR': (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `Os dados de exemplo não puderam ser carregados, porque "${p.object}" não existe. Corrija o objeto ` + + `indicado nos dados de exemplo, ou crie e publique "${p.object}", e publique novamente.` + : p.cause === 'unreadable' ? `Não foi possível verificar os dados de exemplo de "${p.object}", porque não foi possível ler ` + `"${p.object}" após a publicação. Publique novamente e, se acontecer de novo, entre em contato com o ` + `administrador.` : `Os dados de exemplo de "${p.object}" não foram carregados, então "${p.object}" ainda não tem registros. ` + `Verifique os dados de exemplo e publique novamente.`, ru: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `Примеры данных не удалось загрузить: объекта «${p.object}» не существует. Исправьте объект, указанный ` + + `в примерах данных, или создайте и опубликуйте «${p.object}», затем опубликуйте снова.` + : p.cause === 'unreadable' ? `Не удалось проверить примеры данных для объекта «${p.object}»: после публикации объект «${p.object}» ` + `не удалось прочитать. Опубликуйте снова, а если это повторится, обратитесь к администратору.` : `Примеры данных для объекта «${p.object}» не загрузились, поэтому в объекте «${p.object}» пока нет ` + `записей. Проверьте примеры данных и опубликуйте снова.`, de: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `Die Beispieldaten konnten nicht geladen werden, weil „${p.object}“ nicht existiert. Korrigieren Sie das ` + + `Objekt, das die Beispieldaten nennen, oder erstellen und veröffentlichen Sie „${p.object}“, und ` + + `veröffentlichen Sie dann erneut.` + : p.cause === 'unreadable' ? `Die Beispieldaten für „${p.object}“ konnten nicht geprüft werden, weil „${p.object}“ nach dem ` + `Veröffentlichen nicht gelesen werden konnte. Veröffentlichen Sie erneut und wenden Sie sich an Ihren ` + `Administrator, wenn das wieder passiert.` : `Die Beispieldaten für „${p.object}“ wurden nicht geladen, daher enthält „${p.object}“ noch keine ` + `Datensätze. Prüfen Sie die Beispieldaten und veröffentlichen Sie dann erneut.`, ja: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `「${p.object}」が存在しないため、サンプルデータを読み込めませんでした。サンプルデータが指すオブジェクトを` + + `修正するか、「${p.object}」を作成して公開してから、もう一度公開してください。` + : p.cause === 'unreadable' ? `公開後に「${p.object}」を読み取れなかったため、「${p.object}」のサンプルデータを確認できませんでした。` + `もう一度公開し、再び発生する場合は管理者にお問い合わせください。` : `「${p.object}」のサンプルデータが読み込まれなかったため、「${p.object}」にはまだレコードがありません。` + `サンプルデータを確認してから、もう一度公開してください。`, ko: (p) => - p.cause === 'unreadable' + p.cause === 'missing' + ? `"${p.object}"이(가) 존재하지 않아 샘플 데이터를 불러오지 못했습니다. 샘플 데이터가 가리키는 개체를 ` + + `수정하거나 "${p.object}"을(를) 만들어 게시한 다음 다시 게시하세요.` + : p.cause === 'unreadable' ? `게시 후 "${p.object}"을(를) 읽을 수 없어 "${p.object}"의 샘플 데이터를 확인하지 못했습니다. ` + `다시 게시하고, 문제가 반복되면 관리자에게 문의하세요.` : `"${p.object}"의 샘플 데이터를 불러오지 못해 "${p.object}"에 아직 레코드가 없습니다. ` + diff --git a/packages/metadata-protocol/src/protocol-save-door-refusals.ts b/packages/metadata-protocol/src/protocol-save-door-refusals.ts index 2a2c693a376..72f70d5f806 100644 --- a/packages/metadata-protocol/src/protocol-save-door-refusals.ts +++ b/packages/metadata-protocol/src/protocol-save-door-refusals.ts @@ -1004,39 +1004,29 @@ const KEYED_SEED_MODES: ReadonlySet = new Set(['upsert', 'update', 'igno * The body of `ObjectStackProtocolImplementation#seedExternalIdSaveRefusal`; * the method's docblock there is its contract. Written here, beside the other * refusals the save door and the publish promotion ask in turn, rather than - * moved: its reads are the engine's registered object and, on a draft save, - * the object drafts. + * moved: its reads are the engine's registered object, the by-name object + * read (`readMetaItem`) and, on a draft save, the object drafts. */ export async function seedExternalIdSaveRefusal( - this: Pick, + this: Pick, singularType: string, item: unknown, name: string, pending?: 'drafts' | ReadonlyArray, writeFace?: MetadataWriteFace, + door?: 'save', ): Promise<(Error & { code: 'INVALID_METADATA'; status: 422; issues: MetadataIssueEntry[] }) | undefined> { if (singularType !== 'seed') return undefined; if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined; const seed = item as { object?: unknown; mode?: unknown; externalId?: unknown }; if (typeof seed.object !== 'string' || seed.object === '') return undefined; const objectName = seed.object; - // `SeedSchema`'s defaults, as the loader applies them (the `mode` default, - // read from the schema rather than restated here [#30081], and - // `externalId: 'name'`): a body read before the parse filled them keys the - // same way a parsed one does. - const mode = typeof seed.mode === 'string' ? seed.mode : SeedSchema.shape.mode.parse(undefined); - if (!KEYED_SEED_MODES.has(mode)) return undefined; - const declared = seed.externalId !== undefined; - const externalId = declared ? seed.externalId : 'name'; - const composite = Array.isArray(externalId); - const members = (composite ? externalId : [externalId]) as unknown[]; // The object as the publish will have it: a draft of it in the same // package batch, else the engine's registered definition (its fields as // the runtime serves them, extension fields and injected columns // included). On a draft save, an object that is itself still a draft may // gain the field before it is published, so the seed is judged at its - // publish instead. An object resolved by neither is not judged here: - // the load reports an object it cannot find. + // publish instead. const pendingObject = Array.isArray(pending) ? pending.find((o) => (o as { name?: unknown } | null)?.name === objectName) as { fields?: unknown } | undefined : undefined; @@ -1044,9 +1034,27 @@ export async function seedExternalIdSaveRefusal( && (await this.listDrafts({ type: 'object' })).drafts.some((d) => d.name === objectName)) { return undefined; } - const registered = (this.engine?.registry as { getObject?(name: string): unknown } | undefined) - ?.getObject?.(objectName) as { fields?: unknown } | undefined; - if (!pendingObject && !registered) return undefined; + const registry = this.engine?.registry as { getObject?(name: string): unknown } | undefined; + const registered = registry?.getObject?.(objectName) as { fields?: unknown } | undefined; + // [#34864] An object resolved by neither: the save door refuses it, so + // the seed is never stored to load into nothing; the publish promotion + // and the restore doors leave it to the load, which reports an object it + // cannot find (#27393 keeps the publish as it is). + if (!pendingObject && !registered) { + return door === 'save' + ? unknownSeedObjectRefusal(this, typeof registry?.getObject === 'function', objectName, name, pending, writeFace) + : undefined; + } + // `SeedSchema`'s defaults, as the loader applies them (the `mode` default, + // read from the schema rather than restated here [#30081], and + // `externalId: 'name'`): a body read before the parse filled them keys the + // same way a parsed one does. + const mode = typeof seed.mode === 'string' ? seed.mode : SeedSchema.shape.mode.parse(undefined); + if (!KEYED_SEED_MODES.has(mode)) return undefined; + const declared = seed.externalId !== undefined; + const externalId = declared ? seed.externalId : 'name'; + const composite = Array.isArray(externalId); + const members = (composite ? externalId : [externalId]) as unknown[]; const fieldNames = new Set(resolveInjectedSystemColumns(pendingObject ?? registered).names); for (const def of [registered, pendingObject]) { const fields = def?.fields; @@ -1078,3 +1086,57 @@ export async function seedExternalIdSaveRefusal( err.issues = issues; return err; } + +/** + * [#34864] The save door's refusal of a seed whose `object` neither a draft + * of the same save (asked by the caller) nor the engine's registry resolves. + * Before it, such a seed was stored 200; its publish then reported + * `published` with a failed load, and the probe asked the author to publish + * again, which could never work. + * + * Unknown follows the permission-set grant refusal ({@link unknownGrantObjectSaveRefusal}): + * a registry that cannot look an object up by name cannot say a name is + * unknown, so nothing is refused on it; an object the environment stores or + * the code layer defines that the registry has not (yet) registered is known + * (`readMetaItem`); a name two packages hold is held, so known too. An object + * of a dependency package answers the same registry read as the package's + * own. Answered as the schema gate answers: `422 INVALID_METADATA`, one + * finding at `object`, naming the seed and the object, and the fix. + */ +async function unknownSeedObjectRefusal( + host: Pick, + canLookUp: boolean, + objectName: string, + name: string, + pending: 'drafts' | ReadonlyArray | undefined, + writeFace: MetadataWriteFace | undefined, +): Promise<(Error & { code: 'INVALID_METADATA'; status: 422; issues: MetadataIssueEntry[] }) | undefined> { + if (!canLookUp) return undefined; + try { + if ((await host.readMetaItem({ type: 'object', name: objectName }))?.item) return undefined; + } catch (error) { + if (error instanceof PackageScopedNameRefusedError) return undefined; + throw error; + } + const draft = pending === 'drafts'; + const looked = draft + ? 'no package registers an object of that name, and no object, published or draft, is saved here' + : 'no package registers an object of that name, and no published object is saved here'; + const fix = draft + ? 'or create the object first: a draft of it is enough for this draft.' + : 'or create and publish the object first.'; + const issues: MetadataIssueEntry[] = [{ + path: 'object', + message: `Seed '${name}' loads its records into object '${objectName}', which is not defined: ${looked}, ` + + "so publishing it would load no record. Correct the name to the object's full name " + + `(e.g. 'crm_lead', not 'lead'), ${fix}`, + code: 'custom', + }]; + const err = new Error( + `seed/${name} failed spec validation: ${specValidationFindings(writeFace, issues)}`, + ) as Error & { code: 'INVALID_METADATA'; status: 422; issues: MetadataIssueEntry[] }; + err.code = 'INVALID_METADATA'; + err.status = 422; + err.issues = issues; + return err; +} diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index d5b5ad9a9a4..1d47fb7d4f9 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1784,10 +1784,14 @@ export class ProtocolSaveFacet { // before the authoring gate and every write: every load of it would // insert each record again. A draft seed whose object is itself still a // draft is judged at its publish. A `migrate-stored` re-save rewrites an - // existing row and is not judged. See {@link seedExternalIdSaveRefusal}. + // existing row and is not judged. [#34864] This door alone (`'save'`) + // also refuses a seed whose object nothing resolves: no draft (on a + // draft save), no registered, stored or code-defined object. See + // {@link seedExternalIdSaveRefusal}. if (writeSource !== 'migrate-stored') { const seedKeyRefusal = await host.seedExternalIdSaveRefusal( singularType, request.item, request.name, mode === 'draft' ? 'drafts' : undefined, request.writeFace, + 'save', ); if (seedKeyRefusal) throw seedKeyRefusal; } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 73dd33deb17..36f72037c66 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -9064,10 +9064,20 @@ export class ObjectStackProtocolImplementation implements * same package batch (`pending` as the batch's object declarations), else * the engine's registered definition, whose fields include extension * fields; the columns the registry injects (`id`, the audit and tenant - * columns) count. Not refused when the object cannot be resolved: on a - * draft save, an object that is itself still a draft (`pending` as - * `'drafts'`) is judged at the seed's publish; an object resolved by - * neither is reported by the load. + * columns) count. On a draft save, an object that is itself still a draft + * (`pending` as `'drafts'`) is judged at the seed's publish. + * + * [#34864] An object resolved by none of these, nor by the by-name object + * read (an object stored here or defined in code that the registry has + * not registered yet), is refused by the save door alone (`door` as + * `'save'`), whatever the mode: `422 INVALID_METADATA`, one finding at + * `object` naming the object and the fix (correct the name, or create the + * object first: a draft of it is enough for a draft seed, a live seed + * needs it published). Before this, such a seed was stored and its + * publish answered `published` with a load that wrote nothing. The + * publish promotion and the restore doors pass no `door` and leave that + * object to the load, which reports it (#27393 keeps the publish as it + * is). A registry that cannot look an object up by name refuses nothing. * * Asked in draft and in publish mode by {@link saveMetaItem} after the * schema gate (except a `migrate-stored` re-save, the platform healing @@ -9088,13 +9098,15 @@ export class ObjectStackProtocolImplementation implements name: string, pending?: 'drafts' | ReadonlyArray, writeFace?: MetadataWriteFace, + door?: 'save', ): Promise<(Error & { code: 'INVALID_METADATA'; status: 422; issues: MetadataIssueEntry[] }) | undefined> { const readEngine = () => this.engine; const host: ThisParameterType = { get engine() { return readEngine(); }, listDrafts: (...a) => this.listDrafts(...a), + readMetaItem: (...a) => this.readMetaItem(...a), }; - return seedExternalIdSaveRefusal.call(host, singularType, item, name, pending, writeFace); + return seedExternalIdSaveRefusal.call(host, singularType, item, name, pending, writeFace, door); } /** From 93e394d908e9880ab2365df02612e048bb27f285 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:37:36 +0000 Subject: [PATCH 3/6] test(objectql): stage the missing-object seed drafts at rest; register the seeded object Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .../34864-seed-unknown-object-save-door.md | 18 ++++++++++++++++++ packages/objectql/src/protocol-meta.test.ts | 3 +++ ...-package-drafts-seed-receipt-counts.test.ts | 10 +++++++++- .../publish-seed-receipt-landed-ids.test.ts | 10 +++++++++- 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 .changeset/34864-seed-unknown-object-save-door.md diff --git a/.changeset/34864-seed-unknown-object-save-door.md b/.changeset/34864-seed-unknown-object-save-door.md new file mode 100644 index 00000000000..7d196b1f5c3 --- /dev/null +++ b/.changeset/34864-seed-unknown-object-save-door.md @@ -0,0 +1,18 @@ +--- +'@objectstack/metadata-protocol': minor +--- + +fix(metadata-protocol): the save door refuses a seed whose object does not exist, and the publish probe names a missing object instead of asking to publish again + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + +**The save door refuses a seed bound to an unknown object.** `saveMetaItem` (the `PUT /api/v1/meta/seed/:name` door, the MCP draft save and every other caller) now answers `422 INVALID_METADATA` for a `seed` whose `object` no package registers and no stored or code-defined object carries, with one finding at `object` that names the seed, the object and the fix. Before this, such a seed was stored 200; its publish answered `published` while the load wrote nothing. + +- A draft save also accepts an object that is itself only a draft (it is judged at the seed's publish, as before). A live save needs the object published. +- An object of a dependency package, or any object the registry serves, is accepted as before. +- Unchanged: the publish promotion and the restore doors do not refuse such a seed (the load reports it, and a publish keeps going), and a `migrate-stored` re-save is not judged. + +Fix for a refused save: correct `object` to the object's full name (for example `crm_lead`, not `lead`), or create the object first, as a draft for a draft seed or published for a live one. + +**The publish probe names a missing object.** When a published seed's object does not exist, the `seed_not_applied` finding now says so: `message` and `fix` name the missing object, and the person's sentence (`userMessage`, cause `missing`, in every platform locale) tells them to correct the object or create and publish it. A read that fails on an object that does exist still asks to publish again (cause `unreadable`). diff --git a/packages/objectql/src/protocol-meta.test.ts b/packages/objectql/src/protocol-meta.test.ts index 37534156630..e2d761d1c1c 100644 --- a/packages/objectql/src/protocol-meta.test.ts +++ b/packages/objectql/src/protocol-meta.test.ts @@ -1548,6 +1548,9 @@ describe('ObjectStackProtocolImplementation - Metadata Persistence', () => { // true` — so the tier keeps a live specimen. it('accepts brand-new mapping and seed (allowRuntimeCreate:true)', async () => { mockEngine.findOne.mockResolvedValue(null); + // [#34864] The seed's object exists: the save door refuses a seed + // whose object nothing resolves. + registry.registerObject({ name: 'case', label: 'Case', fields: { name: { type: 'text', label: 'Name' } } } as never); const mappingResult = await scoped.saveMetaItem({ type: 'mapping', diff --git a/packages/objectql/src/publish-package-drafts-seed-receipt-counts.test.ts b/packages/objectql/src/publish-package-drafts-seed-receipt-counts.test.ts index 064618da3ff..ee2d4a5c77a 100644 --- a/packages/objectql/src/publish-package-drafts-seed-receipt-counts.test.ts +++ b/packages/objectql/src/publish-package-drafts-seed-receipt-counts.test.ts @@ -156,7 +156,15 @@ async function stage( drafts: Array<{ type: string; name: string; item: unknown }>, ): Promise { for (const d of drafts) { - await (p as any).saveMetaItem({ type: d.type, name: d.name, item: d.item, mode: 'draft', packageId: PKG }); + // [#34864] The save door refuses a seed whose object does not exist, so + // a seed draft naming `MISSING` stands for one stored before that rule: + // written through the platform's own `migrate-stored` re-save, the one + // save the rule does not judge. Its publish is unchanged (#27393). + const atRest = d.type === 'seed' && (d.item as { object?: unknown }).object === MISSING; + await (p as any).saveMetaItem({ + type: d.type, name: d.name, item: d.item, mode: 'draft', packageId: PKG, + ...(atRest ? { source: 'migrate-stored' } : {}), + }); } } diff --git a/packages/objectql/src/publish-seed-receipt-landed-ids.test.ts b/packages/objectql/src/publish-seed-receipt-landed-ids.test.ts index ac8305d6244..5a2811d9c63 100644 --- a/packages/objectql/src/publish-seed-receipt-landed-ids.test.ts +++ b/packages/objectql/src/publish-seed-receipt-landed-ids.test.ts @@ -153,7 +153,15 @@ async function stage( drafts: Array<{ type: string; name: string; item: unknown }>, ): Promise { for (const d of drafts) { - await (p as any).saveMetaItem({ type: d.type, name: d.name, item: d.item, mode: 'draft', packageId: PKG }); + // [#34864] The save door refuses a seed whose object does not exist, so + // a seed draft naming `MISSING` stands for one stored before that rule: + // written through the platform's own `migrate-stored` re-save, the one + // save the rule does not judge. Its publish is unchanged (#27393). + const atRest = d.type === 'seed' && (d.item as { object?: unknown }).object === MISSING; + await (p as any).saveMetaItem({ + type: d.type, name: d.name, item: d.item, mode: 'draft', packageId: PKG, + ...(atRest ? { source: 'migrate-stored' } : {}), + }); } } From d83266275c31ce2de3b21994ab7eac1b2304e597 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:04:17 +0000 Subject: [PATCH 4/6] fix(metadata-protocol): keep the facade within its ceiling; state the ADR-0087 disposition Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .../34864-seed-unknown-object-save-door.md | 2 ++ .../src/protocol-save-door-refusals.ts | 9 ++++++++- packages/metadata-protocol/src/protocol.ts | 17 +++-------------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/.changeset/34864-seed-unknown-object-save-door.md b/.changeset/34864-seed-unknown-object-save-door.md index 7d196b1f5c3..c6ab31c3732 100644 --- a/.changeset/34864-seed-unknown-object-save-door.md +++ b/.changeset/34864-seed-unknown-object-save-door.md @@ -16,3 +16,5 @@ Metadata-protocol: narrowed Fix for a refused save: correct `object` to the object's full name (for example `crm_lead`, not `lead`), or create the object first, as a draft for a draft seed or published for a live one. **The publish probe names a missing object.** When a published seed's object does not exist, the `seed_not_applied` finding now says so: `message` and `fix` name the missing object, and the person's sentence (`userMessage`, cause `missing`, in every platform locale) tells them to correct the object or create and publish it. A read that fails on an object that does exist still asks to publish again (cause `unreadable`). + + diff --git a/packages/metadata-protocol/src/protocol-save-door-refusals.ts b/packages/metadata-protocol/src/protocol-save-door-refusals.ts index 72f70d5f806..ad78c37b85d 100644 --- a/packages/metadata-protocol/src/protocol-save-door-refusals.ts +++ b/packages/metadata-protocol/src/protocol-save-door-refusals.ts @@ -1101,7 +1101,14 @@ export async function seedExternalIdSaveRefusal( * (`readMetaItem`); a name two packages hold is held, so known too. An object * of a dependency package answers the same registry read as the package's * own. Answered as the schema gate answers: `422 INVALID_METADATA`, one - * finding at `object`, naming the seed and the object, and the fix. + * finding at `object`, naming the seed and the object, and the fix: correct + * the name, or create the object first (a draft of it is enough for a draft + * seed; a live seed needs it published). + * + * Asked by the save door alone (`door` as `'save'`), in draft and in publish + * mode, never for a `migrate-stored` re-save. The publish promotion and the + * restore doors pass no `door` and leave such an object to the load, which + * reports it (#27393 keeps the publish as it is). */ async function unknownSeedObjectRefusal( host: Pick, diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 36f72037c66..a41ea1fd0f2 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -9064,20 +9064,9 @@ export class ObjectStackProtocolImplementation implements * same package batch (`pending` as the batch's object declarations), else * the engine's registered definition, whose fields include extension * fields; the columns the registry injects (`id`, the audit and tenant - * columns) count. On a draft save, an object that is itself still a draft - * (`pending` as `'drafts'`) is judged at the seed's publish. - * - * [#34864] An object resolved by none of these, nor by the by-name object - * read (an object stored here or defined in code that the registry has - * not registered yet), is refused by the save door alone (`door` as - * `'save'`), whatever the mode: `422 INVALID_METADATA`, one finding at - * `object` naming the object and the fix (correct the name, or create the - * object first: a draft of it is enough for a draft seed, a live seed - * needs it published). Before this, such a seed was stored and its - * publish answered `published` with a load that wrote nothing. The - * publish promotion and the restore doors pass no `door` and leave that - * object to the load, which reports it (#27393 keeps the publish as it - * is). A registry that cannot look an object up by name refuses nothing. + * columns) count; on a draft save, an object itself still a draft (`pending` + * as `'drafts'`) is judged at the seed's publish. [#34864] One nothing resolves is + * refused by the save door alone (`door`): `unknownSeedObjectRefusal`'s docblock. * * Asked in draft and in publish mode by {@link saveMetaItem} after the * schema gate (except a `migrate-stored` re-save, the platform healing From 913a0d5dc253fa4a9470002b4395d26331c6447a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:05:08 +0000 Subject: [PATCH 5/6] chore(changeset): name the ADR-0087 entry this narrowing registers Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .changeset/34864-seed-unknown-object-save-door.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34864-seed-unknown-object-save-door.md b/.changeset/34864-seed-unknown-object-save-door.md index c6ab31c3732..ce110c9e07b 100644 --- a/.changeset/34864-seed-unknown-object-save-door.md +++ b/.changeset/34864-seed-unknown-object-save-door.md @@ -17,4 +17,4 @@ Fix for a refused save: correct `object` to the object's full name (for example **The publish probe names a missing object.** When a published seed's object does not exist, the `seed_not_applied` finding now says so: `message` and `fix` name the missing object, and the person's sentence (`userMessage`, cause `missing`, in every platform locale) tells them to correct the object or create and publish it. A read that fails on an object that does exist still asks to publish again (cause `unreadable`). - + From 468886742c089180014c6d8dc1da1d0c68b59405 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:49:23 +0000 Subject: [PATCH 6/6] chore(spec): register the ADR-0087 entry seed-object-unknown-refused Claude-Session: https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x Co-authored-by: Claude --- .../18.seed-object-unknown-refused.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 packages/spec/src/migrations/entries/semantic/18.seed-object-unknown-refused.ts diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-object-unknown-refused.ts b/packages/spec/src/migrations/entries/semantic/18.seed-object-unknown-refused.ts new file mode 100644 index 00000000000..912fdb8a16e --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seed-object-unknown-refused.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'seed-object-unknown-refused', + surface: + 'data.Seed.object on a seed saved through the metadata save door (PUT /api/v1/meta/seed/NAME in draft or ' + + 'publish mode, the MCP draft save): a seed whose object no package registers and no stored or code-defined ' + + 'object carries', + replacement: + 'Name the object by its full name (crm_lead, not lead), or create the object first: a draft of it is enough ' + + 'for a draft seed, and a live seed needs it published', + reason: + 'A seed loads its records into the object it names. The save door stored a seed naming an object that does ' + + 'not exist (200); its publish then answered published while the load wrote nothing, and the post-publish ' + + 'probe asked the author to publish again, which could never work. The save door now refuses it 422 ' + + 'INVALID_METADATA at object, naming the object. The publish promotion and the restore doors are unchanged: ' + + 'a seed stored before this refusal still publishes, and its load reports the missing object. There is no ' + + 'mechanical rewrite: whether the author meant another object or one still to be created is a judgement ' + + 'about the seed.', + acceptanceCriteria: + 'PUT /api/v1/meta/seed/NAME?mode=draft&package=PKG with object naming an object the package has published, ' + + 'or drafted, answers 200; POST /api/v1/packages/PKG/publish-drafts publishes it and its seedApplied.success ' + + 'is true.', +};