Skip to content

Commit ebcc472

Browse files
committed
feat(runtime,spec)!: the flow clone door lands the copy in <base>.custom, switched off (WIP)
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5pRVPsxnFxPBAQLUMh
1 parent cd065d3 commit ebcc472

10 files changed

Lines changed: 742 additions & 50 deletions

File tree

‎packages/runtime/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
"@objectstack/driver-sql": "workspace:*",
4545
"@objectstack/driver-sqlite-wasm": "workspace:*",
4646
"@objectstack/formula": "workspace:*",
47+
"@objectstack/lint": "workspace:*",
4748
"@objectstack/metadata": "workspace:*",
4849
"@objectstack/objectql": "workspace:*",
4950
"@objectstack/metadata-protocol": "workspace:*",

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

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

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

Lines changed: 143 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ import {
7373
FLOW_CLONE_NAME_TAKEN_STATUS,
7474
FLOW_CLONE_NOTICE,
7575
} from '../flow-clone.js';
76+
// [#28149, ADR-0146 D4] The clone body's declaration (its closed member set)
77+
// and the target rule every "new similar" door shares.
78+
import { CloneFlowRequestSchema } from '@objectstack/spec/api';
79+
import { newSimilarTargetRefusal, newSimilarTargetRefusalAnswer } from './new-similar-target.js';
7680
import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js';
7781
import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js';
7882
import { readDispatchedBody } from '../deferred-request-body.js';
@@ -2314,6 +2318,12 @@ async function registerAndSaveFlow(
23142318
name: string,
23152319
definition: unknown,
23162320
door: 'definition' | 'clone',
2321+
/**
2322+
* [#28149] The package the clone door resolved for its copy
2323+
* ({@link resolveCloneTarget}) — the one caller here that holds a package
2324+
* of its own choosing rather than a stamp. The definition doors pass none.
2325+
*/
2326+
packageId?: string,
23172327
): Promise<{ registered: unknown } | { refused: HttpDispatcherResult }> {
23182328
const store: (Partial<Pick<ObjectStackProtocolImplementation, 'saveMetaItem'>>
23192329
& Partial<Pick<MetadataProtocol, 'getMetaItems'>>) | undefined =
@@ -2337,7 +2347,13 @@ async function registerAndSaveFlow(
23372347
// with no user passes no actor, an unattributed write as before.
23382348
const { userId: actor } = activationCaller(context);
23392349
try {
2340-
await store.saveMetaItem({ type: FLOW_METADATA_TYPE, name, item: definition, ...(actor ? { actor } : {}) });
2350+
await store.saveMetaItem({
2351+
type: FLOW_METADATA_TYPE,
2352+
name,
2353+
item: definition,
2354+
...(packageId !== undefined ? { packageId } : {}),
2355+
...(actor ? { actor } : {}),
2356+
});
23412357
} catch (e) {
23422358
restoreFlowRegistration(automationService, name, held);
23432359
return {
@@ -2348,6 +2364,95 @@ async function registerAndSaveFlow(
23482364
return { registered };
23492365
}
23502366

2367+
/**
2368+
* [#28149, ADR-0146 D3/D4] WHERE the clone door's copy lands — "new similar":
2369+
* a package, always (ADR-0070 D5/D6 retired the package-less scope, and ⛔ no
2370+
* clone is written without one), resolved before anything is registered.
2371+
*
2372+
* - **`package` sent** — that package, judged by the target rule every "new
2373+
* similar" door shares ({@link newSimilarTargetRefusal}): installed,
2374+
* writable, and holding the source's package in its dependency closure.
2375+
* - **`package` omitted** — the source's paired customization package
2376+
* `<base>.custom`, where `<base>` is the package the loader's set says
2377+
* ships the source (`packagedArtifactOwner` — the loader's fact, ⛔ never
2378+
* the `_packageId` stamp on the definition the engine holds, which for a
2379+
* name two packages hold is the boot bind's pick). The pair is ensured
2380+
* through the protocol's `ensureCustomizationPackage` — the body of
2381+
* `POST /packages/:id/ensure-customization`, the ONE creation path of the
2382+
* pair (ADR-0146 D3), called in process and ⛔ never re-implemented. This
2383+
* door already holds the authority that door asks (`manage_metadata`, then
2384+
* the walled refusal, both judged before the domain is entered), so the
2385+
* call creates nothing a caller could not create there. Its refusals (a
2386+
* writable base, a base with no pair namespace, a namespace another package
2387+
* owns) are relayed as the protocol built them. The pair it answers is then
2388+
* judged by the same target rule, so a pair that is not writable here is
2389+
* refused before the copy is written into it.
2390+
* - **`package` omitted, and no package ships the source** — refused
2391+
* `400 VALIDATION_ERROR` on `package`: a flow authored in the deployment,
2392+
* or one stored in a writable package, has no base and so no pair, and
2393+
* this door does not guess one (its stored binding is not the engine's to
2394+
* tell, see {@link registerAndSaveFlow}). The caller names the package.
2395+
*
2396+
* A composition whose protocol cannot ensure a pair or save into a package
2397+
* has nowhere to land a copy: `501`, never the package-less write it used to
2398+
* make.
2399+
*
2400+
* Ordering: the pair is ensured before the copy is registered and saved, so a
2401+
* save the store then refuses leaves the pair in place. That is the pair's
2402+
* ordinary state — ensure is idempotent and an empty pair is a valid one —
2403+
* and the next clone reuses it.
2404+
*/
2405+
async function resolveCloneTarget(
2406+
deps: DomainHandlerDeps,
2407+
context: HttpProtocolContext,
2408+
sourceName: string,
2409+
requested: string | undefined,
2410+
): Promise<{ packageId: string } | { refused: HttpDispatcherResult }> {
2411+
const protocol: Partial<Pick<ObjectStackProtocolImplementation,
2412+
'ensureCustomizationPackage' | 'packagedArtifactOwner' | 'saveMetaItem'>> | undefined =
2413+
await deps.resolveServiceOrLoud(context, 'protocol');
2414+
if (typeof protocol?.ensureCustomizationPackage !== 'function'
2415+
|| typeof protocol.packagedArtifactOwner !== 'function'
2416+
|| typeof protocol.saveMetaItem !== 'function') {
2417+
return {
2418+
refused: {
2419+
handled: true,
2420+
response: deps.error(
2421+
'Flow clone not supported: a copy lands in a package, and this deployment has no metadata '
2422+
+ 'protocol that can ensure a customization package and save a flow into it.',
2423+
501,
2424+
),
2425+
},
2426+
};
2427+
}
2428+
const subject = `flow '${sourceName}'`;
2429+
const owner = protocol.packagedArtifactOwner({ type: FLOW_METADATA_TYPE, name: sourceName });
2430+
let target: string;
2431+
if (requested !== undefined) {
2432+
target = requested;
2433+
} else {
2434+
if (owner === undefined) {
2435+
throw validationFailure(
2436+
`Flow '${sourceName}' is not shipped by a package, so it has no paired customization package to `
2437+
+ 'land a copy in (ADR-0146 D3): name the package the copy lands in with `package`.',
2438+
[{ field: 'package', code: 'required', message: 'the source has no paired customization package' }],
2439+
);
2440+
}
2441+
try {
2442+
target = (await protocol.ensureCustomizationPackage({ basePackageId: owner })).packageId;
2443+
} catch (e) {
2444+
return { refused: { handled: true, response: deps.errorFromThrown(e) } };
2445+
}
2446+
}
2447+
const refusal = newSimilarTargetRefusal(await deps.getObjectQL(context), {
2448+
target,
2449+
subject,
2450+
...(owner !== undefined ? { sourcePackageId: owner } : {}),
2451+
});
2452+
if (refusal) return { refused: newSimilarTargetRefusalAnswer(deps, refusal) };
2453+
return { packageId: target };
2454+
}
2455+
23512456
/** The engine methods {@link unregisterAndDeleteFlow} drives. */
23522457
type FlowRemovalService =
23532458
Required<Pick<IAutomationService, 'unregisterFlow'>> & Pick<IAutomationService, 'registerFlow' | 'getFlow'>;
@@ -3537,13 +3642,18 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
35373642
{ field: '(body)', code: 'invalid_type', message: 'expected an object' },
35383643
]);
35393644
}
3540-
const unknownKeys = Object.keys(cloneBody).filter((k) => k !== 'name' && k !== 'label');
3645+
// [#28149] The closed member set is the declaration's
3646+
// (`CloneFlowRequestSchema`, `@objectstack/spec/api`), read off
3647+
// it rather than re-listed, so the door and the contract cannot
3648+
// disagree about which keys a clone reads.
3649+
const declaredKeys = new Set(Object.keys(CloneFlowRequestSchema.shape));
3650+
const unknownKeys = Object.keys(cloneBody).filter((k) => !declaredKeys.has(k));
35413651
if (unknownKeys.length > 0) {
35423652
throw validationFailure(
3543-
`Unknown key${unknownKeys.length > 1 ? 's' : ''} ${unknownKeys.map((k) => `\`${k}\``).join(', ')} — the clone body is { name: string, label: string }`,
3653+
`Unknown key${unknownKeys.length > 1 ? 's' : ''} ${unknownKeys.map((k) => `\`${k}\``).join(', ')} — the clone body is { name: string, label: string, package?: string }`,
35443654
// `unknown_field` — the ADR-0114 catalog member for "a
35453655
// key the target does not declare" (#8124).
3546-
unknownKeys.map((k) => ({ field: k, code: 'unknown_field', message: 'not a clone field — the clone body is { name, label }' })),
3656+
unknownKeys.map((k) => ({ field: k, code: 'unknown_field', message: 'not a clone field — the clone body is { name, label, package? }' })),
35473657
);
35483658
}
35493659
// The NEW MACHINE NAME IS MANDATORY (ADR-0126 §7.1, commit e170b0ae5's
@@ -3575,6 +3685,19 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
35753685
[{ field: 'label', code: targetLabel === undefined ? 'required' : 'invalid_type', message: 'expected a non-empty string' }],
35763686
);
35773687
}
3688+
// [#28149, ADR-0146 D4] `package` is optional — the package the
3689+
// copy lands in — and, when sent, a non-empty string: a blank or
3690+
// a non-string is refused here rather than read as "omitted",
3691+
// so a caller who meant to name a target never has the copy
3692+
// land somewhere it did not name.
3693+
const requestedPackage = (cloneBody as { package?: unknown }).package;
3694+
if (requestedPackage !== undefined && (typeof requestedPackage !== 'string' || requestedPackage.trim() === '')) {
3695+
throw validationFailure(
3696+
'The clone\'s `package` names the package the copy lands in, and must be a non-empty package id '
3697+
+ 'when sent. Omit it to land the copy in the source\'s paired customization package.',
3698+
[{ field: 'package', code: 'invalid_type', message: 'expected a non-empty string' }],
3699+
);
3700+
}
35783701

35793702
// The SOURCE must exist — the same existence probe `GET /:name`
35803703
// and the toggle arm use, so the three routes cannot disagree
@@ -3611,6 +3734,13 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
36113734
};
36123735
}
36133736

3737+
// [#28149, ADR-0146 D3/D4] WHERE the copy lands — never without
3738+
// a package (ADR-0070 D5/D6). Resolved after every refusal above
3739+
// and before anything is registered, so a refused target leaves
3740+
// no copy behind (see `resolveCloneTarget`).
3741+
const target = await resolveCloneTarget(deps, context, name, requestedPackage);
3742+
if ('refused' in target) return target.refused;
3743+
36143744
const clone = cloneFlowDefinition(source, { name: targetName, label: targetLabel });
36153745
// [#20761, ADR-0126 §7.1] The copy is TENANT-AUTHORED, stated by
36163746
// the server: `cloneFlowDefinition` drops the base's whole
@@ -3637,7 +3767,7 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
36373767
// deployment can no longer register. The target name is new (the
36383768
// collision probe above), so a save that fails withdraws it.
36393769
const written = await registerAndSaveFlow(
3640-
deps, context, automationService as FlowRegistrationService, targetName, clone, 'clone',
3770+
deps, context, automationService as FlowRegistrationService, targetName, clone, 'clone', target.packageId,
36413771
);
36423772
if ('refused' in written) return written.refused;
36433773
// ⛔ NO ANCESTRY on the way out either (ADR-0126 amendment
@@ -3650,7 +3780,14 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
36503780
// [#20552] The ANSWER is a served definition like any other. A
36513781
// source holding a credential never reaches this line (#20790
36523782
// C1, above), so the clone carries none.
3653-
return { handled: true, response: deps.success({ flow: servedFlowDefinition(clone), notice: FLOW_CLONE_NOTICE }) };
3783+
// [#28149] …and NAMES the package it landed in, so a console
3784+
// opens the copy where it lives (Setup's "Open the clone in
3785+
// Studio"): the package is where the copy is, not where it
3786+
// came from, so it records no lineage.
3787+
return {
3788+
handled: true,
3789+
response: deps.success({ flow: servedFlowDefinition(clone), packageId: target.packageId, notice: FLOW_CLONE_NOTICE }),
3790+
};
36543791
}
36553792
}
36563793

0 commit comments

Comments
 (0)