Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/38595-rename-flow-references.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/metadata-protocol': patch
---

fix(metadata-protocol): a package copied under a new namespace calls its own flows

Clause-②: no
Metadata-protocol: none

A package copy under a new namespace (an `unmanaged` install with `targetNamespace`, or `duplicatePackage`) renames the package's flows, `crm_child` to `crm2_child`. The names that call those flows now follow them: a `subflow` step's `config.flowName`, a translation's `flows` keys, and an action's `target` when its executor is `flow` (`type: 'flow'` on an action or an API endpoint, `actionType: 'flow'` on an `action:button` or `action:icon` page block). Before, the copy kept the source's name: its step failed on every run with "Flow not found", or, with the source package still installed, ran the source's flow.

A value is rewritten only when it is exactly the name of a flow the copy renames. A flow the package does not hold keeps its name, and so does a `target` beside any other executor. A renamed name that meets a name the item already holds there (a translation's `flows` keyed by both `crm_child` and `crm2_child`) refuses that item, as the same meeting does for an object name. Nothing an author writes changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38595] A package copy under a new namespace renames its flows, and every
* name that calls them follows: a `subflow` step's `config.flowName` and a
* flow action's `target` name the COPY's flow, through both copy doors — the
* unmanaged import's `targetNamespace` (ADR-0131 D6) and `duplicatePackage`
* (ADR-0070 D4), which share the one rename engine
* (`package-namespace-rename.ts`).
*
* Before the fix the copy's step kept the source's name: with no such flow it
* failed on every run, and with the source still installed it called the
* SOURCE's flow. The automation service here answers `listFlows` so a publish
* gate that judges a step's called flow against the deployment has a
* non-empty universe; the pins read the stored rows, so they hold with that
* gate and without it.
*
* The harness (`makeEngine`, `crmBody`) is copied from
* `package-unmanaged-install.test.ts`: a stub engine that keeps real rows, so
* the REAL save door and the REAL copy doors run against it.
*/
// Pays the lint root's first load at collection, never inside a clocked case.
import './lint-root-preload.testkit.js';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core';
import { ObjectStackProtocolImplementation } from './protocol.js';
import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js';

type Row = Record<string, any>;

/** Equality, `null` and `$in`; any other operator is refused, so a matcher that ignored one cannot prove anything. */
function matches(row: Row, where: Record<string, unknown> = {}): boolean {
for (const [key, want] of Object.entries(where)) {
if (want === undefined) continue;
if (key.startsWith('$')) throw new Error(`stub engine: unsupported operator ${key}`);
const have = row[key] ?? null;
if (want !== null && typeof want === 'object' && !Array.isArray(want)) {
const ops = Object.keys(want);
if (ops.length !== 1 || ops[0] !== '$in') throw new Error(`stub engine: unsupported operator ${ops.join(',')}`);
if (!(want as { $in: unknown[] }).$in.includes(have)) return false;
continue;
}
if (have !== want) return false;
}
return true;
}

/** A stub engine that keeps rows, and a registry that keeps packages and namespaces. */
function makeEngine(opts: { artifacts?: Array<{ type: string; name: string; packageId: string }>; owners?: Record<string, string[]> } = {}) {
const tables = new Map<string, Row[]>();
const table = (name: string) => {
if (!tables.has(name)) tables.set(name, []);
return tables.get(name)!;
};
let nextId = 0;
const writes: Array<{ op: string; table: string }> = [];
const packages = new Map<string, any>();
const namespaces = new Map<string, Set<string>>(
Object.entries(opts.owners ?? {}).map(([ns, ids]) => [ns, new Set(ids)]),
);
const artifacts = opts.artifacts ?? [];
// What the registry was handed — the body every read then serves.
const registered: Array<{ type: string; item: any }> = [];
const objects: Array<{ item: any; packageId: string }> = [];
const ddl: string[] = [];
const engine: any = {
async syncObjectSchema(name: any) { ddl.push(`sync ${typeof name === 'string' ? name : name?.name}`); },
async dropObjectSchema(name: any) { ddl.push(`drop ${typeof name === 'string' ? name : name?.name}`); },
async find(t: string, q?: { where?: Record<string, unknown>; limit?: number }) {
const rows = table(t).filter((r) => matches(r, q?.where));
// The caller's bound, after the filter, by presence — as the engine applies it.
return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows;
},
async findOne(t: string, q: { where: Record<string, unknown> }) {
assertEngineFindOnePredicate(t, q);
return table(t).find((r) => matches(r, q.where)) ?? null;
},
// One record, or the batch the seed loader inserts a dataset in.
async insert(t: string, data: Row | Row[]): Promise<Row | Row[]> {
const one = (record: Row) => {
writes.push({ op: 'insert', table: t });
nextId += 1;
const row = { id: `r_${nextId}`, ...record };
table(t).push(row);
return { ...row };
};
return Array.isArray(data) ? data.map(one) : one(data);
},
async update(t: string, data: Row, q?: Record<string, unknown>) {
assertEngineUpdateDispatch(data, q);
writes.push({ op: 'update', table: t });
const where = (q as { where?: Record<string, unknown> } | undefined)?.where;
const hit = table(t).filter((r) => matches(r, where));
for (const r of hit) Object.assign(r, data);
return { id: hit[0]?.id ?? null };
},
async delete(t: string, q?: Record<string, unknown>) {
assertEngineDeleteDispatch(q);
writes.push({ op: 'delete', table: t });
const where = (q as { where?: Record<string, unknown> } | undefined)?.where;
const keep = table(t).filter((r) => !matches(r, where));
const deleted = table(t).length - keep.length;
tables.set(t, keep);
return { deleted };
},
registry: {
registerItem: (type: string, item: any) => { registered.push({ type, item }); },
// The OBJECT schema every data and metadata read serves, and the
// package it is registered under.
registerObject: (item: any, packageId: string) => { objects.push({ item, packageId }); },
unregisterItem: () => {},
listItems: () => [],
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: (type: string, name: string) => {
const hit = artifacts.find((a) => a.type === type && a.name === name);
return hit ? { name, _packageId: hit.packageId } : undefined;
},
getPackage: (id: string) => packages.get(id),
installPackage: (manifest: any) => {
const pkg = { manifest, status: 'installed', enabled: true };
packages.set(manifest.id, pkg);
if (manifest.namespace) {
if (!namespaces.has(manifest.namespace)) namespaces.set(manifest.namespace, new Set());
namespaces.get(manifest.namespace)!.add(manifest.id);
}
return pkg;
},
uninstallPackage: (id: string) => {
const pkg = packages.get(id);
packages.delete(id);
if (pkg?.manifest?.namespace) namespaces.get(pkg.manifest.namespace)?.delete(id);
},
getNamespaceOwners: (ns: string) => [...(namespaces.get(ns) ?? [])],
},
};
return { engine, table, writes, packages, registered, objects, ddl };
}

/**
* A protocol whose automation engine holds `engineFlows`, so a gate that
* judges a step's called flow against the deployment is not judging an empty
* universe.
*/
function makeProtocol(engineFlows: readonly string[] = ['other_flow']) {
const harness = makeEngine();
const services = new Map<string, unknown>([['automation', { listFlows: async () => [...engineFlows] }]]);
const protocol = new ObjectStackProtocolImplementation(harness.engine, () => services as Map<string, any>) as any;
return { ...harness, protocol };
}

/** A small, schema-valid package body — an object, a view of it, and an app. */
function crmBody(extra: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 'com.example.crm',
namespace: 'crm',
version: '4.0.0',
type: 'app',
name: 'CRM',
scope: 'cloud',
objects: [{
name: 'crm_lead',
label: 'Lead',
sharingModel: 'private',
fields: { title: { type: 'text', label: 'Title' } },
}],
views: [{
name: 'crm_lead_open',
label: 'Open leads',
object: 'crm_lead',
viewKind: 'list',
columns: [{ field: 'title', label: 'Title' }],
}],
// Not this verb's: seeds are data, and the door states what it did with them.
data: [{ object: 'crm_lead', records: [{ title: 'First' }] }],
// An empty bundle list converts into no `translation` item.
translations: [],
i18n: { defaultLocale: 'en' },
...extra,
};
}

