Skip to content

Commit 4895661

Browse files
fix(metadata-protocol): a package copy under a new namespace calls its own flows (#38642)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9St4eUWHFcCKuRUrCZPperJ)_ Fixes #38595 Clause-②: no Metadata-protocol: none ## 维护者速读 - 管理员把一个应用包以新的命名空间安装或复制之后,复制出来的流程调用的是复制包自己的子流程,按钮触发的也是复制包自己的流程;以前调用的是原包的流程,或者因为找不到流程而每次运行都失败。复制时如果调用方流程排在被调用流程前面,现在两个流程都会复制成功,不再被保存检查拒掉调用方;如果被调用的流程本身复制失败,调用它的流程也一并列为失败并撤回,不会留下指向不存在流程的调用。 - 属于"软件包安装与复制"这块能力,替用新命名空间安装应用包、或复制一份应用包来改的管理员解决"复制后流程跑不起来或串到原包"的问题。 - 只影响带新命名空间的安装和复制;如果改名规则出错,复制包里的某个流程调用会指向错误的名字,原包不受影响,可以直接撤回这次合并恢复原来的行为。 - 无 ## What changes `planNamespaceRename` (`packages/metadata-protocol/src/package-namespace-rename.ts`), the one rename engine behind the unmanaged install's `targetNamespace` and `duplicatePackage`, renamed a package flow under the prefix swap (`crm_child` to `crm2_child`) but rewrote no name that calls it. It now builds a flow rename map from the package's own `flow` items and rewrites a value that EQUALS a renamed flow name, whole, at: - the derived index's `flow` sites, `REFERENCE_SITES.byTarget.get('flow')`, read the same way the object sites are (by property, wherever it occurs). Dumped at runtime on this tree it holds `{fromType:'flow', property:'flowName'}` and `{fromType:'translation', property:'flows'}`, so a `subflow` step's `config.flowName` and a translation's `flows` keys follow; - the one hand-written site, commented as such in the code: a `target` whose sibling executor is `'flow'`. That is `type: 'flow'` on an action (`ActionSchema`, an object's `actions[]`, an inline action, an `action:group` member, an API endpoint) and `actionType: 'flow'` on an `action:button` / `action:icon` page block, where `type` is the component. The index cannot carry `target`, because on every other executor it names a URL, script, page, endpoint or form, and a property-wide site would rewrite those too and list them in the "Used by" answer. A flow the package does not hold keeps its name, a flow the prefix swap keeps keeps its name, and nothing is substring-rewritten. A value that is not a renamed flow name falls through to the rules every string already took, so nothing that read the same before reads differently now. Collisions work as they do for objects: a renamed flow name that meets a name the item already holds at that site (a translation keyed by both `crm_child` and `crm2_child`) refuses the item, and the refusal names the flow. The internal `atReference: boolean` of the walk became the site's rename map (object or flow), so both kinds share one walk and one collision rule. **This round (delta after PR #38594 merged as d33183a).** `origin/main` was merged into this branch with a merge commit (3a7134a, no conflicts). With both changes on one tree, a parent-first `duplicatePackage` was refused by the publish gate (measurement below). So the `duplicatePackage` leg's `host.saveMetaItem` call in `protocol-package-commits.ts` now passes `copyPlanFlowNames` on a flow write, the unmanaged-install leg's way: the copy names (`rename.copyName`) of every flow row the same duplicate writes. On a non-flow write nothing is passed. The gate's rule itself is not touched; the names are additive (`pending.flows`), so they can let a call to a flow of the same copy through and refuse nothing. **Third round (L1 REWORK 7267334209, route per claim amendment 7267347516).** `duplicatePackage` is best-effort, so a planned flow can still land in `failed[]` after the gate passed its caller on the plan's word. The duplicate leg now closes its flow plan after the copy loop. Each copied flow whose `subflow` / `map` step calls a planned flow (its copy name) that was not written is taken back out of the copy, through the same `undoBatchRowWrite` the object settle uses. It is reported in `failed[]` with an error that names that callee. This repeats until nothing changes, so a caller's caller goes too. The loop reads a caller's address before and after its write for that undo, only when the caller calls a planned flow. The plan is now one list built before the loop (`planFlowSources`). The callee walk uses the spec's `FLOW_REGION_SLOTS_BY_TYPE`, the region table the publish gate walks. The install leg is not touched. ## Tests <details><summary>Engine pins, package-namespace-rename.test.ts (7 new cases)</summary> `flowName` follows; `other_flow`, an unprefixed `bare_child` and a superstring `crm_child_v2` keep their names; a flow action's `target` follows while `modal` / `script` / `api` targets equal to the same string do not; the object `actions[]`, API endpoint and page `actionType` spellings; translation `flows` keys; the collision refusal; and a copy that keeps the source namespace renames nothing. </details> <details><summary>Door pins, new package-namespace-rename-flow-refs-38595.test.ts (6 cases)</summary> The harness (`makeEngine`, `crmBody`) is copied from `package-unmanaged-install.test.ts`, which is not edited. Its automation service answers `listFlows`, so a gate that judges a step's called flow has a non-empty universe. - an unmanaged install with `targetNamespace: 'crm2'` installs, and the stored `crm2_parent` calls `crm2_child`; - the copied flow action reads `target: 'crm2_child'`, and the `modal` control keeps `target: 'crm_child'`; - with the source package installed under its own names beside the copy, the copy's `crm2_parent` calls `crm2_child`; - a call to `other_flow` keeps its name; - `duplicatePackage` into `crm2` gives the same result with the source installed, and the source still calls `crm_child`; - parity: the duplicate and the import into `crm2` store identical flow and action items. </details> <details><summary>Stacking measurement (this round), new describe in package-namespace-rename-flow-refs-38595.test.ts (2 cases)</summary> The source package is installed with its stored flow rows in the order `crm_parent` (a `subflow` step calling `crm_child`), then `crm_child`; the test asserts that order. It is then duplicated into `crm2`. The automation service holds `other_flow`, `crm_child`, `crm_parent`, never `crm2_child`. Measured at 2af21e1 (merge of `main` plus the test, before the fix), the gate refuses. `duplicated.failed` was, verbatim: ``` [{ type: 'flow', name: 'crm_parent', error: 'flow/crm2_parent failed author-time validation: 1 issue — flows[0].nodes[1].config.flowName [flow-subflow-unknown]' }] ``` and only `crm2_child` was copied (`Tests 2 failed | 6 passed (8)`). With the fix (300cf74) the case passes: `failed` is empty, both flows are stored and `crm2_parent` calls `crm2_child`. CONTROL, the gate is live in this harness: a third flow `crm_caller` calls `crm_ghost`, which the engine holds at the source install and no longer at the copy, and the package holds no such flow. The copy keeps the name `crm_ghost`, and with the fix the duplicate still refuses exactly `flow/crm_caller` with `flow-subflow-unknown` while both other flows are copied. So the plan names let through only the copy's own flows. </details> <details><summary>Withdrawal pins (third round), same describe (2 cases)</summary> - (a) L1's parent-first case. `crm_parent` calls `crm_child`, and `crm_child` calls `crm_ghost`, which the engine holds at the source install and drops before the duplicate. `failed` holds `flow/crm_child` and `flow/crm_parent`, and the parent's error names `'crm2_child'`. No flow of the copy is stored, no stored copied flow calls a flow the deployment does not hold, and the copy's object is still copied. - (b) A two-level chain, `crm_a` to `crm_b` to `crm_c`, with `crm_c` calling the dropped `crm_ghost`. All three end in `failed[]` (the errors of `a` and `b` name `'crm2_b'` and `'crm2_c'`). `crm2_solo`, outside the chain, is the only copied flow, and nothing copied calls a missing flow. - The success pins and the `crm_ghost` CONTROL pass unchanged: `Tests 10 passed (10)` for the card file at 712fda7. Ablations, each run after the fix commit 28e4856 with `scripts/ablation-replace.mjs`: - Cascade off: `if (withdrawn.length === 0) break;` became `if (withdrawn.length >= 0) break;` (blob `4ca8e112244c` to `6eec66471fb7`). Result: `Tests 2 failed | 8 passed (10)`. (a) fails with `expected [ 'flow/crm_child' ] to deeply equal [ 'flow/crm_child', 'flow/crm_parent' ]`, which is L1's measured state, and (b) fails with `expected [ 'flow/crm_c' ] …`. - Transitive step off: the line that marks a withdrawn caller as not written was deleted (blob `4ca8e112244c` to `378006812f35`). Result: `Tests 1 failed | 9 passed (10)`. Only (b) fails, with `expected [ 'flow/crm_b', 'flow/crm_c' ] …`. - Both times the tool restored the file: blob equal to HEAD, and `git diff HEAD` empty. </details> <details><summary>Ablation of the second round's line</summary> The fix was committed first (300cf74). `node scripts/ablation-replace.mjs` replaced the guard `...(singular === 'flow'` of the new spread with `...(false` (anchor 1 to 0, blob `d064b03b149a` to `f110fae517f4`). The card test file then failed both new cases (`Tests 2 failed | 6 passed (8)`): the parent-first case with the refusal above, the CONTROL because `crm2_parent` was refused beside `crm_caller`. The tool restored the file: blob equal to HEAD, `git diff HEAD` empty. </details> <details><summary>Package run at 712fda7 (third round)</summary> `pnpm --filter @objectstack/metadata-protocol typecheck && pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2` under the verify lock: `VERDICT command-exit 0`, `Test Files 374 passed | 9 skipped (383)`, `Tests 23690 passed | 45 skipped (23735)`. The 69 families `dispatch-gates --commands` derives for this round's four paths: 67 exit 0. `check:dual-build-cjs-loads` and `check:lean-entry-closure` exit 3 (PREREQUISITE NOT MET: they read every package's `dist`), so they are NOT MEASURED here and left to CI. `overlap-check`: clean. </details> <details><summary>Package run at 964a326 (second round)</summary> `pnpm --filter @objectstack/metadata-protocol typecheck && pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2` under the verify lock, after building the closure (`pnpm --filter '@objectstack/metadata-protocol^...' build`): `VERDICT command-exit 0`, `Test Files 374 passed | 9 skipped (383)`, `Tests 23688 passed | 45 skipped (23733)`. The card pins after the merge (`package-namespace-rename-flow-refs-38595.test.ts`, `package-namespace-rename.test.ts`, `package-unmanaged-install.test.ts`): `Test Files 3 passed (3)`, `Tests 152 passed (152)`. </details> <details><summary>Package run at 5ec669b (first round)</summary> `pnpm --filter @objectstack/metadata-protocol typecheck && … exec vitest run --maxWorkers=2` under the verify lock: `VERDICT command-exit 0`, `Test Files 373 passed | 9 skipped (382)`, `Tests 23670 passed | 45 skipped (23715)`. The typecheck program lists the test files. </details> <details><summary>Ablation</summary> The fix commit came first. Then `scripts/ablation-replace.mjs` swapped the one line that fills the flow rename map for a no-op (anchor 1 to 0, blob `e90813508b99` to `114356add0b3`). With that in place, 9 of the 13 new cases failed (`Tests 9 failed | 26 passed (35)`): every rewrite pin on both test files. The four that stayed green were the three controls and the parity case, which stays equal when both doors are equally wrong. The tool then restored the file: the blob matched HEAD again and `git diff HEAD` was empty. </details> <details><summary>Under PR #38594's gate (head 93f3643)</summary> In a throwaway tree at that head, with this branch's two commits cherry-picked, the closure was built and both test files passed (`Tests 42 passed`). With the same ablation there, the install pins fail with the gate's own 422: `INVALID_METADATA`, `flow-subflow-unknown` at `flows[0].nodes[1].config.flowName`, "calls flow 'crm_child' … Did you mean crm2_child". So the gate is live in this harness and the pins pass under it, without depending on its code. The tree was removed afterwards. </details> ## Acceptance notes - **The parent-first duplicate is fixed in this PR now.** The first round reported that with this branch and PR #38594 both applied, a parent-first `duplicatePackage` fails `flow-subflow-unknown` and writes only the child. PR #38594 merged without a copy-plan on its duplicate leg, so the seat routed the fix here (claim amendment 7266007014). It was re-measured on the merged tree (see Tests) and fixed on the duplicate leg's `saveMetaItem` call alone. - The `copyPlanFlowNames` doc comment in `protocol-door-requests.ts` said "`duplicatePackage` copies stored rows, which the gate's own read of the stored flows already holds". That stopped being true once the copy's calls name the copy's flows. Per claim amendment 7266793287, 48420e0 rewords that comment only: both copy doors state the field, the names the same copy writes under their written names. In the third round (712fda7), the comment and the changeset sentence say the gate is told the flows the copy PLANS to write. They also say that on the duplicate, a caller whose planned callee was not written is withdrawn with it. No logic changes; metadata-protocol typecheck exits 0, and the 48 families `dispatch-gates --commands` derives for that path ran with 46 at exit 0 and `check:dual-build-cjs-loads` / `check:lean-entry-closure` at exit 3 (PREREQUISITE NOT MET, left to CI). - Measured with the same engine probe, outside this card: the names of other non-object items (dashboard, page, report) are renamed by the prefix swap, but their references are not. That covers app navigation's `dashboardName` / `pageName` / `reportName` and a translation's `dashboards` / `pages` / `reports` keys. A dashboard header action with `actionType: 'flow'` keeps its `actionUrl`. These are reported to the seat as one family. They are not fixed here. - Outside the dispatched file surface, added by the PM's amendment: `scripts/engine-double-contract.pinned.json` gains 3 rows (15 lines) for the new test file's copied stub engine, produced by `node scripts/check-engine-double-contract.mjs --write`. No existing row changed, and `pnpm check:engine-double-contract` exits 0 at fb44b0f and again at 964a326. - Local gates at 964a326: the 77 families `dispatch-gates --commands` derives for this diff were run; 75 exit 0, and `check:dual-build-cjs-loads` and `check:lean-entry-closure` exit 3 (`PREREQUISITE NOT MET`: they read every package's built `dist`, which this worktree built only for the closure), so those two are NOT MEASURED here and are left to CI. `overlap-check`: clean against `origin/main`, #38618 and #38497. - Read, not changed (for the seat): whether `importUnmanagedPackage` has the same gap on partial failure. It does not, as read at 712fda7. Its prepare pass refuses the whole install before the base exists if any item fails to convert or rename (422 or the rename refusal). Its `copyPlanFlowNames` is built from `prepared`, which is exactly the items the write loop writes. Any `saveMetaItem` throw in that loop, and any object the batch settle refuses, goes through `rollBackUnmanagedImport`, which deletes the whole new base. So on success every planned flow is written, and on failure nothing remains. The one residue is a rollback that itself fails. It is not silent: `console.error`, plus an answer saying the base could NOT be fully removed and must be uninstalled. ## Verification Read first, by risk: 1. `protocol-package-commits.ts`, the `duplicatePackage` leg's close: the withdrawal block after the copy loop (the fixpoint, the undo and the error text), and `plannedCalleesOf` with `planFlowSources` above the loop. Check that a withdrawn caller is removed from `copied` and pushed to `failed[]` exactly once. 2. `package-namespace-rename.ts`, the `deepRewrite` object branch: the child-site expression `referenceSiteOf(k) ?? (site && k === 'name' ? site : flowTargetSite(v, k))` replaced the old boolean. Object sites must behave exactly as before. 3. `package-namespace-rename-flow-refs-38595.test.ts`: the parent-first duplicate and its CONTROL, the source-still-installed case and the duplicate parity. (`flowTargetSite` and `FLOW_EXECUTOR_KEYS` in `package-namespace-rename.ts`, the one hand-written site, were read in the first round's review.) Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/package-namespace-rename-flow-refs-38595.test.ts src/package-namespace-rename.test.ts` should report 2 files and 39 tests passing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmQJUGAAa5rz9Yi2DvW <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmQJUGAAa5rz9Yi2DvW --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 25ac5df commit 4895661

7 files changed

Lines changed: 764 additions & 19 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a package copied under a new namespace calls its own flows
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.

‎packages/metadata-protocol/src/package-namespace-rename-flow-refs-38595.test.ts‎

Lines changed: 415 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/metadata-protocol/src/package-namespace-rename.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,3 +323,102 @@ describe('planNamespaceRename — a copied capability, and every grant and requi
323323
});
324324
});
325325

