Skip to content

Commit 97489b2

Browse files
committed
fix(runtime): the clone's save is a first write; existing clone suites land in a package
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5pRVPsxnFxPBAQLUMh
1 parent ebcc472 commit 97489b2

4 files changed

Lines changed: 101 additions & 19 deletions

File tree

‎packages/runtime/src/domains/automation-flow-clone-credential.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,18 @@ function makeDispatcher(
5656
}),
5757
};
5858
if (holdings) spies.flowCredentialHoldings = vi.fn(holdings);
59-
const services: Record<string, unknown> = { automation: spies };
59+
// [#28149] The door writes every copy into a package (ADR-0146 D4): the
60+
// loader's set names a base, the ensure door answers its pair, and the
61+
// registry holds both, so the one case that clones reaches its save.
62+
const protocol = {
63+
packagedArtifactOwner: () => 'base',
64+
ensureCustomizationPackage: async () => ({ packageId: 'base.custom' }),
65+
saveMetaItem: vi.fn(async () => ({ success: true })),
66+
tenantAuthoredWriteRefusal: async () => undefined,
67+
};
68+
const packages: Record<string, unknown> = { base: { id: 'base' }, 'base.custom': { id: 'base.custom', dependencies: { base: '^1' } } };
69+
const objectql = { registry: { getPackage: (id: string) => (packages[id] ? { manifest: packages[id] } : undefined) } };
70+
const services: Record<string, unknown> = { automation: spies, protocol, objectql };
6071
const resolve = (name: string) => services[name];
6172
const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
6273
return { dispatcher: new HttpDispatcher(kernel), spies };

‎packages/runtime/src/domains/automation-flow-clone.test.ts‎

Lines changed: 52 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,46 @@ function makeDispatcher(seed: Record<string, unknown>[] = [packagedExemplar()])
147147
flows.set(name, definition as Record<string, unknown>);
148148
}),
149149
};
150-
const services: Record<string, unknown> = { automation: spies };
150+
const services: Record<string, unknown> = { automation: spies, ...packageLanding() };
151151
const resolve = (name: string) => services[name];
152152
const kernel: any = {
153153
getService: resolve,
154154
getServiceAsync: async (name: string) => resolve(name),
155155
context: { getService: resolve },
156156
};
157-
return { dispatcher: new HttpDispatcher(kernel), spies, flows };
157+
return { dispatcher: new HttpDispatcher(kernel), spies, flows, protocol: services.protocol as PackageLandingProtocol };
158+
}
159+
160+
/** The base the exemplar's loader-set owner names, and its paired customization package. */
161+
const BASE_PACKAGE = 'crm';
162+
const PAIR_PACKAGE = 'crm.custom';
163+
164+
type PackageLandingProtocol = ReturnType<typeof packageLanding>['protocol'];
165+
166+
/**
167+
* [#28149] Where the copy lands. The door now writes every copy into a
168+
* package (ADR-0146 D4), so the rig carries the protocol members it asks —
169+
* the loader's set naming the exemplar's base, the ensure door answering its
170+
* pair, and the save — plus the `objectql` registry the target rule reads.
171+
* The real protocol and registry are exercised in
172+
* `automation-flow-clone-custom-package.test.ts`; here they are the minimum
173+
* that lets each case reach the behaviour it is named after.
174+
*/
175+
function packageLanding() {
176+
const manifests: Record<string, { id: string; dependencies?: Record<string, string> }> = {
177+
[BASE_PACKAGE]: { id: BASE_PACKAGE },
178+
[PAIR_PACKAGE]: { id: PAIR_PACKAGE, dependencies: { [BASE_PACKAGE]: '^3' } },
179+
};
180+
const protocol = {
181+
packagedArtifactOwner: vi.fn(() => BASE_PACKAGE),
182+
ensureCustomizationPackage: vi.fn(async ({ basePackageId }: { basePackageId: string }) => ({
183+
basePackageId, packageId: `${basePackageId}.custom`, namespace: 'crm_custom', dependencyRange: '^3', created: false, writable: true,
184+
})),
185+
saveMetaItem: vi.fn(async () => ({ success: true })),
186+
tenantAuthoredWriteRefusal: vi.fn(async () => undefined),
187+
};
188+
const objectql = { registry: { getPackage: (id: string) => (manifests[id] ? { manifest: manifests[id] } : undefined) } };
189+
return { protocol, objectql };
158190
}
159191