const ENV_KEYS = ['OS_TENANCY_POSTURE', 'OS_MULTI_ORG_ENABLED', 'OS_METADATA_WRITABLE'] as const;
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
for (const k of ENV_KEYS) saved[k] = process.env[k];
for (const k of ENV_KEYS) delete process.env[k];
resetEnvWritableMetadataTypes();
});
afterEach(() => {
for (const k of ENV_KEYS) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
resetEnvWritableMetadataTypes();
});

/** A flow; with `calls`, its one step is a `subflow` calling that flow by name. */
const flow = (name: string, calls?: string) => ({
name,
label: name,
type: 'autolaunched',
status: 'active',
nodes: [
{ id: 'start', type: 'start', label: 'Start' },
...(calls !== undefined ? [{ id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } }] : []),
],
edges: calls !== undefined ? [{ id: 'e1', source: 'start', target: 'call' }] : [],
});

/** The package the card names: a flow calling a sibling, a flow action naming it, and a control action. */
const callerBody = (flows = [flow('crm_parent', 'crm_child'), flow('crm_child')]) => crmBody({
flows,
actions: [
{ name: 'crm_run_child', label: 'Run child', objectName: 'crm_lead', type: 'flow', target: 'crm_child' },
// CONTROL: the same string as the target of another executor names no flow.
{ name: 'crm_open_child', label: 'Open child', objectName: 'crm_lead', type: 'modal', target: 'crm_child' },
],
});

/** Every active row of one package: `type/name` → its stored body. */
const itemsOf = (table: (name: string) => Row[], packageId: string): Record<string, any> => Object.fromEntries(
table('sys_metadata')
.filter((r) => r.package_id === packageId && r.state === 'active')
.map((r) => [`${r.type}/${r.name}`, typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata])
.sort(([a], [b]) => String(a).localeCompare(String(b))),
);