326+
327+
describe('planNamespaceRename — a flow name follows the flow, at every site that calls it (#38595)', () => {
328+
const subflow = (name: string, calls: string) => ({
329+
name, label: name, type: 'autolaunched',
330+
nodes: [
331+
{ id: 'start', type: 'start', label: 'Start' },
332+
{ id: 'call', type: 'subflow', label: 'Call', config: { flowName: calls } },
333+
],
334+
edges: [{ id: 'e1', source: 'start', target: 'call' }],
335+
});
336+
const flowItems: NamespaceRenameItem[] = [
337+
...items,
338+
{ type: 'flow', name: 'crm_parent', body: subflow('crm_parent', 'crm_child') },
339+
{ type: 'flow', name: 'crm_child', body: { name: 'crm_child', label: 'Child', type: 'autolaunched', nodes: [], edges: [] } },
340+
// The prefix swap keeps a flow without the source prefix, so nothing names it anew.
341+
{ type: 'flow', name: 'bare_child', body: { name: 'bare_child', label: 'Bare', type: 'autolaunched', nodes: [], edges: [] } },
342+
];
343+
const plan = (targetNamespace = 'crm2', list = flowItems) => planNamespaceRename({
344+
sourcePackageId: 'com.example.crm', sourceNamespace: 'crm', targetNamespace, items: list, retryVerb: 'install',
345+
});
346+
const itemOf = (out: unknown) => (out as { item: any }).item;
347+
348+
it('a subflow step\'s `config.flowName` naming a package flow takes that flow\'s copy name', () => {
349+
const rename = plan();
350+
expect(rename.copyName('flow', 'crm_child')).toBe('crm2_child');
351+
const parent = itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body));
352+
expect(parent.name).toBe('crm2_parent');
353+
expect(parent.nodes[1].config.flowName).toBe('crm2_child');
354+
// The edge's `target` is a node id, not a flow: it is never a flow site.
355+
expect(parent.edges[0]).toEqual({ id: 'e1', source: 'start', target: 'call' });
356+
});
357+
358+
it('CONTROL: a flow the package does not hold keeps its name, and so does one the prefix swap keeps', () => {
359+
const rename = plan();
360+
expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'other_flow'))).nodes[1].config.flowName)
361+
.toBe('other_flow');
362+
expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'bare_child'))).nodes[1].config.flowName)
363+
.toBe('bare_child');
364+
// Never a substring: a name that merely contains a renamed flow's is another name.
365+
expect(itemOf(rename.rewrite('flow', 'crm_parent', subflow('crm_parent', 'crm_child_v2'))).nodes[1].config.flowName)
366+
.toBe('crm_child_v2');
367+
});
368+
369+
it('a flow action\'s `target` follows the flow; a `target` beside any other executor does not (CONTROL)', () => {
370+
const rename = plan();
371+
const flowAction = itemOf(rename.rewrite('action', 'crm_run_child', {
372+
name: 'crm_run_child', objectName: 'crm_lead', type: 'flow', target: 'crm_child',
373+
}));
374+
expect(flowAction).toMatchObject({ name: 'crm2_run_child', objectName: 'crm2_lead', type: 'flow', target: 'crm2_child' });
375+
for (const type of ['modal', 'script', 'api']) {
376+
const other = itemOf(rename.rewrite('action', 'crm_open_child', {
377+
name: 'crm_open_child', objectName: 'crm_lead', type, target: 'crm_child',
378+
}));
379+
expect(other.target).toBe('crm_child');
380+
}
381+
});
382+
383+
it('the same `target` rule holds wherever an action sits: an object\'s actions, an API endpoint, a page action block', () => {
384+
const rename = plan();
385+
const object = itemOf(rename.rewrite('object', 'crm_lead', {
386+
name: 'crm_lead', fields: {}, actions: [{ name: 'run', type: 'flow', target: 'crm_child' }, { name: 'open', type: 'modal', target: 'crm_child' }],
387+
}));
388+
expect(object.actions.map((a: any) => a.target)).toEqual(['crm2_child', 'crm_child']);
389+
const api = itemOf(rename.rewrite('api', 'crm_run', { name: 'crm_run', path: '/api/v1/apps/crm/run', method: 'POST', type: 'flow', target: 'crm_child' }));
390+
expect(api.target).toBe('crm2_child');
391+
// On a page block `type` is the component, so the executor is `actionType`.
392+
const page = itemOf(rename.rewrite('page', 'crm_home', {
393+
name: 'crm_home',
394+
regions: [{ components: [
395+
{ type: 'action:button', properties: { label: 'Run', actionType: 'flow', target: 'crm_child' } },
396+
{ type: 'action:button', properties: { label: 'Go', actionType: 'url', target: '/crm_child' } },
397+
] }],
398+
}));
399+
expect(page.regions[0].components.map((c: any) => c.properties.target)).toEqual(['crm2_child', '/crm_child']);
400+
});
401+
402+
it('a translation\'s `flows` keys follow the flows — the index\'s second flow site', () => {
403+
const rename = plan();
404+
const bundle = itemOf(rename.rewrite('translation', 'crm_en', {
405+
name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, other_flow: { label: 'Other' } },
406+
}));
407+
expect(bundle.flows).toEqual({ crm2_child: { label: 'Child' }, other_flow: { label: 'Other' } });
408+
});
409+
410+
it('a renamed flow name meeting one the item already holds there is refused, never merged — as for an object', () => {
411+
const out = plan().rewrite('translation', 'crm_en', {
412+
name: 'crm_en', locale: 'en', flows: { crm_child: { label: 'Child' }, crm2_child: { label: 'Copy' } },
413+
});
414+
expect((out as { refusal: string }).refusal).toMatch(
415+
/^Translation 'crm_en' is not copied: its `flows` key 'crm_child' follows the copied flow to 'crm2_child', a key it already holds there/,
416+
);
417+
});
418+
419+
it('CONTROL: a copy that keeps the source namespace renames no flow and rewrites no call', () => {
420+
const rename = plan('crm');
421+
expect(rename.copyName('flow', 'crm_child')).toBe('crm_child');
422+
expect(itemOf(rename.rewrite('flow', 'crm_parent', flowItems[3]!.body)).nodes[1].config.flowName).toBe('crm_child');
423+
});
424+
});