160192
/** Drop `keys` from a shallow copy — used to state "everything except …". */
@@ -204,9 +236,10 @@ describe('#12156 — whole-definition copy (the #11703 counter-example as a test
204236

205237
expect(clone.name).toBe(NEW.name);
206238
expect(clone.label).toBe(NEW.label);
207-
// `draft`: the schema's own default for something never deployed. It is
208-
// NOT an off-switch — see `flow-clone.ts` and the notice assertion below.
239+
// [#28149, ADR-0146 D4] `obsolete`: the copy is written switched off,
240+
// so it never runs beside its original — see `flow-clone.ts`.
209241
expect(clone.status).toBe(FLOW_CLONE_STATUS);
242+
expect(FLOW_CLONE_STATUS).toBe('obsolete');
210243
expect(clone.status).not.toBe(source.status);
211244

212245
// The set that differs is exactly the mutated set.
@@ -216,14 +249,20 @@ describe('#12156 — whole-definition copy (the #11703 counter-example as a test
216249

217250
it('registers the clone under the NEW name, with the definition it returned', async () => {
218251
const source = packagedExemplar();
219-
const { dispatcher, spies, flows } = makeDispatcher([source]);
252+
const { dispatcher, spies, flows, protocol } = makeDispatcher([source]);
220253

221254
const result = await dispatcher.handleAutomation(clonePath(source.name as string), 'POST', NEW, CTX);
222255
const clone = (result.response?.body?.data ?? result.response?.body)?.flow;
223256

224257
expect(spies.registerFlow).toHaveBeenCalledTimes(1);
225258
expect(spies.registerFlow).toHaveBeenCalledWith(NEW.name, clone);
226259
expect(flows.get(NEW.name)).toEqual(clone);
260+
// [#28149] …and saved into the source's paired customization package,
261+
// never package-less, as a first write.
262+
expect(protocol.saveMetaItem).toHaveBeenCalledTimes(1);
263+
expect(protocol.saveMetaItem).toHaveBeenCalledWith(expect.objectContaining({
264+
type: 'flow', name: NEW.name, packageId: PAIR_PACKAGE, parentVersion: null,
265+
}));
227266
// …and the source is still there, untouched. A clone is not a rename.
228267
expect(flows.get(source.name as string)).toEqual(packagedExemplar());
229268
});
@@ -442,24 +481,23 @@ describe('#12156 — the source, the notice, and the gate', () => {
442481
expect(spies.registerFlow).not.toHaveBeenCalled();
443482
});
444483

445-
it('states in one line that the clone runs alongside the original, and that references are NOT re-pointed', async () => {
484+
it('states in one line that the copy is switched off, and that references are NOT re-pointed', async () => {
446485
const source = packagedExemplar();
447486
const { dispatcher } = makeDispatcher([source]);
448487

449488
const result = await dispatcher.handleAutomation(clonePath(source.name as string), 'POST', NEW, CTX);
450489
const notice: string = ((result.response?.body?.data ?? result.response?.body) as any)?.notice ?? '';
451490

452-
// The fact an admin is most likely to be caught by: `draft` is a
453-
// lifecycle label, not an off-switch — the engine only disables on
454-
// `obsolete`/`invalid`, so a cloned record-change flow runs beside the
455-
// one it was copied from. Saying so is cheaper than the surprise.
456-
expect(notice).toContain('runs alongside the original until you switch one of them off');
491+
// [#28149, ADR-0146 D4] "The copy is written inactive … and the
492+
// response says so": the copy does not run until someone switches it
493+
// on, stated in the server's words so no console restates it.
494+
expect(notice).toContain('switched off and does not run until you switch it on');
457495
// ADR-0126 §9: automatic re-pointing is explicitly not chartered, and
458496
// the ADR requires the surface to TELL the admin so.
459497
expect(notice).toContain('still uses the same subflows, actions and objects as the original');
460-
// [#27886] One line in business words. The console shows it beside a
461-
// "Switch the original off" button, so the engine words and the switch
462-
// locations stay in `flow-clone.ts`'s TSDoc.
498+
// [#27886] One line in business words. The console shows it verbatim,
499+
// so the engine words and the switch locations stay in
500+
// `flow-clone.ts`'s TSDoc.
463501
expect(notice.match(/[.!?](\s|$)/g)).toHaveLength(1);
464502
expect(notice).not.toMatch(/\b(draft|status|off-switch|lifecycle|Studio)\b/i);
465503
});

‎packages/runtime/src/domains/automation-flow-door-package-address.test.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,8 @@ async function boot() {
145145
const getFlow = vi.fn(async (name: string) => flows.get(name) ?? null);
146146
const services: Record<string, unknown> = {
147147
protocol,
148+
// [#28149] The registry the clone door's target rule reads.
149+
objectql: engine,
148150
automation: { handlerReady: true, registerFlow, unregisterFlow, getFlow },
149151
};
150152
const get = (name: string) => services[name] ?? null;
@@ -305,7 +307,9 @@ for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) {
305307
rig.flows.set('source_flow', flowOf('source_flow', 'Source'));
306308
const before = await rig.rows(SHARED);
307309

308-
const answer = await rig.call('POST', '/automation/source_flow/clone', { name: SHARED, label: 'The clone' });
310+
// [#28149] A source no package ships names the package its copy
311+
// lands in; one of the two packages holding the name.
312+
const answer = await rig.call('POST', '/automation/source_flow/clone', { name: SHARED, label: 'The clone', package: ALPHA });
309313

310314
expect(answer).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' });
311315
expect(await rig.rows(SHARED)).toEqual(before);
@@ -373,7 +377,10 @@ for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) {
373377
rig.flows.set('source_flow', flowOf('source_flow', 'Source'));
374378
const before = await rig.rows(SHARED);
375379

376-
const answer = await rig.refusal('POST', '/automation/source_flow/clone', { name: SHARED, label: 'The clone' });
380+
// [#28149] Into one of the two packages holding the name: the
381+
// clone's first-write pin meets that package's row, and the answer
382+
// is the same taken-name refusal.
383+
const answer = await rig.refusal('POST', '/automation/source_flow/clone', { name: SHARED, label: 'The clone', package: ALPHA });
377384

378385
expect({ status: answer.status, code: answer.code }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' });
379386
// A clone takes a NEW name (ADR-0126 §7.1): no package route is prescribed.
@@ -383,10 +390,10 @@ for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) {
383390
.filter((candidate) => candidate !== SHARED);
384391
expect(suggested).toHaveLength(1);
385392

386-
const followed = await rig.call('POST', '/automation/source_flow/clone', { name: suggested[0], label: 'The clone' });
393+
const followed = await rig.call('POST', '/automation/source_flow/clone', { name: suggested[0], label: 'The clone', package: ALPHA });
387394

388395
expect(followed).toEqual({ status: 200, code: undefined });
389-
expect(await rig.bindings(suggested[0]!)).toEqual([null]);
396+
expect(await rig.bindings(suggested[0]!)).toEqual([ALPHA]);
390397
expect(await rig.rows(SHARED)).toEqual(before);
391398
}, 60_000);
392399

‎packages/runtime/src/domains/automation.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2221,6 +2221,16 @@ function flowPackageRefusalMessage(verb: 'save' | 'delete', name: string, packag
22212221
+ `packages (${shown}${more}), and a ${verb} that names none has ${single}.`;
22222222
}
22232223

2224+
/**
2225+
* [#28149] Whether a store refusal is the ADR-0008 first-write pin's: a save
2226+
* that asserted "no current row" (`parentVersion: null`) met one. Read from
2227+
* the ADR-0112 envelope (`409 METADATA_CONFLICT`), never from the sentence.
2228+
*/
2229+
function isFirstWriteConflict(refusal: unknown): boolean {
2230+
const envelope = refusal as { code?: unknown; status?: unknown; statusCode?: unknown } | null | undefined;
2231+
return envelope?.code === 'METADATA_CONFLICT' && (envelope.status ?? envelope.statusCode) === 409;
2232+
}
2233+
22242234
/**
22252235
* [#23501] The refusal a definition door answers for a write the store refused:
22262236
* the store's own, as it was thrown, unless {@link flowPackagesRefusingWrite}
@@ -2245,6 +2255,14 @@ async function flowWriteRefusal(
22452255
name: string,
22462256
door: 'definition' | 'clone' | 'delete',
22472257
): Promise<unknown> {
2258+
// [#28149] The clone's first-write pin met a row the target package
2259+
// already holds under the new name: the name is taken, so the clone door's
2260+
// own taken-name refusal, with its remedy (a name no flow uses).
2261+
if (door === 'clone' && isFirstWriteConflict(refusal)) {
2262+
return Object.assign(new Error(flowCloneNameTakenMessage(name)), {
2263+
code: 'RESOURCE_CONFLICT', status: FLOW_CLONE_NAME_TAKEN_STATUS,
2264+
});
2265+
}
22482266
const packageIds = await flowPackagesRefusingWrite(store, refusal, name);
22492267
if (!packageIds) return refusal;
22502268
const [message, status] = door === 'clone'
@@ -2351,6 +2369,14 @@ async function registerAndSaveFlow(
23512369
type: FLOW_METADATA_TYPE,
23522370
name,
23532371
item: definition,
2372+
// [#28149] The clone CREATES: its save carries the first-write
2373+
// pin (`parentVersion: null`, "no current row"), so a row the
2374+
// target package already holds under the new name — one the
2375+
// engine's collision probe cannot see (a row that failed to
2376+
// register, or one stored and never bound) — is refused, never
2377+
// overwritten by the copy. Answered as the taken-name refusal
2378+
// ({@link flowWriteRefusal}).
2379+
...(door === 'clone' ? { parentVersion: null } : {}),
23542380
...(packageId !== undefined ? { packageId } : {}),
23552381
...(actor ? { actor } : {}),
23562382
});

0 commit comments

Comments
 (0)