From 3611170e96e10694ba92570a8ad65412372850ba Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:57:57 +0000 Subject: [PATCH 1/7] wip(metadata-protocol): stored view bulkActions judged with declared actions; served-invalid verdict Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- packages/cli/src/commands/migrate/meta.ts | 14 +- .../metadata-protocol/src/protocol-save.ts | 47 +++- .../src/protocol-stored-view-selection.ts | 260 ++++++++++++++++++ .../metadata-protocol/src/stored-migration.ts | 78 +++++- 4 files changed, 392 insertions(+), 7 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-stored-view-selection.ts diff --git a/packages/cli/src/commands/migrate/meta.ts b/packages/cli/src/commands/migrate/meta.ts index 62e6334bfe4..3d5a74d83c2 100644 --- a/packages/cli/src/commands/migrate/meta.ts +++ b/packages/cli/src/commands/migrate/meta.ts @@ -1939,6 +1939,7 @@ export default class MigrateMeta extends Command { rewritten: 0, skipped: 0, failed: 0, + servedInvalid: 0, rows: [], decisionModeReview: [], viewAllFieldsReview: [], @@ -2008,12 +2009,23 @@ export default class MigrateMeta extends Command { : '') + '.', ); - } else { + } else if (report.pending > 0) { printWarning( `${report.pending} row(s) carry a pre-protocol shape. They read canonically today (the chain ` + 'runs on every load); re-run with --apply to persist it.', ); } + // [#38923] Beside whichever line above: a row the runtime serves + // invalid is what a green run must never hide. The report lists each + // one with its id and fix; this line says it is why the run is red. + const servedInvalid = report.servedInvalid ?? 0; + if (servedInvalid > 0) { + printError( + `${servedInvalid} stored row(s) are served INVALID by the runtime on protocol ${report.protocol} — ` + + 'each is listed above with its id, the site the schema refuses and its fix. The run is not clean ' + + 'until each is fixed.', + ); + } } } catch (error: any) { exitCode = 1; diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index a319a51b134..ff970cb1e52 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -40,6 +40,7 @@ import { } from './protocol-translated-echo.js'; import { PROTOCOL_VERSION, stripReadDecorations } from '@objectstack/spec/kernel'; import { collectDecisionModeReview, collectViewAllFieldsReview } from './stored-migration.js'; +import { judgeStoredViewBulkActions, servedInvalidOf } from './protocol-stored-view-selection.js'; import type { StoredFlowCanonicalization, StoredMigrationNotice, @@ -2688,6 +2689,7 @@ export class ProtocolSaveFacet { rewritten: 0, skipped: 0, failed: 0, + servedInvalid: 0, rows: [], decisionModeReview: [], viewAllFieldsReview: [], @@ -2761,6 +2763,8 @@ export class ProtocolSaveFacet { return; } report[entry.outcome]++; + // [#38923] The runtime's own verdict, counted whatever the outcome. + if (entry.servedInvalid) report.servedInvalid++; report.rows.push(entry); }; @@ -2886,6 +2890,7 @@ export class ProtocolSaveFacet { if (!canonicalizeFlow) { record({ ...base, + ...servedInvalidOf(singular, body), outcome: 'skipped', reason: 'flows canonicalize at AutomationEngine.registerFlow — its registration ' + 'checks need the live node registry, and no automation service ' @@ -2901,6 +2906,7 @@ export class ProtocolSaveFacet { // already broken at runtime. Report it; never persist a guess. record({ ...base, + ...servedInvalidOf(singular, body), outcome: 'failed', reason: `the flow does not canonicalize: ${e?.message ?? String(e)}`, }); @@ -2913,6 +2919,7 @@ export class ProtocolSaveFacet { if (!overlayAllowed && !runtimeCreateAllowed) { record({ ...base, + ...servedInvalidOf(singular, flowResult ? body : host.convertStoredItemDetailed(singular, body).item), outcome: 'skipped', reason: `type '${singular}' has no repository write path (allowEnvironmentOverlay and ` + 'allowRuntimeCreate are both false), so a rewrite would record no history', @@ -2942,11 +2949,26 @@ export class ProtocolSaveFacet { // [#25279] A stored object's `external` binding is judged against the // datasource the save door reads for it, so the listing names the // row exactly when that door refuses its next save. - const { item, notices, todos } = flowResult + const converted = flowResult ? { item: flowResult.storable, notices: flowResult.notices, todos: flowResult.todos ?? [] } : host.convertStoredItemDetailed( singular, body, undefined, await host.storedRowKnownDatasources(singular, body), ); + // [#38923] What the runtime serves for this row today (`convertStoredItem` + // converts every type but `flow`, which is served as stored), judged + // below by the runtime's own verdict ({@link servedInvalidVerdict}). + const servedBody = flowResult ? body : converted.item; + // [#38923] A stored view's `bulkActions`, re-judged by the same entry + // with the deployment's declared actions beside the row, which the + // stored seam does not see ({@link judgeStoredViewBulkActions}). + const judged = !flowResult && singular === 'view' + ? judgeStoredViewBulkActions(converted.item, converted.todos, host.engine.registry) + : { kind: 'unchanged' as const }; + const { item, notices, todos }: { item: unknown; notices: StoredMigrationNotice[]; todos: StoredMigrationTodo[] } = + judged.kind === 'moves' + ? { item: judged.item, notices: [...converted.notices, ...judged.notices], todos: judged.todos } + : judged.kind === 'unchanged' ? converted : { ...converted, todos: judged.todos }; + const asServed = servedBody === undefined ? {} : servedInvalidOf(singular, servedBody); // [#29673] …and, for an `object` row, the save door's translated-echo // restoration ({@link restoreTranslatedObjectEchoes}), asked of the // row against itself and the platform's injected columns: a row a @@ -2982,10 +3004,23 @@ export class ProtocolSaveFacet { message: t.message, })); if (!changed) { - if (flattenedTodos.length === 0) { + if (flattenedTodos.length === 0 && !asServed.servedInvalid) { record({ ...base, outcome: 'canonical' }); continue; } + // [#38923] Nothing to convert, and the runtime serves the row + // invalid: not on protocol, and outside what this pass can rewrite. + if (flattenedTodos.length === 0) { + record({ + ...base, + ...asServed, + outcome: 'skipped', + reason: 'the conversion chain rewrites nothing here, and the runtime serves the row invalid: ' + + 'its body fails the current spec schema at the site named below, which no conversion ' + + 'covers. Correct the row by hand.', + }); + continue; + } // Nothing to persist, and not on protocol either: every site the // chain recognised here is one it has no lossless rewrite for. // `skipped` — outside what a body-canonicalization pass can do, @@ -2995,6 +3030,7 @@ export class ProtocolSaveFacet { // `storedMigrationClean`: no run of this pass could ever clear it. record({ ...base, + ...asServed, todos: flattenedTodos, outcome: 'skipped', reason: `the conversion chain rewrites nothing here: it left ${flattenedTodos.length} ` @@ -3037,7 +3073,7 @@ export class ProtocolSaveFacet { } if (!apply) { - record({ ...base, notices: flattened, todos: flattenedTodos, outcome: 'pending' }); + record({ ...base, ...asServed, notices: flattened, todos: flattenedTodos, outcome: 'pending' }); continue; } @@ -3059,7 +3095,9 @@ export class ProtocolSaveFacet { // #4556 default). The pass's name is on `source` above. ...(request.actor ? { actor: request.actor } : {}), }); - const entry: StoredMigrationRow = { ...base, notices: flattened, todos: flattenedTodos, outcome: 'rewritten' }; + const entry: StoredMigrationRow = { + ...base, ...servedInvalidOf(singular, item), notices: flattened, todos: flattenedTodos, outcome: 'rewritten', + }; // [#32369] Read back BEFORE the row is recorded rewritten: a read // that fails records the row failed alone (the `catch` below). if (judging && state === 'active' && organizationId === null && isBatchObjectType(singular)) { @@ -3106,6 +3144,7 @@ export class ProtocolSaveFacet { // below, whole. record({ ...base, + ...asServed, notices: flattened, todos: flattenedTodos, outcome: 'failed', diff --git a/packages/metadata-protocol/src/protocol-stored-view-selection.ts b/packages/metadata-protocol/src/protocol-stored-view-selection.ts new file mode 100644 index 00000000000..bf1c070759e --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-view-selection.ts @@ -0,0 +1,260 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Two per-row judgements of the stored-metadata pass + * (`ProtocolSaveFacet.migrateStoredMetadata`), kept beside it because that file + * is past the size where a new concern goes into the file itself. + * + * ## 1. A stored view's `bulkActions`, judged with the actions the deployment declares + * + * The protocol-19 conversion `view-bulk-actions-to-action-selection` moves a + * list's `bulkActions` onto the actions it names. The stored seam wraps a row + * ALONE (`{ views: [row] }`), so the conversion sees no action and leaves every + * stored list as a TODO saying its actions are "not declared as an action of + * that object" — false wherever a package declares them, and the one line an + * operator reads before upgrading. + * + * {@link judgeStoredViewBulkActions} runs THE SAME ENTRY again (one predicate, + * read from `ALL_CONVERSIONS`, never restated here) over the row with the + * deployment's declared objects and actions beside it, as the registry holds + * them, and sorts what it answers into three cases: + * + * - **moves** — the entry rewrites the view row and nothing else (every action + * it names already carries `selection`, and no `actionLayout.selection` is + * needed): the row is the whole write, so the pass converts it like any other + * (`pending`, and `--apply` re-saves it); + * - **declared** — the entry would also write the actions or the object, which + * are the package's and no stored row: the row stays as stored, and its TODO + * says the actions ARE declared and what the two ways out are; + * - **left** — the entry, now able to see the actions, still leaves the list + * (an action really undeclared, two lists ordering it differently, an arm the + * object already declares): the entry's own reason replaces the one it gave + * blind. + * + * ## 2. Whether the runtime serves the row invalid + * + * {@link servedInvalidVerdict} asks the runtime's own question: the boot + * hydration (`loadMetaFromDb`) converts each row through `convertStoredItem` + * (the chain plus the page `type` default) and warns + * `[metadata_spec_invalid]` when `computeMetadataDiagnostics` answers + * `valid: false`; the reads badge the row with the same verdict. Nothing here + * is a second rule. + */ + +import { ALL_CONVERSIONS, type ConversionApplication, type ConversionTodoDetail } from '@objectstack/spec'; +import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; +import { withDeclaredPageTypeDefault } from './protocol-view-normalization.js'; +import type { StoredMigrationNotice, StoredMigrationTodo, StoredServedInvalid } from './stored-migration.js'; + +/** The conversion whose stored TODO this module re-judges. */ +export const VIEW_BULK_ACTIONS_CONVERSION_ID = 'view-bulk-actions-to-action-selection'; + +/** The registry reads this module makes — `SchemaRegistry`'s own, as the runtime's action listing reads them. */ +export interface DeclaredActionRegistry { + getAllObjects?: () => unknown; + listItems?: (type: string, packageId?: string, options?: { includeDisabledPackages?: boolean }) => unknown; +} + +/** What the re-judgement decided for one stored view row. */ +export type StoredViewBulkActionsJudgement = + /** Nothing to re-judge: the row carries no TODO of the entry, or no registry can be read. */ + | { kind: 'unchanged' } + /** The row alone is the write: convert it. */ + | { kind: 'moves'; item: unknown; notices: StoredMigrationNotice[]; todos: StoredMigrationTodo[] } + /** The row stays as stored; its TODOs (of the entry) are replaced by these. */ + | { kind: 'declared' | 'left'; todos: StoredMigrationTodo[] }; + +type Dict = Record; + +function isDict(v: unknown): v is Dict { + return v !== null && typeof v === 'object' && !Array.isArray(v); +} + +function stringOf(v: unknown): string | undefined { + return typeof v === 'string' && v.length > 0 ? v : undefined; +} + +/** + * The deployment's declared objects (name, actions, `actionLayout` — the three + * keys the entry reads) and its standalone actions bound to an object, as the + * registry holds them: the shape a stack carries them in. `undefined` when the + * registry cannot be read, so the caller keeps the answer it has. + */ +function declaredStack(registry: DeclaredActionRegistry | undefined): { objects: Dict[]; actions: Dict[] } | undefined { + if (!registry || typeof registry.getAllObjects !== 'function' || typeof registry.listItems !== 'function') { + return undefined; + } + const objects: Dict[] = []; + const allObjects = registry.getAllObjects(); + for (const obj of Array.isArray(allObjects) ? allObjects : []) { + if (!isDict(obj) || !stringOf(obj.name)) continue; + objects.push({ + name: obj.name, + ...(Array.isArray(obj.actions) ? { actions: obj.actions } : {}), + ...(obj.actionLayout !== undefined ? { actionLayout: obj.actionLayout } : {}), + }); + } + const actions: Dict[] = []; + const listed = registry.listItems('action', undefined, { includeDisabledPackages: true }); + for (const action of Array.isArray(listed) ? listed : []) { + if (!isDict(action) || !stringOf(action.name)) continue; + // A standalone action declares `objectName`; a bundle collector attaches + // `object` (`standaloneActionOwnerKey`). The entry reads `objectName`. + const owner = stringOf(action.objectName) ?? stringOf(action.object); + if (!owner) continue; + actions.push(action.objectName === owner ? action : { ...action, objectName: owner }); + } + return { objects, actions }; +} + +/** The notice a conversion emits, in the chain's own words (`applyConversions`). */ +function noticeOf(entry: { id: string; surface: string; toMajor: number }, d: ConversionApplication): StoredMigrationNotice { + const retiresIn = entry.toMajor + 1; + return { + conversionId: entry.id, + surface: entry.surface, + from: d.from, + to: d.to, + path: d.path, + message: + `[protocol] converted ${entry.surface} at ${d.path}: '${d.from}' → '${d.to}' (deprecated; ADR-0087 ` + + `conversion '${entry.id}', retires from the load path in protocol ${retiresIn}). Update the source to '${d.to}'.`, + }; +} + +/** The TODO a conversion reports, in the chain's own words (`applyConversions`). */ +function todoOf(entry: { id: string; surface: string }, t: ConversionTodoDetail): StoredMigrationTodo { + return { + conversionId: entry.id, + surface: entry.surface, + from: t.from, + path: t.path, + reason: t.reason, + message: + `[protocol] left ${entry.surface} at ${t.path} as stored — ADR-0087 conversion '${entry.id}' has no ` + + `lossless rewrite for it: ${t.reason}`, + }; +} + +/** The declared action a notice path writes `selection` onto, by name. */ +function actionNameAt(stack: { objects: Dict[]; actions: Dict[] }, path: string): string | undefined { + const top = /^actions\[(\d+)\]\.locations$/.exec(path); + if (top) return stringOf(stack.actions[Number(top[1])]?.name); + const inline = /^objects\[(\d+)\]\.actions\[(\d+)\]\.locations$/.exec(path); + if (inline) { + const obj = stack.objects[Number(inline[1])]; + const actions = Array.isArray(obj?.actions) ? obj.actions : []; + return isDict(actions[Number(inline[2])]) ? stringOf((actions[Number(inline[2])] as Dict).name) : undefined; + } + return undefined; +} + +/** The object a notice path writes `actionLayout.selection` onto, by name. */ +function armObjectAt(stack: { objects: Dict[] }, path: string): string | undefined { + const arm = /^objects\[(\d+)\]\.actionLayout\.selection$/.exec(path); + return arm ? stringOf(stack.objects[Number(arm[1])]?.name) : undefined; +} + +/** + * Re-judge one stored `view` row's `bulkActions` TODOs with the deployment's + * declared actions beside it. `item` is the row as the chain converted it (its + * lists still carry `bulkActions`); `todos` are the TODOs the chain reported. + * See the module header for the three answers. + * + * ⛔ Throws when the entry is gone from the registry: a stored list would then + * be re-judged by nothing while the chain's blind answer stood. + */ +export function judgeStoredViewBulkActions( + item: unknown, + todos: readonly StoredMigrationTodo[], + registry: DeclaredActionRegistry | undefined, +): StoredViewBulkActionsJudgement { + if (!isDict(item) || !todos.some((t) => t.conversionId === VIEW_BULK_ACTIONS_CONVERSION_ID)) { + return { kind: 'unchanged' }; + } + const entry = ALL_CONVERSIONS.find((c) => c.id === VIEW_BULK_ACTIONS_CONVERSION_ID); + if (!entry) { + throw new Error( + `the stored pass re-judges a view's bulkActions with the conversion '${VIEW_BULK_ACTIONS_CONVERSION_ID}', ` + + 'and the registry no longer carries it. Remove the re-judgement together with the conversion.', + ); + } + const declared = declaredStack(registry); + if (!declared) return { kind: 'unchanged' }; + + const stack = { views: [item], objects: declared.objects, actions: declared.actions }; + const applied: ConversionApplication[] = []; + const left: ConversionTodoDetail[] = []; + const out = entry.apply(stack, (d) => applied.push(d), { atRest: true, reportTodo: (t) => left.push(t) }); + const others = todos.filter((t) => t.conversionId !== VIEW_BULK_ACTIONS_CONVERSION_ID); + + if (left.length > 0) { + return { kind: 'left', todos: [...others, ...left.map((t) => todoOf(entry, t))] }; + } + const beyondRow = applied.filter((d) => !d.path.startsWith('views[0]')); + if (beyondRow.length === 0) { + const views = (out as { views?: unknown[] }).views; + return { + kind: 'moves', + item: Array.isArray(views) ? views[0] : item, + notices: applied.map((d) => noticeOf(entry, d)), + todos: others, + }; + } + + // The entry would also write the package's actions (or object): no stored + // row carries that write, so the view row stays as stored and says why. + const names = [...new Set(beyondRow.map((d) => actionNameAt(declared, d.path)).filter((n): n is string => !!n))]; + const arms = [...new Set(beyondRow.map((d) => armObjectAt(declared, d.path)).filter((n): n is string => !!n))]; + const owed: string[] = []; + if (names.length > 0) { + owed.push(`${names.map((n) => `\`${n}\``).join(', ')} ${names.length === 1 ? 'is' : 'are'} declared on its object ` + + 'and carr' + (names.length === 1 ? 'ies' : 'y') + ' no `\'selection\'` location yet'); + } + if (arms.length > 0) { + owed.push(`the bar's order needs \`actionLayout.selection\` on ${arms.map((n) => `\`${n}\``).join(', ')}`); + } + const blocked = todos + .filter((t) => t.conversionId === VIEW_BULK_ACTIONS_CONVERSION_ID) + .map((t) => ({ + ...t, + reason: `This stored view still carries the retired \`bulkActions\`, which protocol 19 refuses, so the ` + + `view is served invalid. The actions it names are declared by the deployment: ${owed.join('; ')}. ` + + 'That write is the package\'s, not this row\'s, so no run of this pass makes it. Fix it one of two ' + + 'ways: add `\'selection\'` to the `locations` of those actions (and the order as the object\'s ' + + '`actionLayout.selection` where named) in the package source — `os migrate meta --from 18 --write` ' + + 'does it where the package\'s own views name them — then deploy it and re-run this pass, which then ' + + 'rewrites the row; or re-save the view without `bulkActions` (Studio: edit the view and save).', + })) + .map((t) => ({ + ...t, + message: + `[protocol] left ${t.surface} at ${t.path} as stored — ADR-0087 conversion '${t.conversionId}' has ` + + `no lossless rewrite for it: ${t.reason}`, + })); + return { kind: 'declared', todos: [...others, ...blocked] }; +} + +/** + * The runtime's verdict on the body it serves for one stored row: `undefined` + * when the runtime serves it valid (or its type has no schema), else the first + * error the schema names — preferring one with a path, which is where the fix + * goes. `served` is the row as `convertStoredItem` serves it, before the page + * `type` default, which this applies exactly as that seam does. + */ +export function servedInvalidVerdict(type: string, served: unknown): StoredServedInvalid | undefined { + const verdict = computeMetadataDiagnostics(type, withDeclaredPageTypeDefault(type, served)); + if (!verdict || verdict.valid) return undefined; + const errors = verdict.errors ?? []; + const first = errors.find((e) => typeof e.path === 'string' && e.path !== '') ?? errors[0]; + return { + path: first?.path ?? '', + message: first?.message ?? 'the document fails the current spec schema', + }; +} + +/** {@link servedInvalidVerdict} as the row field it fills: `{}` when the runtime serves the row valid. */ +export function servedInvalidOf(type: string, served: unknown): { servedInvalid?: StoredServedInvalid } { + const verdict = servedInvalidVerdict(type, served); + return verdict ? { servedInvalid: verdict } : {}; +} diff --git a/packages/metadata-protocol/src/stored-migration.ts b/packages/metadata-protocol/src/stored-migration.ts index 03b22caa106..6ab6dd64fb7 100644 --- a/packages/metadata-protocol/src/stored-migration.ts +++ b/packages/metadata-protocol/src/stored-migration.ts @@ -167,6 +167,32 @@ export interface StoredMigrationRow { todos: StoredMigrationTodo[]; /** Why a `skipped` / `failed` row was not rewritten. Absent otherwise. */ reason?: string; + /** + * The runtime serves this row marked invalid — see {@link StoredServedInvalid}. + * Absent when it serves it valid. Orthogonal to `outcome`, and every row that + * carries it flips {@link storedMigrationClean}. + */ + servedInvalid?: StoredServedInvalid; +} + +/** + * The runtime's own verdict that it serves a stored row INVALID: the body the + * boot hydration registers for the row (`convertStoredItem`: the conversion + * chain, then the page `type` default) fails the type's current spec schema + * under `computeMetadataDiagnostics` — the check behind the boot's + * `[metadata_spec_invalid]` line and the reads' `_diagnostics` badge. One + * predicate: the pass asks that function, never a rule of its own. + * + * Judged on every row whose body the pass reads. Rows it reports before the + * read — a non-canonical stored `type`, an organization-scoped row — and a row + * the chain yields no item of are not judged: the runtime serves none of them + * on that type. On an apply run a rewritten row is judged as rewritten. + */ +export interface StoredServedInvalid { + /** Where the schema refuses the body, e.g. `list.bulkActions` (`''` for the root). */ + path: string; + /** The schema's own message for that site. */ + message: string; } /** @@ -225,6 +251,12 @@ export interface StoredMigrationReport { rewritten: number; skipped: number; failed: number; + /** + * Rows the runtime serves invalid ({@link StoredServedInvalid}), whatever + * their outcome. Each is listed in {@link rows} with its verdict, and any one + * makes the run not clean ({@link storedMigrationClean}). + */ + servedInvalid: number; /** Every row that is not `canonical`, in scan order. */ rows: StoredMigrationRow[]; /** @@ -318,6 +350,16 @@ export interface StoredViewAllFieldsReview { * that also converts something stays `pending` / `rewritten` / `failed` exactly * as it would without them. * + * ⛔ Except a row the runtime serves INVALID ({@link StoredServedInvalid}), + * whatever its outcome or skip class: a green run over a row the runtime then + * serves invalid is a false green on the upgrade path, so every such row makes + * the run not clean, and its line names the row and the fix. That holds for a + * row this pass has no lever for too (a TODO only a hand rewrite clears): the + * row is fixed by hand, and the next run is clean. A deployment holding an + * unrelated invalid stored row therefore goes non-green until that row is + * fixed. The skip classes above keep their meaning for rows the runtime + * serves valid. + * * The decision review list ({@link StoredMigrationReport.decisionModeReview}) * is not a skip class and never moves this verdict either: a row it names is ON * protocol — by ruling it takes the protocol-18 meaning as stored — so there is @@ -326,7 +368,9 @@ export interface StoredViewAllFieldsReview { * whose rows take the protocol-19 meaning as stored. */ export function storedMigrationClean(report: StoredMigrationReport): boolean { - return report.pending === 0 && report.failed === 0; + // `?? 0`: a report from a protocol older than the field (the CLI reads the + // project stack's protocol, which can be an older release) judged no row. + return report.pending === 0 && report.failed === 0 && (report.servedInvalid ?? 0) === 0; } /** @@ -525,6 +569,24 @@ export function formatStoredMigrationReport(report: StoredMigrationReport): stri } } + // A row the runtime serves invalid, whatever its outcome above: one line + // each, naming the row by id, the site and the fix, because it is what keeps + // the run from being clean (`storedMigrationClean`). + const invalid = report.rows.filter((r) => r.servedInvalid !== undefined); + if (invalid.length > 0) { + lines.push( + `✗ ${invalid.length} row(s) are served INVALID by the runtime on protocol ${report.protocol} ` + + '(it registers them marked invalid and its reads badge them with _diagnostics):', + ); + for (const row of invalid) { + const verdict = row.servedInvalid!; + lines.push( + ` • ${row.type}/${row.name} ${describeScope(row)} id=${row.id} — ${verdict.path || '(root)'}: ${verdict.message}`, + ); + lines.push(` fix: ${servedInvalidFix(report, row)}`); + } + } + const withTodos = report.rows.filter((r) => r.todos.length > 0); if (withTodos.length > 0) { const sites = withTodos.reduce((sum, r) => sum + r.todos.length, 0); @@ -591,7 +653,7 @@ export function formatStoredMigrationReport(report: StoredMigrationReport): stri 'a deployment that has never authored metadata looks like, and also what running ' + 'from the wrong project root looks like — check the database named above.', ); - } else if (converting.length === 0 && failed.length === 0 && withTodos.length === 0) { + } else if (converting.length === 0 && failed.length === 0 && withTodos.length === 0 && invalid.length === 0) { // Not printed beside a TODO: a site left as stored is exactly a row that is // NOT on protocol, and the line would contradict the list above it. lines.push( @@ -602,6 +664,18 @@ export function formatStoredMigrationReport(report: StoredMigrationReport): stri return lines; } +/** The way out for one row the runtime serves invalid, by what the pass did with it. */ +function servedInvalidFix(report: StoredMigrationReport, row: StoredMigrationRow): string { + if (row.outcome === 'pending') { + return 'run this pass with --apply, which rewrites the row; the rewrite is what the runtime then serves.'; + } + const where = `the row (sys_metadata id ${row.id})`; + const todo = row.todos.length > 0 ? ' Each TODO line under the row above names the hand rewrite.' : ''; + return `correct ${where} at the site named and save it again — in Studio, or with PUT /api/v1/meta/${row.type}/${row.name} ` + + `carrying the corrected body — or delete it by name through the metadata API once nothing needs it.${todo} ` + + `Re-run this pass to confirm (protocol ${report.protocol}).`; +} + /** A row's TODOs, nested under its line the way its notices are. */ function pushTodos(lines: string[], row: StoredMigrationRow): void { for (const t of row.todos) { From 49cfeb0913b03520d354c6cefa33c47e81528a93 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:07:14 +0000 Subject: [PATCH 2/7] test(metadata-protocol): pin the stored view bulkActions judgement and the served-invalid verdict Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .../protocol-stored-view-selection.test.ts | 243 ++++++++++++++++++ ...l.migrate-stored-noncanonical-type.test.ts | 3 +- .../src/protocol.stored-migration.test.ts | 15 +- 3 files changed, 257 insertions(+), 4 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-stored-view-selection.test.ts diff --git a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts new file mode 100644 index 00000000000..e81ef554ccd --- /dev/null +++ b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts @@ -0,0 +1,243 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #38923 — `os migrate meta --stored` over a stored view whose list still + * carries the retired `bulkActions`, naming actions the deployment declares. + * + * Measured on `origin/main` before this pin: the stored seam wraps the row + * alone, so the conversion `view-bulk-actions-to-action-selection` called the + * actions "not declared as an action of that object", the row was `skipped`, + * `storedMigrationClean` answered true (exit 0), and the runtime served the + * row invalid. Pinned here, over the same stub engine as the other stored-pass + * tests (rows seeded straight into `sys_metadata`), with a registry holding + * the package's declared object and actions: + * + * - the TODO says the actions ARE declared and names both ways out, and the + * run is not clean; + * - where the package's actions already carry `selection`, the row alone is + * the write: pending on a preview, rewritten on `--apply`, then clean; + * - the runtime's own verdict (`convertStoredItem`, then + * `computeMetadataDiagnostics`, as the boot hydration judges a row) and the + * pass's `servedInvalid` agree row by row; + * - the report-only review lists still move no count and no verdict. + */ +import { describe, expect, it } from 'vitest'; +// Paid during collection, not inside a clocked case: the diagnostics `import()` it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/lint'; +import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; +import { NO_PACKAGE_SCOPED_READS } from './no-package-scoped-reads.testkit.js'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +import { judgeStoredViewBulkActions } from './protocol-stored-view-selection.js'; +import { formatStoredMigrationReport, storedMigrationClean } from './stored-migration.js'; + +type SeedRow = { type: string; name: string; metadata: unknown; state?: string; package_id?: string | null }; + +function matches(r: Record, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (v === undefined) continue; + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if ((r[k] ?? null) !== v) return false; + } + return true; +} + +/** The deployment's registry: the package's objects and its standalone actions. */ +interface Declared { + objects: Record[]; + actions: Record[]; +} + +function makeStubEngine(seedRows: SeedRow[], declared: Declared) { + let nextId = 0; + const tables = new Map[]>(); + tables.set( + 'sys_metadata', + seedRows.map((r) => ({ + id: `r_${++nextId}`, + organization_id: null, + package_id: null, + state: 'active', + checksum: `sha256:seed_${nextId}`, + ...r, + metadata: JSON.stringify(r.metadata), + })), + ); + const rowsOf = (t: string): Record[] => { + let rows = tables.get(t); + if (!rows) tables.set(t, (rows = [])); + return rows; + }; + const engine: any = { + async find(t: string, opts?: { where?: Record }) { + return rowsOf(t).filter((r) => matches(r, opts?.where ?? {})); + }, + async findOne(t: string, opts?: { where?: Record }) { + assertEngineFindOnePredicate(t, opts); + return rowsOf(t).find((r) => matches(r, opts?.where ?? {})) ?? null; + }, + async insert(t: string, row: Record) { + const withId = { id: row.id ?? `r_${++nextId}`, ...row }; + rowsOf(t).push(withId); + return withId; + }, + async update(t: string, patch: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(patch, opts); + const target = rowsOf(t).find((r) => matches(r, opts.where)); + if (target) Object.assign(target, patch); + return target ?? { id: 'x' }; + }, + async delete() { + return { deleted: 0 }; + }, + registry: { + ...NO_PACKAGE_SCOPED_READS, + getAllObjects: () => declared.objects, + listItems: (type: string) => (type === 'action' ? declared.actions : []), + getItem: () => undefined, + getObject: (name: string) => declared.objects.find((o) => o.name === name), + isPackageDisabled: () => false, + registerItem: () => { /* no-op */ }, + registerObject: () => { /* no-op */ }, + removeRuntimeShadow: () => false, + removeOverlayEntry: () => { /* no-op */ }, + }, + }; + return { engine, tables }; +} + +/** What Studio's save stored on 18: the GET body with a column changed, `bulkActions` and all. */ +const storedView = (bulkActions: unknown[]) => ({ + name: 'lead_grid', + object: 'crm_lead', + list: { + type: 'grid', + data: { provider: 'object', object: 'crm_lead' }, + columns: ['name', 'status'], + bulkActions, + }, +}); + +const leadObject = { name: 'crm_lead', label: 'Lead', fields: { name: { type: 'text' } } }; + +/** The package's actions on `crm_lead`, as 19 serves them: without `selection` (B) or with it (C). */ +const packageActions = (withSelection: boolean) => [ + { name: 'merge_leads', label: 'Merge', objectName: 'crm_lead', type: 'script', ...(withSelection ? { locations: ['selection'] } : {}) }, + { name: 'score_lead', label: 'Score', objectName: 'crm_lead', type: 'script', locations: withSelection ? ['record_row', 'selection'] : ['record_row'] }, +]; + +const viewRow = (bulkActions: unknown[]): SeedRow => ({ + type: 'view', name: 'lead_grid', package_id: 'app.crm', metadata: storedView(bulkActions), +}); + +describe('a stored view whose bulkActions name actions the package declares (#38923)', () => { + it('names the actions as declared, with both ways out, and the run is not clean', async () => { + const { engine } = makeStubEngine([viewRow(['merge_leads', 'score_lead'])], { objects: [leadObject], actions: packageActions(false) }); + const report = await new ObjectStackProtocolImplementation(engine).migrateStoredMetadata(); + + expect(report).toMatchObject({ scanned: 1, skipped: 1, pending: 0, failed: 0, servedInvalid: 1 }); + const row = report.rows[0]!; + expect(row).toMatchObject({ type: 'view', name: 'lead_grid', outcome: 'skipped' }); + const todo = row.todos.find((t) => t.conversionId === 'view-bulk-actions-to-action-selection')!; + expect(todo.reason).not.toContain('does not declare'); + expect(todo.reason).toContain('`merge_leads`, `score_lead` are declared on its object'); + expect(todo.reason).toContain('re-save the view without `bulkActions`'); + expect(row.servedInvalid).toMatchObject({ path: 'list.bulkActions' }); + expect(storedMigrationClean(report)).toBe(false); + }); + + it('converts the row where the actions already carry selection: pending, then rewritten and clean', async () => { + const declared = { objects: [leadObject], actions: packageActions(true) }; + const { engine, tables } = makeStubEngine([viewRow(['merge_leads', 'score_lead'])], declared); + const protocol = new ObjectStackProtocolImplementation(engine); + + const preview = await protocol.migrateStoredMetadata(); + expect(preview).toMatchObject({ pending: 1, skipped: 0, servedInvalid: 1 }); + expect(preview.rows[0]!.todos).toEqual([]); + expect(preview.rows[0]!.notices.map((n) => n.path)).toContain('views[0].list.bulkActions'); + expect(storedMigrationClean(preview)).toBe(false); + + const applied = await protocol.migrateStoredMetadata({ apply: true }); + expect(applied).toMatchObject({ rewritten: 1, servedInvalid: 0, failed: 0 }); + const stored = JSON.parse(tables.get('sys_metadata')!.find((r) => r.name === 'lead_grid')!.metadata); + expect(stored.list).not.toHaveProperty('bulkActions'); + expect(storedMigrationClean(applied)).toBe(true); + + const rerun = await protocol.migrateStoredMetadata(); + expect(rerun).toMatchObject({ canonical: 1, pending: 0, skipped: 0, servedInvalid: 0 }); + expect(storedMigrationClean(rerun)).toBe(true); + }); + + it('keeps the conversion\'s own reason where an action really is undeclared', async () => { + const { engine } = makeStubEngine([viewRow(['merge_leads', 'ghost_action'])], { objects: [leadObject], actions: packageActions(true) }); + const report = await new ObjectStackProtocolImplementation(engine).migrateStoredMetadata(); + + const todo = report.rows[0]!.todos.find((t) => t.conversionId === 'view-bulk-actions-to-action-selection')!; + expect(todo.reason).toContain('names `ghost_action` in `bulkActions`, which this metadata does not declare'); + expect(todo.reason).not.toContain('`merge_leads`'); + expect(report.servedInvalid).toBe(1); + expect(storedMigrationClean(report)).toBe(false); + }); + + it('prints one line naming the row id, the site and the fix', async () => { + const { engine } = makeStubEngine([viewRow(['merge_leads'])], { objects: [leadObject], actions: packageActions(false) }); + const report = await new ObjectStackProtocolImplementation(engine).migrateStoredMetadata(); + const text = formatStoredMigrationReport(report).join('\n'); + + expect(text).toContain('row(s) are served INVALID by the runtime'); + expect(text).toMatch(/view\/lead_grid \[env-wide, package=app\.crm\] id=r_1 — list\.bulkActions: /); + expect(text).toContain('fix: correct the row (sys_metadata id r_1)'); + expect(text).not.toContain('already on protocol'); + }); +}); + +describe('the served-invalid verdict is the runtime\'s own (#38923)', () => { + const rows: SeedRow[] = [ + viewRow(['merge_leads']), + { type: 'view', name: 'plain_grid', metadata: { name: 'plain_grid', list: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'] } } }, + // A row no conversion touches that the 19 schema still refuses. + { type: 'view', name: 'odd_grid', metadata: { name: 'odd_grid', list: { type: 'grid', data: { provider: 'object', object: 'crm_lead' }, columns: ['name'], notAKey: true } } }, + { type: 'permission', name: 'ops_all', metadata: { name: 'ops_all', label: 'Ops', objects: { crm_lead: { allowRead: true, viewAllRecords: true } } } }, + ]; + + it('agrees row by row with convertStoredItem + computeMetadataDiagnostics, the boot hydration\'s judgement', async () => { + const { engine } = makeStubEngine(rows, { objects: [leadObject], actions: packageActions(false) }); + const protocol = new ObjectStackProtocolImplementation(engine); + const report = await protocol.migrateStoredMetadata(); + + for (const seed of rows) { + const served = protocol.convertStoredItem(seed.type, seed.metadata); + const runtimeInvalid = computeMetadataDiagnostics(seed.type, served)?.valid === false; + const listed = report.rows.find((r) => r.name === seed.name); + expect({ name: seed.name, invalid: listed?.servedInvalid !== undefined }).toEqual({ name: seed.name, invalid: runtimeInvalid }); + } + expect(report.servedInvalid).toBe(2); + // The row no conversion touches is no longer counted canonical. + expect(report.rows.find((r) => r.name === 'odd_grid')).toMatchObject({ outcome: 'skipped' }); + }); + + it('leaves the report-only review list as it was: listed, no count, no verdict (ruling A on #36055)', async () => { + const { engine } = makeStubEngine([rows[3]!], { objects: [leadObject], actions: [] }); + const report = await new ObjectStackProtocolImplementation(engine).migrateStoredMetadata(); + + expect(report.viewAllFieldsReview).toHaveLength(1); + expect(report).toMatchObject({ servedInvalid: 0, pending: 0, failed: 0 }); + expect(storedMigrationClean(report)).toBe(true); + }); +}); + +describe('judgeStoredViewBulkActions', () => { + const todo = { + conversionId: 'view-bulk-actions-to-action-selection', surface: 's', from: '["merge_leads"]', + path: 'views[0].list.bulkActions', reason: 'blind', message: 'blind', + }; + + it('answers unchanged with no registry to read, so the chain\'s answer stands', () => { + expect(judgeStoredViewBulkActions(storedView(['merge_leads']), [todo], undefined)).toEqual({ kind: 'unchanged' }); + }); + + it('answers unchanged for a row carrying no TODO of the entry', () => { + const registry = { getAllObjects: () => [leadObject], listItems: () => packageActions(true) }; + expect(judgeStoredViewBulkActions(storedView(['merge_leads']), [], registry)).toEqual({ kind: 'unchanged' }); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts b/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts index 2e9180a5e92..dd298dd3724 100644 --- a/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts +++ b/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts @@ -173,7 +173,8 @@ const canonicalObjectRow: SeedRow = { name: 'crm_quote', label: 'Quote', fields: { - status: { type: 'select', label: 'Status' }, + // `options`: a canonical row is one the runtime also serves valid (#38923). + status: { type: 'select', label: 'Status', options: [{ label: 'Sent', value: 'sent' }] }, amount: { type: 'currency', label: 'Amount', requiredWhen: "record.status == 'sent'" }, }, }, diff --git a/packages/metadata-protocol/src/protocol.stored-migration.test.ts b/packages/metadata-protocol/src/protocol.stored-migration.test.ts index bcf25936e40..e78d6cd8ee7 100644 --- a/packages/metadata-protocol/src/protocol.stored-migration.test.ts +++ b/packages/metadata-protocol/src/protocol.stored-migration.test.ts @@ -532,8 +532,13 @@ describe('migrateStoredMetadata — what it declines to touch, loudly (#4327)', type: 'flow', name: 'purge_flow', metadata: { + // A flow the runtime serves valid apart from its legacy D2 spelling, + // so the skip alone is what this pins (#38923 judges served validity). name: 'purge_flow', - nodes: [{ id: 'n1', type: 'delete_record', config: { objectName: 'lead', filters: { status: 'stale' } } }], + label: 'Purge', + type: 'autolaunched', + nodes: [{ id: 'n1', type: 'delete_record', label: 'Delete', config: { objectName: 'lead', filters: { status: 'stale' } } }], + edges: [], }, }; const { engine, tables } = makeStubEngine([legacyFlow]); @@ -1290,8 +1295,12 @@ describe('migrateStoredMetadata — the v18 stored shapes refused with no lossle expect(text).toContain('TODO cbp-master-relation-tiers-retired:'); expect(text).toMatch(/which of them is the master is the owner's choice: the upgrade never picks one/); expect(text).toMatch(/☐ TODO: 3 site\(s\) in 3 row\(s\) are left as stored/); - // Listed, never written — on --apply too — and no verdict flips over it. - expect(storedMigrationClean(report)).toBe(true); + // Listed, never written — on --apply too. Protocol 19 serves each of + // the three invalid, so the run is not clean (#38923): the verdict and + // the runtime's own predicate agree, and each row's line names it. + expect(report.servedInvalid).toBe(3); + expect(report.rows.every((r) => r.servedInvalid !== undefined)).toBe(true); + expect(storedMigrationClean(report)).toBe(false); const applied = await protocol.migrateStoredMetadata({ apply: true }); expect(applied.rewritten).toBe(0); expect(JSON.stringify(metaRows(tables))).toBe(before); From c84fe0f41ba4da618df715362c7cda12cac4f835 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:15:28 +0000 Subject: [PATCH 3/7] test(cli): migrate meta --stored exits non-zero over a row the runtime serves invalid Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .../meta.stored-served-invalid.test.ts | 163 ++++++++++++++++++ .../protocol-stored-view-selection.test.ts | 4 +- 2 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/commands/migrate/meta.stored-served-invalid.test.ts diff --git a/packages/cli/src/commands/migrate/meta.stored-served-invalid.test.ts b/packages/cli/src/commands/migrate/meta.stored-served-invalid.test.ts new file mode 100644 index 00000000000..a75ff9506e1 --- /dev/null +++ b/packages/cli/src/commands/migrate/meta.stored-served-invalid.test.ts @@ -0,0 +1,163 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #38923 — `os migrate meta --stored` is not green over a stored row the + * runtime serves invalid. + * + * The pass (`migrateStoredMetadata`) judges each row it reads with the + * runtime's own verdict and reports `servedInvalid`; `storedMigrationClean` + * then answers false. This pins the command's half: the exit is non-zero, + * `--json` carries the count and the per-row verdict beside `clean` (added, + * nothing renamed), and the human output names the row and says why the run + * is red — and a report with none stays green. + * + * The boot is replaced, so no database is opened; the command's own control + * flow runs for real, the formatter and the verdict included. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { stripVTControlCharacters } from 'node:util'; +import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; + +const boot = vi.hoisted(() => vi.fn()); +vi.mock('../../utils/schema-migrate.js', () => ({ bootSchemaStack: boot })); +vi.mock('../../utils/migrate-occupancy-gate.js', () => ({ + OCCUPANCY_HINT: 'occupancy hint', + probeMigrationTarget: vi.fn(async () => ({ status: 'free' })), +})); +vi.mock('../../utils/data-migration-plugins.js', () => ({ buildDataMigrationPlugins: vi.fn(async () => []) })); + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +/** oclif builds its whole command table on the first `run()` in a process. */ +const RUN_TIMEOUT = 60_000; + +/** The stored view of the card: a TODO, nothing to convert, and served invalid. */ +const VIEW_ROW = { + id: 'r_7', + type: 'view', + name: 'lead_grid', + organizationId: null, + packageId: 'app.crm', + state: 'active' as const, + outcome: 'skipped' as const, + notices: [], + todos: [{ + conversionId: 'view-bulk-actions-to-action-selection', + surface: 'view.list.bulkActions', + from: '["merge_leads"]', + path: 'views[0].list.bulkActions', + reason: 'This stored view still carries the retired `bulkActions`.', + message: 'left as stored', + }], + reason: 'the conversion chain rewrites nothing here', + servedInvalid: { path: 'list.bulkActions', message: '`view.list.bulkActions` was removed in @objectstack/spec 19.0.0' }, +}; + +function reportOf(servedInvalid: boolean) { + return { + apply: false, + protocol: '19.0.0', + scanned: 2, + canonical: 1, + pending: 0, + rewritten: 0, + skipped: 1, + failed: 0, + servedInvalid: servedInvalid ? 1 : 0, + rows: [servedInvalid ? VIEW_ROW : { ...VIEW_ROW, servedInvalid: undefined }], + decisionModeReview: [], + viewAllFieldsReview: [], + }; +} + +const migrateStoredMetadata = vi.fn(); +let written: string[]; +let stdout: ReturnType; +let stderr: ReturnType; +let log: ReturnType; + +beforeEach(() => { + migrateStoredMetadata.mockReset(); + boot.mockReset(); + boot.mockResolvedValue({ + kernel: { getService: (name: string) => (name === 'protocol' ? { migrateStoredMetadata } : undefined) }, + dbLabel: 'file:test.db', + tableAbsent: () => false, + shutdown: vi.fn(async () => {}), + }); + written = []; + // `emitJson` awaits the write's DRAIN callback, so the double invokes it. + stdout = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, enc?: unknown, cb?: unknown) => { + written.push(String(chunk)); + const done = typeof enc === 'function' ? enc : cb; + if (typeof done === 'function') done(); + return true; + }) as typeof process.stdout.write); + stderr = vi.spyOn(process.stderr, 'write').mockImplementation((() => true) as typeof process.stderr.write); + log = vi.spyOn(console, 'log').mockImplementation(() => {}); +}); +afterEach(() => { + stdout.mockRestore(); + stderr.mockRestore(); + log.mockRestore(); +}); + +/** Run the command over `report`; the printed text, colour stripped, and the exit code it raised. */ +async function run(argv: string[], report: ReturnType) { + migrateStoredMetadata.mockResolvedValue(report); + let exit: number | undefined; + try { + await MigrateMeta.run(argv, { root: CLI_ROOT }); + } catch (error: any) { + exit = error?.oclif?.exit; + if (exit === undefined) throw error; + } + const text = log.mock.calls.map((call: unknown[]) => stripVTControlCharacters(call.map(String).join(' '))).join('\n'); + return { exit, text }; +} + +describe('os migrate meta --stored — a row the runtime serves invalid makes the run non-green (#38923)', () => { + it('exits 1, names the row by id with its fix, and says why the run is red', async () => { + const { exit, text } = await run(['--stored'], reportOf(true)); + + expect(exit).toBe(1); + expect(text).toContain('view/lead_grid [env-wide, package=app.crm] id=r_7 — list.bulkActions:'); + expect(text).toContain('fix: correct the row (sys_metadata id r_7)'); + expect(text).toContain('1 stored row(s) are served INVALID by the runtime on protocol 19.0.0'); + expect(text).not.toMatch(/already on protocol/); + }, RUN_TIMEOUT); + + it('--json adds `servedInvalid` beside `clean: false`, and the per-row verdict', async () => { + const { exit } = await run(['--stored', '--json'], reportOf(true)); + + expect(exit).toBe(1); + const out = JSON.parse(written.join('')); + expect(out).toMatchObject({ clean: false, servedInvalid: 1, skipped: 1, pending: 0, failed: 0 }); + expect(out.rows[0].servedInvalid).toEqual(VIEW_ROW.servedInvalid); + }, RUN_TIMEOUT); + + it('CONTROL — the same skipped row served valid leaves the run green', async () => { + const { exit } = await run(['--stored', '--json'], reportOf(false)); + + expect(exit).toBeUndefined(); + expect(JSON.parse(written.join(''))).toMatchObject({ clean: true, servedInvalid: 0 }); + }, RUN_TIMEOUT); +}); diff --git a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts index e81ef554ccd..7fd40f435ed 100644 --- a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts @@ -205,8 +205,10 @@ describe('the served-invalid verdict is the runtime\'s own (#38923)', () => { const protocol = new ObjectStackProtocolImplementation(engine); const report = await protocol.migrateStoredMetadata(); + // The boot hydration's own seam (private on the class; the same method `loadMetaFromDb` calls). + const hydrate = protocol as unknown as { convertStoredItem(type: string, data: unknown): unknown }; for (const seed of rows) { - const served = protocol.convertStoredItem(seed.type, seed.metadata); + const served = hydrate.convertStoredItem(seed.type, seed.metadata); const runtimeInvalid = computeMetadataDiagnostics(seed.type, served)?.valid === false; const listed = report.rows.find((r) => r.name === seed.name); expect({ name: seed.name, invalid: listed?.servedInvalid !== undefined }).toEqual({ name: seed.name, invalid: runtimeInvalid }); From 4b4ddb9872eece94e65ec5d209bdfee6e4016b4b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:21:23 +0000 Subject: [PATCH 4/7] chore(changeset): stored bulkActions judgement and served-invalid verdict Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .changeset/38923-stored-bulk-actions.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .changeset/38923-stored-bulk-actions.md diff --git a/.changeset/38923-stored-bulk-actions.md b/.changeset/38923-stored-bulk-actions.md new file mode 100644 index 00000000000..a537f17c661 --- /dev/null +++ b/.changeset/38923-stored-bulk-actions.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/cli': patch +--- + +fix(migrate): `os migrate meta --stored` judges a stored view's `bulkActions` with the actions the deployment declares, and is not green over a row the runtime serves invalid + +Clause-②: no +Metadata-protocol: none + +**A stored view's `bulkActions`.** The stored pass replays the conversion chain over each `sys_metadata` row on its own, so a Studio-saved list view whose `list` still carried `bulkActions` was told its actions were "not declared as an action of that object", even where the package declares them on that object. The pass now runs the same conversion (`view-bulk-actions-to-action-selection`) again for such a row, with the deployment's declared objects and actions beside it, as the registry holds them: + +- the package's actions already carry the `selection` location, and no `actionLayout.selection` is needed: the view row alone is the write, so it is listed as pending and `--stored --apply` rewrites it without `bulkActions`; +- the actions are declared but still lack `selection` (or the bar's order needs the object's `actionLayout.selection`): that write is the package's, not the row's, so the row stays as stored and its TODO says so. It names the actions and both fixes: add `'selection'` to those actions in the package source and deploy it, or re-save the view without `bulkActions`; +- an action really is undeclared, two lists order the bar differently, or the object already declares an arm: the conversion's own reason, now given with the actions in view. + +**Rows the runtime serves invalid.** Each row whose body the pass reads is judged with the runtime's own check. That is the body the boot hydration registers for the row (`convertStoredItem`), validated by `computeMetadataDiagnostics`, the check behind the `[metadata_spec_invalid]` boot line and the reads' `_diagnostics` badge. A row that fails it carries `servedInvalid: { path, message }`, and the report counts them in `servedInvalid`. `storedMigrationClean` is false while that count is not zero, so `os migrate meta --stored` exits 1. The output lists each such row with its id, the site the schema refuses and its fix, and says why the run is red. `--json` gains `servedInvalid` (the count, and the per-row field) beside `clean`; no existing field is renamed or removed. Not judged: a row stored under a non-canonical type, an organization-scoped row, and a row the chain yields no item of, because the runtime serves none of them under that type. A row that converts nothing and is served invalid is now listed `skipped` with that reason, where it used to be counted `canonical`. + +**Cost.** A deployment holding an unrelated invalid stored row now goes non-green (exit 1) until that row is fixed. The line names the row and its fix. That includes a row whose only finding is a TODO no conversion can rewrite (for example a `controlled_by_parent` object the protocol refuses): those used to be `skipped` and left the run green. The report-only review lists (stored decision nodes, stored permission-set View All / Modify All entries) are unchanged: they still move no count and no verdict. From ba040070fd05c18265be2d22e3da87b686dcb750 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:37:49 +0000 Subject: [PATCH 5/7] test(metadata-protocol): the stored-view-selection double routes delete through the dispatch contract Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .../src/protocol-stored-view-selection.test.ts | 10 +++++++--- scripts/engine-double-contract.pinned.json | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts index 7fd40f435ed..b7699fcf38c 100644 --- a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts @@ -24,7 +24,7 @@ import { describe, expect, it } from 'vitest'; // Paid during collection, not inside a clocked case: the diagnostics `import()` it in a function body (`scripts/check-test-source-alias.mjs`). import '@objectstack/lint'; -import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; import { NO_PACKAGE_SCOPED_READS } from './no-package-scoped-reads.testkit.js'; import { ObjectStackProtocolImplementation } from './protocol.js'; @@ -87,8 +87,12 @@ function makeStubEngine(seedRows: SeedRow[], declared: Declared) { if (target) Object.assign(target, patch); return target ?? { id: 'x' }; }, - async delete() { - return { deleted: 0 }; + async delete(t: string, opts?: Record) { + assertEngineDeleteDispatch(opts); + const rows = rowsOf(t); + const at = rows.findIndex((r) => r.id === (opts as { where?: { id?: unknown } })?.where?.id); + if (at >= 0) rows.splice(at, 1); + return { deleted: at >= 0 ? 1 : 0 }; }, registry: { ...NO_PACKAGE_SCOPED_READS, diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 10fe42fff02..f1ebd3913a3 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -456,6 +456,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol-stored-view-selection.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol-stored-view-selection.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol-stored-view-selection.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.active-save-namespace-prefix.test.ts", "verb": "delete", From 1f4ddbd970cf0d3f28521f5bbdd5a2e73b0d1980 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:46:35 +0000 Subject: [PATCH 6/7] test(metadata-protocol): the stored-view-selection find double holds the caller's limit Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .../src/protocol-stored-view-selection.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts index b7699fcf38c..8dcda25a76b 100644 --- a/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts +++ b/packages/metadata-protocol/src/protocol-stored-view-selection.test.ts @@ -69,8 +69,9 @@ function makeStubEngine(seedRows: SeedRow[], declared: Declared) { return rows; }; const engine: any = { - async find(t: string, opts?: { where?: Record }) { - return rowsOf(t).filter((r) => matches(r, opts?.where ?? {})); + async find(t: string, opts?: { where?: Record; limit?: number }) { + const rows = rowsOf(t).filter((r) => matches(r, opts?.where ?? {})); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; }, async findOne(t: string, opts?: { where?: Record }) { assertEngineFindOnePredicate(t, opts); From 0122451b9244605d066e5a8b5fccd076132b0b83 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:56:10 +0000 Subject: [PATCH 7/7] test(metadata-protocol): pay the lint load at collection where the stored pass now reaches it Claude-Session: https://claude.ai/code/session_01QSeKYoSKoNUygbCoMBTbGc Co-authored-by: Claude --- .../src/protocol.migrate-stored-noncanonical-type.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts b/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts index dd298dd3724..dce835ac764 100644 --- a/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts +++ b/packages/metadata-protocol/src/protocol.migrate-stored-noncanonical-type.test.ts @@ -49,6 +49,8 @@ * exactly as it did — so a vacuous pass is impossible in either direction. */ import { describe, expect, it } from 'vitest'; +// Paid during collection, not inside a clocked case: the pass's served-validity verdict reaches the diagnostics, which `import()` it in a function body (`scripts/check-test-source-alias.mjs`). +import '@objectstack/lint'; // [#5619] The producer's OWN write-verb dispatch decisions, so this fake engine // cannot accept a call the real ObjectQL engine refuses (#4550 delete / #5480 // update). Imported from `@objectstack/metadata-core` rather than