Skip to content

Commit 74e85da

Browse files
fix(service-automation): the two-package flow collision line says neither flow is armed (#31802)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9ENWEBFHM19dDwc5CiBumP9)_ Fixes #31754 Clause-②: no — log text only; what the engine arms, refuses or runs does not change. Measured on head ea1c60c on a real cold boot (ObjectKernel + ObjectQLPlugin + SqlDriver): in all three refused shapes the engine refuses the name and arms nothing, the same as on base; only the collision line and its meta change. `engine.ts` is not in the diff, and the returned winner and `FlowShadowingRecord` are unchanged. Metadata-protocol: none ## 维护者速读 - 改了什么:启动日志里「流程名冲突」那一行,现在先问引擎用的同一个包作用域解析器。解析器拒绝这个名字时(另有一个包也发了同名流程),这一行写「两个都不启用」,日志附带的 meta 也不再写 armed。 - 为什么改:E1(#31738)后引擎对这类名字一个都不启用,但日志在三种情形下仍写「启用了 X」:两个包、两个包加覆盖件、两个包加一条存储行。 - 风险与回滚:只改日志文字和 meta,引擎行为不变;解析器放行的名字、以及没接解析器的组合,日志逐字节同 main。回滚即 revert。 - 先看:`packages/services/service-automation/src/flow-precedence.ts`(`refusalOf` 分支),`plugin.ts` 的 `resolveFlowContenders`,再看 `flow-declared-override-first-boot-pull.integration.test.ts` 末尾新增的 describe。 - 两分钟验证:`pnpm --filter @objectstack/service-automation exec vitest run src/flow-declared-override-first-boot-pull.integration.test.ts -t 31754`,预期 7 条全绿。 - 需要你做的:无,席位落地。 ## What changes The boot pull's collision warning (`resolveFlowPrecedence`) now asks the resolver the engine asks. Following the seat's ruling (A, card comment 6732521115): - `resolveFlowPrecedence` takes an optional fifth argument, `refusalOf(name)` (type `FlowNameRefusalReader`, exported as a type from the package root). It returns the refusal message the engine's flow-name resolver gives `name` for a caller with no package, or `undefined` when it serves the name. - `AutomationServicePlugin.resolveFlowContenders` (the one precedence path for the boot pull, the `kernel:ready` sync and the `metadata:reloaded` re-sync) fills it from `flowNameResolver(ctx)`, the same reader `init()` attaches to the engine (`setFlowNameResolver`), so the warning says "refused" exactly when `registerFlow` refuses. - When the resolver refuses, every arm reads, instead of "arming FIRST …": ```text [Automation] Flow name collision: 'NAME' is claimed by N definitions (CONTENDERS); arming neither: the engine refuses this bare name for a caller with no package (ADR-0150 D3), so no definition dispatches; the 'failed to register flow' warning for 'NAME' names every holder. Rename one of them. ``` ("arming none of them" when three or more definitions are listed), and the warning's meta is `{ flow, refused: true, contenders }` (no `armed`, no `shadowed`). - When the resolver serves the name, or no resolver is attached, every arm's line and meta are byte for byte main's. Measured on base f647430 with a real cold boot (the round-2 report, 6732507604), three shapes in which the engine refuses while main's line said a flow was armed: | Shape | main's line | Engine | This PR | |:--|:--|:--|:--| | two packages | "arming package 'A' by package id" | refuses, arms nothing | arming neither | | the declared override (A's `.custom`) beside a second package | "arming the declared override in 'A.custom' …" | refuses, arms nothing | arming neither / arming none of them | | two packages plus a package-less stored row | "arming package 'A' because a managed package's flow is sealed" | refuses, arms nothing | arming neither / arming none of them | The shadowing record and its three readers (the bootstrap restatement in `plugin.ts`, the CLI banner via `serve.ts`/`format.ts`, `armedFrom` on runtime states) are unchanged: measured on the dogfood showcase boot holding a two-package clash, the engine records no receipt for a refused name (`getShadowedFlows()` is `[]`, no runtime-state row, no "is ARMED" line), because the boot pull records it only after `registerFlow` succeeds. Pinned strings, found by searching the tree for "by package id", "arming", "Flow name collision" and "other definition(s)": - `packages/cli/src/utils/format.boot-warning-classes.test.ts` (print-once case): **forced test change.** Its collision record paired a package with a runtime row (the sealed class) but spelled the "by package id" arm. It now carries the line the sealed class prints. The assertions (one collision record kept, the restatement withheld) are unchanged. Because this PR edits the file, `check:test-source-alias` judged its reach and asked for ten module-top side-effect imports (the dynamic `import()`s `serve.ts` reaches), the same block `dev-mcp-connect-hint-origin.test.ts` carries; added, gate green. - `flow-name-shadowing.test.ts`, `flow-precedence-loader-set.test.ts`: pin the sealed and override arms with no resolver; unchanged and green. - `flow-declared-override-first-boot-pull.integration.test.ts`: its boot helper gains an optional second package (`Second`: none, before or after the shipping package); every existing case passes `none` by default and is unchanged. ## Tests - **Pins, real cold boot** (new top-level describe `[#31754]` in `flow-declared-override-first-boot-pull.integration.test.ts`): the three shapes above × the second package registered before and after the shipping one (6 cases). Each asserts the engine's refusal (every 'failed to register flow' record for the name says "held by 2 packages" and names both packages; `getFlow` null before and after `kernel:ready`; no receipt) and that every collision line for the name agrees ("arming neither"/"arming none of them", the pointer, no "arming package / the declared override / a runtime-authored", no "Only the armed definition dispatches"; meta `refused: true` without `armed`). - **CONTROL, a name the resolver serves**: one package plus a package-less row on the same real boot; the line is `toBe` main's sealed line, the meta is main's, nothing refused, the base armed. - **CONTROL, no resolver** (E1 harness, `flow-package-scoped-resolution.test.ts`): the four arms (by package id, sealed, declared override, arrival order), each `toBe` main's line. - **Pin, E1 harness**: two packages in both registration orders, with `refusalOf` built as the plugin builds it; line `toBe` the new text, and the engine refuses naming both. Ablations (fix committed first, `scripts/ablation-replace.mjs`, each restored to the HEAD blob with `git diff HEAD` empty): <details><summary>refusalOf dropped in plugin.resolveFlowContenders</summary> ```text ablation-replace: ok mutation landed: anchor 1 -> 0, blob 68793fa -> 47f53d7e7487 × two packages, the second package registered before the shipping one × two packages, the second package registered after the shipping one × the declared override beside a second package, the second package registered before the shipping one × the declared override beside a second package, the second package registered after the shipping one × two packages and a package-less stored row, the second package registered before the shipping one × two packages and a package-less stored row, the second package registered after the shipping one Tests 6 failed | 7 passed (13) Received: "[Automation] Flow name collision: 'crm_ticket_created' is claimed by 2 definitions (package 'com.acme.crm', package 'com.acme.other'); arming package 'com.acme.crm' by package id, …" Received: "… (the declared override in 'com.acme.crm.custom' (sys_metadata), package 'com.acme.crm', package 'com.acme.other'); arming the declared override in 'com.acme.crm.custom' (sys_metadata) because it is the declared override of 'com.acme.crm' (ADR-0146 D9), …" Received: "… (package 'com.acme.crm', package 'com.acme.other', a runtime-authored row (sys_metadata)); arming package 'com.acme.crm' because a managed package's flow is sealed (ADR-0126 §2), …" ablation-replace: ok restored: blob == HEAD (68793fa) and `git diff HEAD` is empty ``` </details> <details><summary>The refused branch in flow-precedence.ts disabled</summary> ```text ablation-replace: ok mutation landed: anchor 1 -> 0, blob 56e9626 -> 1bcc1dc269fb × two packages, registered alpha first: the line arms neither, and the engine refuses × two packages, registered stranger first: the line arms neither, and the engine refuses × (the six real-boot cases, as above) Tests 8 failed | 5 passed | 26 skipped (39) ablation-replace: ok restored: blob == HEAD (56e9626) and `git diff HEAD` is empty ``` The 5 passing cases are the five CONTROLs. </details> ## Acceptance notes - **Correction.** An earlier revision of this body said that two packages plus an environment row keep a true "arming package …" line, because the resolver answers a caller with no package with the environment row. That was **reasoned from the resolver's code, not measured, and it is wrong**: on a real cold boot the engine refuses that name too (round-2 report 6732507604, shape 3 above). This revision covers it. - The line asks `flowNameResolver(ctx)`, the reader `init()` attaches to the engine, not the engine itself (no new engine method). A host that attaches a different resolver to the engine by hand would bypass the plugin altogether; no such caller exists in this repository. - `FlowNameRefusalReader` is a new exported type name (the optional parameter's type), named after the existing `FlowNameResolver`. Open question for the seat. ## Verification Every reading below is on head ea1c60c (the final commit), base f647430. - `pnpm --filter @objectstack/service-automation test`: Test Files 267 passed (267), Tests 3493 passed (3493). `typecheck`: exit 0. Root `eslint --no-inline-config packages/services/service-automation`: exit 0 (the package has no `lint` script). - `pnpm --filter @objectstack/cli exec vitest run --project unit src/utils/format.boot-warning-classes.test.ts src/commands/serve-automation-shadowing.test.ts`: 34 passed (34). The CLI `integration` tier is declared to CI. - `node scripts/pm/dispatch-gates.mjs --commands`: 73 derived gates, each run, all exit 0; `--ran` reconciliation: 73 run, 0 NOT-MEASURED, 0 UNRUN. - Full dogfood: not run (no `!` in the title, no `(narrowing)` arm); the CI queue runs it. <!-- signed: domain:server#3 · os-steve · session_01ADHkmT3p3cREt88Gsd1rP3 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 98ba756 commit 74e85da

7 files changed

Lines changed: 316 additions & 16 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
fix(service-automation): the boot log's flow name collision line says no flow is armed when the engine refuses the name
6+
7+
Clause-②: no — log text only; what the engine arms, refuses or runs does not change.
8+
Metadata-protocol: none
9+
10+
When a second package ships a flow of the same name, the engine's package-scoped resolver refuses the bare name for a caller with no package, and `registerFlow` arms neither flow, naming both packages (ADR-0150 D3). The boot pull's collision warning still read "arming package 'FIRST' by package id", "arming package 'FIRST' because a managed package's flow is sealed" or "arming the declared override …", depending on which other definitions sat beside the two packages, and its log meta named an armed contender.
11+
12+
The warning now asks the same resolver the engine asks. When it refuses the name, every such line reads "arming neither: the engine refuses this bare name for a caller with no package (ADR-0150 D3), so no definition dispatches; the 'failed to register flow' warning for 'NAME' names every holder. Rename one of them." ("arming none of them" for three or more definitions), and its meta carries `refused: true` and the contenders instead of `armed`/`shadowed`.
13+
14+
A name the resolver serves keeps its line byte for byte, and so does every line when no resolver is attached. `resolveFlowPrecedence` takes the reader as an optional fifth argument (`FlowNameRefusalReader`, exported as a type); the automation plugin passes it.

‎packages/cli/src/utils/format.boot-warning-classes.test.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,19 @@ import {
1515
import { BootLogCapture, isVerboseBootLevel } from './boot-log-capture.js';
1616
import { collectAutomationSummary } from '../commands/serve.js';
1717

18+
// Pay the first load of what `serve.ts` reaches through dynamic `import()`s at
19+
// MODULE LOAD, outside any clocked case (`pnpm check:test-source-alias`).
20+
import '@objectstack/metadata-protocol';
21+
import '@objectstack/metadata';
22+
import '@objectstack/plugin-hono-server';
23+
import '@objectstack/rest';
24+
import '@objectstack/service-settings';
25+
import '@objectstack/service-datasource';
26+
import '@objectstack/driver-turso';
27+
import '@objectstack/driver-sql';
28+
import '@objectstack/platform-objects/plugin';
29+
import '@objectstack/plugin-security';
30+
1831
/**
1932
* #22073 — one boot line per warning class, and each warning printed once.
2033
*
@@ -491,8 +504,9 @@ describe('print-once: Boot diagnostics withholds what the banner restated (forma
491504
);
492505
const collision = record(
493506
"[Automation] Flow name collision: 'dup_flow' is claimed by 2 definitions (package 'crm', a runtime-authored " +
494-
"row (sys_metadata)); arming package 'crm' by package id, and shadowing 1 other definition(s). " +
495-
'Only the armed definition dispatches. Rename one of them.',
507+
"row (sys_metadata)); arming package 'crm' because a managed package's flow is sealed (ADR-0126 §2), and " +
508+
'shadowing 1 other definition(s). Only the armed definition dispatches. To change what runs, declare it ' +
509+
"as an override in 'crm.custom' (overrides: { package: 'crm', basedOn }), or save it under a new name.",
496510
);
497511
printServerReady({
498512
...BASE,

‎packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts‎

Lines changed: 98 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,17 @@ const shippingStack = () =>
9393
{ strict: false },
9494
) as Record<string, unknown>;
9595

96+
/** [#31754] A second package shipping FLOW's bare name — a clash sealed before ADR-0150 phase 1. */
97+
const OTHER = 'com.acme.other';
98+
const otherStack = () =>
99+
defineStack(
100+
{ manifest: { ...pluginManifest(OTHER), namespace: 'other', name: 'other' }, flows: [ticketFlow('OTHER')] } as never,
101+
{ strict: false },
102+
) as Record<string, unknown>;
103+
104+
/** Whether, and before or after the shipping package, OTHER is registered. */
105+
type Second = 'none' | 'before' | 'after';
106+
96107
type Row = 'override' | 'legacy';
97108

98109
const storedRow = (row: Row) =>
@@ -153,7 +164,7 @@ afterEach(async () => {
153164
* Boot the composition on `file`. `start` runs in a plugin that starts after
154165
* the automation plugin: after the boot pull, before `kernel:ready`.
155166
*/
156-
async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>) {
167+
async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>, second: Second = 'none') {
157168
const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never);
158169
kernels.push(kernel);
159170
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true });
@@ -174,9 +185,11 @@ async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEn
174185
version: '1.0.0',
175186
dependencies: ['com.objectstack.engine.objectql', 'com.objectstack.service-automation'],
176187
async init(ctx: PluginContext) {
177-
const stack = shippingStack();
178-
await ctx.getService<{ register(m: unknown): Promise<void> }>('manifest')
179-
.register({ ...(stack.manifest as object), ...stack });
188+
const manifests = ctx.getService<{ register(m: unknown): Promise<void> }>('manifest');
189+
const registerStack = (stack: Record<string, unknown>) => manifests.register({ ...(stack.manifest as object), ...stack });
190+
if (second === 'before') await registerStack(otherStack());
191+
await registerStack(shippingStack());
192+
if (second === 'after') await registerStack(otherStack());
180193
const ql = () => ctx.getService<ObjectQL>('objectql');
181194
const automation = () => ctx.getService<AutomationEngine>('automation');
182195
automation().registerTrigger(objectqlRecordTrigger(ql, automation, fired));
@@ -192,7 +205,11 @@ async function boot(file: string, start: (ql: ObjectQL, automation: AutomationEn
192205
}
193206

194207
/** The first boot stores `rows`, in this order; the second, cold, is measured. */
195-
async function measuredBoot(rows: readonly Row[], start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>) {
208+
async function measuredBoot(
209+
rows: readonly Row[],
210+
start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>,
211+
second: Second = 'none',
212+
) {
196213
const dir = mkdtempSync(join(tmpdir(), 'qa-28717-'));
197214
dirs.push(dir);
198215
const file = join(dir, 'store.db');
@@ -202,11 +219,16 @@ async function measuredBoot(rows: readonly Row[], start: (ql: ObjectQL, automati
202219
await first.kernel.shutdown();
203220
kernels.splice(kernels.indexOf(first.kernel), 1);
204221
const warn = vi.spyOn(ObjectLogger.prototype, 'warn');
205-
const measured = await boot(file, start);
206-
const collisions = warn.mock.calls
207-
.map(([message]) => String(message))
208-
.filter((message) => message.includes('Flow name collision') && message.includes(`'${FLOW}'`));
209-
return { ...measured, collisions };
222+
const measured = await boot(file, start, second);
223+
const collisionCalls = warn.mock.calls
224+
.filter(([message]) => String(message).includes('Flow name collision') && String(message).includes(`'${FLOW}'`));
225+
const collisions = collisionCalls.map(([message]) => String(message));
226+
// [#31754] The engine's own answer for FLOW: each refusal it logged while arming.
227+
const refusals = warn.mock.calls
228+
.filter(([message, meta]) =>
229+
String(message).endsWith('failed to register flow') && (meta as { flow?: unknown } | undefined)?.flow === FLOW)
230+
.map(([, meta]) => String((meta as { error?: unknown }).error));
231+
return { ...measured, collisions, collisionMeta: collisionCalls.map(([, meta]) => meta), refusals };
210232
}
211233

212234
const insertTicket = (ql: ObjectQL, title: string) => ql.insert(TICKET, { title }, { context: SYS } as never);
@@ -273,3 +295,69 @@ describe('[#28717] a declared .custom flow override is armed from the first boot
273295
expect(collisions).toEqual([]);
274296
});
275297
});
298+
299+
/**
300+
* [#31754, ADR-0150 D3] The collision line agrees with the engine on a real
301+
* cold boot. A second package shipping FLOW's bare name (a clash sealed before
302+
* phase 1) makes the engine's resolver refuse the name for a caller with no
303+
* package, so `registerFlow` arms nothing — in each of the three shapes the
304+
* pull ranks differently (the two packages alone; the declared override beside
305+
* them; a package-less stored row beside them). Every collision line for the
306+
* name then reads "arming neither"/"arming none of them", its meta names no
307+
* armed contender, and the engine's refusal names both packages. The line asks
308+
* the resolver the engine asks (`refusalOf`), never a guess from the shapes.
309+
*/
310+
describe('[#31754] a name a second package also ships: the collision line says no definition is armed, as the engine does', () => {
311+
const SHAPES: ReadonlyArray<readonly [string, readonly Row[]]> = [
312+
['two packages', []],
313+
['the declared override beside a second package', ['override']],
314+
['two packages and a package-less stored row', ['legacy']],
315+
];
316+
for (const [shape, rows] of SHAPES) {
317+
for (const second of ['before', 'after'] as const) {
318+
it(`${shape}, the second package registered ${second} the shipping one`, async () => {
319+
let armedAtPull: unknown = 'unread';
320+
const { automation, collisions, collisionMeta, refusals } = await measuredBoot(rows, async (_ql, engine) => {
321+
armedAtPull = await engine.getFlow(FLOW);
322+
}, second);
323+
324+
// The engine: refused at every arming step, naming both packages; nothing armed.
325+
expect(refusals.length, 'the engine refused the name').toBeGreaterThan(0);
326+
for (const refusal of refusals) {
327+
expect(refusal).toContain('held by 2 packages in this environment');
328+
expect(refusal).toContain(`package "${BASE}"`);
329+
expect(refusal).toContain(`package "${OTHER}"`);
330+
}
331+
expect(armedAtPull).toBeNull();
332+
expect(await automation.getFlow(FLOW)).toBeNull();
333+
expect(automation.getShadowedFlows()).toEqual([]);
334+
335+
// The line: every collision warning for the name agrees.
336+
expect(collisions.length, 'the pull warned about the collision').toBeGreaterThan(0);
337+
for (const line of collisions) {
338+
expect(line).toMatch(/; arming (neither|none of them): the engine refuses this bare name for a caller with no package \(ADR-0150 D3\), so no definition dispatches; /);
339+
expect(line).toContain(`the 'failed to register flow' warning for '${FLOW}' names every holder. Rename one of them.`);
340+
expect(line).not.toMatch(/arming (package|the declared override|a runtime-authored)/);
341+
expect(line).not.toContain('Only the armed definition dispatches');
342+
}
343+
for (const meta of collisionMeta) {
344+
expect(meta).toMatchObject({ flow: FLOW, refused: true });
345+
expect(meta).not.toHaveProperty('armed');
346+
}
347+
});
348+
}
349+
}
350+
351+
it('CONTROL: a name the resolver serves (one package and a package-less row) keeps its line byte for byte', async () => {
352+
const { automation, collisions, collisionMeta, refusals } = await measuredBoot(['legacy'], async () => {});
353+
expect(refusals).toEqual([]);
354+
expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('BASE');
355+
expect(collisions).toEqual([
356+
`[Automation] Flow name collision: '${FLOW}' is claimed by 2 definitions (package '${BASE}', a runtime-authored ` +
357+
`row (sys_metadata)); arming package '${BASE}' because a managed package's flow is sealed (ADR-0126 §2), and ` +
358+
'shadowing 1 other definition(s). Only the armed definition dispatches. To change what runs, declare it as ' +
359+
`an override in '${PAIR}' (overrides: { package: '${BASE}', basedOn }), or save it under a new name.`,
360+
]);
361+
expect(collisionMeta).toEqual([{ flow: FLOW, armed: { source: 'package', packageId: BASE }, shadowed: [{ source: 'runtime' }] }]);
362+
});
363+
});

‎packages/services/service-automation/src/flow-package-scoped-resolution.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ import { installBuiltinNodes } from './builtin/index.js';
2424
import { flowNameResolver } from './plugin.js';
2525
import { InMemoryFlowActivationStore } from './flow-activation-store.js';
2626
import { FlowActivationProjection } from './flow-activation-projection.js';
27+
import { resolveFlowPrecedence } from './flow-precedence.js';
28+
import { bindStoredRow } from '@objectstack/metadata-protocol';
29+
import { installedManifestsOf } from '@objectstack/metadata-core';
2730

2831
const P = 'com.acme.caller';
2932
const A = 'com.acme.alpha';
@@ -364,3 +367,131 @@ describe('FlowActivationProjection', () => {
364367
expect(projection.has('notify')).toBe(true);
365368
});
366369
});
370+
371+
/**
372+
* [#31754, ADR-0150 D3] The boot pull's flow name collision line asks the
373+
* resolver the engine asks (`refusalOf`, built here as the plugin builds it,
374+
* from `flowNameResolver`). For a name two packages hold, precedence still
375+
* hands the lexicographically first body on and `registerFlow` refuses it
376+
* (red line 2 above), so the line says NEITHER is armed and points at that
377+
* refusal. The three shapes on a real cold boot are pinned in
378+
* `flow-declared-override-first-boot-pull.integration.test.ts`. CONTROL: with
379+
* no resolver handed in, every arm's line is byte for byte main's.
380+
*/
381+
describe('[#31754] the collision line for a name two packages hold says neither is armed', () => {
382+
const NOTHING_INSTALLED = installedManifestsOf(undefined);
383+
/** The boot pull's two steps over the registry: precedence (its one warning), then registration. */
384+
function pull(): { line: string; refusal: unknown } {
385+
const warn = vi.fn();
386+
const resolver = flowNameResolver({ getService: () => ({ registry }) } as never);
387+
const [winner] = resolveFlowPrecedence(
388+
registry.listItems('flow') as unknown[],
389+
{ warn },
390+
(name) => engine.packagedFlowOwner(name),
391+
NOTHING_INSTALLED,
392+
(name) => {
393+
const resolution = resolver(name, null);
394+
return resolution?.status === 'refused' ? resolution.message : undefined;
395+
},
396+
);
397+
expect(warn).toHaveBeenCalledTimes(1);
398+
let refusal: unknown;
399+
try {
400+
engine.registerFlow(winner.name, winner.definition as never);
401+
} catch (e) {
402+
refusal = e;
403+
}
404+
return { line: String(warn.mock.calls[0][0]), refusal };
405+
}
406+
/** One collision line from precedence alone. */
407+
function lineOf(listed: unknown[], owner: Record<string, string>): string {
408+
const warn = vi.fn();
409+
resolveFlowPrecedence(listed, { warn }, (name) => owner[name], NOTHING_INSTALLED);
410+
expect(warn).toHaveBeenCalledTimes(1);
411+
return String(warn.mock.calls[0][0]);
412+
}
413+
414+
for (const order of [[A, Q], [Q, A]] as const) {
415+
it(`two packages, registered ${order[0] === A ? 'alpha' : 'stranger'} first: the line arms neither, and the engine refuses`, async () => {
416+
install(A);
417+
install(Q);
418+
for (const id of order) registry.registerItem('flow', { ...leaf('notify'), _packageId: id }, 'name' as never, id);
419+
loaderSet.notify = A;
420+
421+
const { line, refusal } = pull();
422+
expect(line).toBe(
423+
"[Automation] Flow name collision: 'notify' is claimed by 2 definitions (package 'com.acme.alpha', " +
424+
"package 'com.acme.stranger'); arming neither: the engine refuses this bare name for a caller with " +
425+
"no package (ADR-0150 D3), so no definition dispatches; the 'failed to register flow' warning for " +
426+
"'notify' names every holder. Rename one of them.",
427+
);
428+
expect(line).not.toContain('arming package');
429+
expect(line).not.toContain('by package id');
430+
expect(line).not.toContain('Only the armed definition dispatches');
431+
expect(line).not.toContain('\n');
432+
// What the line points at: the refusal, naming both, and nothing armed.
433+
const refused = String((refusal as Error)?.message);
434+
expect(refused).toContain('held by 2 packages in this environment');
435+
expect(refused).toContain('package "com.acme.alpha"');
436+
expect(refused).toContain('package "com.acme.stranger"');
437+
expect(await engine.getFlow('notify')).toBeNull();
438+
});
439+
}
440+
441+
it('CONTROL: with no resolver, two packages keep main\'s line byte for byte (by package id)', () => {
442+
const line = lineOf(
443+
[{ ...leaf('notify'), _packageId: Q, _provenance: 'package' }, { ...leaf('notify'), _packageId: A, _provenance: 'package' }],
444+
{ notify: A },
445+
);
446+
expect(line).toBe(
447+
"[Automation] Flow name collision: 'notify' is claimed by 2 definitions (package 'com.acme.alpha', " +
448+
"package 'com.acme.stranger'); arming package 'com.acme.alpha' by package id, and shadowing 1 other " +
449+
'definition(s). Only the armed definition dispatches. Rename one of them.',
450+
);
451+
});
452+
453+
it('CONTROL: a package beside an environment row keeps its line byte for byte (ADR-0126 §2)', () => {
454+
const line = lineOf(
455+
[{ ...leaf('notify'), _packageId: A, _provenance: 'package' }, { ...leaf('notify'), _provenance: 'org' }],
456+
{ notify: A },
457+
);
458+
expect(line).toBe(
459+
"[Automation] Flow name collision: 'notify' is claimed by 2 definitions (package 'com.acme.alpha', " +
460+
"a runtime-authored row (sys_metadata)); arming package 'com.acme.alpha' because a managed package's " +
461+
'flow is sealed (ADR-0126 §2), and shadowing 1 other definition(s). Only the armed definition ' +
462+
"dispatches. To change what runs, declare it as an override in 'com.acme.alpha.custom' (overrides: " +
463+
"{ package: 'com.acme.alpha', basedOn }), or save it under a new name.",
464+
);
465+
});
466+
467+
it('CONTROL: the declared override beside a stored row keeps its line byte for byte (ADR-0146 D9)', () => {
468+
const pair = `${A}.custom`;
469+
const declared = { overrides: { package: A, basedOn: '1.0.0' }, _provenance: 'org' };
470+
const line = lineOf(
471+
[
472+
bindStoredRow({ ...leaf('notify'), _provenance: 'org' }, null),
473+
{ ...leaf('notify'), _packageId: A, _provenance: 'package' },
474+
bindStoredRow({ ...leaf('notify'), ...declared }, pair),
475+
],
476+
{ notify: A },
477+
);
478+
expect(line).toBe(
479+
"[Automation] Flow name collision: 'notify' is claimed by 3 definitions (the declared override in " +
480+
"'com.acme.alpha.custom' (sys_metadata), package 'com.acme.alpha', a runtime-authored row " +
481+
"(sys_metadata)); arming the declared override in 'com.acme.alpha.custom' (sys_metadata) because it " +
482+
"is the declared override of 'com.acme.alpha' (ADR-0146 D9), and shadowing 2 other definition(s). " +
483+
"Only the armed definition dispatches. To change what runs, declare it as an override in " +
484+
"'com.acme.alpha.custom' (overrides: { package: 'com.acme.alpha', basedOn }), or save it under a new name.",
485+
);
486+
});
487+
488+
it('CONTROL: two environment rows of a name no package ships keep their line byte for byte (arrival order)', () => {
489+
const line = lineOf([{ ...leaf('notify'), _provenance: 'org' }, { ...leaf('notify'), _provenance: 'org' }], {});
490+
expect(line).toBe(
491+
"[Automation] Flow name collision: 'notify' is claimed by 2 definitions (a runtime-authored row " +
492+
'(sys_metadata), a runtime-authored row (sys_metadata)); arming a runtime-authored row (sys_metadata) ' +
493+
'by arrival order, and shadowing 1 other definition(s). Only the armed definition dispatches. ' +
494+
'Rename one of them.',
495+
);
496+
});
497+
});

0 commit comments

Comments
 (0)