‎packages/metadata-protocol/src/package-namespace-rename.ts‎

Lines changed: 75 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ export interface NamespaceRename {
9494
*/
9595
copyNameRefusal(type: string, name: string): string | undefined;
9696
/**
97-
* The body as the copy writes it: every name the copy renames rewritten,
97+
* The body as the copy writes it: every name the copy renames rewritten
98+
* (an object's, and a flow's at the sites that call a flow, #38595),
9899
* `name` set to {@link copyName}, a permission set's field-rule keys
99100
* following the renamed objects — or the collision that refuses it.
100101
* `item` is the body converted to today's protocol; `name` is its SOURCE
@@ -138,6 +139,21 @@ function isCapabilityType(type: string): boolean {
138139
return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'capability';
139140
}
140141

142+
/** A `flow` row, in either spelling of the type. */
143+
function isFlowType(type: string): boolean {
144+
return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'flow';
145+
}
146+
147+
/**
148+
* [#38595] The keys that name an action's EXECUTOR beside its `target`: `type`
149+
* on an action (`ActionSchema`, an inline action, an `action:group` member, an
150+
* API endpoint), `actionType` on an `action:button` / `action:icon` page block,
151+
* whose `type` is the component itself. When the executor is `'flow'`, the
152+
* `target` is a flow name ("the flow name to invoke", `ActionSchema`'s
153+
* docblock), so it is a flow reference site. See `flowTargetSite` below.
154+
*/
155+
const FLOW_EXECUTOR_KEYS = ['type', 'actionType'] as const;
156+
141157
/**
142158
* [#35157] The keys a body names capabilities under: a permission set GRANTS
143159
* them (`systemPermissions`) and a resource REQUIRES them
@@ -463,10 +479,58 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam
463479
const objectReferenceProperties = new Set(
464480
(REFERENCE_SITES.byTarget.get('object') ?? []).map((site) => site.property),
465481
);
466-
type ReferenceCollision = { at: string; shape: 'key' | 'entry'; moved: string; met: string };
467-
const deepRewrite = (v: any, collisions: ReferenceCollision[], atReference = false, at = ''): any => {
482+
483+
// [#38595] ⭐ A FLOW NAME FOLLOWS THE FLOW, AS AN OBJECT NAME FOLLOWS THE
484+
// OBJECT. A package flow is copied under the prefix swap (`crm_child` →
485+
// `crm2_child`), and a flow is called by name: a `subflow` step's
486+
// `config.flowName`, a flow action's `target`. Left as written, the copy's
487+
// step called `crm_child` — a flow no copy holds, so every run failed, or,
488+
// with the source package still installed, the SOURCE's flow. So every
489+
// value that names a flow this copy renames is rewritten to the copy's
490+
// name, whole and only whole, at a flow reference site: the derived index's
491+
// `flow` sites (`REFERENCE_SITES`, target `flow`: `flowName`, a
492+
// translation's `flows` keys), read by property wherever it occurs, as the
493+
// object sites are, since a node config is declared by a node descriptor
494+
// the index reaches only through that property. A flow the package does
495+
// not hold, or one the prefix swap keeps (no source prefix), is not
496+
// renamed, so every name of it stays as written. A name that is not a
497+
// renamed flow's falls through to the rules every string takes, so
498+
// nothing that read the same before reads differently now.
499+
//
500+
// ⛔ REFUSED, NEVER MERGED, exactly as at an object site: a renamed flow
501+
// name meeting one the item already holds there (a translation's `flows`
502+
// keyed by both `crm_child` and `crm2_child`) is a collision.
503+
const flowRenames = new Map<string, string>();
504+
for (const item of items) {
505+
if (!isFlowType(item?.type) || typeof item.name !== 'string') continue;
506+
const nn = renameName(item.name);
507+
if (nn !== item.name) flowRenames.set(item.name, nn);
508+
}
509+
const flowReferenceProperties = new Set(
510+
(REFERENCE_SITES.byTarget.get('flow') ?? []).map((site) => site.property),
511+
);
512+
type ReferenceSiteRename = { readonly noun: 'object' | 'flow'; readonly renames: ReadonlyMap<string, string> };
513+
const OBJECT_SITE: ReferenceSiteRename = { noun: 'object', renames: renameMap };
514+
const FLOW_SITE: ReferenceSiteRename = { noun: 'flow', renames: flowRenames };
515+
// ⚠️ THE ONE HAND-WRITTEN FLOW SITE: an action's `target` when its
516+
// executor is `'flow'` ({@link FLOW_EXECUTOR_KEYS}). The derived index
517+
// cannot carry it — `target` names a URL, a script, a page, an endpoint
518+
// or a form on the other executors, so a property-wide site would rewrite
519+
// those too, and its "Used by" answer (`findReferencesToMeta`) would list
520+
// them as flow references. The site is keyed on the declared shape, the
521+
// `target` beside a `'flow'` executor in one object, and nothing else.
522+
const flowTargetSite = (node: Record<string, unknown>, key: string): ReferenceSiteRename | undefined =>
523+
key === 'target' && typeof node.target === 'string'
524+
&& FLOW_EXECUTOR_KEYS.some((executor) => node[executor] === 'flow')
525+
? FLOW_SITE
526+
: undefined;
527+
const referenceSiteOf = (key: string): ReferenceSiteRename | undefined =>
528+
objectReferenceProperties.has(key) ? OBJECT_SITE : flowReferenceProperties.has(key) ? FLOW_SITE : undefined;
529+
530+
type ReferenceCollision = { at: string; shape: 'key' | 'entry'; noun: 'object' | 'flow'; moved: string; met: string };
531+
const deepRewrite = (v: any, collisions: ReferenceCollision[], site?: ReferenceSiteRename, at = ''): any => {
468532
if (typeof v === 'string') {
469-
const whole = atReference ? renameMap.get(v) : undefined;
533+
const whole = site ? site.renames.get(v) : undefined;
470534
if (whole !== undefined) return whole;
471535
const viewItem = viewItemRenames.get(v);
472536
if (viewItem !== undefined) return viewItem;
@@ -484,16 +548,16 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam
484548
return last === 0 ? objectPass(v) : out + objectPass(v.slice(last));
485549
}
486550
if (Array.isArray(v)) {
487-
const out = v.map((element, i) => deepRewrite(element, collisions, atReference, `${at}[${i}]`));
488-
if (atReference) {
551+
const out = v.map((element, i) => deepRewrite(element, collisions, site, `${at}[${i}]`));
552+
if (site) {
489553
const firstAt = new Map<string, number>();
490554
out.forEach((element, i) => {
491555
if (typeof element !== 'string') return;
492556
const j = firstAt.get(element);
493557
if (j === undefined) {
494558
firstAt.set(element, i);
495559
} else if (v[j] !== v[i]) {
496-
collisions.push({ at, shape: 'entry', moved: v[i] !== element ? v[i] : v[j], met: element });
560+
collisions.push({ at, shape: 'entry', noun: site.noun, moved: v[i] !== element ? v[i] : v[j], met: element });
497561
}
498562
});
499563
}
@@ -503,10 +567,10 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam
503567
const o: any = {};
504568
const from = new Map<string, string>();
505569
for (const [k, val] of Object.entries(v)) {
506-
const key = atReference ? (renameMap.get(k) ?? k) : k;
570+
const key = site ? (site.renames.get(k) ?? k) : k;
507571
const other = from.get(key);
508572
if (other !== undefined) {
509-
collisions.push({ at, shape: 'key', moved: key === k ? other : k, met: key });
573+
collisions.push({ at, shape: 'key', noun: site?.noun ?? 'object', moved: key === k ? other : k, met: key });
510574
}
511575
from.set(key, k);
512576
if (CAPABILITY_REFERENCE_KEYS.has(k)) {
@@ -515,7 +579,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam
515579
}
516580
const entry = deepRewrite(
517581
val, collisions,
518-
objectReferenceProperties.has(k) || (atReference && k === 'name'),
582+
referenceSiteOf(k) ?? (site && k === 'name' ? site : flowTargetSite(v, k)),
519583
at ? `${at}.${k}` : k,
520584
);
521585
// ⭐ A RECORD ENTRY'S `name` FOLLOWS ITS KEY. An entry that
@@ -540,7 +604,7 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam
540604
return v;
541605
};
542606
const describeCollision = (c: ReferenceCollision): string =>
543-
`its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied object to '${c.met}', `
607+
`its \`${c.at}\` ${c.shape} '${c.moved}' follows the copied ${c.noun} to '${c.met}', `
544608
+ `${c.shape === 'key' ? 'a key' : 'an entry'} it already holds there, which this copy does not rename. `
545609
+ (c.shape === 'key'
546610
? 'A record keeps one entry per key, so the copy would drop one of the two. '

‎packages/metadata-protocol/src/protocol-door-requests.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,18 @@ type SaveMetaItemRequest = {
2929
*/
3030
inheritedGrantObjects?: readonly string[],
3131
/**
32-
* [#35143] The names of the flows the same package copy writes, the copy
33-
* door's plan (`importUnmanagedPackage`, whose items are the request's
34-
* body; `duplicatePackage` copies stored rows, which the gate's own read
35-
* of the stored flows already holds). A `flow`
36-
* write's `subflow` / `map` call naming one of them is a call to a flow the
37-
* copy holds once its loop ends, so the publish gate resolves it, as it
38-
* resolves a flow of a `publishPackageDrafts` batch (`pending.flows`).
32+
* [#35143, #38595] The names of the flows the same package copy plans to
33+
* write, under the names it writes them as: the copy door's plan. Both
34+
* copy doors state it on each flow write: `importUnmanagedPackage`, whose
35+
* items are the request's body, and `duplicatePackage`, whose items are
36+
* stored rows renamed into the target namespace (a copied step calls the
37+
* COPY's flow, which no stored row holds until the loop writes it). A
38+
* `flow` write's `subflow` / `map` call naming one of them is resolved by
39+
* the publish gate, as it resolves a flow of a `publishPackageDrafts`
40+
* batch (`pending.flows`). The plan holds once the loop ends: the import
41+
* is all-or-nothing, and on the best-effort duplicate a copied caller
42+
* whose planned callee was not written is withdrawn with it, into
43+
* `failed[]`.
3944
* Additive only: a name can let a call through, never refuse one. Set by
4045
* server code only; no HTTP door forwards it.
4146
*/

0 commit comments

Comments
 (0)