/** The flow a stored flow's `subflow` step calls. */
const calledBy = (body: any): unknown => body?.nodes?.find((n: any) => n?.type === 'subflow')?.config?.flowName;

describe('importUnmanagedPackage with `targetNamespace` — the copy\'s callers name the copy\'s flows (#38595)', () => {
it('installs, and the stored `crm2_parent` calls `crm2_child`', async () => {
const { protocol, table } = makeProtocol();
const result = await protocol.importUnmanagedPackage({ manifest: callerBody(), targetNamespace: 'crm2' });
expect(result.copied.filter((c: { type: string }) => c.type === 'flow').map((c: { name: string }) => c.name).sort())
.toEqual(['crm2_child', 'crm2_parent']);
const items = itemsOf(table, 'com.example.crm-copy');
expect(Object.keys(items).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_child', 'flow/crm2_parent']);
expect(calledBy(items['flow/crm2_parent'])).toBe('crm2_child');
});

it('a copied flow action\'s `target` names the copy\'s flow; a non-flow action\'s equal `target` keeps it (CONTROL)', async () => {
const { protocol, table } = makeProtocol();
await protocol.importUnmanagedPackage({ manifest: callerBody(), targetNamespace: 'crm2' });
const items = itemsOf(table, 'com.example.crm-copy');
expect(items['action/crm2_run_child']).toMatchObject({ objectName: 'crm2_lead', type: 'flow', target: 'crm2_child' });
expect(items['action/crm2_open_child']).toMatchObject({ objectName: 'crm2_lead', type: 'modal', target: 'crm_child' });
});

it('with the source package\'s `crm_child` still installed, the copy calls its own `crm2_child`, never the source\'s', async () => {
const { protocol, table } = makeProtocol(['other_flow', 'crm_child']);
// The source, installed under its own names.
await protocol.importUnmanagedPackage({ manifest: callerBody(), targetPackageId: 'com.example.crm-base' });
expect(calledBy(itemsOf(table, 'com.example.crm-base')['flow/crm_parent'])).toBe('crm_child');
// The copy, beside it.
await protocol.importUnmanagedPackage({
manifest: callerBody(), targetPackageId: 'com.example.crm2', targetNamespace: 'crm2',
});
const copy = itemsOf(table, 'com.example.crm2');
expect(calledBy(copy['flow/crm2_parent'])).toBe('crm2_child');
expect(copy['action/crm2_run_child'].target).toBe('crm2_child');
});

it('CONTROL: a flow the package does not hold keeps its name', async () => {
const { protocol, table } = makeProtocol();
await protocol.importUnmanagedPackage({
manifest: callerBody([flow('crm_parent', 'other_flow'), flow('crm_child')]), targetNamespace: 'crm2',
});
expect(calledBy(itemsOf(table, 'com.example.crm-copy')['flow/crm2_parent'])).toBe('other_flow');
});
});

describe('duplicatePackage — the same items as the import: the copy\'s callers name the copy\'s flows (#38595)', () => {
// The called flow is stored first, so the copy loop writes it before its caller.
const body = () => callerBody([flow('crm_child'), flow('crm_parent', 'crm_child')]);

it('the duplicate\'s `crm2_parent` calls `crm2_child` and its flow action names it, the source staying installed', async () => {
const viaDuplicate = makeProtocol(['other_flow', 'crm_child', 'crm_parent']);
await viaDuplicate.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm-base' });
const duplicated = await viaDuplicate.protocol.duplicatePackage({
sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2',
});
expect(duplicated.failed).toEqual([]);
const copy = itemsOf(viaDuplicate.table, 'com.example.crm2');
expect(calledBy(copy['flow/crm2_parent'])).toBe('crm2_child');
expect(copy['action/crm2_run_child'].target).toBe('crm2_child');
expect(copy['action/crm2_open_child'].target).toBe('crm_child');
// The source is untouched: it still calls its own flow.
expect(calledBy(itemsOf(viaDuplicate.table, 'com.example.crm-base')['flow/crm_parent'])).toBe('crm_child');
});

it('parity: the duplicate and the import into the same namespace store identical flows and actions', async () => {
const viaDuplicate = makeProtocol(['other_flow', 'crm_child', 'crm_parent']);
await viaDuplicate.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm-base' });
await viaDuplicate.protocol.duplicatePackage({
sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2',
});
const viaImport = makeProtocol();
await viaImport.protocol.importUnmanagedPackage({ manifest: body(), targetPackageId: 'com.example.crm2', targetNamespace: 'crm2' });
const pick = (items: Record<string, any>) => Object.fromEntries(
Object.entries(items).filter(([k]) => k.startsWith('flow/') || k.startsWith('action/')),
);
const imported = pick(itemsOf(viaImport.table, 'com.example.crm2'));
expect(Object.keys(imported)).toEqual([
'action/crm2_open_child', 'action/crm2_run_child', 'flow/crm2_child', 'flow/crm2_parent',
]);
expect(pick(itemsOf(viaDuplicate.table, 'com.example.crm2'))).toEqual(imported);
});
});
Loading
Loading