Skip to content
Merged
19 changes: 19 additions & 0 deletions .changeset/38923-stored-bulk-actions.md
Original file line number Diff line number Diff line change
@@ -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.
163 changes: 163 additions & 0 deletions packages/cli/src/commands/migrate/meta.stored-served-invalid.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof vi.spyOn>;
let stderr: ReturnType<typeof vi.spyOn>;
let log: ReturnType<typeof vi.spyOn>;

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<typeof reportOf>) {
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);
});
14 changes: 13 additions & 1 deletion packages/cli/src/commands/migrate/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1939,6 +1939,7 @@ export default class MigrateMeta extends Command {
rewritten: 0,
skipped: 0,
failed: 0,
servedInvalid: 0,
rows: [],
decisionModeReview: [],
viewAllFieldsReview: [],
Expand Down Expand Up @@ -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;
Expand Down
47 changes: 43 additions & 4 deletions packages/metadata-protocol/src/protocol-save.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -2688,6 +2689,7 @@ export class ProtocolSaveFacet {
rewritten: 0,
skipped: 0,
failed: 0,
servedInvalid: 0,
rows: [],
decisionModeReview: [],
viewAllFieldsReview: [],
Expand Down Expand Up @@ -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);
};

Expand Down Expand Up @@ -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 '
Expand All @@ -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)}`,
});
Expand All @@ -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',
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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} `
Expand Down Expand Up @@ -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;
}

Expand All @@ -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)) {
Expand Down Expand Up @@ -3106,6 +3144,7 @@ export class ProtocolSaveFacet {
// below, whole.
record({
...base,
...asServed,
notices: flattened,
todos: flattenedTodos,
outcome: 'failed',
Expand Down
Loading
Loading