From a55189908289515ff39f530c9891d569532378cd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:09:21 +0000 Subject: [PATCH 01/10] fix(metadata-protocol): a package copy's flow references follow its renamed flows planNamespaceRename renamed a package flow under the prefix swap but kept every name that calls it: a subflow step's config.flowName, a translation's flows keys and a flow action's target still named the source's flow. The copy now rewrites a value equal to a renamed flow name, whole, at the derived index's flow sites and at a target beside a 'flow' executor. Claude-Session: https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE Co-authored-by: Claude --- .../src/package-namespace-rename.ts | 86 ++++++++++++++++--- 1 file changed, 75 insertions(+), 11 deletions(-) diff --git a/packages/metadata-protocol/src/package-namespace-rename.ts b/packages/metadata-protocol/src/package-namespace-rename.ts index 0bd58b7141d..e90813508b9 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.ts @@ -94,7 +94,8 @@ export interface NamespaceRename { */ copyNameRefusal(type: string, name: string): string | undefined; /** - * The body as the copy writes it: every name the copy renames rewritten, + * The body as the copy writes it: every name the copy renames rewritten + * (an object's, and a flow's at the sites that call a flow, #38595), * `name` set to {@link copyName}, a permission set's field-rule keys * following the renamed objects — or the collision that refuses it. * `item` is the body converted to today's protocol; `name` is its SOURCE @@ -138,6 +139,21 @@ function isCapabilityType(type: string): boolean { return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'capability'; } +/** A `flow` row, in either spelling of the type. */ +function isFlowType(type: string): boolean { + return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'flow'; +} + +/** + * [#38595] The keys that name an action's EXECUTOR beside its `target`: `type` + * on an action (`ActionSchema`, an inline action, an `action:group` member, an + * API endpoint), `actionType` on an `action:button` / `action:icon` page block, + * whose `type` is the component itself. When the executor is `'flow'`, the + * `target` is a flow name ("the flow name to invoke", `ActionSchema`'s + * docblock), so it is a flow reference site. See `flowTargetSite` below. + */ +const FLOW_EXECUTOR_KEYS = ['type', 'actionType'] as const; + /** * [#35157] The keys a body names capabilities under: a permission set GRANTS * them (`systemPermissions`) and a resource REQUIRES them @@ -463,10 +479,58 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam const objectReferenceProperties = new Set( (REFERENCE_SITES.byTarget.get('object') ?? []).map((site) => site.property), ); - type ReferenceCollision = { at: string; shape: 'key' | 'entry'; moved: string; met: string }; - const deepRewrite = (v: any, collisions: ReferenceCollision[], atReference = false, at = ''): any => { + + // [#38595] ⭐ A FLOW NAME FOLLOWS THE FLOW, AS AN OBJECT NAME FOLLOWS THE + // OBJECT. A package flow is copied under the prefix swap (`crm_child` → + // `crm2_child`), and a flow is called by name: a `subflow` step's + // `config.flowName`, a flow action's `target`. Left as written, the copy's + // step called `crm_child` — a flow no copy holds, so every run failed, or, + // with the source package still installed, the SOURCE's flow. So every + // value that names a flow this copy renames is rewritten to the copy's + // name, whole and only whole, at a flow reference site: the derived index's + // `flow` sites (`REFERENCE_SITES`, target `flow`: `flowName`, a + // translation's `flows` keys), read by property wherever it occurs, as the + // object sites are, since a node config is declared by a node descriptor + // the index reaches only through that property. A flow the package does + // not hold, or one the prefix swap keeps (no source prefix), is not + // renamed, so every name of it stays as written. A name that is not a + // renamed flow's falls through to the rules every string takes, so + // nothing that read the same before reads differently now. + // + // ⛔ REFUSED, NEVER MERGED, exactly as at an object site: a renamed flow + // name meeting one the item already holds there (a translation's `flows` + // keyed by both `crm_child` and `crm2_child`) is a collision. + const flowRenames = new Map(); + for (const item of items) { + if (!isFlowType(item?.type) || typeof item.name !== 'string') continue; + const nn = renameName(item.name); + if (nn !== item.name) flowRenames.set(item.name, nn); + } + const flowReferenceProperties = new Set( + (REFERENCE_SITES.byTarget.get('flow') ?? []).map((site) => site.property), + ); + type ReferenceSiteRename = { readonly noun: 'object' | 'flow'; readonly renames: ReadonlyMap }; + const OBJECT_SITE: ReferenceSiteRename = { noun: 'object', renames: renameMap }; + const FLOW_SITE: ReferenceSiteRename = { noun: 'flow', renames: flowRenames }; + // ⚠️ THE ONE HAND-WRITTEN FLOW SITE: an action's `target` when its + // executor is `'flow'` ({@link FLOW_EXECUTOR_KEYS}). The derived index + // cannot carry it — `target` names a URL, a script, a page, an endpoint + // or a form on the other executors, so a property-wide site would rewrite + // those too, and its "Used by" answer (`findReferencesToMeta`) would list + // them as flow references. The site is keyed on the declared shape, the + // `target` beside a `'flow'` executor in one object, and nothing else. + const flowTargetSite = (node: Record, key: string): ReferenceSiteRename | undefined => + key === 'target' && typeof node.target === 'string' + && FLOW_EXECUTOR_KEYS.some((executor) => node[executor] === 'flow') + ? FLOW_SITE + : undefined; + const referenceSiteOf = (key: string): ReferenceSiteRename | undefined => + objectReferenceProperties.has(key) ? OBJECT_SITE : flowReferenceProperties.has(key) ? FLOW_SITE : undefined; + + type ReferenceCollision = { at: string; shape: 'key' | 'entry'; noun: 'object' | 'flow'; moved: string; met: string }; + const deepRewrite = (v: any, collisions: ReferenceCollision[], site?: ReferenceSiteRename, at = ''): any => { if (typeof v === 'string') { - const whole = atReference ? renameMap.get(v) : undefined; + const whole = site ? site.renames.get(v) : undefined; if (whole !== undefined) return whole; const viewItem = viewItemRenames.get(v); if (viewItem !== undefined) return viewItem; @@ -484,8 +548,8 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam return last === 0 ? objectPass(v) : out + objectPass(v.slice(last)); } if (Array.isArray(v)) { - const out = v.map((element, i) => deepRewrite(element, collisions, atReference, `${at}[${i}]`)); - if (atReference) { + const out = v.map((element, i) => deepRewrite(element, collisions, site, `${at}[${i}]`)); + if (site) { const firstAt = new Map(); out.forEach((element, i) => { if (typeof element !== 'string') return; @@ -493,7 +557,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam if (j === undefined) { firstAt.set(element, i); } else if (v[j] !== v[i]) { - collisions.push({ at, shape: 'entry', moved: v[i] !== element ? v[i] : v[j], met: element }); + collisions.push({ at, shape: 'entry', noun: site.noun, moved: v[i] !== element ? v[i] : v[j], met: element }); } }); } @@ -503,10 +567,10 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam const o: any = {}; const from = new Map(); for (const [k, val] of Object.entries(v)) { - const key = atReference ? (renameMap.get(k) ?? k) : k; + const key = site ? (site.renames.get(k) ?? k) : k; const other = from.get(key); if (other !== undefined) { - collisions.push({ at, shape: 'key', moved: key === k ? other : k, met: key }); + collisions.push({ at, shape: 'key', noun: site?.noun ?? 'object', moved: key === k ? other : k, met: key }); } from.set(key, k); if (CAPABILITY_REFERENCE_KEYS.has(k)) { @@ -515,7 +579,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam } const entry = deepRewrite( val, collisions, - objectReferenceProperties.has(k) || (atReference && k === 'name'), + referenceSiteOf(k) ?? (site && k === 'name' ? site : flowTargetSite(v, k)), at ? `${at}.${k}` : k, ); // ⭐ A RECORD ENTRY'S `name` FOLLOWS ITS KEY. An entry that @@ -540,7 +604,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam return v; }; const describeCollision = (c: ReferenceCollision): string => - `its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied object to '${c.met}', ` + `its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied ${c.noun} to '${c.met}', ` + `${c.shape === 'key' ? 'a key' : 'an entry'} it already holds there, which this copy does not rename. ` + (c.shape === 'key' ? 'A record keeps one entry per key, so the copy would drop one of the two. ' From 042c684597f314d035517ea202603d2337492f4f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:11:47 +0000 Subject: [PATCH 02/10] test(metadata-protocol): pin flow references following a package copy's renamed flows Engine pins (subflow flowName, flow action target with a non-flow control, the API endpoint and page action-block spellings, translation flows keys and their collision refusal) and door pins for the unmanaged import with targetNamespace and duplicatePackage, including the source-still-installed case and the parity of the two doors. Claude-Session: https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE Co-authored-by: Claude --- ...e-namespace-rename-flow-refs-38595.test.ts | 310 ++++++++++++++++++ .../src/package-namespace-rename.test.ts | 99 ++++++ 2 files changed, 409 insertions(+) create mode 100644 packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts diff --git a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts new file mode 100644 index 00000000000..dfeaa94f5b9 --- /dev/null +++ b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts @@ -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; + +/** Equality, `null` and `$in`; any other operator is refused, so a matcher that ignored one cannot prove anything. */ +function matches(row: Row, where: Record = {}): 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 } = {}) { + const tables = new Map(); + 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(); + const namespaces = new Map>( + 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; 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 }) { + 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 { + 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) { + assertEngineUpdateDispatch(data, q); + writes.push({ op: 'update', table: t }); + const where = (q as { where?: Record } | 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) { + assertEngineDeleteDispatch(q); + writes.push({ op: 'delete', table: t }); + const where = (q as { where?: Record } | 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([['automation', { listFlows: async () => [...engineFlows] }]]); + const protocol = new ObjectStackProtocolImplementation(harness.engine, () => services as Map) as any; + return { ...harness, protocol }; +} + +/** A small, schema-valid package body — an object, a view of it, and an app. */ +function crmBody(extra: Record = {}): Record { + 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 = {}; +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 => 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) => 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); + }); +}); diff --git a/packages/metadata-protocol/src/package-namespace-rename.test.ts b/packages/metadata-protocol/src/package-namespace-rename.test.ts index f57c27752d3..2e775ecbe05 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.test.ts @@ -323,3 +323,102 @@ describe('planNamespaceRename — a copied capability, and every grant and requi }); }); + +describe('planNamespaceRename — a flow name follows the flow, at every site that calls it (#38595)', () => { + const subflow = (name: string, calls: string) => ({ + name, label: name, type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'call' }], + }); + const flowItems: NamespaceRenameItem[] = [ + ...items, + { type: 'flow', name: 'crm_parent', body: subflow('crm_parent', 'crm_child') }, + { type: 'flow', name: 'crm_child', body: { name: 'crm_child', label: 'Child', type: 'autolaunched', nodes: [], edges: [] } }, + // The prefix swap keeps a flow without the source prefix, so nothing names it anew. + { type: 'flow', name: 'bare_child', body: { name: 'bare_child', label: 'Bare', type: 'autolaunched', nodes: [], edges: [] } }, + ]; + const plan = (targetNamespace = 'crm2', list = flowItems) => planNamespaceRename({ + sourcePackageId: 'com.example.crm', sourceNamespace: 'crm', targetNamespace, items: list, retryVerb: 'install', + }); + const itemOf = (out: unknown) => (out as { item: any }).item; + + it('a subflow step\'s `config.flowName` naming a package flow takes that flow\'s copy name', () => { + const rename = plan(); + expect(rename.copyName('flow', 'crm_child')).toBe('crm2_child'); + const parent = itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body)); + expect(parent.name).toBe('crm2_parent'); + expect(parent.nodes[1].config.flowName).toBe('crm2_child'); + // The edge's `target` is a node id, not a flow: it is never a flow site. + expect(parent.edges[0]).toEqual({ id: 'e1', source: 'start', target: 'call' }); + }); + + it('CONTROL: a flow the package does not hold keeps its name, and so does one the prefix swap keeps', () => { + const rename = plan(); + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'other_flow'))).nodes[1].config.flowName) + .toBe('other_flow'); + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'bare_child'))).nodes[1].config.flowName) + .toBe('bare_child'); + // Never a substring: a name that merely contains a renamed flow's is another name. + expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'crm_child_v2'))).nodes[1].config.flowName) + .toBe('crm_child_v2'); + }); + + it('a flow action\'s `target` follows the flow; a `target` beside any other executor does not (CONTROL)', () => { + const rename = plan(); + const flowAction = itemOf(rename.rewrite('action', 'crm_run_child', { + name: 'crm_run_child', objectName: 'crm_lead', type: 'flow', target: 'crm_child', + })); + expect(flowAction).toMatchObject({ name: 'crm2_run_child', objectName: 'crm2_lead', type: 'flow', target: 'crm2_child' }); + for (const type of ['modal', 'script', 'api']) { + const other = itemOf(rename.rewrite('action', 'crm_open_child', { + name: 'crm_open_child', objectName: 'crm_lead', type, target: 'crm_child', + })); + expect(other.target).toBe('crm_child'); + } + }); + + it('the same `target` rule holds wherever an action sits: an object\'s actions, an API endpoint, a page action block', () => { + const rename = plan(); + const object = itemOf(rename.rewrite('object', 'crm_lead', { + name: 'crm_lead', fields: {}, actions: [{ name: 'run', type: 'flow', target: 'crm_child' }, { name: 'open', type: 'modal', target: 'crm_child' }], + })); + expect(object.actions.map((a: any) => a.target)).toEqual(['crm2_child', 'crm_child']); + const api = itemOf(rename.rewrite('api', 'crm_run', { name: 'crm_run', path: '/api/v1/apps/crm/run', method: 'POST', type: 'flow', target: 'crm_child' })); + expect(api.target).toBe('crm2_child'); + // On a page block `type` is the component, so the executor is `actionType`. + const page = itemOf(rename.rewrite('page', 'crm_home', { + name: 'crm_home', + regions: [{ components: [ + { type: 'action:button', properties: { label: 'Run', actionType: 'flow', target: 'crm_child' } }, + { type: 'action:button', properties: { label: 'Go', actionType: 'url', target: '/crm_child' } }, + ] }], + })); + expect(page.regions[0].components.map((c: any) => c.properties.target)).toEqual(['crm2_child', '/crm_child']); + }); + + it('a translation\'s `flows` keys follow the flows — the index\'s second flow site', () => { + const rename = plan(); + const bundle = itemOf(rename.rewrite('translation', 'crm_en', { + name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, other_flow: { label: 'Other' } }, + })); + expect(bundle.flows).toEqual({ crm2_child: { label: 'Child' }, other_flow: { label: 'Other' } }); + }); + + it('a renamed flow name meeting one the item already holds there is refused, never merged — as for an object', () => { + const out = plan().rewrite('translation', 'crm_en', { + name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, crm2_child: { label: 'Copy' } }, + }); + expect((out as { refusal: string }).refusal).toMatch( + /^Translation 'crm_en' is not copied: its `flows` key 'crm_child' follows the copied flow to 'crm2_child', a key it already holds there/, + ); + }); + + it('CONTROL: a copy that keeps the source namespace renames no flow and rewrites no call', () => { + const rename = plan('crm'); + expect(rename.copyName('flow', 'crm_child')).toBe('crm_child'); + expect(itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body)).nodes[1].config.flowName).toBe('crm_child'); + }); +}); From 5ec669b169b29c43469cce4c2e90c999b7aad7db Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:21:23 +0000 Subject: [PATCH 03/10] chore(changeset): metadata-protocol patch for flow references following a copy's flows Claude-Session: https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE Co-authored-by: Claude --- .changeset/38595-rename-flow-references.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .changeset/38595-rename-flow-references.md diff --git a/.changeset/38595-rename-flow-references.md b/.changeset/38595-rename-flow-references.md new file mode 100644 index 00000000000..d8f3f8347b8 --- /dev/null +++ b/.changeset/38595-rename-flow-references.md @@ -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. From fb44b0f29e0379caad9cd73d7bfc531cfbd98a11 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 18:50:22 +0000 Subject: [PATCH 04/10] chore(engine-double-contract): record the new card test's pinned engine doubles The door pins for the flow-reference rename copy the stub engine of package-unmanaged-install.test.ts; `check-engine-double-contract --write` records its three pinned verbs (15 lines added, none changed, no seam lost). Claude-Session: https://claude.ai/code/session_01ADHkmRar3Kkg6SpwVgaaVE Co-authored-by: Claude --- scripts/engine-double-contract.pinned.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 59522064a98..d376134e2ba 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -301,6 +301,21 @@ "verb": "update", "pinned": 4 }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/package-unmanaged-install.test.ts", "verb": "delete", From 2af21e1a6e241d30312473aeeaab840329cf0033 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:20:27 +0000 Subject: [PATCH 05/10] test(metadata-protocol): measure a parent-first duplicate under the publish gate Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- ...e-namespace-rename-flow-refs-38595.test.ts | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts index dfeaa94f5b9..31c14f0a9f1 100644 --- a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts @@ -308,3 +308,50 @@ describe('duplicatePackage — the same items as the import: the copy\'s callers expect(pick(itemsOf(viaDuplicate.table, 'com.example.crm2'))).toEqual(imported); }); }); + +describe('duplicatePackage of a parent-first package — the publish gate resolves a call to a flow the same copy writes later (#38595)', () => { + // The CALLER is stored first: the copy loop writes `crm2_parent`, whose + // step now names `crm2_child`, before `crm2_child` exists anywhere the + // gate reads (the engine, the registry, the stored rows). + const parentFirst = () => callerBody([flow('crm_parent', 'crm_child'), flow('crm_child')]); + + it('copies both flows, and the stored `crm2_parent` calls `crm2_child`', async () => { + const { protocol, table } = makeProtocol(['other_flow', 'crm_child', 'crm_parent']); + await protocol.importUnmanagedPackage({ manifest: parentFirst(), targetPackageId: 'com.example.crm-base' }); + // The stored order is the one the card measures: parent before child. + expect(table('sys_metadata') + .filter((r) => r.package_id === 'com.example.crm-base' && r.type === 'flow') + .map((r) => r.name)).toEqual(['crm_parent', 'crm_child']); + + const duplicated = await protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + + expect(duplicated.failed).toEqual([]); + const copy = itemsOf(table, 'com.example.crm2'); + expect(Object.keys(copy).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_child', 'flow/crm2_parent']); + expect(calledBy(copy['flow/crm2_parent'])).toBe('crm2_child'); + }); + + it('CONTROL: the gate is live here — a copied call to a flow neither the copy nor the deployment holds is refused', async () => { + // The engine holds `crm_ghost` while the source installs, and no longer + // when it is copied. The package holds no such flow, so the copy keeps + // the name, and nothing the copy writes can resolve it. + const engineFlows = ['other_flow', 'crm_ghost', 'crm_child', 'crm_parent']; + const { protocol, table } = makeProtocol(engineFlows); + await protocol.importUnmanagedPackage({ + manifest: callerBody([flow('crm_parent', 'crm_child'), flow('crm_child'), flow('crm_caller', 'crm_ghost')]), + targetPackageId: 'com.example.crm-base', + }); + engineFlows.splice(engineFlows.indexOf('crm_ghost'), 1); + + const duplicated = await protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + + expect(duplicated.failed.map((f: { type: string; name: string }) => `${f.type}/${f.name}`)).toEqual(['flow/crm_caller']); + expect(duplicated.failed[0].error).toContain('flow-subflow-unknown'); + const copy = itemsOf(table, 'com.example.crm2'); + expect(Object.keys(copy).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_child', 'flow/crm2_parent']); + }); +}); From 300cf74f038b4ed625b1020f7cb6c06a0e61a541 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:25:18 +0000 Subject: [PATCH 06/10] fix(metadata-protocol): a duplicate's flow writes state the copy's flow names to the publish gate Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- .../src/protocol-package-commits.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 6208dd0b9a3..d064b03b149 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -596,6 +596,20 @@ export class ProtocolPackageCommitsFacet { // Derived from the stored row, never from the request; a key // the rewrite above renamed is not the source's, and is judged. ...(singular === 'permission' ? { inheritedGrantObjects: storedGrantObjectKeys(body) } : {}), + // [#35143, #38595] Every flow this copy writes, under its + // copy name: the rows go in one at a time, in stored order, + // and the rename engine points a copied `subflow` / `map` + // step at the COPY's flow, so a caller stored before its + // callee would meet a publish gate that holds no such flow + // yet. Stated on a flow write only, as the unmanaged + // install leg states its own (`copyPlanFlowNames`). + ...(singular === 'flow' + ? { + copyPlanFlowNames: rows + .filter((r) => (PLURAL_TO_SINGULAR[String(r?.type)] ?? String(r?.type)) === 'flow' && typeof r?.name === 'string') + .map((r) => rename.copyName(String(r.type), r.name)), + } + : {}), ...(request.actor ? { actor: request.actor } : {}), }); // [#32369] Read back BEFORE the row is answered copied: a read From 964a3267d6a7b78f2df160ee862de8271a26c8de Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:25:48 +0000 Subject: [PATCH 07/10] docs(changeset): a parent-first duplicate copies both flows Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- .changeset/38595-rename-flow-references.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38595-rename-flow-references.md b/.changeset/38595-rename-flow-references.md index d8f3f8347b8..f7e908508e6 100644 --- a/.changeset/38595-rename-flow-references.md +++ b/.changeset/38595-rename-flow-references.md @@ -9,4 +9,4 @@ 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. +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. A `duplicatePackage` whose stored rows hold a calling flow before the flow it calls now copies both: the publish gate is told the flows the same copy writes, as it already was on the `unmanaged` install, where before it refused the caller with `flow-subflow-unknown` and only the called flow was copied. Nothing an author writes changes. From 48420e0856cb35fd889d0cee976b0d6ac0b418ec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:13:09 +0000 Subject: [PATCH 08/10] docs(metadata-protocol): copyPlanFlowNames is stated by both copy doors Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- .../metadata-protocol/src/protocol-door-requests.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index e26a7196da6..51b518a911f 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -29,10 +29,12 @@ type SaveMetaItemRequest = { */ inheritedGrantObjects?: readonly string[], /** - * [#35143] The names of the flows the same package copy writes, the copy - * door's plan (`importUnmanagedPackage`, whose items are the request's - * body; `duplicatePackage` copies stored rows, which the gate's own read - * of the stored flows already holds). A `flow` + * [#35143, #38595] The names of the flows the same package copy writes, + * under the names it writes them as: the copy door's plan. Both copy doors + * state it on each flow write: `importUnmanagedPackage`, whose items are + * the request's body, and `duplicatePackage`, whose items are stored rows + * renamed into the target namespace (a copied step calls the COPY's flow, + * which no stored row holds until the loop writes it). A `flow` * write's `subflow` / `map` call naming one of them is a call to a flow the * copy holds once its loop ends, so the publish gate resolves it, as it * resolves a flow of a `publishPackageDrafts` batch (`pending.flows`). From 28e48567ee88a596385ddec2951b932b0d311f24 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:54:49 +0000 Subject: [PATCH 09/10] fix(metadata-protocol): a duplicate withdraws a copied caller whose planned callee was not written Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- ...e-namespace-rename-flow-refs-38595.test.ts | 58 +++++++ .../src/protocol-package-commits.ts | 151 ++++++++++++++++-- 2 files changed, 194 insertions(+), 15 deletions(-) diff --git a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts index 31c14f0a9f1..9baf76815a6 100644 --- a/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts @@ -354,4 +354,62 @@ describe('duplicatePackage of a parent-first package — the publish gate resolv const copy = itemsOf(table, 'com.example.crm2'); expect(Object.keys(copy).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_child', 'flow/crm2_parent']); }); + + /** Every stored flow of the copy whose `subflow` step calls a flow the deployment does not hold. */ + const danglingCalls = (table: (name: string) => Row[], engineFlows: readonly string[]) => { + const stored = table('sys_metadata').filter((r) => r.type === 'flow' && r.state === 'active').map((r) => r.name); + const held = new Set([...engineFlows, ...stored]); + return Object.entries(itemsOf(table, 'com.example.crm2')) + .filter(([k, body]) => k.startsWith('flow/') && typeof calledBy(body) === 'string' && !held.has(calledBy(body) as string)) + .map(([k]) => k); + }; + + it('a caller whose planned callee fails is withdrawn with it: no copied flow calls a flow that exists nowhere', async () => { + // `crm_child` calls `crm_ghost`, which the engine holds at the source + // install and no longer at the copy, so the copy of `crm_child` fails. + const engineFlows = ['other_flow', 'crm_ghost', 'crm_child', 'crm_parent']; + const { protocol, table } = makeProtocol(engineFlows); + await protocol.importUnmanagedPackage({ + manifest: callerBody([flow('crm_parent', 'crm_child'), flow('crm_child', 'crm_ghost')]), + targetPackageId: 'com.example.crm-base', + }); + engineFlows.splice(engineFlows.indexOf('crm_ghost'), 1); + + const duplicated = await protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + + expect(duplicated.failed.map((f: { type: string; name: string }) => `${f.type}/${f.name}`).sort()) + .toEqual(['flow/crm_child', 'flow/crm_parent']); + const parent = duplicated.failed.find((f: { name: string }) => f.name === 'crm_parent'); + expect(parent.error).toContain("'crm2_child'"); + expect(duplicated.copied.filter((c: { type: string }) => c.type === 'flow')).toEqual([]); + expect(Object.keys(itemsOf(table, 'com.example.crm2')).filter((k) => k.startsWith('flow/'))).toEqual([]); + expect(danglingCalls(table, engineFlows)).toEqual([]); + // The copy's other items are still copied: the withdrawal is the callers' alone. + expect(itemsOf(table, 'com.example.crm2')['object/crm2_lead']).toBeDefined(); + }); + + it('transitive: in a chain a → b → c whose c fails, all three are withdrawn, and a flow outside the chain is copied', async () => { + const engineFlows = ['other_flow', 'crm_ghost', 'crm_a', 'crm_b', 'crm_c', 'crm_solo']; + const { protocol, table } = makeProtocol(engineFlows); + await protocol.importUnmanagedPackage({ + manifest: callerBody([ + flow('crm_a', 'crm_b'), flow('crm_b', 'crm_c'), flow('crm_c', 'crm_ghost'), flow('crm_solo'), + ]), + targetPackageId: 'com.example.crm-base', + }); + engineFlows.splice(engineFlows.indexOf('crm_ghost'), 1); + + const duplicated = await protocol.duplicatePackage({ + sourcePackageId: 'com.example.crm-base', targetPackageId: 'com.example.crm2', targetNamespace: 'crm2', + }); + + expect(duplicated.failed.map((f: { type: string; name: string }) => `${f.type}/${f.name}`).sort()) + .toEqual(['flow/crm_a', 'flow/crm_b', 'flow/crm_c']); + expect(duplicated.failed.find((f: { name: string }) => f.name === 'crm_a').error).toContain("'crm2_b'"); + expect(duplicated.failed.find((f: { name: string }) => f.name === 'crm_b').error).toContain("'crm2_c'"); + expect(Object.keys(itemsOf(table, 'com.example.crm2')).filter((k) => k.startsWith('flow/'))).toEqual(['flow/crm2_solo']); + expect(danglingCalls(table, engineFlows)).toEqual([]); + }); }); diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index d064b03b149..4ca8e112244 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -42,6 +42,7 @@ import { type UnmanagedImportRenameRefusal, } from './package-unmanaged-install.js'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; +import { FLOW_REGION_SLOTS_BY_TYPE } from '@objectstack/spec/automation'; import { DEFAULT_METADATA_TYPE_REGISTRY, ManifestSchema, @@ -470,6 +471,52 @@ export class ProtocolPackageCommitsFacet { // the same engine, and a package with fifty flows should not walk the // service table fifty times. const canonicalizeFlow = host.resolveFlowCanonicalizer(); + // [#35143, #38595] The copy's flow plan: every flow row this copy plans + // to write, under its copy name, and the copy name back to its source + // row. The publish gate is told the plan on each flow write (the + // `saveMetaItem` call below), so a caller stored before its callee + // passes; the close below withdraws every caller whose planned callee + // the copy did not, in the end, write. + const planFlowSources = new Map(); + for (const r of rows) { + if ((PLURAL_TO_SINGULAR[String(r?.type)] ?? String(r?.type)) !== 'flow' || typeof r?.name !== 'string') continue; + planFlowSources.set(rename.copyName(String(r.type), r.name), r.name); + } + const copyPlanFlowNames = [...planFlowSources.keys()]; + // The planned flows a copied body calls through a `subflow` / `map` + // step, at any depth of its regions (the publish gate's walk, over the + // spec's region table), other than itself. + const plannedCalleesOf = (flowBody: unknown, ownName: string): string[] => { + const out = new Set(); + const visit = (nodes: unknown, depth: number): void => { + if (!Array.isArray(nodes) || depth > 16) return; + for (const node of nodes) { + if (!node || typeof node !== 'object' || Array.isArray(node)) continue; + const config = (node as { config?: unknown }).config; + const configRec = config && typeof config === 'object' && !Array.isArray(config) ? config as Record : undefined; + const type = (node as { type?: unknown }).type; + if ((type === 'subflow' || type === 'map') && typeof configRec?.flowName === 'string') { + const called = configRec.flowName.trim(); + if (called !== ownName && planFlowSources.has(called)) out.add(called); + } + const slots = typeof type === 'string' ? FLOW_REGION_SLOTS_BY_TYPE.get(type) : undefined; + if (!slots || !configRec) continue; + for (const slot of slots) { + const value = configRec[slot.key]; + const regions = slot.arity === 'many' ? (Array.isArray(value) ? value : []) : [value]; + for (const region of regions) { + if (region && typeof region === 'object' && !Array.isArray(region)) visit((region as { nodes?: unknown }).nodes, depth + 1); + } + } + } + }; + if (flowBody && typeof flowBody === 'object' && !Array.isArray(flowBody)) visit((flowBody as { nodes?: unknown }).nodes, 0); + return [...out]; + }; + // The copied flows that call a planned flow, with how to take each back. + const writtenCallers: Array<{ + name: string; source: { type: string; name: string }; calls: readonly string[]; undo: () => Promise; + }> = []; for (const row of rows) { const refusal = row?.type === 'object' ? rename.objectRefusal(row.name) : undefined; @@ -570,7 +617,11 @@ export class ProtocolPackageCommitsFacet { // [#32369] The copy's own address before it writes there: what an // undo puts back if the registry refuses the row (a duplicate // again writes over its earlier copy). - const before = judging && isBatchObjectType(singular) + // [#38595] A copied flow that calls a planned flow is withdrawn + // by the close below if that callee is not written, so its + // address is read for the same undo. + const calls = singular === 'flow' ? plannedCalleesOf(rewritten, newName) : []; + const before = (judging && isBatchObjectType(singular)) || calls.length > 0 ? await readActiveBatchRow(host, { type: singular, name: newName, packageId: request.targetPackageId }) : null; await host.saveMetaItem({ @@ -596,22 +647,34 @@ export class ProtocolPackageCommitsFacet { // Derived from the stored row, never from the request; a key // the rewrite above renamed is not the source's, and is judged. ...(singular === 'permission' ? { inheritedGrantObjects: storedGrantObjectKeys(body) } : {}), - // [#35143, #38595] Every flow this copy writes, under its - // copy name: the rows go in one at a time, in stored order, - // and the rename engine points a copied `subflow` / `map` - // step at the COPY's flow, so a caller stored before its - // callee would meet a publish gate that holds no such flow - // yet. Stated on a flow write only, as the unmanaged - // install leg states its own (`copyPlanFlowNames`). - ...(singular === 'flow' - ? { - copyPlanFlowNames: rows - .filter((r) => (PLURAL_TO_SINGULAR[String(r?.type)] ?? String(r?.type)) === 'flow' && typeof r?.name === 'string') - .map((r) => rename.copyName(String(r.type), r.name)), - } - : {}), + // [#35143, #38595] Every flow this copy plans to write, under + // its copy name: the rows go in one at a time, in stored + // order, and the rename engine points a copied `subflow` / + // `map` step at the COPY's flow, so a caller stored before + // its callee would meet a publish gate that holds no such + // flow yet. Stated on a flow write only, as the unmanaged + // install leg states its own (`copyPlanFlowNames`). The + // plan is the gate's word only until the loop ends: the + // close below withdraws a caller whose callee failed. + ...(singular === 'flow' ? { copyPlanFlowNames } : {}), ...(request.actor ? { actor: request.actor } : {}), }); + if (calls.length > 0) { + const stored = await readActiveBatchRow(host, { type: singular, name: newName, packageId: request.targetPackageId }); + const address = { + type: singular, name: newName, packageId: request.targetPackageId, + prevVersion: before?.version ?? null, + writtenHash: stored?.hash ?? null, + }; + writtenCallers.push({ + name: newName, source: { type: row.type, name: row.name }, calls, + undo: () => undoBatchRowWrite(host, address, { + ...(request.actor ? { actor: request.actor } : {}), + source: 'protocol.duplicatePackage', + message: `undo the copy of ${row.type}/${row.name}: a flow it calls was not copied`, + }), + }); + } // [#32369] Read back BEFORE the row is answered copied: a read // that fails lands the row in `failed[]` alone (the `catch` // below), never in both lists. @@ -663,6 +726,64 @@ export class ProtocolPackageCommitsFacet { ); } } + // [#38595] The flow plan, settled. The publish gate passed every + // copied caller on the plan's word, but this copy is best-effort: a + // planned flow can still land in `failed[]` (it does not canonicalize, + // does not convert, its rename collides, or the save door refuses it). + // A caller of such a flow would be copied calling a flow that exists + // nowhere, which is what the gate refuses, and whether it was copied + // would depend on the stored order. So every copied caller of a planned + // flow that was not written is taken back out of the copy, through the + // same undo the object settle uses, and reported in `failed[]` naming + // that callee. Transitive: a caller taken back is itself not written, + // so its own callers go too, until nothing changes. + { + const writtenFlows = new Set(copied + .filter((c) => (PLURAL_TO_SINGULAR[c.type] ?? c.type) === 'flow') + .map((c) => c.name)); + const notWritten = new Map(); + for (const [copyName, sourceName] of planFlowSources) { + if (!writtenFlows.has(copyName)) notWritten.set(copyName, `the copy of flow '${sourceName}' is in failed[]`); + } + let live = writtenCallers; + for (;;) { + const withdrawn = live.filter((w) => w.calls.some((c) => notWritten.has(c))); + if (withdrawn.length === 0) break; + live = live.filter((w) => !withdrawn.includes(w)); + for (const w of withdrawn) { + const callee = w.calls.find((c) => notWritten.has(c))!; + const at = copied.findIndex((c) => c.name === w.name && c.type === w.source.type); + if (at !== -1) copied.splice(at, 1); + const reason = `the copy '${w.name}' calls flow '${callee}' through a subflow or map step, but this ` + + `duplicate did not write '${callee}' (${notWritten.get(callee)}), so the copy was withdrawn with it; ` + + 'fix that flow, then copy again.'; + let undoError: unknown; + try { + await w.undo(); + } catch (e) { + undoError = e; + } + failed.push({ + type: w.source.type, + name: w.source.name, + error: undoError === undefined + ? reason + : undoError instanceof BatchRowHealError + ? `${reason} The copy '${w.name}' was taken back, but the registry could not be put back ` + + `(${clientFacingFailureText(undoError.healError, 'heal failed')}) and may serve it until the server restarts.` + : `${reason} The copy '${w.name}' could not be taken back ` + + `(${clientFacingFailureText(undoError, 'undo failed')}): it is stored although it calls a flow that was not copied; ` + + 'delete it, then copy the corrected source again.', + }); + console.warn( + `[protocol.duplicatePackage] the copy of ${w.source.type}/${w.source.name} → ` + + `'${request.targetPackageId}' calls '${callee}', which was not copied, and ` + + `${undoOutcomeForLog(undoError)}`, + ); + notWritten.set(w.name, `the copy of flow '${w.source.name}' was withdrawn`); + } + } + } // [#32369, ADR-0144 D2 and D6] The copied objects as ONE unit, after the // copy's own registrations: a row whose pair the registry refuses — at // its registration (D6's roll-up door, only logged at the write-through) From 712fda7a6db7ff43af8b13f9fab2e6dd16d78464 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:55:37 +0000 Subject: [PATCH 10/10] docs(metadata-protocol): the copy plan is what a copy plans to write, and a duplicate withdraws callers of an unwritten flow Claude-Session: https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW Co-authored-by: Claude --- .changeset/38595-rename-flow-references.md | 2 +- .../src/protocol-door-requests.ts | 21 +++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.changeset/38595-rename-flow-references.md b/.changeset/38595-rename-flow-references.md index f7e908508e6..ef2d07556e4 100644 --- a/.changeset/38595-rename-flow-references.md +++ b/.changeset/38595-rename-flow-references.md @@ -9,4 +9,4 @@ 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. A `duplicatePackage` whose stored rows hold a calling flow before the flow it calls now copies both: the publish gate is told the flows the same copy writes, as it already was on the `unmanaged` install, where before it refused the caller with `flow-subflow-unknown` and only the called flow was copied. Nothing an author writes changes. +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. A `duplicatePackage` whose stored rows hold a calling flow before the flow it calls now copies both: the publish gate is told the flows the copy plans to write, as it already was on the `unmanaged` install, where before it refused the caller with `flow-subflow-unknown` and only the called flow was copied. When a planned flow is not copied after all (it lands in `failed[]`), every copied flow that calls it is withdrawn with it, transitively, into `failed[]` with an error naming that flow, so no copied flow calls a flow that exists nowhere. Nothing an author writes changes. diff --git a/packages/metadata-protocol/src/protocol-door-requests.ts b/packages/metadata-protocol/src/protocol-door-requests.ts index 51b518a911f..d0eb72540cb 100644 --- a/packages/metadata-protocol/src/protocol-door-requests.ts +++ b/packages/metadata-protocol/src/protocol-door-requests.ts @@ -29,15 +29,18 @@ type SaveMetaItemRequest = { */ inheritedGrantObjects?: readonly string[], /** - * [#35143, #38595] The names of the flows the same package copy writes, - * under the names it writes them as: the copy door's plan. Both copy doors - * state it on each flow write: `importUnmanagedPackage`, whose items are - * the request's body, and `duplicatePackage`, whose items are stored rows - * renamed into the target namespace (a copied step calls the COPY's flow, - * which no stored row holds until the loop writes it). A `flow` - * write's `subflow` / `map` call naming one of them is a call to a flow the - * copy holds once its loop ends, so the publish gate resolves it, as it - * resolves a flow of a `publishPackageDrafts` batch (`pending.flows`). + * [#35143, #38595] The names of the flows the same package copy plans to + * write, under the names it writes them as: the copy door's plan. Both + * copy doors state it on each flow write: `importUnmanagedPackage`, whose + * items are the request's body, and `duplicatePackage`, whose items are + * stored rows renamed into the target namespace (a copied step calls the + * COPY's flow, which no stored row holds until the loop writes it). A + * `flow` write's `subflow` / `map` call naming one of them is resolved by + * the publish gate, as it resolves a flow of a `publishPackageDrafts` + * batch (`pending.flows`). The plan holds once the loop ends: the import + * is all-or-nothing, and on the best-effort duplicate a copied caller + * whose planned callee was not written is withdrawn with it, into + * `failed[]`. * Additive only: a name can let a call through, never refuse one. Set by * server code only; no HTTP door forwards it. */