From 31ae6e53a3ade7b6597950a7670502d23a6fb05d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:53:45 +0000 Subject: [PATCH 01/14] wip(metadata-protocol): the move door's protocol method and spec schemas (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .../metadata-protocol/src/protocol-host.ts | 1 + .../src/protocol-package-move-in.ts | 467 ++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 26 + .../spec/src/api/package-lifecycle.zod.ts | 121 +++++ 4 files changed, 615 insertions(+) create mode 100644 packages/metadata-protocol/src/protocol-package-move-in.ts diff --git a/packages/metadata-protocol/src/protocol-host.ts b/packages/metadata-protocol/src/protocol-host.ts index 17e58bcd1b8..3ae22227029 100644 --- a/packages/metadata-protocol/src/protocol-host.ts +++ b/packages/metadata-protocol/src/protocol-host.ts @@ -96,6 +96,7 @@ export interface ProtocolHost { readonly credentialChannels: ObjectStackProtocolImplementation['credentialChannels']; readonly declinesStoredRow: ObjectStackProtocolImplementation['declinesStoredRow']; readonly defaultRecordPageSaveRefusal: ObjectStackProtocolImplementation['defaultRecordPageSaveRefusal']; + readonly deleteMetaItem: ObjectStackProtocolImplementation['deleteMetaItem']; readonly deleteMetaItemUnaudited: ObjectStackProtocolImplementation['deleteMetaItemUnaudited']; readonly detachMetadataMutationPubSub: ObjectStackProtocolImplementation['detachMetadataMutationPubSub']; readonly diffMetaItem: ObjectStackProtocolImplementation['diffMetaItem']; diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts new file mode 100644 index 00000000000..45faf5acbd6 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -0,0 +1,467 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The move door: `POST /packages/:id/move-in` (`protocol.moveIntoPackage`) — + * move a SELECTION of loose (package-less) metadata items into one installed, + * writable package. + * + * ## Why one door, and why it reuses the doors + * + * ADR-0084's amendment of 2026-11-26 ("Loose items stay where they are, and one + * door moves them") and its ruling: a loose item stays where it is unless an + * author moves it, and the move "runs each item through the save door's judges, + * judging the selection as a set for the ADR-0150 D3 (a) cross-boundary rule". + * The old all-at-once adoption (`reassignOrphanedMetadata`) rebound rows with a + * bare `engine.update` and asked none of the save door's questions, which let it + * adopt into a package nothing installed, adopt an object its target's namespace + * prefix refuses, and leave the runtime serving the old address until a restart. + * This door asks none of those questions itself: every item is removed from its + * package-less address by the delete door and written into the target by the + * save door — exactly the two steps the save door's own refusal prescribes for + * an object held by a package-less definition (`overlayPackageMismatchError`: + * "delete its package-less definition without dropStorage … then send this save + * again") — so each item is refused with the save door's code, and every write + * leaves history, a watch event and the registry write-through the save door + * performs for every type. + * + * ## Whole or nothing (ADR-0067 D2) + * + * Three phases, the shape `publishPackageDrafts` takes: + * + * 0. Judge, write nothing: every item is loose; the target is installed and + * writable; an object's name carries the target's prefix and does not clash + * with a namespace; and the selection as a set — a moved item that names a + * loose item the selection leaves behind would be read from a package caller + * that never resolves a bare name to an environment item (ADR-0150 D3 (a)), + * so it is refused naming what it leaves behind. + * 1. Every delete and save inside ONE `engine.transaction()`, the package + * commit recorded inside it too. Any refusal rolls the whole move back. A + * dry run runs the same writes and always rolls back. + * 2. On a runtime that cannot roll back (`engineCanRollBack`), a refusal in + * phase 1 undoes every step already taken, newest first; a dry run there + * answers phase 0's judgement alone, because only a rollback makes a write + * invisible. + * + * After any rollback the registry is put back from the restored rows: the save + * and delete doors mutate the in-memory registry as they go, and that cannot + * roll back with the store. + */ + +import { isPlatformRecordRow } from '@objectstack/metadata'; +import { engineCanRollBack, isPackageScopedType } from '@objectstack/core'; +import { ENVIRONMENT_ADDRESS_SEGMENT } from '@objectstack/spec/kernel'; +import { deriveAiFaceName } from '@objectstack/spec/ai'; +import type { + MoveIntoPackageMovedItemParsed, + MoveIntoPackageRefusedItemParsed, + MoveIntoPackageResponseParsed, +} from '@objectstack/spec/api'; +import { canonicalMetaType } from './protocol-meta-type-schema.js'; +import { collectReferenceHits } from './protocol-reference-hits.js'; +import { REFERENCE_SITES } from './reference-sites.js'; +import { resolveCallerPackageAddress } from './protocol-exact-qualifier.js'; +import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; +import type { ProtocolHost } from './protocol-host.js'; + +/** What the door is asked, after the route parsed the body. */ +export interface MoveIntoPackageRequest { + readonly targetPackageId: string; + readonly items: ReadonlyArray<{ readonly type: string; readonly name: string; readonly member?: string }>; + readonly dryRun?: boolean; + /** The signed-in caller the history rows credit; never a name the body supplies. */ + readonly actor?: string; +} + +type MoveHost = Pick; + +/** A stored `sys_metadata` row, as the system-context read answers it. */ +interface StoredRow { + readonly id?: string; + readonly type: string; + readonly name: string; + readonly state?: string; + readonly package_id?: string | null; + readonly member?: string | null; + readonly metadata?: unknown; +} + +/** One selected item, judged loose, with its rows. */ +interface LooseItem { + readonly type: string; + readonly name: string; + readonly member?: string; + readonly active?: StoredRow; + readonly draft?: StoredRow; +} + +/** The ADR-0150 D6 faces: these types are listed to AI clients by a derived name. */ +const AI_FACE_TYPES: ReadonlySet = new Set(['tool', 'skill', 'agent', 'action']); + +/** The sentinel a dry run throws to roll its transaction back. */ +const DRY_RUN_ROLLBACK = Symbol('move-in dry run'); + +/** Whether a stored row is bound to no package (null, empty, or the legacy `sys_metadata` sentinel). */ +function isPackageLessRow(row: { package_id?: unknown }): boolean { + return row.package_id == null || row.package_id === '' || row.package_id === 'sys_metadata'; +} + +function bodyOf(row: StoredRow | undefined): Record | undefined { + if (!row) return undefined; + const raw = row.metadata; + if (typeof raw === 'string') { + try { return JSON.parse(raw) as Record; } catch { return undefined; } + } + return raw && typeof raw === 'object' ? raw as Record : undefined; +} + +function keyOf(item: { type: string; name: string; member?: string | null }): string { + return `${item.type}/${item.name}${item.member ? `#${item.member}` : ''}`; +} + +/** The refusal an error thrown by a door becomes: the door's own code and words. */ +function refusalOf(item: { type: string; name: string; member?: string }, e: unknown): MoveIntoPackageRefusedItemParsed { + const err = e as { code?: unknown; message?: unknown } | undefined; + return { + type: item.type, + name: item.name, + ...(item.member ? { member: item.member } : {}), + code: typeof err?.code === 'string' && err.code !== '' ? err.code : 'MOVE_FAILED', + error: typeof err?.message === 'string' ? err.message : String(e), + }; +} + +/** Only the namespace a package's manifest declares (`undefined` for none). */ +function namespaceOf(host: Pick, packageId: string): string | undefined { + const ns = (host.engine as { registry?: { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } } | undefined) + ?.registry?.getPackage?.(packageId)?.manifest?.namespace; + return typeof ns === 'string' && ns !== '' ? ns : undefined; +} + +/** A package's own item of a name in the registry's per-package slot, or `undefined`. */ +function packageScopedItemAt(host: Pick, type: string, name: string, packageId: string): unknown { + const registry = (host.engine as { registry?: { getPackageScopedItem?: (t: string, n: string, p: string) => unknown } } | undefined)?.registry; + return typeof registry?.getPackageScopedItem === 'function' ? registry.getPackageScopedItem(type, name, packageId) : undefined; +} + +/** What a move changes in one item's addresses (ADR-0150 D5 and D6). */ +function movedAnswer(item: LooseItem, namespace: string | undefined): MoveIntoPackageMovedItemParsed { + const states: Array<'active' | 'draft'> = []; + if (item.active) states.push('active'); + if (item.draft) states.push('draft'); + const answer: MoveIntoPackageMovedItemParsed = { + type: item.type, + name: item.name, + ...(item.member ? { member: item.member } : {}), + states, + }; + if (isPackageScopedType(item.type) && namespace) { + answer.environmentAddress = `${ENVIRONMENT_ADDRESS_SEGMENT}/${item.name}`; + answer.qualifiedAddress = `${namespace}/${item.name}`; + } + if (AI_FACE_TYPES.has(item.type) && namespace) { + const body = bodyOf(item.active ?? item.draft); + // An object-bound action's face is `OBJECT-ACTION` under any holder: + // the move does not change it. + const objectName = item.type === 'action' && typeof body?.objectName === 'string' && body.objectName !== '' + ? body.objectName : undefined; + if (!objectName) { + const before = deriveAiFaceName({ name: item.name }); + const after = deriveAiFaceName({ name: item.name, namespace }); + if (before !== after) answer.aiFaceName = { before, after }; + } + } + return answer; +} + +export class ProtocolPackageMoveInFacet { + /** The body of `ObjectStackProtocolImplementation#moveIntoPackage`; the method's docblock there is its contract. */ + static async moveIntoPackage(host: MoveHost, request: MoveIntoPackageRequest): Promise { + const target = request.targetPackageId; + host.refuseOrganizationScopedWrite(`Package '${target}'`, request); + const refused: MoveIntoPackageRefusedItemParsed[] = []; + const refuse = (r: MoveIntoPackageRefusedItemParsed) => { refused.push(r); }; + const answerRefused = (): MoveIntoPackageResponseParsed => ({ + outcome: 'refused', targetPackageId: target, moved: [], refused, + }); + + // ── Phase 0: judge, write nothing ───────────────────────────────── + const rows = (await host.findEnvironmentRows('sys_metadata', { where: {}, context: { isSystem: true } })) as StoredRow[]; + const looseRows = rows.filter((r) => isPackageLessRow(r) && !isPlatformRecordRow(r)); + const items: LooseItem[] = []; + const seen = new Set(); + for (const asked of request.items) { + const type = canonicalMetaType(asked.type); + const name = asked.name; + const member = asked.member; + const key = keyOf({ type, name, member }); + if (seen.has(key)) continue; + seen.add(key); + const mine = looseRows.filter((r) => canonicalMetaType(String(r.type)) === type && r.name === name + && (member === undefined ? r.member == null : r.member === member)); + const active = mine.find((r) => r.state === 'active'); + const draft = mine.find((r) => r.state === 'draft'); + if (!active && !draft) { + refuse({ + type, name, ...(member ? { member } : {}), code: 'NOT_LOOSE', + error: `No loose ${type} '${name}' is stored here: the door moves only an item bound to no package. ` + + 'An item a package holds is moved by editing that package, never by this door.', + }); + continue; + } + // [#23198] An overlay of an item the deployment ships keeps its binding (ADR-0070). + if (host.isArtifactBacked(type, name)) { + refuse({ + type, name, ...(member ? { member } : {}), code: 'NOT_LOOSE', + error: `The ${type} '${name}' is an item a package ships, and its package-less row is that item's ` + + 'customization, not a loose item. It stays bound to the item it customizes.', + }); + continue; + } + items.push({ type, name, ...(member ? { member } : {}), ...(active ? { active } : {}), ...(draft ? { draft } : {}) }); + } + + // The target, by the save door's own predicates: installed (A1) and writable. + const probe = items[0] ?? { type: 'flow', name: '_' }; + const unbound = host.uninstalledNamedBaseRefusal({ type: probe.type, name: probe.name, packageId: target }); + if (unbound) { + for (const item of items) refuse(refusalOf(item, unbound)); + return answerRefused(); + } + if (!host.isWritablePackage(target)) { + for (const item of items) { + refuse({ + type: item.type, name: item.name, ...(item.member ? { member: item.member } : {}), + code: 'WRITABLE_PACKAGE_REQUIRED', + error: `Package '${target}' is not writable here: its items are authored where it is built. ` + + 'Move loose items into a package you author (or create one).', + }); + } + return answerRefused(); + } + + // An object's literal name and the target's namespace (A2, child K). + for (const item of items) { + if (item.type !== 'object') continue; + const err = host.objectNamespacePrefixViolation(item.name, target) ?? host.objectNamespaceObjectNameClash(item.name, target); + if (err) { + const code = host.objectNamespacePrefixViolation(item.name, target) ? 'NAMESPACE_PREFIX' : 'NAMESPACE_CONFLICT'; + refuse({ type: item.type, name: item.name, code, error: err }); + } + } + + // The set rule (ADR-0150 D3 (a)): every bare name a moved item writes for + // a type addressed by package must resolve from the target once the + // selection has moved. A loose item it names that stays behind is read + // from a package caller, which never resolves a bare name to an + // environment item. + const selected = new Set(items.map((i) => `${i.type}/${i.name}`)); + const looseBehind = looseRows.filter((r) => r.state === 'active' + && isPackageScopedType(canonicalMetaType(String(r.type))) + && !selected.has(`${canonicalMetaType(String(r.type))}/${r.name}`) + && !host.isArtifactBacked(canonicalMetaType(String(r.type)), String(r.name))); + for (const item of items) { + const body = bodyOf(item.active ?? item.draft); + if (!body) continue; + const behind: Array<{ type: string; name: string }> = []; + for (const row of looseBehind) { + const targetType = canonicalMetaType(String(row.type)); + const properties = new Map(); + for (const site of REFERENCE_SITES.byTarget.get(targetType) ?? []) { + if (site.fromType === item.type) properties.set(site.property, site.target); + } + if (properties.size === 0) continue; + if (collectReferenceHits(body, properties, String(row.name)).length === 0) continue; + // Resolved from the target, a package holder in its closure answers + // the name; only a name no such holder has is left behind. + let reachable = false; + try { + const address = resolveCallerPackageAddress(host, { type: targetType, name: String(row.name), callerPackageId: target }); + reachable = address.kind === 'package' + && packageScopedItemAt(host, targetType, String(row.name), address.packageId) !== undefined; + } catch { + reachable = false; + } + if (!reachable) behind.push({ type: targetType, name: String(row.name) }); + } + if (behind.length > 0) { + refuse({ + type: item.type, name: item.name, ...(item.member ? { member: item.member } : {}), + code: 'REFERENCE_LEFT_BEHIND', + error: `The ${item.type} '${item.name}' names ${behind.map((b) => `${b.type} '${b.name}'`).join(', ')}, ` + + `which ${behind.length === 1 ? 'is a loose item' : 'are loose items'} this move leaves behind. ` + + `Read from package '${target}', a bare name never resolves to a loose item (ADR-0150 D3 (a)), ` + + 'so the reference would stop resolving. Add them to the selection to move them together.', + references: behind, + }); + } + } + if (refused.length > 0) return answerRefused(); + + const namespace = namespaceOf(host, target); + const moved = items.map((item) => movedAnswer(item, namespace)); + const canRollBack = engineCanRollBack(host.engine); + if (request.dryRun && !canRollBack) { + return { outcome: 'would_move', targetPackageId: target, moved, refused: [] }; + } + + // ── Phase 1: every delete and save in one transaction ───────────── + // Objects first, so an item of another type that names one meets it + // already moved; the rest in the order asked. + const ordered = [...items.filter((i) => i.type === 'object'), ...items.filter((i) => i.type !== 'object')]; + const landed: Array<{ item: LooseItem; state: 'active' | 'draft' }> = []; + let commitId: string | undefined; + let current: LooseItem | undefined; + const run = async () => { + for (const item of ordered) { + current = item; + for (const state of ['active', 'draft'] as const) { + const row = state === 'active' ? item.active : item.draft; + const body = bodyOf(row); + if (!row || !body) continue; + await host.deleteMetaItem({ + type: item.type, + name: item.name, + state, + packageId: null, + dropStorage: false, + ...(item.member ? { member: item.member } : {}), + ...(request.actor ? { actor: request.actor } : {}), + }); + landed.push({ item, state }); + await host.saveMetaItem({ + type: item.type, + name: item.name, + item: body, + mode: state === 'active' ? 'publish' : 'draft', + packageId: target, + ...(item.member ? { member: item.member } : {}), + ...(request.actor ? { actor: request.actor } : {}), + } as Parameters[0]); + } + } + current = undefined; + const commit = await host.recordPackageCommit({ + packageId: target, + operation: 'apply', + message: `Move ${items.length} loose item(s) into package '${target}'`, + ...(request.actor ? { actor: request.actor } : {}), + items: ordered.filter((i) => i.active).map((i) => ({ + type: i.type, name: i.name, existedBefore: false, prevVersion: null, + ...(i.member ? { member: i.member } : {}), + })), + }); + commitId = commit?.commitId; + if (request.dryRun) throw DRY_RUN_ROLLBACK; + }; + try { + const engine = host.engine; + if (engineCanRollBack(engine)) { + await retireOverlayCacheOnRollback(engine, () => engine.transaction(() => run())); + } else { + await run(); + } + } catch (e: unknown) { + if (canRollBack) { + await ProtocolPackageMoveInFacet.restoreRegistry(host, items, target); + } else { + await ProtocolPackageMoveInFacet.undoLanded(host, landed, target, request.actor); + } + if (e === DRY_RUN_ROLLBACK) { + return { outcome: 'would_move', targetPackageId: target, moved, refused: [] }; + } + const cause = current ?? items[0]!; + refuse(refusalOf(cause, e)); + return answerRefused(); + } + return { outcome: 'moved', targetPackageId: target, moved, refused: [], ...(commitId ? { commitId } : {}) }; + } + + /** + * After a rollback the store holds every loose row again, but the delete + * and save doors already moved the in-memory registry: put each item back + * at its package-less address, from its restored body. + */ + private static async restoreRegistry(host: MoveHost, items: readonly LooseItem[], target: string): Promise { + for (const item of items) { + const body = bodyOf(item.active); + if (!item.active || !body) continue; + try { + const [entry] = host.storedOverlayEntries({ type: item.type }, [item.active as never]); + await host.applyRegistryWriteThrough({ + type: item.type, + name: entry?.name ?? item.name, + item: entry?.data ?? body, + packageId: null, + organizationId: null, + reboundFrom: { packageId: target }, + }); + } catch (err: any) { + console.error( + `[Protocol] moveIntoPackage: the move of ${item.type}/${item.name} into '${target}' was rolled back ` + + `in storage, but the registry could not be put back: ${err?.message ?? err}. Until the next restart ` + + 'the running process may serve the item at its package address although no row binds it there. ' + + 'Fix: restart the server; the boot registers the item from its stored row.', + ); + } + } + } + + /** + * On a runtime that cannot roll back: undo each step already taken, newest + * first — remove the row written into the target, then put the loose row + * back as it was stored. + */ + private static async undoLanded( + host: MoveHost, + landed: ReadonlyArray<{ item: LooseItem; state: 'active' | 'draft' }>, + target: string, + actor: string | undefined, + ): Promise { + const repo = host.getOverlayRepo(); + for (const { item, state } of [...landed].reverse()) { + const row = state === 'active' ? item.active : item.draft; + const body = bodyOf(row); + try { + try { + await host.deleteMetaItem({ + type: item.type, name: item.name, state, packageId: target, dropStorage: false, + ...(item.member ? { member: item.member } : {}), + ...(actor ? { actor } : {}), + }); + } catch { + // The save never wrote it: nothing to remove. + } + await repo.put({ type: item.type, name: item.name, org: 'env' } as never, body, { + state, + source: 'protocol.moveIntoPackage', + actor: actor ?? null, + message: `undo the move of ${item.type}/${item.name}: the move into '${target}' was refused`, + ...(item.member ? { member: item.member } : {}), + } as never); + } catch (err: any) { + console.error( + `[Protocol] moveIntoPackage: the refused move of ${item.type}/${item.name} into '${target}' could ` + + `not be undone on this runtime, which cannot roll back: ${err?.message ?? err}. The item may now be ` + + 'stored in neither place, or in the target, although the answer says nothing moved. Fix: ' + + `re-save ${item.type}/${item.name} from its history (GET /meta/${item.type}/${item.name}/history).`, + ); + } + } + await ProtocolPackageMoveInFacet.restoreRegistry(host, landed.map((l) => l.item), target); + } +} diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index cbd8f442c8d..3f1fdef909e 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -70,6 +70,7 @@ import type { // body holds, what is copied, what is refused) lives beside this file. import type { MetadataCacheRequest, MetadataCacheResponse } from '@objectstack/spec/api'; import type { SeedAppliedLandedParsed } from '@objectstack/spec/api'; +import type { MoveIntoPackageResponseParsed } from '@objectstack/spec/api'; // [#24395] The save's authoring surface. import { REFERENCE_VALUE_TYPES, @@ -626,6 +627,8 @@ import { ProtocolHistoryAndPublishFacet } from './protocol-history-and-publish.j import type { RegistryQuestion } from './registry-question.js'; // [#29985 codemod] Package revert, duplicate, import, orphans, commits, revertCommit, rollback: the members below delegate to its facet, `ProtocolPackageCommitsFacet`. import { ProtocolPackageCommitsFacet } from './protocol-package-commits.js'; +// [ADR-0084 amendment 2026-11-26] The move door's body: `moveIntoPackage` delegates to `ProtocolPackageMoveInFacet`. +import { ProtocolPackageMoveInFacet, type MoveIntoPackageRequest } from './protocol-package-move-in.js'; // [#29985 codemod] Diff, deleteMetaItem, loadMetaFromDb, load reports, findReferencesToMeta: the members below delegate to its facet, `ProtocolDiffDeleteLoadFacet`. import { ProtocolDiffDeleteLoadFacet } from './protocol-diff-delete-load.js'; @@ -1232,6 +1235,7 @@ export class ObjectStackProtocolImplementation implements get credentialChannels() { return protocol.credentialChannels; }, declinesStoredRow: (...a) => protocol.declinesStoredRow(...a), defaultRecordPageSaveRefusal: (...a) => protocol.defaultRecordPageSaveRefusal(...a), + deleteMetaItem: (...a) => protocol.deleteMetaItem(...a), deleteMetaItemUnaudited: (...a) => protocol.deleteMetaItemUnaudited(...a), detachMetadataMutationPubSub: (...a) => protocol.detachMetadataMutationPubSub(...a), diffMetaItem: (...a) => protocol.diffMetaItem(...a), @@ -10697,6 +10701,28 @@ export class ObjectStackProtocolImplementation implements return ProtocolPackageCommitsFacet.reassignOrphanedMetadata(protocolHost(this), request); } + /** + * [ADR-0084 amendment of 2026-11-26] Move a SELECTION of loose + * (package-less) items into one installed, writable package — the door + * `POST /packages/:id/move-in` serves (`packages.moveIn`). + * + * Each item is removed from its package-less address by + * {@link deleteMetaItem} (storage kept) and written into the target by + * {@link saveMetaItem}, so it is refused with the save door's own code and + * every write leaves history and the registry write-through. The selection + * is judged as a set first (ADR-0150 D3 (a)): an item that names a loose + * item the selection leaves behind is refused `REFERENCE_LEFT_BEHIND`. + * Whole or nothing (ADR-0067 D2): one transaction, rolled back on any + * refusal; a runtime that cannot roll back undoes the steps already taken. + * `dryRun` answers the same judgement and writes nothing. + * + * Not a patch of {@link reassignOrphanedMetadata}, which this door replaces + * (ruled not to be patched in place). + */ + async moveIntoPackage(request: MoveIntoPackageRequest): Promise { + return ProtocolPackageMoveInFacet.moveIntoPackage(protocolHost(this), request); + } + /** * [#23646, ADR-0070 D5] Hand an adopted object's registry name over to its * rebound row: answers whether {@link reassignOrphanedMetadata} registers diff --git a/packages/spec/src/api/package-lifecycle.zod.ts b/packages/spec/src/api/package-lifecycle.zod.ts index 02d9f6010aa..ee7a95ec169 100644 --- a/packages/spec/src/api/package-lifecycle.zod.ts +++ b/packages/spec/src/api/package-lifecycle.zod.ts @@ -377,6 +377,112 @@ export const ReassignOrphanedMetadataResponseSchema = lazySchema(() => z.object( targetPackageId: z.string().describe('The package the items were adopted into.'), })); +/** + * One item a move names: the item's metadata type and name, and for a bundled + * type (an email template's locale) the one member. See + * {@link MoveIntoPackageRequestSchema}. + */ +export const MoveIntoPackageItemSchema = lazySchema(() => z.object({ + type: z.string().min(1).describe('Metadata type of the loose item (singular, e.g. `flow`, `dataset`, `object`).'), + name: z.string().min(1).describe('Machine name of the loose item.'), + member: z.string().min(1).optional().describe( + 'The bundle member to move, for a bundled type (an email template\'s locale). Omitted, the canonical member.', + ), +}).strict()); + +/** + * `POST /packages/:id/move-in` — move a selection of loose (package-less) + * metadata items into one installed, writable package; the client method is + * `packages.moveIn` (ADR-0084 amendment of 2026-11-26, "Loose items stay where + * they are, and one door moves them"). + * + * Every item goes through the save door into the target, so it is refused + * with the save door's own code, and the selection is judged as a set first: + * a moved item that names a loose item left behind is refused (ADR-0150 + * D3 (a)). Any refusal refuses the whole call and nothing is written. + * `dryRun: true` answers the same judgement and writes nothing. + */ +export const MoveIntoPackageRequestSchema = lazySchema(() => z.object({ + items: z.array(MoveIntoPackageItemSchema).min(1).describe( + 'The loose items to move: one, several, or every loose item of a type, across types. Each names an item ' + + 'bound to no package; an item a package holds, a customization pair item and an overlay of a shipped item ' + + 'are not loose and are refused. Listed once each.', + ), + dryRun: z.boolean().optional().describe( + 'Judge the move and answer what it would do, writing nothing. Omitted or false, the move is made.', + ), +}).strict().describe( + 'Body of `POST /packages/:id/move-in`: the selection of loose items to move into the package the path names.', +)); + +/** What a move changes in one moved item's addresses. See {@link MoveIntoPackageResponseSchema}. */ +export const MoveIntoPackageMovedItemSchema = lazySchema(() => z.object({ + type: z.string().describe('Metadata type of the moved item.'), + name: z.string().describe('Name of the moved item; a move never renames.'), + member: z.string().optional().describe('The bundle member moved, for a bundled type.'), + states: z.array(z.enum(['active', 'draft'])).min(1).describe( + 'Which of the item\'s rows moved: its published row, its pending draft, or both.', + ), + environmentAddress: z.string().optional().describe( + 'The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type ' + + 'addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at ' + + '`qualifiedAddress` and, while it is the only holder of its name, at its bare name.', + ), + qualifiedAddress: z.string().optional().describe( + 'The package-qualified address the item answers at after the move (`NAMESPACE/NAME`), present beside ' + + '`environmentAddress`.', + ), + aiFaceName: z.object({ + before: z.string().describe('The name AI clients listed the item under before the move.'), + after: z.string().describe('The name AI clients list it under after the move.'), + }).optional().describe( + 'The AI face name change (ADR-0150 D6), present for a tool, skill, agent or object-less action whose face ' + + 'the move changes.', + ), +})); + +/** One refused item of a move. See {@link MoveIntoPackageResponseSchema}. */ +export const MoveIntoPackageRefusedItemSchema = lazySchema(() => z.object({ + type: z.string().describe('Metadata type of the refused item.'), + name: z.string().describe('Name of the refused item.'), + member: z.string().optional().describe('The bundle member, for a bundled type.'), + code: z.string().describe( + 'The refusal\'s code: the save door\'s own (`WRITABLE_PACKAGE_REQUIRED`, `NAMESPACE_PREFIX`, …), ' + + '`NOT_LOOSE` for an item bound to a package or not found, or `REFERENCE_LEFT_BEHIND` for an item that ' + + 'names a loose item the selection leaves behind.', + ), + error: z.string().describe('What refused the item and what to do.'), + references: z.array(z.object({ + type: z.string().describe('Metadata type of the loose item left behind.'), + name: z.string().describe('Name of the loose item left behind.'), + })).optional().describe( + 'For `REFERENCE_LEFT_BEHIND`: every loose item this item names that the selection leaves behind. Adding ' + + 'them to the selection moves them together.', + ), +})); + +/** + * Answer of `POST /packages/:id/move-in`. Whole or nothing: `refused` empty + * exactly when the move was made (or, on a dry run, would be made). + */ +export const MoveIntoPackageResponseSchema = lazySchema(() => z.object({ + outcome: z.enum(['moved', 'would_move', 'refused']).describe( + '`moved`: every item moved. `would_move`: a dry run that would move every item; nothing was written. ' + + '`refused`: at least one item is refused, so nothing moved.', + ), + targetPackageId: z.string().describe('The package the items move into.'), + moved: z.array(MoveIntoPackageMovedItemSchema).describe( + 'Every item, with what the move changes in its addresses. Empty on `refused`.', + ), + refused: z.array(MoveIntoPackageRefusedItemSchema).describe( + 'Every refused item, each with its own code. Empty unless `outcome` is `refused`.', + ), + commitId: z.string().optional().describe('The package commit the move recorded (absent on a dry run or a refusal).'), +}).strict().describe( + 'Answer of the move door: what moved (or would move) and what each moved item\'s addresses become, or every ' + + 'refusal with nothing moved.', +)); + /** * `POST /packages/:id/duplicate` — clone this base into a NEW writable * package, re-namespacing objects and rewriting references (ADR-0070 D4). @@ -766,6 +872,21 @@ export type PackageExportBundleParsed = z.infer; /** Post-parse shape of {@link ReassignOrphanedMetadataResponse} — defaults applied, transforms run (ADR-0122). */ export type ReassignOrphanedMetadataResponseParsed = z.infer; +export type MoveIntoPackageItem = z.input; +/** Post-parse shape of {@link MoveIntoPackageItem} — defaults applied, transforms run (ADR-0122). */ +export type MoveIntoPackageItemParsed = z.infer; +export type MoveIntoPackageRequest = z.input; +/** Post-parse shape of {@link MoveIntoPackageRequest} — defaults applied, transforms run (ADR-0122). */ +export type MoveIntoPackageRequestParsed = z.infer; +export type MoveIntoPackageMovedItem = z.input; +/** Post-parse shape of {@link MoveIntoPackageMovedItem} — defaults applied, transforms run (ADR-0122). */ +export type MoveIntoPackageMovedItemParsed = z.infer; +export type MoveIntoPackageRefusedItem = z.input; +/** Post-parse shape of {@link MoveIntoPackageRefusedItem} — defaults applied, transforms run (ADR-0122). */ +export type MoveIntoPackageRefusedItemParsed = z.infer; +export type MoveIntoPackageResponse = z.input; +/** Post-parse shape of {@link MoveIntoPackageResponse} — defaults applied, transforms run (ADR-0122). */ +export type MoveIntoPackageResponseParsed = z.infer; export type DuplicatePackageResponse = z.input; /** Post-parse shape of {@link DuplicatePackageResponse} — defaults applied, transforms run (ADR-0122). */ export type DuplicatePackageResponseParsed = z.infer; From ecc88e306aa22ec00c81d896d4c7d906ceaed870 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:03:33 +0000 Subject: [PATCH 02/14] wip(runtime): POST /packages/:id/move-in, its ledger row and SDK method (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- packages/client/src/index.ts | 19 +++++ .../src/protocol-package-move-in.ts | 2 +- packages/runtime/src/dispatcher-plugin.ts | 2 + packages/runtime/src/domains/packages.ts | 77 +++++++++++++++++++ packages/runtime/src/route-ledger.ts | 5 ++ packages/spec/src/system/operation-message.ts | 4 + 6 files changed, 108 insertions(+), 1 deletion(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 028855d363d..17c4f5b51fd 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -136,6 +136,8 @@ import { PackageExportManifest, PackageExportBundle, ReassignOrphanedMetadataResponse, + MoveIntoPackageRequest, + MoveIntoPackageResponse, DuplicatePackageResponse, EnsureCustomizationPackageResponse, CloneFlowRequest, @@ -3627,6 +3629,23 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, + /** + * Move a selection of loose (package-less) items into this package — one + * item, several, or every loose item of a type, across types. Whole or + * nothing: the answer's `outcome` is `moved`, or `refused` with every + * refused item's own code and nothing moved; `dryRun: true` answers + * `would_move` and writes nothing, so a confirm step can show what each + * item's addresses become. + */ + moveIn: async (id: string, request: MoveIntoPackageRequest): Promise => { + const route = this.getRoute('packages'); + const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/move-in`, { + method: 'POST', + body: JSON.stringify(request), + }); + return this.unwrapResponse(res); + }, + /** * ADR-0070 D4: clone this base into a NEW writable package, * re-namespacing objects and rewriting references. diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index 45faf5acbd6..25b0402a8c5 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -90,7 +90,7 @@ type MoveHost = Pick; /** A stored `sys_metadata` row, as the system-context read answers it. */ -interface StoredRow { +interface StoredRow extends Record { readonly id?: string; readonly type: string; readonly name: string; diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 18b9f712fff..8cc65191fba 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -1702,6 +1702,8 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // the ADR-0067 commit-history / rollback family. mountPackagesRoute('post', '/:id/duplicate', (req) => `/${req.params.id}/duplicate`); mountPackagesRoute('post', '/:id/adopt-orphans', (req) => `/${req.params.id}/adopt-orphans`); + // [ADR-0084 amendment 2026-11-26] Move a selection of loose items into the package. + mountPackagesRoute('post', '/:id/move-in', (req) => `/${req.params.id}/move-in`); mountPackagesRoute('post', '/:id/discard-drafts', (req) => `/${req.params.id}/discard-drafts`); mountPackagesRoute('get', '/:id/commits', (req) => `/${req.params.id}/commits`); mountPackagesRoute('post', '/:id/commits/:commitId/revert', (req) => `/${req.params.id}/commits/${req.params.commitId}/revert`); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 47ee716f3bf..f49e767a95e 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -188,6 +188,7 @@ import { PackageInstallManifestSchema, PackageInstallRequestSchema, PublishPackageDraftsRequestSchema, + MoveIntoPackageRequestSchema, } from '@objectstack/spec/api'; // [#28640 ruling ③A] The export names each connector map the served read // withheld: the declaration of that list, and the redactor that decided it. @@ -297,6 +298,7 @@ export type PackagesDomainProtocol = revertCommit?(request: any): Promise; rollbackToPackageCommit?(request: any): Promise; reassignOrphanedMetadata?(request: any): Promise; + moveIntoPackage?(request: { targetPackageId: string; items: ReadonlyArray<{ type: string; name: string; member?: string }>; dryRun?: boolean; actor?: string }): Promise; duplicatePackage?(request: any): Promise; updatePackage?(request: any): Promise; /** @@ -4058,6 +4060,81 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin const result = await protocol.reassignOrphanedMetadata({ targetPackageId: id, ...(actor !== undefined ? { actor } : {}), + }) as { outcome?: string; refused?: ReadonlyArray<{ type: string; name: string; code: string; error: string }> }; + // A refused move wrote nothing, and answers as the save door + // answers the same refusal: 422 with the first item's own code + // in `error.code`. `error.details` is the whole move answer + // (`MoveIntoPackageResponseSchema`, `outcome: 'refused'`), so a + // caller reads every item's refusal, not only the first. + if (result?.outcome === 'refused' && result.refused && result.refused.length > 0) { + const first = result.refused[0]; + const others = result.refused.length - 1; + return { + handled: true, + response: deps.error( + `Nothing was moved into package "${id}": ${first.type} '${first.name}' — ${first.error}` + + (others > 0 ? ` (and ${others} more refusal${others === 1 ? '' : 's'} in error.details.refused)` : ''), + 422, + { ...result, code: first.code }, + ), + }; + } + return { handled: true, response: deps.success(result) }; + } catch (e: any) { + return { handled: true, response: deps.errorFromThrown(e, 500) }; + } + } + + // POST /packages/:id/move-in → move a SELECTION of loose items into + // this package (ADR-0084 amendment of 2026-11-26, "Loose items stay + // where they are, and one door moves them"). Body + // `MoveIntoPackageRequestSchema`: `{ items: [{ type, name, member? }], + // dryRun? }`. The door's gates are the package write doors'; what each + // item is judged by is the save door's, inside the protocol. + if (parts.length === 2 && parts[1] === 'move-in' && m === 'POST') { + const denied = requireManageMetadata(deps, _context); if (denied) return denied; + const id = decodeURIComponent(parts[0]); + // [ADR-0131 D12 items 7–8] Under a wall, the platform operator's. + const walled = await refuseWalledCatalogPackageWrite(deps, _context, `Moving loose metadata into package "${id}"`); + if (walled) return walled; + // [ADR-0161 K4, guard one] A package that holds a knowledge source + // asks `manage_knowledge_sources` too. + const sourceGate = await refuseKnowledgeSourcePackageWrite(deps, _context, { + packageId: id, action: `Moving loose metadata into package "${id}"`, reach: ['drafts', 'items'], + }); + if (sourceGate) return sourceGate; + const queryRefused = refusePackageWriteDoorQuery(deps, query, PACKAGE_WRITE_NO_QUERY_PARAMS); if (queryRefused) return queryRefused; + // A package the deployment ships is not a target, answered as every + // package write door answers it. An id nothing installed passes + // this predicate; the protocol refuses it with the save door's own + // named-base judge (`422 WRITABLE_PACKAGE_REQUIRED`), never by + // moving anything into it. + const readOnly = requireWritablePackage(deps, qlService, id, 'move items into'); if (readOnly) return readOnly; + const declared = MoveIntoPackageRequestSchema.safeParse(body); + if (!declared.success) { + const located = declared.error.issues + .map((issue) => `${issue.path.map(String).join('.') || '(body)'}: ${issue.message}`) + .join('; '); + return { + handled: true, + response: deps.error( + `Invalid move-in body — ${located}. Nothing was moved: the body is { "items": [{ "type": string, ` + + '"name": string, "member"?: string }, …], "dryRun"?: boolean }, naming at least one loose item.', + 400, + ), + }; + } + const protocol = await resolveProtocol(deps, _context); + if (!protocol || typeof protocol.moveIntoPackage !== 'function') { + return catalogNotImplemented(deps, _context, 'packages_move_in_unsupported'); + } + try { + const actor = resolvePackageWriteActor(_context); + const result = await protocol.moveIntoPackage({ + targetPackageId: id, + items: declared.data.items, + ...(declared.data.dryRun ? { dryRun: true } : {}), + ...(actor !== undefined ? { actor } : {}), }); return { handled: true, response: deps.success(result) }; } catch (e: any) { diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 4354f3876a2..b165d927481 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -590,6 +590,11 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'POST /packages/:id/adopt-orphans', domain: '/packages', disposition: 'sdk', client: 'packages.adoptOrphans', responseSchema: 'ReassignOrphanedMetadataResponseSchema', note: 'Enveloped — the named schema is the `data`: `reassignOrphanedMetadata`\'s declared return, transcribed describe-only. Conformance: spec `api/package-lifecycle.test.ts`' }, + // [ADR-0084 amendment of 2026-11-26] The move door: a selection of loose items into one package. + { route: 'POST /packages/:id/move-in', domain: '/packages', disposition: 'sdk', client: 'packages.moveIn', + requestSchema: 'MoveIntoPackageRequestSchema', + responseSchema: 'MoveIntoPackageResponseSchema', + note: 'Enveloped — the named schema is the `data`. A new route whose declaration is its contract: the body is parsed with `MoveIntoPackageRequestSchema` (strict; a body it refuses answers 400 VALIDATION_ERROR naming the member, nothing moved), the query set is closed and empty. Whole or nothing: every item goes through the delete door (storage kept) and the save door into the target inside one transaction, so a refusal writes nothing and answers 422 with the first item\'s own save-door code in `error.code` and the whole answer (`outcome: refused`, every item\'s refusal) in `error.details`; `dryRun` answers the same judgement with `outcome: would_move`. Gates as the package write doors: manage-metadata, the wall, the knowledge-source gate, a read-only package refused 422 before the protocol. Pinned in `qa/dogfood/test/package-move-in.dogfood.test.ts`, which drives THIS route and parses the payload through the response schema' }, { route: 'POST /packages/:id/duplicate', domain: '/packages', disposition: 'sdk', client: 'packages.duplicate', responseSchema: 'DuplicatePackageResponseSchema', note: 'Enveloped — the named schema is the `data`: `duplicatePackage`\'s declared return, transcribed describe-only. ⚠ `data.success` is the operation\'s verdict; the envelope `success` is transport-level and true even for a partial/empty duplicate (a console that read the envelope `success` reported a partial or empty duplicate as done). The SOURCE must be a writable base: a code-loaded or platform/marketplace source is refused 422 `DUPLICATE_SOURCE_NOT_A_BASE` (`requireDuplicableSource`, `domains/packages.ts`), BEFORE the protocol call and therefore before the target package record is minted — `duplicatePackage` installs that record ahead of its copy loop, so refusing any later still left a real, listed, empty shell package behind. ADR-0070 D4 is declared-and-not-built and its object is a BASE, so cloning a code package\'s items would EXTEND D4 rather than implement it; the unbuilt case refuses loudly instead of answering 200 with `copiedCount: 0`, which no caller could tell from a base that really is empty. An empty WRITABLE base still answers 200 / `copiedCount: 0` — that read happened and found nothing. Pinned in `domains/packages-readonly-gate.test.ts`. Conformance: spec `api/package-lifecycle.test.ts`' }, diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index 2acc5b32062..d80be99c9bb 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -509,6 +509,7 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_revert_unsupported: 'Commit revert not supported', packages_commit_rollback_unsupported: 'Commit rollback not supported', packages_orphan_adoption_unsupported: 'Orphan adoption not supported', + packages_move_in_unsupported: 'Moving loose items into a package is not supported', packages_duplication_unsupported: 'Package duplication not supported', packages_customization_ensure_unsupported: 'Customization package ensure not supported', automation_connector_credentials_unsupported: @@ -625,6 +626,7 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_revert_unsupported: '不支持撤销提交。', packages_commit_rollback_unsupported: '不支持回滚到某次提交。', packages_orphan_adoption_unsupported: '不支持认领孤立的元数据。', + packages_move_in_unsupported: '不支持把散落项移入软件包。', packages_duplication_unsupported: '不支持复制软件包。', packages_customization_ensure_unsupported: '不支持确保定制软件包存在。', automation_connector_credentials_unsupported: @@ -757,6 +759,7 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_revert_unsupported: 'コミットの取り消しはサポートされていません。', packages_commit_rollback_unsupported: 'コミットへのロールバックはサポートされていません。', packages_orphan_adoption_unsupported: '孤立したメタデータの引き取りはサポートされていません。', + packages_move_in_unsupported: '未所属のメタデータをパッケージへ移動する操作はサポートされていません。', packages_duplication_unsupported: 'パッケージの複製はサポートされていません。', packages_customization_ensure_unsupported: 'カスタマイズパッケージの確保はサポートされていません。', automation_connector_credentials_unsupported: @@ -902,6 +905,7 @@ export const BUILTIN_OPERATION_MESSAGES: Record> packages_commit_revert_unsupported: 'No se admite revertir una confirmación.', packages_commit_rollback_unsupported: 'No se admite restaurar una confirmación anterior.', packages_orphan_adoption_unsupported: 'No se admite adoptar metadatos huérfanos.', + packages_move_in_unsupported: 'No se admite mover metadatos sueltos a un paquete.', packages_duplication_unsupported: 'No se admite duplicar paquetes.', packages_customization_ensure_unsupported: 'No se admite asegurar el paquete de personalización.', automation_connector_credentials_unsupported: From b0e096ddd98fb7ee5260bea4c332740d8be63f92 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:31:06 +0000 Subject: [PATCH 03/14] wip(metadata-protocol): objects move outside the transaction with an undo; the move door's dogfood (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .../src/protocol-package-move-in.ts | 168 ++++++--- .../test/package-move-in.dogfood.test.ts | 319 ++++++++++++++++++ packages/runtime/src/domains/packages.ts | 40 +-- 3 files changed, 452 insertions(+), 75 deletions(-) create mode 100644 packages/qa/dogfood/test/package-move-in.dogfood.test.ts diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index 25b0402a8c5..f875e17315f 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -30,17 +30,23 @@ * * 0. Judge, write nothing: every item is loose; the target is installed and * writable; an object's name carries the target's prefix and does not clash - * with a namespace; and the selection as a set — a moved item that names a - * loose item the selection leaves behind would be read from a package caller - * that never resolves a bare name to an environment item (ADR-0150 D3 (a)), - * so it is refused naming what it leaves behind. - * 1. Every delete and save inside ONE `engine.transaction()`, the package - * commit recorded inside it too. Any refusal rolls the whole move back. A - * dry run runs the same writes and always rolls back. - * 2. On a runtime that cannot roll back (`engineCanRollBack`), a refusal in - * phase 1 undoes every step already taken, newest first; a dry run there - * answers phase 0's judgement alone, because only a rollback makes a write - * invisible. + * with a namespace, no other package owns it, and its fields keep the `__c` + * reservation; and the selection as a set — a moved item that names a loose + * item the selection leaves behind would be read from a package caller that + * never resolves a bare name to an environment item (ADR-0150 D3 (a)), so it + * is refused naming what it leaves behind. + * 1. Objects, each through the delete door (storage kept) and the save door, + * OUTSIDE the transaction: an object's save runs its storage sync, which is + * DDL, and DDL inside the driver transaction waits forever on the lock the + * transaction holds (measured on SQLite; `publishPackageDrafts` defers the + * same DDL past its transaction for the same reason). A later refusal undoes + * them, newest first. A dry run judges objects in phase 0 alone. + * 2. Every other item's delete and save inside ONE `engine.transaction()`, the + * package commit recorded inside it too. Any refusal rolls them back and + * undoes phase 1. A dry run runs the same writes and always rolls back. + * 3. On a runtime that cannot roll back (`engineCanRollBack`), a refusal undoes + * every step already taken, newest first; a dry run there answers phase 0's + * judgement alone, because only a rollback makes a write invisible. * * After any rollback the registry is put back from the restored rows: the save * and delete doors mutate the in-memory registry as they go, and that cannot @@ -61,6 +67,7 @@ import { collectReferenceHits } from './protocol-reference-hits.js'; import { REFERENCE_SITES } from './reference-sites.js'; import { resolveCallerPackageAddress } from './protocol-exact-qualifier.js'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; +import { extensionFieldSuffixRefusalError, judgeExtensionFieldSuffix } from './protocol-extension-field-suffix.js'; import type { ProtocolHost } from './protocol-host.js'; /** What the door is asked, after the route parsed the body. */ @@ -74,14 +81,17 @@ export interface MoveIntoPackageRequest { type MoveHost = Pick { const target = request.targetPackageId; host.refuseOrganizationScopedWrite(`Package '${target}'`, request); + // The store's lazy DDL, BEFORE the transaction, as `publishPackageDrafts` + // runs it: the first save of a process would otherwise run it inside + // the driver transaction, where DDL waits on the lock the transaction + // holds (measured: a move as a fresh boot's first write never answered). + await host.ensureOverlayIndex(); const refused: MoveIntoPackageRefusedItemParsed[] = []; const refuse = (r: MoveIntoPackageRefusedItemParsed) => { refused.push(r); }; const answerRefused = (): MoveIntoPackageResponseParsed => ({ @@ -254,13 +269,30 @@ export class ProtocolPackageMoveInFacet { return answerRefused(); } - // An object's literal name and the target's namespace (A2, child K). + // An object, by the save door's own object judges, against the target: + // its literal name and the target's namespace (A2, child K), the + // package that owns the name, and the `__c` reservation. Objects are + // judged here because phase 1 writes them before the transaction, and a + // dry run writes none of them. for (const item of items) { if (item.type !== 'object') continue; - const err = host.objectNamespacePrefixViolation(item.name, target) ?? host.objectNamespaceObjectNameClash(item.name, target); - if (err) { - const code = host.objectNamespacePrefixViolation(item.name, target) ? 'NAMESPACE_PREFIX' : 'NAMESPACE_CONFLICT'; - refuse({ type: item.type, name: item.name, code, error: err }); + const prefix = host.objectNamespacePrefixViolation(item.name, target); + const clash = prefix ? null : host.objectNamespaceObjectNameClash(item.name, target); + if (prefix || clash) { + refuse({ type: item.type, name: item.name, code: prefix ? 'NAMESPACE_PREFIX' : 'NAMESPACE_CONFLICT', error: (prefix ?? clash)! }); + continue; + } + // The object's own loose registration is the `'sys_metadata'` owner + // this move hands over; any other owner refuses it. + const layer = host.classifyObjectContribution(item.name, target); + if (layer.kind === 'mismatch' && layer.ownerPackageId !== 'sys_metadata') { + refuse(refusalOf(item, host.overlayPackageMismatchError(item.name, target, layer.ownerPackageId))); + continue; + } + const body = bodyOf(item.active ?? item.draft); + if (body) { + const suffix = judgeExtensionFieldSuffix({ packageId: target, objects: { [item.name]: { ...body, name: item.name } } }); + if (suffix.length > 0) refuse(refusalOf(item, extensionFieldSuffixRefusalError(suffix))); } } @@ -319,48 +351,49 @@ export class ProtocolPackageMoveInFacet { return { outcome: 'would_move', targetPackageId: target, moved, refused: [] }; } - // ── Phase 1: every delete and save in one transaction ───────────── - // Objects first, so an item of another type that names one meets it - // already moved; the rest in the order asked. - const ordered = [...items.filter((i) => i.type === 'object'), ...items.filter((i) => i.type !== 'object')]; + const objects = items.filter((i) => i.type === 'object'); + const others = items.filter((i) => i.type !== 'object'); const landed: Array<{ item: LooseItem; state: 'active' | 'draft' }> = []; let commitId: string | undefined; let current: LooseItem | undefined; - const run = async () => { - for (const item of ordered) { - current = item; - for (const state of ['active', 'draft'] as const) { - const row = state === 'active' ? item.active : item.draft; - const body = bodyOf(row); - if (!row || !body) continue; - await host.deleteMetaItem({ - type: item.type, - name: item.name, - state, - packageId: null, - dropStorage: false, - ...(item.member ? { member: item.member } : {}), - ...(request.actor ? { actor: request.actor } : {}), - }); - landed.push({ item, state }); - await host.saveMetaItem({ - type: item.type, - name: item.name, - item: body, - mode: state === 'active' ? 'publish' : 'draft', - packageId: target, - ...(item.member ? { member: item.member } : {}), - ...(request.actor ? { actor: request.actor } : {}), - } as Parameters[0]); - } + /** One item: its loose row out through the delete door (storage kept), its body into the target through the save door. */ + const moveItem = async (item: LooseItem) => { + current = item; + for (const state of ['active', 'draft'] as const) { + const row = state === 'active' ? item.active : item.draft; + const body = bodyOf(row); + if (!row || !body) continue; + await host.deleteMetaItem({ + type: item.type, + name: item.name, + state, + packageId: null, + dropStorage: false, + ...(item.member ? { member: item.member } : {}), + ...(request.actor ? { actor: request.actor } : {}), + }); + landed.push({ item, state }); + await host.saveMetaItem({ + type: item.type, + name: item.name, + item: body, + mode: state === 'active' ? 'publish' : 'draft', + packageId: target, + ...(item.member ? { member: item.member } : {}), + ...(request.actor ? { actor: request.actor } : {}), + } as Parameters[0]); } current = undefined; + }; + // ── Phase 2's body: every other item, then the package commit ───── + const run = async () => { + for (const item of others) await moveItem(item); const commit = await host.recordPackageCommit({ packageId: target, operation: 'apply', message: `Move ${items.length} loose item(s) into package '${target}'`, ...(request.actor ? { actor: request.actor } : {}), - items: ordered.filter((i) => i.active).map((i) => ({ + items: [...objects, ...others].filter((i) => i.active).map((i) => ({ type: i.type, name: i.name, existedBefore: false, prevVersion: null, ...(i.member ? { member: i.member } : {}), })), @@ -368,16 +401,32 @@ export class ProtocolPackageMoveInFacet { commitId = commit?.commitId; if (request.dryRun) throw DRY_RUN_ROLLBACK; }; + const landedObjects = () => landed.filter((l) => l.item.type === 'object'); + let transacted = false; try { + // ── Phase 1: objects, outside the transaction (their storage sync is DDL) ── + if (!request.dryRun) { + for (const item of objects) await moveItem(item); + } + const objectSteps = landed.length; + // ── Phase 2: the rest, in one transaction ───────────────────── + transacted = true; const engine = host.engine; if (engineCanRollBack(engine)) { - await retireOverlayCacheOnRollback(engine, () => engine.transaction(() => run())); + try { + await retireOverlayCacheOnRollback(engine, () => engine.transaction(() => run())); + } catch (e: unknown) { + // Rolled back in storage: what the transaction wrote is gone. + landed.splice(objectSteps); + throw e; + } } else { await run(); } } catch (e: unknown) { if (canRollBack) { - await ProtocolPackageMoveInFacet.restoreRegistry(host, items, target); + if (transacted) await ProtocolPackageMoveInFacet.restoreRegistry(host, others, target); + await ProtocolPackageMoveInFacet.undoLanded(host, landedObjects(), target, request.actor); } else { await ProtocolPackageMoveInFacet.undoLanded(host, landed, target, request.actor); } @@ -422,9 +471,10 @@ export class ProtocolPackageMoveInFacet { } /** - * On a runtime that cannot roll back: undo each step already taken, newest - * first — remove the row written into the target, then put the loose row - * back as it was stored. + * Undo each step no transaction covered, newest first — every step on a + * runtime that cannot roll back, the objects' steps on one that can: + * remove the row written into the target, put the loose row back as it was + * stored, then put the registry back at the package-less address. */ private static async undoLanded( host: MoveHost, @@ -446,22 +496,30 @@ export class ProtocolPackageMoveInFacet { } catch { // The save never wrote it: nothing to remove. } + // `runtime-only`: the loose row is an item no package ships, put + // back where it was. The default intent (`override-artifact`) is + // refused on a type with no overlay channel, an object among them + // (measured: refused as a sealed managed item). await repo.put({ type: item.type, name: item.name, org: 'env' } as never, body, { state, + // The delete above left no head at the package-less address. + parentVersion: null, source: 'protocol.moveIntoPackage', actor: actor ?? null, message: `undo the move of ${item.type}/${item.name}: the move into '${target}' was refused`, + intent: 'runtime-only', + packageId: null, ...(item.member ? { member: item.member } : {}), } as never); + if (state === 'active') await ProtocolPackageMoveInFacet.restoreRegistry(host, [item], target); } catch (err: any) { console.error( `[Protocol] moveIntoPackage: the refused move of ${item.type}/${item.name} into '${target}' could ` - + `not be undone on this runtime, which cannot roll back: ${err?.message ?? err}. The item may now be ` + + `not be undone (a write no transaction covered): ${err?.message ?? err}. The item may now be ` + 'stored in neither place, or in the target, although the answer says nothing moved. Fix: ' + `re-save ${item.type}/${item.name} from its history (GET /meta/${item.type}/${item.name}/history).`, ); } } - await ProtocolPackageMoveInFacet.restoreRegistry(host, landed.map((l) => l.item), target); } } diff --git a/packages/qa/dogfood/test/package-move-in.dogfood.test.ts b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts new file mode 100644 index 00000000000..c40168a9ec9 --- /dev/null +++ b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts @@ -0,0 +1,319 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38150] `POST /api/v1/packages/:id/move-in` — the door that moves a + * SELECTION of loose items into one package (ADR-0084 amendment of + * 2026-11-26, "Loose items stay where they are, and one door moves them"; + * ruling 7184753035 question 3). + * + * What this file pins, through THIS route on a booted CRM stack: + * + * - #37468's three defects of the old `adopt-orphans` door, as regression + * tests on the new one: a move into an uninstalled package (A1), an object + * without the target's namespace prefix (A2), and a moved flow and dataset + * readable at the package's address with no restart (A3). + * - The ADR-0150 D3 (a) set rule: a report that reads a loose dataset is + * refused alone, naming the dataset, and the two move together. (The card + * says "a flow reads a dataset"; no flow property references a dataset — + * the derived reference index names dashboard, object, report, translation + * and view — so the report stands in for it.) + * - One test per save-door judge the move runs (child K, the object owner, + * the permission-set owner, `__c`), each refused with the save door's own + * code. + * - A `.custom` pair item and a served overlay are not loose, and are refused. + * - `dryRun` writes nothing. + * - The `_env` address after a move, measured: 409 naming the new holder. + * + * The loose rows are a FIXTURE: inserted with the system context and read by + * a second boot on the same database file, as + * `flow-shipped-name-layered-read.dogfood.test.ts` does. No public door is + * used to create them, so these tests stay green once package-less creates + * close. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import crmStack from '@objectstack/example-crm'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MoveIntoPackageResponseSchema } from '@objectstack/spec/api'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +const TARGET = 'com.probe.zeta'; +const NAMESPACE = 'zeta'; +const OTHER = 'com.probe.plain'; +const GHOST = 'com.probe.ghost'; +/** A package with no namespace, which owns the object `zeta_owned`. */ +const OWNER = 'com.probe.owner'; +const CRM = 'com.example.crm'; +const SHIPPED_FLOW = 'crm_convert_lead_wizard'; + +const flowBody = (name: string) => ({ + name, label: name, type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start', config: {} }, { id: 'end', type: 'end', label: 'End' }], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}); +const objectBody = (name: string, fields: Record = { title: { type: 'text', label: 'Title' } }) => ({ + name, label: name, sharingModel: 'public_read_write', fields, +}); +const datasetBody = (name: string) => ({ + name, label: name, object: 'zeta_deal', + dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string' }], + measures: [{ name: 'opp_count', label: 'Opportunities', aggregate: 'count' }], +}); +const reportBody = (name: string, dataset: string) => ({ + name, label: name, type: 'summary', dataset, rows: ['stage'], values: ['opp_count'], +}); + +/** Every fixture row: `[type, name, package_id, body]`. */ +const FIXTURE: ReadonlyArray]> = [ + ['flow', 'probe_loose_flow', null, flowBody('probe_loose_flow')], + ['object', 'zeta_deal', null, objectBody('zeta_deal', { stage: { type: 'text', label: 'Stage' } })], + ['dataset', 'probe_env_ds', null, datasetBody('probe_env_ds')], + ['report', 'probe_env_report', null, reportBody('probe_env_report', 'probe_env_ds')], + ['flow', 'probe_dry_flow', null, flowBody('probe_dry_flow')], + ['object', 'probe_widget', null, objectBody('probe_widget')], + ['object', 'zeta_custom', null, objectBody('zeta_custom')], + ['object', 'zeta_undo', null, objectBody('zeta_undo')], + // An object another package holds, beside a loose row of the same name. The + // save door's prefix judge would refuse the owner's row (`owner_`), so it is + // a fixture row too: the case the owner judge exists for is a row that + // reached the store before that judge did. + ['object', 'zeta_owned', OWNER, objectBody('zeta_owned')], + ['object', 'zeta_owned', null, objectBody('zeta_owned')], + ['object', 'zeta_suffix', null, objectBody('zeta_suffix', { note__c: { type: 'text', label: 'Note' } })], + ['permission', 'probe_perm_owner', null, { name: 'probe_perm_owner', label: 'Probe perm', objects: {}, packageId: OTHER }], + // A `.custom` pair item (ADR-0146 D2): bound to the code package's pair, not loose. + ['flow', 'probe_pair_flow', `${CRM}.custom`, flowBody('probe_pair_flow')], + // A served overlay: a package-less row over a flow the CRM ships. + ['flow', SHIPPED_FLOW, null, { ...flowBody(SHIPPED_FLOW), label: 'Customized wizard' }], +]; + +describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeout: 60_000 }, () => { + let stack: VerifyStack; + let token: string; + let dir: string; + let ql: any; + + const boot = (databaseFile: string) => bootStack(crmStack, { databaseFile }); + + /** Every stored row of these names, as `type/name@package:state`, sorted. */ + const stored = async (...names: string[]) => { + const rows = (await ql.find('sys_metadata', { where: {}, context: SYSTEM_CTX })) as Array>; + return rows + .filter((r) => names.includes(String(r.name))) + .map((r) => `${String(r.type)}/${String(r.name)}@${r.package_id == null || r.package_id === '' ? 'loose' : String(r.package_id)}:${String(r.state)}`) + .sort(); + }; + const move = async (packageId: string, body: unknown) => { + const res = await stack.apiAs(token, 'POST', `/packages/${encodeURIComponent(packageId)}/move-in`, body); + return { status: res.status, json: (await res.json()) as any }; + }; + /** The refused answer: 422, the first item's code, and the whole answer in `error.details`. */ + const refusedAnswer = (r: { status: number; json: any }) => { + expect(r.status, JSON.stringify(r.json)).toBe(422); + const answer = MoveIntoPackageResponseSchema.parse(r.json.error.details); + expect(answer.outcome).toBe('refused'); + expect(answer.moved).toEqual([]); + expect(r.json.error.code).toBe(answer.refused[0]?.code); + return answer; + }; + const get = async (path: string) => (await stack.apiAs(token, 'GET', path)).status; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'dogfood-38150-')); + const dbFile = join(dir, 'crm.db'); + + // First boot: the target packages, a package that owns `zeta_owned`, and the loose rows. + stack = await boot(dbFile); + const protocol = await stack.kernel.getServiceAsync('protocol'); + await protocol.installPackage({ manifest: { id: TARGET, name: 'Probe zeta', version: '0.1.0', type: 'app', namespace: NAMESPACE } }); + await protocol.installPackage({ manifest: { id: OTHER, name: 'Probe plain', version: '0.1.0', type: 'app', namespace: 'plain' } }); + await protocol.installPackage({ manifest: { id: OWNER, name: 'Probe owner', version: '0.1.0', type: 'app' } }); + const store = await stack.kernel.getServiceAsync('objectql'); + const now = new Date().toISOString(); + for (const [type, name, packageId, body] of FIXTURE) { + await store.insert('sys_metadata', { + type, name, package_id: packageId, state: 'active', version: 1, checksum: null, + created_at: now, updated_at: now, metadata: JSON.stringify(body), + }, { context: SYSTEM_CTX }); + } + await stack.stop(); + + // The measured boot: cold, on the same file, so the loose rows are served as loose. + stack = await boot(dbFile); + ql = await stack.kernel.getServiceAsync('objectql'); + token = await stack.signIn(); + }, 360_000); + + afterAll(async () => { + await stack?.stop(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }, 60_000); + + it('the fixture is served: the loose flow reads at its bare name before any move', async () => { + expect(await stored('probe_loose_flow', 'probe_env_ds', 'probe_env_report')).toEqual([ + 'dataset/probe_env_ds@loose:active', + 'flow/probe_loose_flow@loose:active', + 'report/probe_env_report@loose:active', + ]); + expect(await get('/automation/probe_loose_flow')).toBe(200); + }); + + it('A1 (#37468): a move into an uninstalled package answers 422 WRITABLE_PACKAGE_REQUIRED and stores nothing', async () => { + const before = await stored('probe_loose_flow'); + const answer = refusedAnswer(await move(GHOST, { items: [{ type: 'flow', name: 'probe_loose_flow' }] })); + expect(answer.refused.map((r) => r.code)).toEqual(['WRITABLE_PACKAGE_REQUIRED']); + expect(answer.targetPackageId).toBe(GHOST); + expect(await stored('probe_loose_flow')).toEqual(before); + }); + + it('A2 (#37468): an object without the target\'s namespace prefix answers 422 NAMESPACE_PREFIX and stores nothing', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'object', name: 'probe_widget' }] })); + expect(answer.refused.map((r) => `${r.name}:${r.code}`)).toEqual(['probe_widget:NAMESPACE_PREFIX']); + expect(await stored('probe_widget')).toEqual(['object/probe_widget@loose:active']); + }); + + it('the set rule: a report alone is refused naming the loose dataset it reads; nothing is stored', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'report', name: 'probe_env_report' }] })); + expect(answer.refused).toHaveLength(1); + expect(answer.refused[0]).toMatchObject({ type: 'report', name: 'probe_env_report', code: 'REFERENCE_LEFT_BEHIND' }); + expect(answer.refused[0].references).toEqual([{ type: 'dataset', name: 'probe_env_ds' }]); + expect(await stored('probe_env_report', 'probe_env_ds')).toEqual([ + 'dataset/probe_env_ds@loose:active', + 'report/probe_env_report@loose:active', + ]); + }); + + it('dryRun answers would_move with what would change, and writes nothing', async () => { + const r = await move(TARGET, { items: [{ type: 'flow', name: 'probe_dry_flow' }], dryRun: true }); + expect(r.status, JSON.stringify(r.json)).toBe(200); + const answer = MoveIntoPackageResponseSchema.parse(r.json.data); + expect(answer.outcome).toBe('would_move'); + expect(answer.commitId).toBeUndefined(); + expect(answer.moved).toEqual([{ + type: 'flow', name: 'probe_dry_flow', states: ['active'], + environmentAddress: '_env/probe_dry_flow', qualifiedAddress: `${NAMESPACE}/probe_dry_flow`, + }]); + expect(await stored('probe_dry_flow')).toEqual(['flow/probe_dry_flow@loose:active']); + expect(await get('/automation/probe_dry_flow')).toBe(200); + }); + + it('A3 (#37468) and the set rule: flow, dataset and report move together and read at the package\'s address with no restart', async () => { + const r = await move(TARGET, { + items: [ + { type: 'report', name: 'probe_env_report' }, + { type: 'dataset', name: 'probe_env_ds' }, + { type: 'object', name: 'zeta_deal' }, + { type: 'flow', name: 'probe_loose_flow' }, + ], + }); + expect(r.status, JSON.stringify(r.json)).toBe(200); + const answer = MoveIntoPackageResponseSchema.parse(r.json.data); + expect(answer.outcome).toBe('moved'); + expect(answer.refused).toEqual([]); + expect(typeof answer.commitId).toBe('string'); + expect(answer.moved.map((m) => `${m.type}/${m.name}`).sort()).toEqual([ + 'dataset/probe_env_ds', 'flow/probe_loose_flow', 'object/zeta_deal', 'report/probe_env_report', + ]); + + // Rebound: one row each, in the target, and no loose row left. + expect(await stored('probe_loose_flow', 'probe_env_ds', 'probe_env_report', 'zeta_deal')).toEqual([ + `dataset/probe_env_ds@${TARGET}:active`, + `flow/probe_loose_flow@${TARGET}:active`, + `object/zeta_deal@${TARGET}:active`, + `report/probe_env_report@${TARGET}:active`, + ]); + // Readable at once, at the package's addresses. + expect(await get(`/automation/${NAMESPACE}/probe_loose_flow`)).toBe(200); + expect(await get(`/meta/dataset/probe_env_ds?callerPackage=${TARGET}`)).toBe(200); + }); + + it('the `_env` address after a move, measured: 409 naming the package that holds it now', async () => { + // Measured on this door, which writes through for every type. The + // environment address names its holder exactly (ADR-0150 D5), and after + // the move the environment holds no flow of the name, so it answers 409 + // RESOURCE_CONFLICT with the one candidate holder: the target package. + // The automation engine follows the save's change event, so the 409 is + // awaited rather than read on the first request; the bare name and the + // package address answer 200 throughout. + await vi.waitFor(async () => { + const env = await stack.apiAs(token, 'GET', '/automation/_env/probe_loose_flow'); + expect(env.status).toBe(409); + const body = (await env.json()) as any; + expect(body.error.code).toBe('RESOURCE_CONFLICT'); + expect(body.error.details.candidates).toEqual([{ kind: 'package', packageId: TARGET }]); + }, { timeout: 15_000, interval: 250 }); + const bare = await stack.apiAs(token, 'GET', '/automation/probe_loose_flow'); + expect(bare.status).toBe(200); + expect(((await bare.json()) as any).data?._packageId).toBe(TARGET); + expect(await get(`/automation/${NAMESPACE}/probe_loose_flow`)).toBe(200); + }); + + it('child K: an object named the target\'s namespace + `_custom` is refused NAMESPACE_CONFLICT', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'object', name: 'zeta_custom' }] })); + expect(answer.refused.map((x) => x.code)).toEqual(['NAMESPACE_CONFLICT']); + expect(await stored('zeta_custom')).toEqual(['object/zeta_custom@loose:active']); + }); + + it('`__c`: an object whose field carries the extension suffix is refused by the save door\'s judge', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'object', name: 'zeta_suffix' }] })); + expect(answer.refused).toHaveLength(1); + expect(answer.refused[0]).toMatchObject({ name: 'zeta_suffix', code: 'VALIDATION_ERROR' }); + expect(answer.refused[0].error).toContain('__c'); + expect(await stored('zeta_suffix')).toEqual(['object/zeta_suffix@loose:active']); + }); + + it('the permission-set owner: a set whose body names another package is refused by the save door\'s judge', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'permission', name: 'probe_perm_owner' }] })); + expect(answer.refused).toHaveLength(1); + expect(answer.refused[0]).toMatchObject({ name: 'probe_perm_owner', code: 'VALIDATION_ERROR' }); + expect(answer.refused[0].error).toContain(OTHER); + expect(await stored('probe_perm_owner')).toEqual(['permission/probe_perm_owner@loose:active']); + }); + + it('the object owner: an object another package owns is refused with the save door\'s mismatch', async () => { + const answer = refusedAnswer(await move(TARGET, { items: [{ type: 'object', name: 'zeta_owned' }] })); + expect(answer.refused).toHaveLength(1); + expect(answer.refused[0]).toMatchObject({ name: 'zeta_owned', code: 'OBJECT_OVERLAY_PACKAGE_MISMATCH' }); + expect(answer.refused[0].error).toContain(OWNER); + expect(await stored('zeta_owned')).toEqual([`object/zeta_owned@${OWNER}:active`, 'object/zeta_owned@loose:active']); + }); + + it('whole or nothing: an object moved before a later item is refused is put back loose', async () => { + // The object moves first, outside the transaction (its storage sync is + // DDL); the permission set is then refused by the save door inside it. + const answer = refusedAnswer(await move(TARGET, { + items: [{ type: 'object', name: 'zeta_undo' }, { type: 'permission', name: 'probe_perm_owner' }], + })); + expect(answer.refused.map((x) => `${x.name}:${x.code}`)).toEqual(['probe_perm_owner:VALIDATION_ERROR']); + expect(await stored('zeta_undo', 'probe_perm_owner')).toEqual([ + 'object/zeta_undo@loose:active', + 'permission/probe_perm_owner@loose:active', + ]); + const read = await stack.apiAs(token, 'GET', '/meta/object/zeta_undo'); + expect(read.status).toBe(200); + expect([undefined, null, 'sys_metadata']).toContain(((await read.json()) as any).item?._packageId); + }); + + it('a `.custom` pair item and a served overlay are not loose: refused NOT_LOOSE, nothing stored', async () => { + const answer = refusedAnswer(await move(TARGET, { + items: [{ type: 'flow', name: 'probe_pair_flow' }, { type: 'flow', name: SHIPPED_FLOW }], + })); + expect(answer.refused.map((x) => `${x.name}:${x.code}`).sort()).toEqual([ + `${SHIPPED_FLOW}:NOT_LOOSE`, 'probe_pair_flow:NOT_LOOSE', + ]); + expect(await stored('probe_pair_flow', SHIPPED_FLOW)).toEqual([ + `flow/${SHIPPED_FLOW}@loose:active`, + `flow/probe_pair_flow@${CRM}.custom:active`, + ]); + }); + + it('a body the schema refuses answers 400 and names the member', async () => { + const r = await move(TARGET, { items: [] }); + expect(r.status).toBe(400); + expect(String(r.json.error.message)).toContain('items'); + }); +}); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index f49e767a95e..cf415631593 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -4060,25 +4060,7 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin const result = await protocol.reassignOrphanedMetadata({ targetPackageId: id, ...(actor !== undefined ? { actor } : {}), - }) as { outcome?: string; refused?: ReadonlyArray<{ type: string; name: string; code: string; error: string }> }; - // A refused move wrote nothing, and answers as the save door - // answers the same refusal: 422 with the first item's own code - // in `error.code`. `error.details` is the whole move answer - // (`MoveIntoPackageResponseSchema`, `outcome: 'refused'`), so a - // caller reads every item's refusal, not only the first. - if (result?.outcome === 'refused' && result.refused && result.refused.length > 0) { - const first = result.refused[0]; - const others = result.refused.length - 1; - return { - handled: true, - response: deps.error( - `Nothing was moved into package "${id}": ${first.type} '${first.name}' — ${first.error}` - + (others > 0 ? ` (and ${others} more refusal${others === 1 ? '' : 's'} in error.details.refused)` : ''), - 422, - { ...result, code: first.code }, - ), - }; - } + }); return { handled: true, response: deps.success(result) }; } catch (e: any) { return { handled: true, response: deps.errorFromThrown(e, 500) }; @@ -4135,7 +4117,25 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin items: declared.data.items, ...(declared.data.dryRun ? { dryRun: true } : {}), ...(actor !== undefined ? { actor } : {}), - }); + }) as { outcome?: string; refused?: ReadonlyArray<{ type: string; name: string; code: string; error: string }> }; + // A refused move wrote nothing, and answers as the save door + // answers the same refusal: 422 with the first item's own code + // in `error.code`. `error.details` is the whole move answer + // (`MoveIntoPackageResponseSchema`, `outcome: 'refused'`), so a + // caller reads every item's refusal, not only the first. + if (result?.outcome === 'refused' && result.refused && result.refused.length > 0) { + const first = result.refused[0]; + const others = result.refused.length - 1; + return { + handled: true, + response: deps.error( + `Nothing was moved into package "${id}": ${first.type} '${first.name}' — ${first.error}` + + (others > 0 ? ` (and ${others} more refusal${others === 1 ? '' : 's'} in error.details.refused)` : ''), + 422, + { ...result, code: first.code }, + ), + }; + } return { handled: true, response: deps.success(result) }; } catch (e: any) { return { handled: true, response: deps.errorFromThrown(e, 500) }; From 767556be0887bff1f74fabe0b3ec9f23092ed08a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:35:04 +0000 Subject: [PATCH 04/14] wip: spec baselines, schema and SDK tests, changeset (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .changeset/38150-move-into-package-door.md | 27 ++++ .../docs/references/api/package-lifecycle.mdx | 126 +++++++++++++++++- content/docs/references/index.mdx | 10 +- .../api.md | 2 +- .../client/src/packages-lifecycle.test.ts | 1 + .../client/src/return-type-precision.test.ts | 2 + packages/spec/api-surface/api.json | 15 +++ packages/spec/authorable-surface/api.json | 23 ++++ packages/spec/declaration-map/api.json | 10 ++ packages/spec/export-origins/api.json | 15 +++ packages/spec/json-schema.manifest/api.json | 5 + .../spec/src/api/package-lifecycle.test.ts | 65 +++++++++ 12 files changed, 293 insertions(+), 8 deletions(-) create mode 100644 .changeset/38150-move-into-package-door.md diff --git a/.changeset/38150-move-into-package-door.md b/.changeset/38150-move-into-package-door.md new file mode 100644 index 00000000000..4b5ca1dd3ef --- /dev/null +++ b/.changeset/38150-move-into-package-door.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': patch +'@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +'@objectstack/client': patch +--- + +feat(runtime): `POST /api/v1/packages/:id/move-in` moves a selection of loose items into one package, each through the save door + +Clause-②: yes (widening) +Metadata-protocol: none + +The door ADR-0084's amendment of 2026-11-26 names ("Loose items stay where they are, and one door moves them"; ruling 7184753035, question 3). It takes a selection, never "everything loose": `{ items: [{ type, name, member? }], dryRun? }` (`MoveIntoPackageRequestSchema`, strict). New in the public surface: the route, `MoveIntoPackageRequestSchema`, `MoveIntoPackageResponseSchema` and their item schemas and types in `@objectstack/spec/api`, the protocol method `moveIntoPackage`, the SDK method `client.packages.moveIn(id, request)`, and the message key `packages_move_in_unsupported` (four locales). Nothing an author writes into metadata changes. + +What a move does: + +- Only an item bound to no package moves. An overlay of a shipped item and a `.custom` pair item are not loose and are refused `NOT_LOOSE`. +- The target is judged by the save door's own predicates: an uninstalled package is refused `422 WRITABLE_PACKAGE_REQUIRED`, and a package the deployment ships is refused as every package write door refuses it. +- An object is judged against the target by the save door's object judges: the namespace prefix (`NAMESPACE_PREFIX`), the namespace clash (`NAMESPACE_CONFLICT`), the package that owns the name (`OBJECT_OVERLAY_PACKAGE_MISMATCH`) and the `__c` reservation. +- The selection is judged as a set (ADR-0150 D3 (a)): a moved item that names a loose item of a package-scoped type the selection leaves behind is refused `REFERENCE_LEFT_BEHIND`, with the names in `references`. +- Then every item goes through the delete door (storage kept) and the save door into the target, so every other save-door judge runs too, and each type writes through to the registry at once: a moved flow and dataset are read at the package's address with no restart. Items other than objects and the package commit (`operation: 'apply'`) run in one transaction. Objects move just before it, outside it, because an object's save syncs its storage, and that DDL waits forever on the lock a SQLite transaction holds. A later refusal undoes them. +- Whole or nothing: any refusal answers `422` with the first item's code in `error.code` and the whole answer (`outcome: 'refused'`, every item's refusal) in `error.details`. Nothing is written. +- `dryRun: true` answers `outcome: 'would_move'` with what each item's addresses become, and writes nothing. + +Measured on this door: after a move, `_env/NAME` answers `409 RESOURCE_CONFLICT` naming the package that now holds the item, and the bare name and `NAMESPACE/NAME` answer `200`. + +`POST /packages/:id/adopt-orphans` is unchanged here. Its retirement is the second half of #38150 and ships in the same release. diff --git a/content/docs/references/api/package-lifecycle.mdx b/content/docs/references/api/package-lifecycle.mdx index 14795ec5e0c..469c5a8d343 100644 --- a/content/docs/references/api/package-lifecycle.mdx +++ b/content/docs/references/api/package-lifecycle.mdx @@ -50,8 +50,8 @@ authored after that retirement per the ruling's sequencing (3A). ## TypeScript Usage ```typescript -import { DiscardPackageDraftsResponseSchema, DuplicatePackageResponseSchema, EnsureCustomizationPackageRequestSchema, EnsureCustomizationPackageResponseSchema, GetPackageCustomizationsRequestSchema, GetPackageCustomizationsResponseSchema, ImportUnmanagedPackageRequestSchema, ImportUnmanagedPackageResponseSchema, ListPackageCommitsResponseSchema, PackageExportBundleSchema, PackageExportManifestSchema, PackagePublishResultSchema, ReassignOrphanedMetadataResponseSchema, RevertPackageCommitResponseSchema, RollbackToPackageCommitResponseSchema } from '@objectstack/spec/api'; -import type { DiscardPackageDraftsResponse, DuplicatePackageResponse, EnsureCustomizationPackageRequest, EnsureCustomizationPackageResponse, GetPackageCustomizationsRequest, GetPackageCustomizationsResponse, ImportUnmanagedPackageRequest, ImportUnmanagedPackageResponse, ListPackageCommitsResponse, PackageExportBundle, PackageExportManifest, PackagePublishResult, ReassignOrphanedMetadataResponse, RevertPackageCommitResponse, RollbackToPackageCommitResponse } from '@objectstack/spec/api'; +import { DiscardPackageDraftsResponseSchema, DuplicatePackageResponseSchema, EnsureCustomizationPackageRequestSchema, EnsureCustomizationPackageResponseSchema, GetPackageCustomizationsRequestSchema, GetPackageCustomizationsResponseSchema, ImportUnmanagedPackageRequestSchema, ImportUnmanagedPackageResponseSchema, ListPackageCommitsResponseSchema, MoveIntoPackageItemSchema, MoveIntoPackageMovedItemSchema, MoveIntoPackageRefusedItemSchema, MoveIntoPackageRequestSchema, MoveIntoPackageResponseSchema, PackageExportBundleSchema, PackageExportManifestSchema, PackagePublishResultSchema, ReassignOrphanedMetadataResponseSchema, RevertPackageCommitResponseSchema, RollbackToPackageCommitResponseSchema } from '@objectstack/spec/api'; +import type { DiscardPackageDraftsResponse, DuplicatePackageResponse, EnsureCustomizationPackageRequest, EnsureCustomizationPackageResponse, GetPackageCustomizationsRequest, GetPackageCustomizationsResponse, ImportUnmanagedPackageRequest, ImportUnmanagedPackageResponse, ListPackageCommitsResponse, MoveIntoPackageItem, MoveIntoPackageMovedItem, MoveIntoPackageRefusedItem, MoveIntoPackageRequest, MoveIntoPackageResponse, PackageExportBundle, PackageExportManifest, PackagePublishResult, ReassignOrphanedMetadataResponse, RevertPackageCommitResponse, RollbackToPackageCommitResponse } from '@objectstack/spec/api'; // Validate data const result = DiscardPackageDraftsResponseSchema.parse(data); @@ -317,6 +317,128 @@ A navigation item another installed package contributes to an app the base owns, | **createdAt** | `string` | optional | When the commit was made (ISO-8601 string), when recorded. | +--- + +## MoveIntoPackageItem + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the loose item (singular, e.g. `flow`, `dataset`, `object`). | +| **name** | `string` | ✅ | Machine name of the loose item. | +| **member** | `string` | optional | The bundle member to move, for a bundled type (an email template's locale). Omitted, the canonical member. | + + +--- + +## MoveIntoPackageMovedItem + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the moved item. | +| **name** | `string` | ✅ | Name of the moved item; a move never renames. | +| **member** | `string` | optional | The bundle member moved, for a bundled type. | +| **states** | `Enum<'active' \| 'draft'>[]` | ✅ | Which of the item's rows moved: its published row, its pending draft, or both. | +| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | +| **qualifiedAddress** | `string` | optional | The package-qualified address the item answers at after the move (`NAMESPACE/NAME`), present beside `environmentAddress`. | +| **aiFaceName** | `{ before: string; after: string }` | optional | The AI face name change (ADR-0150 D6), present for a tool, skill, agent or object-less action whose face the move changes. | + +### Nested Shape: `MoveIntoPackageMovedItem.aiFaceName` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **before** | `string` | ✅ | The name AI clients listed the item under before the move. | +| **after** | `string` | ✅ | The name AI clients list it under after the move. | + + +--- + +## MoveIntoPackageRefusedItem + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the refused item. | +| **name** | `string` | ✅ | Name of the refused item. | +| **member** | `string` | optional | The bundle member, for a bundled type. | +| **code** | `string` | ✅ | The refusal's code: the save door's own (`WRITABLE_PACKAGE_REQUIRED`, `NAMESPACE_PREFIX`, …), `NOT_LOOSE` for an item bound to a package or not found, or `REFERENCE_LEFT_BEHIND` for an item that names a loose item the selection leaves behind. | +| **error** | `string` | ✅ | What refused the item and what to do. | +| **references** | `{ type: string; name: string }[]` | optional | For `REFERENCE_LEFT_BEHIND`: every loose item this item names that the selection leaves behind. Adding them to the selection moves them together. | + +### Nested Shape: `MoveIntoPackageRefusedItem.references[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the loose item left behind. | +| **name** | `string` | ✅ | Name of the loose item left behind. | + + +--- + +## MoveIntoPackageRequest + +Body of `POST /packages/:id/move-in`: the selection of loose items to move into the package the path names. + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **items** | `{ type: string; name: string; member?: string }[]` | ✅ | The loose items to move: one, several, or every loose item of a type, across types. Each names an item bound to no package; an item a package holds, a customization pair item and an overlay of a shipped item are not loose and are refused. Listed once each. | +| **dryRun** | `boolean` | optional | Judge the move and answer what it would do, writing nothing. Omitted or false, the move is made. | + +### Nested Shape: `MoveIntoPackageRequest.items[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the loose item (singular, e.g. `flow`, `dataset`, `object`). | +| **name** | `string` | ✅ | Machine name of the loose item. | +| **member** | `string` | optional | The bundle member to move, for a bundled type (an email template's locale). Omitted, the canonical member. | + + +--- + +## MoveIntoPackageResponse + +Answer of the move door: what moved (or would move) and what each moved item's addresses become, or every refusal with nothing moved. + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **outcome** | `Enum<'moved' \| 'would_move' \| 'refused'>` | ✅ | `moved`: every item moved. `would_move`: a dry run that would move every item; nothing was written. `refused`: at least one item is refused, so nothing moved. | +| **targetPackageId** | `string` | ✅ | The package the items move into. | +| **moved** | `{ type: string; name: string; member?: string; states: Enum<'active' \| 'draft'>[]; … }[]` | ✅ | Every item, with what the move changes in its addresses. Empty on `refused`. | +| **refused** | `{ type: string; name: string; member?: string; code: string; … }[]` | ✅ | Every refused item, each with its own code. Empty unless `outcome` is `refused`. | +| **commitId** | `string` | optional | The package commit the move recorded (absent on a dry run or a refusal). | + +### Nested Shape: `MoveIntoPackageResponse.moved[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the moved item. | +| **name** | `string` | ✅ | Name of the moved item; a move never renames. | +| **member** | `string` | optional | The bundle member moved, for a bundled type. | +| **states** | `Enum<'active' \| 'draft'>[]` | ✅ | Which of the item's rows moved: its published row, its pending draft, or both. | +| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | +| **qualifiedAddress** | `string` | optional | The package-qualified address the item answers at after the move (`NAMESPACE/NAME`), present beside `environmentAddress`. | +| **aiFaceName** | `{ before: string; after: string }` | optional | The AI face name change (ADR-0150 D6), present for a tool, skill, agent or object-less action whose face the move changes. | + +### Nested Shape: `MoveIntoPackageResponse.refused[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **type** | `string` | ✅ | Metadata type of the refused item. | +| **name** | `string` | ✅ | Name of the refused item. | +| **member** | `string` | optional | The bundle member, for a bundled type. | +| **code** | `string` | ✅ | The refusal's code: the save door's own (`WRITABLE_PACKAGE_REQUIRED`, `NAMESPACE_PREFIX`, …), `NOT_LOOSE` for an item bound to a package or not found, or `REFERENCE_LEFT_BEHIND` for an item that names a loose item the selection leaves behind. | +| **error** | `string` | ✅ | What refused the item and what to do. | +| **references** | `{ type: string; name: string }[]` | optional | For `REFERENCE_LEFT_BEHIND`: every loose item this item names that the selection leaves behind. Adding them to the selection moves them together. | + + --- ## PackageExportBundle diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 77c54e199c7..4a1e331afc0 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1739 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1744 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -21,7 +21,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 104 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](/docs/references/api) | 37 | 529 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 186 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1739** | 14 protocol modules | +| **Total** | **224** | **1744** | 14 protocol modules | --- @@ -69,7 +69,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 524 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 529 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -97,7 +97,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`odata.zod.ts`](/docs/references/api/odata) | `ODataConfig`, `ODataError`, `ODataFilterFunction`, `ODataMetadata`, `ODataQuery`, `ODataResponse` | | [`package-api.zod.ts`](/docs/references/api/package-api) | `GetInstalledPackageRequest`, `ListInstalledPackagesRequest`, `PackageApiErrorCode`, `PackageInstallBody`, `PackageInstallManifest`, `PackageInstallRequest`, `PackageInstallResponse`, `PackagePathParams`, `PackageRollbackRequest`, `PackageUpgradeRequest`, `PackageUpgradeResponse`, `ResolveDependenciesRequest`, `ResolveDependenciesResponse`, `UninstallPackageApiRequest`, `UninstallPackageApiResponse`, `UploadArtifactRequest`, `UploadArtifactResponse` | | [`package-api-assembled.zod.ts`](/docs/references/api/package-api-assembled) | `AssembledInstalledPackage`, `GetInstalledPackageResponse`, `InstalledPackageAtEitherStage`, `ListInstalledPackagesResponse` | -| [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | +| [`package-lifecycle.zod.ts`](/docs/references/api/package-lifecycle) | `DiscardPackageDraftsResponse`, `DuplicatePackageResponse`, `EnsureCustomizationPackageRequest`, `EnsureCustomizationPackageResponse`, `GetPackageCustomizationsRequest`, `GetPackageCustomizationsResponse`, `ImportUnmanagedPackageRequest`, `ImportUnmanagedPackageResponse`, `ListPackageCommitsResponse`, `MoveIntoPackageItem`, `MoveIntoPackageMovedItem`, `MoveIntoPackageRefusedItem`, `MoveIntoPackageRequest`, `MoveIntoPackageResponse`, `PackageExportBundle`, `PackageExportManifest`, `PackagePublishResult`, `ReassignOrphanedMetadataResponse`, `RevertPackageCommitResponse`, `RollbackToPackageCommitResponse` | | [`plugin-rest-api.zod.ts`](/docs/references/api/plugin-rest-api) | `ErrorHandlingConfig`, `OpenApiGenerationConfig`, `RequestValidationConfig`, `ResponseEnvelopeConfig`, `RestApiEndpoint`, `RestApiPluginConfig`, `RestApiRouteCategory`, `RestApiRouteRegistration`, `ValidationMode` | | [`protocol.zod.ts`](/docs/references/api/protocol) | `AiAgentCapabilities`, `AiAgentChatRequest`, `AiAgentSummary`, `AiAgentsResponse`, `AiChatRequest`, `AiChatResponse`, `AiCompleteRequest`, `AiConversation`, `AiConversationMessage`, `AiMessage`, `AiModelsResponse`, `AiPendingAction`, `AiPendingActionStatus`, `AiStreamChunk`, `ApproveAiPendingActionResponse`, `AuditMetaItemRequest`, `AuditMetaItemResponse`, `AutomationActionsResponse`, `AutomationTriggerRequest`, `AutomationTriggerResponse`, `BatchDataRequest`, `BatchDataResponse`, `BuildProbeReport`, `CheckPermissionRequest`, `CheckPermissionResponse`, `CloneDataResponse`, `CreateAiConversationRequest`, `CreateDataRequest`, `CreateDataResponse`, `CreateManyDataRequest`, `CreateManyDataResponse`, `DeleteDataRequest`, `DeleteDataResponse`, `DeleteManyDataRequest`, `DeleteManyDataResponse`, `DeleteMetaItemRequest`, `DeleteMetaItemResponse`, `DestructiveChangeIssue`, `DiffMetaItemRequest`, `DiffMetaItemResponse`, `DisablePackageRequest`, `DisablePackageResponse`, `EnablePackageRequest`, `EnablePackageResponse`, `FieldStillShownBy`, `FindDataRequest`, `FindDataResponse`, `FindReferencesToMetaResponse`, `FlowRegistration`, `FlowRegistrationRefusal`, `GetDataRequest`, `GetDataResponse`, `GetDiscoveryRequest`, `GetDiscoveryResponse`, `GetEffectivePermissionsRequest`, `GetEffectivePermissionsResponse`, `GetFieldLabelsRequest`, `GetFieldLabelsResponse`, `GetLocalesRequest`, `GetLocalesResponse`, `GetMetaDiagnosticsResponse`, `GetMetaItemCachedRequest`, `GetMetaItemCachedResponse`, `GetMetaItemLayeredRequest`, `GetMetaItemLayeredResponse`, `GetMetaItemRequest`, `GetMetaItemResponse`, `GetMetaItemsRequest`, `GetMetaItemsResponse`, `GetMetaTypesRequest`, `GetMetaTypesResponse`, `GetNotificationPreferencesRequest`, `GetNotificationPreferencesResponse`, `GetObjectPermissionsRequest`, `GetObjectPermissionsResponse`, `GetPackageRequest`, `GetPackageResponse`, `GetPresenceRequest`, `GetPresenceResponse`, `GetPublishedMetaItemResponse`, `GetRecordFieldAccessResponse`, `GetTranslationsRequest`, `GetTranslationsResponse`, `GetUiViewRequest`, `GetUiViewResponse`, `HistoryMetaItemRequest`, `HistoryMetaItemResponse`, `HttpFindQueryParams`, `InstallPackageRequest`, `InstallPackageResponse`, `ListAiConversationsRequest`, `ListAiConversationsResponse`, `ListAiPendingActionsRequest`, `ListAiPendingActionsResponse`, `ListDraftsResponse`, `ListNotificationsRequest`, `ListNotificationsResponse`, `ListPackagesRequest`, `ListPackagesResponse`, `MarkAllNotificationsReadRequest`, `MarkAllNotificationsReadResponse`, `MarkNotificationsReadRequest`, `MarkNotificationsReadResponse`, `MetadataAuthoringClient`, `MetadataAuthoringSurface`, `MetadataConflictError`, `Notification`, `NotificationPreferences`, `PublicFormSubmitResponse`, `PublishMetaItemRequest`, `PublishMetaItemResponse`, `PublishPackageDraftsRequest`, `PublishPackageDraftsResponse`, `RealtimeConnectRequest`, `RealtimeConnectResponse`, `RealtimeDisconnectRequest`, `RealtimeDisconnectResponse`, `RealtimeSubscribeRequest`, `RealtimeSubscribeResponse`, `RealtimeUnsubscribeRequest`, `RealtimeUnsubscribeResponse`, `RegisterDeviceRequest`, `RegisterDeviceResponse`, `RejectAiPendingActionResponse`, `RollbackMetaItemRequest`, `RollbackMetaItemResponse`, `RuntimeAuthoringIssue`, `RuntimeBuildIssue`, `SaveMetaItemRequest`, `SaveMetaItemResponse`, `SearchAllHit`, `SearchAllPageHit`, `SearchAllResponse`, `SeedAppliedIdList`, `SeedAppliedLanded`, `SetPresenceRequest`, `SetPresenceResponse`, `UninstallPackageRequest`, `UninstallPackageResponse`, `UnregisterDeviceRequest`, `UnregisterDeviceResponse`, `UpdateAiConversationRequest`, `UpdateDataRequest`, `UpdateDataResponse`, `UpdateManyDataRequest`, `UpdateManyDataResponse`, `UpdateNotificationPreferencesRequest`, `UpdateNotificationPreferencesResponse`, `ValidateDataIssue`, `ValidateDataRequest`, `ValidateDataResponse` | | [`push-delivery.zod.ts`](/docs/references/api/push-delivery) | `PushDeliveryData`, `PushRoute` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index ba6340a82b2..9c83f7ff346 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 538 | +| `api/` | 545 | diff --git a/packages/client/src/packages-lifecycle.test.ts b/packages/client/src/packages-lifecycle.test.ts index 6ee6f0db4ff..e94160edd97 100644 --- a/packages/client/src/packages-lifecycle.test.ts +++ b/packages/client/src/packages-lifecycle.test.ts @@ -43,6 +43,7 @@ describe('client.packages lifecycle (#3563 PR-4)', () => { ['discardDrafts', (c: ObjectStackClient) => c.packages.discardDrafts('p1', { actor: 'admin' }), 'POST', `${BASE}/p1/discard-drafts`, { actor: 'admin' }], ['revert', (c: ObjectStackClient) => c.packages.revert('p1'), 'POST', `${BASE}/p1/revert`, undefined], ['adoptOrphans', (c: ObjectStackClient) => c.packages.adoptOrphans('p1'), 'POST', `${BASE}/p1/adopt-orphans`, {}], + ['moveIn', (c: ObjectStackClient) => c.packages.moveIn('p1', { items: [{ type: 'flow', name: 'f' }], dryRun: true }), 'POST', `${BASE}/p1/move-in`, { items: [{ type: 'flow', name: 'f' }], dryRun: true }], ] as const)('%s hits its lifecycle route', async (_name, call, method, url, expectedBody) => { const { client, fetchMock } = createMockClient({ success: true, data: { ok: true } }); await call(client); diff --git a/packages/client/src/return-type-precision.test.ts b/packages/client/src/return-type-precision.test.ts index 852a08c66d7..16bfbf5c260 100644 --- a/packages/client/src/return-type-precision.test.ts +++ b/packages/client/src/return-type-precision.test.ts @@ -114,6 +114,7 @@ import type { RollbackToPackageCommitResponse, PackageExportManifest, ReassignOrphanedMetadataResponse, + MoveIntoPackageResponse, DuplicatePackageResponse, EnsureCustomizationPackageResponse, } from '@objectstack/spec/api'; @@ -448,6 +449,7 @@ export async function returnTypePrecisionPins12038(): Promise { expectTypeOf(await client.packages.rollback('com.acme.crm', 'cmt_1')).toEqualTypeOf(); expectTypeOf(await client.packages.export('com.acme.crm')).toEqualTypeOf(); expectTypeOf(await client.packages.adoptOrphans('com.acme.crm')).toEqualTypeOf(); + expectTypeOf(await client.packages.moveIn('com.acme.crm', { items: [{ type: 'flow', name: 'f' }] })).toEqualTypeOf(); expectTypeOf(await client.packages.duplicate('com.acme.crm', 'com.acme.copy')).toEqualTypeOf(); expectTypeOf(await client.packages.ensureCustomization('com.acme.crm')).toEqualTypeOf(); diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 2fcf3aa790d..fdaf4764e36 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -795,6 +795,21 @@ "ModificationResult (type)", "ModificationResultParsed (type)", "ModificationResultSchema (const)", + "MoveIntoPackageItem (type)", + "MoveIntoPackageItemParsed (type)", + "MoveIntoPackageItemSchema (const)", + "MoveIntoPackageMovedItem (type)", + "MoveIntoPackageMovedItemParsed (type)", + "MoveIntoPackageMovedItemSchema (const)", + "MoveIntoPackageRefusedItem (type)", + "MoveIntoPackageRefusedItemParsed (type)", + "MoveIntoPackageRefusedItemSchema (const)", + "MoveIntoPackageRequest (type)", + "MoveIntoPackageRequestParsed (type)", + "MoveIntoPackageRequestSchema (const)", + "MoveIntoPackageResponse (type)", + "MoveIntoPackageResponseParsed (type)", + "MoveIntoPackageResponseSchema (const)", "Notification (type)", "NotificationParsed (type)", "NotificationPreferences (type)", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 7f0627aa9b0..e5d83765bc4 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1332,6 +1332,29 @@ "api/ModificationResult:id", "api/ModificationResult:index", "api/ModificationResult:success", + "api/MoveIntoPackageItem:member", + "api/MoveIntoPackageItem:name", + "api/MoveIntoPackageItem:type", + "api/MoveIntoPackageMovedItem:aiFaceName", + "api/MoveIntoPackageMovedItem:environmentAddress", + "api/MoveIntoPackageMovedItem:member", + "api/MoveIntoPackageMovedItem:name", + "api/MoveIntoPackageMovedItem:qualifiedAddress", + "api/MoveIntoPackageMovedItem:states", + "api/MoveIntoPackageMovedItem:type", + "api/MoveIntoPackageRefusedItem:code", + "api/MoveIntoPackageRefusedItem:error", + "api/MoveIntoPackageRefusedItem:member", + "api/MoveIntoPackageRefusedItem:name", + "api/MoveIntoPackageRefusedItem:references", + "api/MoveIntoPackageRefusedItem:type", + "api/MoveIntoPackageRequest:dryRun", + "api/MoveIntoPackageRequest:items", + "api/MoveIntoPackageResponse:commitId", + "api/MoveIntoPackageResponse:moved", + "api/MoveIntoPackageResponse:outcome", + "api/MoveIntoPackageResponse:refused", + "api/MoveIntoPackageResponse:targetPackageId", "api/Notification:actionUrl", "api/Notification:body", "api/Notification:createdAt", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index 9c5d1d9e019..1222e449d62 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -591,6 +591,16 @@ "MetadataValidateResponseSchema": "api/MetadataValidateResponse", "ModificationResult": "api/ModificationResult", "ModificationResultSchema": "api/ModificationResult", + "MoveIntoPackageItem": "api/MoveIntoPackageItem", + "MoveIntoPackageItemSchema": "api/MoveIntoPackageItem", + "MoveIntoPackageMovedItem": "api/MoveIntoPackageMovedItem", + "MoveIntoPackageMovedItemSchema": "api/MoveIntoPackageMovedItem", + "MoveIntoPackageRefusedItem": "api/MoveIntoPackageRefusedItem", + "MoveIntoPackageRefusedItemSchema": "api/MoveIntoPackageRefusedItem", + "MoveIntoPackageRequest": "api/MoveIntoPackageRequest", + "MoveIntoPackageRequestSchema": "api/MoveIntoPackageRequest", + "MoveIntoPackageResponse": "api/MoveIntoPackageResponse", + "MoveIntoPackageResponseSchema": "api/MoveIntoPackageResponse", "Notification": "api/Notification", "NotificationPreferences": "api/NotificationPreferences", "NotificationPreferencesSchema": "api/NotificationPreferences", diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index 58ca252dd03..f2af4b6adb4 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -769,6 +769,21 @@ "ModificationResult": "src/api/contract.zod.ts#ModificationResult (type)", "ModificationResultParsed": "src/api/contract.zod.ts#ModificationResultParsed (type)", "ModificationResultSchema": "src/api/contract.zod.ts#ModificationResultSchema (const)", + "MoveIntoPackageItem": "src/api/package-lifecycle.zod.ts#MoveIntoPackageItem (type)", + "MoveIntoPackageItemParsed": "src/api/package-lifecycle.zod.ts#MoveIntoPackageItemParsed (type)", + "MoveIntoPackageItemSchema": "src/api/package-lifecycle.zod.ts#MoveIntoPackageItemSchema (const)", + "MoveIntoPackageMovedItem": "src/api/package-lifecycle.zod.ts#MoveIntoPackageMovedItem (type)", + "MoveIntoPackageMovedItemParsed": "src/api/package-lifecycle.zod.ts#MoveIntoPackageMovedItemParsed (type)", + "MoveIntoPackageMovedItemSchema": "src/api/package-lifecycle.zod.ts#MoveIntoPackageMovedItemSchema (const)", + "MoveIntoPackageRefusedItem": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRefusedItem (type)", + "MoveIntoPackageRefusedItemParsed": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRefusedItemParsed (type)", + "MoveIntoPackageRefusedItemSchema": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRefusedItemSchema (const)", + "MoveIntoPackageRequest": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRequest (type)", + "MoveIntoPackageRequestParsed": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRequestParsed (type)", + "MoveIntoPackageRequestSchema": "src/api/package-lifecycle.zod.ts#MoveIntoPackageRequestSchema (const)", + "MoveIntoPackageResponse": "src/api/package-lifecycle.zod.ts#MoveIntoPackageResponse (type)", + "MoveIntoPackageResponseParsed": "src/api/package-lifecycle.zod.ts#MoveIntoPackageResponseParsed (type)", + "MoveIntoPackageResponseSchema": "src/api/package-lifecycle.zod.ts#MoveIntoPackageResponseSchema (const)", "Notification": "src/api/protocol.zod.ts#Notification (type)", "NotificationParsed": "src/api/protocol.zod.ts#NotificationParsed (type)", "NotificationPreferences": "src/api/protocol.zod.ts#NotificationPreferences (type)", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index 50b66c14438..86863253141 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -321,6 +321,11 @@ "api/MetadataValidateRequest", "api/MetadataValidateResponse", "api/ModificationResult", + "api/MoveIntoPackageItem", + "api/MoveIntoPackageMovedItem", + "api/MoveIntoPackageRefusedItem", + "api/MoveIntoPackageRequest", + "api/MoveIntoPackageResponse", "api/Notification", "api/NotificationPreferences", "api/ODataConfig", diff --git a/packages/spec/src/api/package-lifecycle.test.ts b/packages/spec/src/api/package-lifecycle.test.ts index a9d5f83638d..3d6ce2d39e0 100644 --- a/packages/spec/src/api/package-lifecycle.test.ts +++ b/packages/spec/src/api/package-lifecycle.test.ts @@ -18,6 +18,8 @@ import { PackageExportManifestSchema, PackageExportBundleSchema, ReassignOrphanedMetadataResponseSchema, + MoveIntoPackageRequestSchema, + MoveIntoPackageResponseSchema, DuplicatePackageResponseSchema, PackagePublishResultSchema, EnsureCustomizationPackageRequestSchema, @@ -428,6 +430,69 @@ describe('ReassignOrphanedMetadataResponseSchema declares the adopt-orphans body }); }); +describe('MoveIntoPackageRequestSchema declares the move door\'s body (#38150)', () => { + it('takes a selection of one or more items, each with an optional member, and an optional dryRun', () => { + const body = { + items: [ + { type: 'flow', name: 'probe_loose_flow' }, + { type: 'permission', name: 'probe_set', member: 'admin' }, + ], + dryRun: true, + }; + expect(MoveIntoPackageRequestSchema.parse(body)).toEqual(body); + }); + + it('refuses an empty selection, an unknown key and an item without a name — nothing is moved by a body it cannot read', () => { + expect(MoveIntoPackageRequestSchema.safeParse({ items: [] }).success).toBe(false); + expect(MoveIntoPackageRequestSchema.safeParse({ items: [{ type: 'flow', name: 'f' }], all: true }).success).toBe(false); + expect(MoveIntoPackageRequestSchema.safeParse({ items: [{ type: 'flow' }] }).success).toBe(false); + expect(MoveIntoPackageRequestSchema.safeParse({ items: [{ type: 'flow', name: 'f', packageId: 'x' }] }).success).toBe(false); + }); +}); + +describe('MoveIntoPackageResponseSchema declares the move door\'s answer (#38150)', () => { + /** Verbatim-shaped captures of the door's three answers, from its dogfood run. */ + const moved = { + outcome: 'moved', + targetPackageId: 'com.probe.zeta', + moved: [ + { type: 'flow', name: 'probe_loose_flow', states: ['active'], environmentAddress: '_env/probe_loose_flow', qualifiedAddress: 'zeta/probe_loose_flow' }, + { type: 'object', name: 'zeta_deal', states: ['active'] }, + { type: 'tool', name: 'lookup', states: ['active', 'draft'], environmentAddress: '_env/lookup', qualifiedAddress: 'zeta/lookup', aiFaceName: { before: 'lookup', after: 'zeta-lookup' } }, + ], + refused: [], + commitId: 'cmt_7752a3d8-4518-4c3e-9b37-df0c15966a4a', + }; + const refused = { + outcome: 'refused', + targetPackageId: 'com.probe.zeta', + moved: [], + refused: [{ + type: 'report', name: 'probe_env_report', code: 'REFERENCE_LEFT_BEHIND', + error: "The report 'probe_env_report' names dataset 'probe_env_ds', which is a loose item this move leaves behind.", + references: [{ type: 'dataset', name: 'probe_env_ds' }], + }], + }; + + it('parses a moved answer and PRESERVES every member', () => { + expect(MoveIntoPackageResponseSchema.parse(moved)).toEqual(moved); + }); + + it('parses a refused answer with the references it names, and a dry run\'s would_move answer', () => { + expect(MoveIntoPackageResponseSchema.parse(refused)).toEqual(refused); + const wouldMove = { ...moved, outcome: 'would_move' }; + delete (wouldMove as { commitId?: string }).commitId; + expect(MoveIntoPackageResponseSchema.parse(wouldMove)).toEqual(wouldMove); + }); + + it('refuses an outcome it does not declare and a moved item with no state', () => { + expect(MoveIntoPackageResponseSchema.safeParse({ ...moved, outcome: 'partial' }).success).toBe(false); + expect(MoveIntoPackageResponseSchema.safeParse({ + ...moved, moved: [{ type: 'flow', name: 'f', states: [] }], + }).success).toBe(false); + }); +}); + describe('DuplicatePackageResponseSchema declares the duplicate body', () => { /** A verbatim-shaped capture of a real `duplicatePackage` return (one copy failure). */ const realResponse = { From a976ac3563a05dc1ffa15d8a00eaed83604eb12f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:16:46 +0000 Subject: [PATCH 05/14] fix(metadata-protocol): keep protocol.ts at its line ceiling; route-ledger census reads 158 rows (#38150) The move door reaches deleteMetaItem through the host facade, its class stub carries no docblock (the facet's header is its contract), and the retiring door's docblock folds its namespace-prefix paragraph into a line that names its replacement. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .../metadata-protocol/src/protocol-host.ts | 1 - .../src/protocol-package-move-in.ts | 6 ++-- packages/metadata-protocol/src/protocol.ts | 30 ++----------------- packages/runtime/src/route-ledger.ts | 2 +- 4 files changed, 6 insertions(+), 33 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-host.ts b/packages/metadata-protocol/src/protocol-host.ts index 3ae22227029..17e58bcd1b8 100644 --- a/packages/metadata-protocol/src/protocol-host.ts +++ b/packages/metadata-protocol/src/protocol-host.ts @@ -96,7 +96,6 @@ export interface ProtocolHost { readonly credentialChannels: ObjectStackProtocolImplementation['credentialChannels']; readonly declinesStoredRow: ObjectStackProtocolImplementation['declinesStoredRow']; readonly defaultRecordPageSaveRefusal: ObjectStackProtocolImplementation['defaultRecordPageSaveRefusal']; - readonly deleteMetaItem: ObjectStackProtocolImplementation['deleteMetaItem']; readonly deleteMetaItemUnaudited: ObjectStackProtocolImplementation['deleteMetaItemUnaudited']; readonly detachMetadataMutationPubSub: ObjectStackProtocolImplementation['detachMetadataMutationPubSub']; readonly diffMetaItem: ObjectStackProtocolImplementation['diffMetaItem']; diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index f875e17315f..99123ff0555 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -82,9 +82,9 @@ export interface MoveIntoPackageRequest { type MoveHost = Pick protocol.declinesStoredRow(...a), defaultRecordPageSaveRefusal: (...a) => protocol.defaultRecordPageSaveRefusal(...a), - deleteMetaItem: (...a) => protocol.deleteMetaItem(...a), deleteMetaItemUnaudited: (...a) => protocol.deleteMetaItemUnaudited(...a), detachMetadataMutationPubSub: (...a) => protocol.detachMetadataMutationPubSub(...a), diffMetaItem: (...a) => protocol.diffMetaItem(...a), @@ -10674,11 +10671,7 @@ export class ObjectStackProtocolImplementation implements * target is refused with {@link permissionSetOwnerBindingRefusal} * (`VALIDATION_ERROR` / 400, the save door's words). * - * The namespace-prefix judge is deliberately NOT asked here: every - * installed package declares a namespace, so it would refuse nearly every - * real orphan object, and whether an adoption refuses, renames or leaves - * the prefix unjudged is the maintainer's question (#28776's ruling). A - * draft is judged by both owner judges when it is promoted. + * The namespace-prefix judge is not asked here ({@link moveIntoPackage}, this door's replacement, asks it); a draft meets both owner judges when promoted. * * ## [#37604] The platform's own record is no orphan * @@ -10701,25 +10694,7 @@ export class ObjectStackProtocolImplementation implements return ProtocolPackageCommitsFacet.reassignOrphanedMetadata(protocolHost(this), request); } - /** - * [ADR-0084 amendment of 2026-11-26] Move a SELECTION of loose - * (package-less) items into one installed, writable package — the door - * `POST /packages/:id/move-in` serves (`packages.moveIn`). - * - * Each item is removed from its package-less address by - * {@link deleteMetaItem} (storage kept) and written into the target by - * {@link saveMetaItem}, so it is refused with the save door's own code and - * every write leaves history and the registry write-through. The selection - * is judged as a set first (ADR-0150 D3 (a)): an item that names a loose - * item the selection leaves behind is refused `REFERENCE_LEFT_BEHIND`. - * Whole or nothing (ADR-0067 D2): one transaction, rolled back on any - * refusal; a runtime that cannot roll back undoes the steps already taken. - * `dryRun` answers the same judgement and writes nothing. - * - * Not a patch of {@link reassignOrphanedMetadata}, which this door replaces - * (ruled not to be patched in place). - */ - async moveIntoPackage(request: MoveIntoPackageRequest): Promise { + async moveIntoPackage(request: MoveIntoPackageRequest) { return ProtocolPackageMoveInFacet.moveIntoPackage(protocolHost(this), request); } @@ -11370,7 +11345,6 @@ export class ObjectStackProtocolImplementation implements return reportPageRequiresAbsentAtLoad(name, body, sduiManifest); } - /** * [ADR-0131 D6, triage ruling Q1 → C] Say out loud which stored * ENVIRONMENT rows no read serves because they overlay sealed managed diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index b165d927481..24297b1af75 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -301,7 +301,7 @@ export const NON_DISPATCH_MOUNT_PREFIXES = [ /** * The ledger. * - * CENSUS (generated): this list holds 157 rows. + * CENSUS (generated): this list holds 158 rows. * * ⛔ THAT NUMBER IS WRITTEN BY A TOOL — never by hand. * `pnpm check:route-ledger-census` counts the rows below and fails when the two From 56df8b47a47c8f229fc01cd23943ae3f7324c357 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:25:14 +0000 Subject: [PATCH 06/14] fix(spec): register the move-in door's three codes in the error-code ledger (#38150) NOT_LOOSE, REFERENCE_LEFT_BEHIND and MOVE_FAILED are stamped by moveIntoPackage and reach the wire in error.code and error.details.refused, so they join @objectstack/metadata-protocol's ledger row, as the dispatcher error-code vocabulary guard directs. The reference pages are regenerated. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- content/docs/references/api/automation-api.mdx | 5 ++++- content/docs/references/api/contract.mdx | 5 ++++- content/docs/references/api/error-code-ledger.mdx | 3 +++ packages/spec/src/api/error-code-ledger.zod.ts | 12 ++++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 43303f2d46e..d103ebc751b 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -425,7 +425,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +382 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -665,6 +665,7 @@ const result = AutomationApiErrorCode.parse(data); * `METADATA_SCHEMA_INVALID` * `MIXED_ARTIFACT_COLLECTION_SHAPE` * `MONGODB_MULTI_TENANT_UNSUPPORTED` +* `MOVE_FAILED` * `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` * `MULTI_UPDATE_HOOK_KEY_DIVERGENCE` * `NAMESPACE_CONFLICT` @@ -676,6 +677,7 @@ const result = AutomationApiErrorCode.parse(data); * `NOT_COMPENSABLE` * `NOT_CREATABLE` * `NOT_FOUND` +* `NOT_LOOSE` * `NOT_OVERRIDABLE` * `NOT_UNDOABLE` * `NO_ACTIVE_ORGANIZATION` @@ -729,6 +731,7 @@ const result = AutomationApiErrorCode.parse(data); * `RECORD_GONE` * `RECORD_LOCKED` * `RECORD_NOT_ELIGIBLE` +* `REFERENCE_LEFT_BEHIND` * `REGISTRY_TYPE_NOT_CANONICAL` * `REQUEST_NOT_FOUND` * `RESEED_NO_ROWS` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 129d375ba34..84c2f4e049a 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +382 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +385 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -275,6 +275,7 @@ const result = ApiErrorSchema.parse(data); * `METADATA_SCHEMA_INVALID` * `MIXED_ARTIFACT_COLLECTION_SHAPE` * `MONGODB_MULTI_TENANT_UNSUPPORTED` +* `MOVE_FAILED` * `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` * `MULTI_UPDATE_HOOK_KEY_DIVERGENCE` * `NAMESPACE_CONFLICT` @@ -286,6 +287,7 @@ const result = ApiErrorSchema.parse(data); * `NOT_COMPENSABLE` * `NOT_CREATABLE` * `NOT_FOUND` +* `NOT_LOOSE` * `NOT_OVERRIDABLE` * `NOT_UNDOABLE` * `NO_ACTIVE_ORGANIZATION` @@ -339,6 +341,7 @@ const result = ApiErrorSchema.parse(data); * `RECORD_GONE` * `RECORD_LOCKED` * `RECORD_NOT_ELIGIBLE` +* `REFERENCE_LEFT_BEHIND` * `REGISTRY_TYPE_NOT_CANONICAL` * `REQUEST_NOT_FOUND` * `RESEED_NO_ROWS` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index c582edd15c8..9abf2063341 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -442,6 +442,7 @@ const result = ErrorCode.parse(data); * `METADATA_SCHEMA_INVALID` * `MIXED_ARTIFACT_COLLECTION_SHAPE` * `MONGODB_MULTI_TENANT_UNSUPPORTED` +* `MOVE_FAILED` * `MULTI_REPLICA_PACKAGE_CHANGE_REFUSED` * `MULTI_UPDATE_HOOK_KEY_DIVERGENCE` * `NAMESPACE_CONFLICT` @@ -453,6 +454,7 @@ const result = ErrorCode.parse(data); * `NOT_COMPENSABLE` * `NOT_CREATABLE` * `NOT_FOUND` +* `NOT_LOOSE` * `NOT_OVERRIDABLE` * `NOT_UNDOABLE` * `NO_ACTIVE_ORGANIZATION` @@ -506,6 +508,7 @@ const result = ErrorCode.parse(data); * `RECORD_GONE` * `RECORD_LOCKED` * `RECORD_NOT_ELIGIBLE` +* `REFERENCE_LEFT_BEHIND` * `REGISTRY_TYPE_NOT_CANONICAL` * `REQUEST_NOT_FOUND` * `RESEED_NO_ROWS` diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 3927c0a27c4..66ff4deb1ab 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -752,6 +752,9 @@ export const ERROR_CODE_LEDGER = { 'INVALID_REQUEST', 'ITEM_LOCKED', // _lock refuses the write/delete (ADR-0010 §3.3) 'METADATA_CONFLICT', + // [#38150] The move-in door's per-item code for a refusal the save or + // delete door threw without a code of its own; nothing moves, 422. + 'MOVE_FAILED', // The metadata doors' half of "one name, one holder" for a permission set // (maintainer rulings Q4 = A, record 6050490870, and A, record // 6063176077): the save door, the draft promotion and the restore doors @@ -765,6 +768,11 @@ export const ERROR_CODE_LEDGER = { 'NO_DRAFT', 'NOT_ATTEMPTED', // data-batch row never ran — an earlier row's failure stopped the batch, to roll back (atomic, #4793) or because continueOnError was unset (#7539) 'NOT_CREATABLE', + // [#38150] The move-in door (`moveIntoPackage`, + // protocol-package-move-in.ts, `POST /api/v1/packages/:id/move-in`): a + // selected item that is not loose (an overlay of a shipped item, a + // `.custom` pair item) is refused per item, and nothing moves, 422. + 'NOT_LOOSE', 'NOT_OVERRIDABLE', // [#22737] The data door's two exposure codes, stamped by `findData`'s // nested-relation walk (`refuseUnservedRelationTarget`) when a condition's @@ -780,6 +788,10 @@ export const ERROR_CODE_LEDGER = { // and `/packages` serve protocol throws through `errorFromThrown`. // Reported by the #8087 dispatcher-vocabulary gate. 'QUERY_OBJECT_MISMATCH', + // [#38150] The move-in door's set rule (ADR-0150 D3 (a)): a moved item + // names a loose item of a package-scoped type that the selection leaves + // behind, listed in `references`; nothing moves, 422. + 'REFERENCE_LEFT_BEHIND', 'REGISTRY_TYPE_NOT_CANONICAL', // [#9111] a SchemaRegistry overlay entry was offered a non-canonical metadata `type` — the mint door asserts, the caller folds 'ROLLED_BACK', // atomic data-batch row was written, then undone by the batch rollback (#4793) 'STORED_TYPE_NOT_CANONICAL', // [#8908] a package draft is stored under a non-canonical metadata type (pre-#7894 second-namespace residue) — refused at the publish pre-flight, batch-atomic; [#9174] also refused on `revertCommit`'s restore limb, per-item on `failed[]`, NOT batch-atomic From 4965c0c37fb1c7442f8ec1209af4a60149d9b350 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:45:39 +0000 Subject: [PATCH 07/14] test(spec): the domain-501 sentence census counts packages_move_in_unsupported (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- packages/spec/src/system/operation-message.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 5698f75f4e6..83824c12ce3 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -773,8 +773,9 @@ describe('operation message catalog — the domain modules\' 501 sentences (#378 /^(auth_service_unavailable|i18n_service_unavailable|mcp_server_unavailable|meta_|packages_|automation_(connector|flow|resume|run|screen)|action_activation_|catalog_activation_|permission_set_clone_|security_audience_|share_links_)/.test(key), ); - it('names the thirty-seven keys (thirty-one sentences, six activation nouns)', () => { - expect(KEYS).toHaveLength(37); + // [#38150] +1: `packages_move_in_unsupported`, the move-in door's 501. + it('names the thirty-eight keys (thirty-two sentences, six activation nouns)', () => { + expect(KEYS).toHaveLength(38); }); it.each(KEYS)('%s: every locale translates it and keeps the English placeholders', (key) => { From 5ea8aadd1a429115db7119641aebcc5382d6bfeb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:54:00 +0000 Subject: [PATCH 08/14] chore(changeset): Metadata-protocol added, spec at minor, by the claim amendment (#38150) The five MoveIntoPackage* schemas enter the api authorable-surface shard (23 keys), which Check Changeset reads as an added metadata-protocol change. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .changeset/38150-move-into-package-door.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/38150-move-into-package-door.md b/.changeset/38150-move-into-package-door.md index 4b5ca1dd3ef..4f673e8b3ab 100644 --- a/.changeset/38150-move-into-package-door.md +++ b/.changeset/38150-move-into-package-door.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/metadata-protocol': patch '@objectstack/runtime': patch '@objectstack/client': patch @@ -8,7 +8,7 @@ feat(runtime): `POST /api/v1/packages/:id/move-in` moves a selection of loose items into one package, each through the save door Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added — the five new `@objectstack/spec/api` MoveIntoPackage* schemas enter the `api` authorable-surface shard (23 keys); no metadata key an author writes is added The door ADR-0084's amendment of 2026-11-26 names ("Loose items stay where they are, and one door moves them"; ruling 7184753035, question 3). It takes a selection, never "everything loose": `{ items: [{ type, name, member? }], dryRun? }` (`MoveIntoPackageRequestSchema`, strict). New in the public surface: the route, `MoveIntoPackageRequestSchema`, `MoveIntoPackageResponseSchema` and their item schemas and types in `@objectstack/spec/api`, the protocol method `moveIntoPackage`, the SDK method `client.packages.moveIn(id, request)`, and the message key `packages_move_in_unsupported` (four locales). Nothing an author writes into metadata changes. From 650b2b0d35f952c7187cc820d6cf209fc1b32dfb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:22:28 +0000 Subject: [PATCH 09/14] fix(metadata-protocol): the move-in undo writes the registry back in the member that puts the row; both write censuses record it (#38150) undoLanded now calls applyRegistryWriteThrough right after its repo.put, so the stored-row write census reads the write and its route in one member. The write-through caller census counts ten sites, traced. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .../src/protocol-package-move-in.ts | 19 ++++++++++++++++--- ...ct-registry-write-through-spelling.test.ts | 14 +++++++++++--- ...iew-expansion-reconcile-call-sites.test.ts | 4 ++++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index 99123ff0555..065df279a22 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -445,7 +445,7 @@ export class ProtocolPackageMoveInFacet { * and save doors already moved the in-memory registry: put each item back * at its package-less address, from its restored body. */ - private static async restoreRegistry(host: MoveHost, items: readonly LooseItem[], target: string): Promise { + static async restoreRegistry(host: MoveHost, items: readonly LooseItem[], target: string): Promise { for (const item of items) { const body = bodyOf(item.active); if (!item.active || !body) continue; @@ -476,7 +476,7 @@ export class ProtocolPackageMoveInFacet { * remove the row written into the target, put the loose row back as it was * stored, then put the registry back at the package-less address. */ - private static async undoLanded( + static async undoLanded( host: MoveHost, landed: ReadonlyArray<{ item: LooseItem; state: 'active' | 'draft' }>, target: string, @@ -511,7 +511,20 @@ export class ProtocolPackageMoveInFacet { packageId: null, ...(item.member ? { member: item.member } : {}), } as never); - if (state === 'active') await ProtocolPackageMoveInFacet.restoreRegistry(host, [item], target); + // The registry is put back here, after the put, so the census + // (protocol.view-expansion-reconcile-call-sites.test.ts) reads + // the write and its write-through in one member. + if (state === 'active') { + const [entry] = host.storedOverlayEntries({ type: item.type }, [row as never]); + await host.applyRegistryWriteThrough({ + type: item.type, + name: entry?.name ?? item.name, + item: entry?.data ?? body, + packageId: null, + organizationId: null, + reboundFrom: { packageId: target }, + }); + } } catch (err: any) { console.error( `[Protocol] moveIntoPackage: the refused move of ${item.type}/${item.name} into '${target}' could ` diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index c0d10f85ca2..ba54784cc3d 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -38,7 +38,7 @@ // The trace, measured on `origin/main` — all four routes fold at the producer // --------------------------------------------------------------------------- // `applyObjectRegistryMutation` has exactly ONE caller -// (`applyRegistryWriteThrough`), which has exactly EIGHT: +// (`applyRegistryWriteThrough`), which has exactly TEN: // // 1. `saveMetaItem` passes `singularTypeForRepo`, and the method // already ran `canonicalizeMetaRequestType`. @@ -78,6 +78,14 @@ // `'view'`: it heals the old-shape `view` row a // `form` save, publish or delete re-saved, so no // stored spelling reaches it. +// 9. `restoreRegistry` (#38150) passes the item's type as the move-in +// door folded it through `canonicalMetaType` +// when it judged the selection: it puts each +// moved item back at its package-less address +// after a rolled-back move. +// 10. `undoLanded` (#38150) passes the same folded type: it writes back +// through each loose row a refused move put +// back with no transaction to cover it. // // Both fold maps resolve the plural — `PLURAL_TO_SINGULAR.objects === 'object'` // and `canonicalMetaUrlType('objects') === 'object'` — so no route can deliver @@ -610,9 +618,9 @@ describe('[#8862] the `applyRegistryWriteThrough` caller set stays closed', () = const sources = [source, ...SPLIT_MODULES.map((file) => readFileSync(fileURLToPath(new URL(`./${file}`, import.meta.url)), 'utf8'))]; const sitesOf = (pattern: RegExp) => sources.flatMap((text) => text.match(pattern) ?? []); - it('has exactly eight call sites, all traced in this file’s header', () => { + it('has exactly ten call sites, all traced in this file’s header', () => { const callSites = sitesOf(/\b(?:this|host)\.applyRegistryWriteThrough\(/g); - expect(callSites).toHaveLength(8); + expect(callSites).toHaveLength(10); }); it('`applyObjectRegistryMutation` is reached only through the write-through', () => { diff --git a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts index 7e9e34a47bb..047dd05cba3 100644 --- a/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.view-expansion-reconcile-call-sites.test.ts @@ -178,6 +178,9 @@ const WRITES: ReadonlyArray<{ readonly member: string; readonly verb: string; re { member: 'undoLandedPromotions', verb: 'repo.restoreVersion(', route: { sameMember: 'restoreArtifactRegistryView' } }, { member: 'undoLandedPromotions', verb: 'repo.delete(', route: { sameMember: 'restoreArtifactRegistryView' } }, { member: 'undoLandedPromotions', verb: 'repo.put(', route: { sameMember: 'restoreArtifactRegistryView' } }, + // [#38150] A refused move into a package puts back each loose row no transaction covered (the + // objects; every row on a runtime that cannot roll back), and writes the registry back through. + { member: 'undoLanded', verb: 'repo.put(', route: { sameMember: 'applyRegistryWriteThrough' } }, // [ADR-0159 D5] A `form` save, publish or delete removes (or re-saves) the old-shape `view` row of // its name in the same transaction; each door heals the registry from the rows handed back. { member: 'applyOldShapeFormRowRemovals', verb: 'repo.delete(', route: { handedTo: 'module callers', then: 'healOldShapeFormRowRemovals' } }, @@ -287,6 +290,7 @@ describe('[#29985] the census reads the modules the split moved bodies to', () = 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', 'protocol-form-writes.ts: applyOldShapeFormRowRemovals', 'protocol-form-writes.ts: restoreOldShapeFormRowRemovals', + 'protocol-package-move-in.ts: undoLanded', 'protocol-packageless-overlay-migration.ts: migratePackagelessOverlays', ]); }); From 0d9ab261bc9395c3024fdcba28c007a429f46e25 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:55:45 +0000 Subject: [PATCH 10/14] fix(metadata-protocol): record the move-in door's saveMetaItem among the registry-question producers (#38150) It re-saves stored loose rows, bodies unchanged, into one package: body-only. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- packages/metadata-protocol/src/registry-question.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index 14dccb38283..23e9b783e46 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -115,6 +115,7 @@ export const REGISTRY_QUESTION_PRODUCERS: readonly RegistryQuestionProducer[] = { file: 'packages/services/service-automation/src/flow-credential-migration.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a stored-flow migration pass writes flows, never an object.' }, { file: 'packages/metadata-protocol/src/protocol-package-commits.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'faces `package-duplicate` and `package-unmanaged-import`: a package copied or imported row by row (batch); its objects are judged as one unit after the loop.' }, { file: 'packages/metadata-protocol/src/protocol-packageless-overlay-migration.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'the packageless overlay migration rewrites stored rows (batch).' }, + { file: 'packages/metadata-protocol/src/protocol-package-move-in.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the move-in door (#38150) re-saves stored loose rows, bodies unchanged, into one package (batch): only the binding moves, and the save door\'s own object judges run on each.' }, { file: 'packages/metadata-protocol/src/protocol-save.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the stored-object migration pass re-saves stored rows (batch); its rewritten objects are judged as one unit after the pass.' }, { file: 'packages/cli/src/commands/migrate/organization-ownership.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the CLI organization-ownership migration re-saves stored rows (batch).' }, { file: 'packages/metadata-protocol/src/protocol-history-and-publish.ts', callee: 'promoteDraftForPublish', calls: 2, question: 'by-face', why: 'states `registryQuestion` per call: the per-item publish `item-publish` (against the registry), `publishPackageDrafts` `package-publish` (body-only, the promoted unit judged before its commit).' }, From 3777fbcfe0ffefa186a20219258ddf415cdc0987 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:02:53 +0000 Subject: [PATCH 11/14] fix(metadata-protocol): no tracker id in the registry-question row's prose (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- packages/metadata-protocol/src/registry-question.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index 23e9b783e46..d5085eb8467 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -115,7 +115,7 @@ export const REGISTRY_QUESTION_PRODUCERS: readonly RegistryQuestionProducer[] = { file: 'packages/services/service-automation/src/flow-credential-migration.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'a stored-flow migration pass writes flows, never an object.' }, { file: 'packages/metadata-protocol/src/protocol-package-commits.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'faces `package-duplicate` and `package-unmanaged-import`: a package copied or imported row by row (batch); its objects are judged as one unit after the loop.' }, { file: 'packages/metadata-protocol/src/protocol-packageless-overlay-migration.ts', callee: 'saveMetaItem', calls: 2, question: 'body-only', why: 'the packageless overlay migration rewrites stored rows (batch).' }, - { file: 'packages/metadata-protocol/src/protocol-package-move-in.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the move-in door (#38150) re-saves stored loose rows, bodies unchanged, into one package (batch): only the binding moves, and the save door\'s own object judges run on each.' }, + { file: 'packages/metadata-protocol/src/protocol-package-move-in.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the move-in door re-saves stored loose rows, bodies unchanged, into one package (batch): only the binding moves, and the save door\'s own object judges run on each.' }, { file: 'packages/metadata-protocol/src/protocol-save.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the stored-object migration pass re-saves stored rows (batch); its rewritten objects are judged as one unit after the pass.' }, { file: 'packages/cli/src/commands/migrate/organization-ownership.ts', callee: 'saveMetaItem', calls: 1, question: 'body-only', why: 'the CLI organization-ownership migration re-saves stored rows (batch).' }, { file: 'packages/metadata-protocol/src/protocol-history-and-publish.ts', callee: 'promoteDraftForPublish', calls: 2, question: 'by-face', why: 'states `registryQuestion` per call: the per-item publish `item-publish` (against the registry), `publishPackageDrafts` `package-publish` (body-only, the promoted unit judged before its commit).' }, From 61d7ebc5ecef34fa5d991893a5b255243dc71c91 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:09:52 +0000 Subject: [PATCH 12/14] fix(metadata-protocol,runtime): the move-in door judges each item's type, calls no door on a dry run, and puts the process back when a move stops (#38150) - Each selected item's type is judged as a write of that type before anything is read or written (403 with its code), and a selected knowledge source is admitted for its new author as its save admits one. - A dry run answers the judgement made before any door runs and calls no door. - After a rollback or an undo, the registry, the mutation projector and the mutation signal run again at both addresses, so a refused move leaves every item served loose, as before. - An undo that fails answers a 500 naming the items that did not go back. A failure that is not a refusal, or a failed package commit, answers a 500 fault; a door's refusal keeps its code and sentence, filtered as the publish door filters them, and one with no code is MOVE_FAILED. - Each delete names the version the judgement read, so a save in between answers METADATA_CONFLICT. - client.packages.moveIn documents and tests that a refusal rejects with the code and the whole answer in details. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .changeset/38150-move-into-package-door.md | 8 +- .../docs/references/api/package-lifecycle.mdx | 10 +- packages/client/src/index.ts | 13 +- .../client/src/packages-lifecycle.test.ts | 19 ++ .../src/protocol-package-move-in.test.ts | 167 +++++++++++++ .../src/protocol-package-move-in.ts | 236 +++++++++++++----- ...ct-registry-write-through-spelling.test.ts | 2 +- .../test/package-move-in.dogfood.test.ts | 99 +++++++- packages/runtime/src/domains/packages.ts | 70 +++++- packages/runtime/src/route-ledger.ts | 2 +- .../spec/src/api/package-lifecycle.zod.ts | 22 +- 11 files changed, 562 insertions(+), 86 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol-package-move-in.test.ts diff --git a/.changeset/38150-move-into-package-door.md b/.changeset/38150-move-into-package-door.md index 4f673e8b3ab..5fb47cccc8e 100644 --- a/.changeset/38150-move-into-package-door.md +++ b/.changeset/38150-move-into-package-door.md @@ -18,9 +18,11 @@ What a move does: - The target is judged by the save door's own predicates: an uninstalled package is refused `422 WRITABLE_PACKAGE_REQUIRED`, and a package the deployment ships is refused as every package write door refuses it. - An object is judged against the target by the save door's object judges: the namespace prefix (`NAMESPACE_PREFIX`), the namespace clash (`NAMESPACE_CONFLICT`), the package that owns the name (`OBJECT_OVERLAY_PACKAGE_MISMATCH`) and the `__c` reservation. - The selection is judged as a set (ADR-0150 D3 (a)): a moved item that names a loose item of a package-scoped type the selection leaves behind is refused `REFERENCE_LEFT_BEHIND`, with the names in `references`. -- Then every item goes through the delete door (storage kept) and the save door into the target, so every other save-door judge runs too, and each type writes through to the registry at once: a moved flow and dataset are read at the package's address with no restart. Items other than objects and the package commit (`operation: 'apply'`) run in one transaction. Objects move just before it, outside it, because an object's save syncs its storage, and that DDL waits forever on the lock a SQLite transaction holds. A later refusal undoes them. -- Whole or nothing: any refusal answers `422` with the first item's code in `error.code` and the whole answer (`outcome: 'refused'`, every item's refusal) in `error.details`. Nothing is written. -- `dryRun: true` answers `outcome: 'would_move'` with what each item's addresses become, and writes nothing. +- Each selected item's type is judged as a write of that type: moving a `datasource` needs the platform-settings capability and moving a `knowledge_source` needs the knowledge-source capability and passes that source's own admission, as saving one does (`403`). +- Then every item goes through the delete door (storage kept, naming the version the judgement read, so a save in between answers `409 METADATA_CONFLICT`) and the save door into the target, so every other save-door judge runs too, and each type writes through to the registry at once: a moved flow and dataset are read at the package's address with no restart. Items other than objects and the package commit (`operation: 'apply'`) run in one transaction. Objects move just before it, outside it, because an object's save syncs its storage, and that DDL waits forever on the lock a SQLite transaction holds. A later refusal undoes them. +- Whole or nothing: any refusal answers `422` with the first item's code in `error.code` and the whole answer (`outcome: 'refused'`, every item's refusal) in `error.details`. What had moved is moved back, with the registry and the mutation signal replayed at both addresses, so every item is loose and resolves as before. A failure that is not a refusal answers `500`, every item loose as before; if moving an item back fails, the `500` names the items that did not go back. +- `dryRun: true` answers `outcome: 'would_move'` with what each item's addresses become from the judgement made before any door runs (loose, target, the object judges, the set). It calls no door and writes nothing, so a save-door judge that runs only on the real move can still refuse an item a dry run passed. +- `client.packages.moveIn` resolves the answer for `moved` and `would_move`. A refusal, a refused dry run included, rejects with the first item's code as `code` and the whole answer as `details`. Measured on this door: after a move, `_env/NAME` answers `409 RESOURCE_CONFLICT` naming the package that now holds the item, and the bare name and `NAMESPACE/NAME` answer `200`. diff --git a/content/docs/references/api/package-lifecycle.mdx b/content/docs/references/api/package-lifecycle.mdx index 469c5a8d343..50c179d9379 100644 --- a/content/docs/references/api/package-lifecycle.mdx +++ b/content/docs/references/api/package-lifecycle.mdx @@ -342,7 +342,7 @@ A navigation item another installed package contributes to an app the base owns, | **name** | `string` | ✅ | Name of the moved item; a move never renames. | | **member** | `string` | optional | The bundle member moved, for a bundled type. | | **states** | `Enum<'active' \| 'draft'>[]` | ✅ | Which of the item's rows moved: its published row, its pending draft, or both. | -| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | +| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5) when the target package declares a namespace. After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | | **qualifiedAddress** | `string` | optional | The package-qualified address the item answers at after the move (`NAMESPACE/NAME`), present beside `environmentAddress`. | | **aiFaceName** | `{ before: string; after: string }` | optional | The AI face name change (ADR-0150 D6), present for a tool, skill, agent or object-less action whose face the move changes. | @@ -388,7 +388,7 @@ Body of `POST /packages/:id/move-in`: the selection of loose items to move into | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **items** | `{ type: string; name: string; member?: string }[]` | ✅ | The loose items to move: one, several, or every loose item of a type, across types. Each names an item bound to no package; an item a package holds, a customization pair item and an overlay of a shipped item are not loose and are refused. Listed once each. | -| **dryRun** | `boolean` | optional | Judge the move and answer what it would do, writing nothing. Omitted or false, the move is made. | +| **dryRun** | `boolean` | optional | Answer what the move would do from the judgement made before any door runs (loose, target, the object judges, the set), calling no door and writing nothing. A save-door judge runs only on the real move, so it can still refuse an item a dry run passed. Omitted or false, the move is made. | ### Nested Shape: `MoveIntoPackageRequest.items[number]` @@ -403,13 +403,13 @@ Body of `POST /packages/:id/move-in`: the selection of loose items to move into ## MoveIntoPackageResponse -Answer of the move door: what moved (or would move) and what each moved item's addresses become, or every refusal with nothing moved. +Answer of the move door: what moved (or would move) and what each moved item's addresses become, or every refusal with every item left loose. ### Properties | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **outcome** | `Enum<'moved' \| 'would_move' \| 'refused'>` | ✅ | `moved`: every item moved. `would_move`: a dry run that would move every item; nothing was written. `refused`: at least one item is refused, so nothing moved. | +| **outcome** | `Enum<'moved' \| 'would_move' \| 'refused'>` | ✅ | `moved`: every item moved. `would_move`: a dry run whose judgement passed every item; no door ran and nothing was written. `refused`: at least one item is refused, so what had moved was moved back and every item is loose, as before. | | **targetPackageId** | `string` | ✅ | The package the items move into. | | **moved** | `{ type: string; name: string; member?: string; states: Enum<'active' \| 'draft'>[]; … }[]` | ✅ | Every item, with what the move changes in its addresses. Empty on `refused`. | | **refused** | `{ type: string; name: string; member?: string; code: string; … }[]` | ✅ | Every refused item, each with its own code. Empty unless `outcome` is `refused`. | @@ -423,7 +423,7 @@ Answer of the move door: what moved (or would move) and what each moved item's a | **name** | `string` | ✅ | Name of the moved item; a move never renames. | | **member** | `string` | optional | The bundle member moved, for a bundled type. | | **states** | `Enum<'active' \| 'draft'>[]` | ✅ | Which of the item's rows moved: its published row, its pending draft, or both. | -| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | +| **environmentAddress** | `string` | optional | The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type addressed by package (ADR-0150 D5) when the target package declares a namespace. After the move it no longer resolves: the item answers at `qualifiedAddress` and, while it is the only holder of its name, at its bare name. | | **qualifiedAddress** | `string` | optional | The package-qualified address the item answers at after the move (`NAMESPACE/NAME`), present beside `environmentAddress`. | | **aiFaceName** | `{ before: string; after: string }` | optional | The AI face name change (ADR-0150 D6), present for a tool, skill, agent or object-less action whose face the move changes. | diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 17c4f5b51fd..4385d440633 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -3632,10 +3632,15 @@ export class ObjectStackClient { /** * Move a selection of loose (package-less) items into this package — one * item, several, or every loose item of a type, across types. Whole or - * nothing: the answer's `outcome` is `moved`, or `refused` with every - * refused item's own code and nothing moved; `dryRun: true` answers - * `would_move` and writes nothing, so a confirm step can show what each - * item's addresses become. + * nothing. A move resolves with `outcome: 'moved'`; `dryRun: true` + * resolves with `outcome: 'would_move'` and calls no write, so a confirm + * step can show what each item's addresses become (the judgement is the + * door's own, so a save-door refusal can still meet the real move). + * + * A refusal is THROWN, never resolved: the server answers it 422, and the + * error carries the first refused item's code as its `code` and the whole + * answer (`outcome: 'refused'`, every item's refusal) in its `details`. + * A refused dry run throws the same way. */ moveIn: async (id: string, request: MoveIntoPackageRequest): Promise => { const route = this.getRoute('packages'); diff --git a/packages/client/src/packages-lifecycle.test.ts b/packages/client/src/packages-lifecycle.test.ts index e94160edd97..d1db62f710f 100644 --- a/packages/client/src/packages-lifecycle.test.ts +++ b/packages/client/src/packages-lifecycle.test.ts @@ -101,6 +101,25 @@ describe('client.packages lifecycle (#3563 PR-4)', () => { }); }); + it('moveIn rejects a refused move with the first item\'s code and the whole answer in details', async () => { + const answer = { + outcome: 'refused', + targetPackageId: 'p1', + moved: [], + refused: [{ type: 'flow', name: 'f', code: 'NOT_LOOSE', error: "flow 'f' is not loose." }], + }; + const { client } = createMockClient({ + success: false, + error: { code: 'NOT_LOOSE', message: "flow 'f' is not loose.", httpStatus: 422, details: answer }, + }, 422); + const err: any = await client.packages + .moveIn('p1', { items: [{ type: 'flow', name: 'f' }] }) + .then(() => { throw new Error('expected the refused move to reject'); }, (e) => e); + expect(err.code).toBe('NOT_LOOSE'); + expect(err.httpStatus).toBe(422); + expect(err.details).toEqual(answer); + }); + it('ensureCustomization POSTs to the ensure door with no body, URL-encoding the base id, and returns the answer', async () => { const answer = { basePackageId: 'com.acme.crm', diff --git a/packages/metadata-protocol/src/protocol-package-move-in.test.ts b/packages/metadata-protocol/src/protocol-package-move-in.test.ts new file mode 100644 index 00000000000..c2a9ac24508 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-package-move-in.test.ts @@ -0,0 +1,167 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The move door's facet against a stub host: what it asks the doors, and what + * it does to the running process when a move stops. The route's answers on a + * booted stack are pinned in `qa/dogfood/test/package-move-in.dogfood.test.ts`; + * this file reaches what no booted stack can stage on request — a fault in the + * middle of a move, an undo that fails, a refusal with no code of its own. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ProtocolPackageMoveInFacet } from './protocol-package-move-in.js'; + +const TARGET = 'com.probe.zeta'; + +const flowRow = (name: string, checksum: string | null = null) => ({ + id: `row-${name}`, type: 'flow', name, state: 'active', package_id: null, member: null, checksum, + metadata: JSON.stringify({ name, label: name, type: 'autolaunched', nodes: [], edges: [] }), +}); + +/** A refusal as a door throws one: a 4xx status, and a code when it has one. */ +const refusal = (message: string, status: number, code?: string) => + Object.assign(new Error(message), { status, ...(code ? { code } : {}) }); + +function stubHost(rows: ReadonlyArray>, opts: { rollback?: boolean } = {}) { + const put = vi.fn(async () => undefined); + const engine: Record = { + registry: { getPackage: () => ({ manifest: { namespace: 'zeta' } }), getPackageScopedItem: () => undefined }, + }; + if (opts.rollback !== false) engine.transaction = async (fn: () => Promise) => fn(); + const host = { + engine, + refuseOrganizationScopedWrite: vi.fn(), + ensureOverlayIndex: vi.fn(async () => undefined), + findEnvironmentRows: vi.fn(async () => rows), + isArtifactBacked: vi.fn(() => false), + uninstalledNamedBaseRefusal: vi.fn(() => undefined), + isWritablePackage: vi.fn(() => true), + objectNamespacePrefixViolation: vi.fn(() => null), + objectNamespaceObjectNameClash: vi.fn(() => null), + classifyObjectContribution: vi.fn(() => ({ kind: 'new' })), + overlayPackageMismatchError: vi.fn(), + receiptVersion: vi.fn(async (stored: string) => `token:${stored}`), + facade: { deleteMetaItem: vi.fn(async () => ({ success: true })) }, + saveMetaItem: vi.fn(async () => ({ success: true })), + recordPackageCommit: vi.fn(async () => ({ commitId: 'c1' })), + applyRegistryWriteThrough: vi.fn(async () => undefined), + runMutationProjector: vi.fn(async () => undefined), + emitMetadataMutation: vi.fn(), + storedOverlayEntries: vi.fn((_q: unknown, stored: Array>) => + stored.map((r) => ({ name: r.name, data: JSON.parse(String(r.metadata)) }))), + getOverlayRepo: vi.fn(() => ({ put })), + }; + return { host, put }; +} + +const move = (host: unknown, items: Array<{ type: string; name: string }>, dryRun?: boolean) => + ProtocolPackageMoveInFacet.moveIntoPackage(host as never, { targetPackageId: TARGET, items, ...(dryRun ? { dryRun } : {}) }); + +describe('the move door facet (#38150)', () => { + it('a dry run answers phase 0\'s judgement and calls no door, no projector and no signal', async () => { + const { host } = stubHost([flowRow('f1')]); + const answer = await move(host, [{ type: 'flow', name: 'f1' }], true); + expect(answer.outcome).toBe('would_move'); + expect(answer.moved.map((m) => m.name)).toEqual(['f1']); + expect(host.facade.deleteMetaItem).not.toHaveBeenCalled(); + expect(host.saveMetaItem).not.toHaveBeenCalled(); + expect(host.recordPackageCommit).not.toHaveBeenCalled(); + expect(host.applyRegistryWriteThrough).not.toHaveBeenCalled(); + expect(host.runMutationProjector).not.toHaveBeenCalled(); + expect(host.emitMetadataMutation).not.toHaveBeenCalled(); + }); + + it('each delete names the version phase 0 read, so a write in between answers the delete door\'s conflict', async () => { + const { host } = stubHost([flowRow('f1', 'h1'), flowRow('f2')]); + const answer = await move(host, [{ type: 'flow', name: 'f1' }, { type: 'flow', name: 'f2' }]); + expect(answer.outcome).toBe('moved'); + expect(host.receiptVersion).toHaveBeenCalledWith('h1'); + const deletes = host.facade.deleteMetaItem.mock.calls.map((c: any[]) => c[0]); + expect(deletes[0]).toMatchObject({ name: 'f1', packageId: null, dropStorage: false, parentVersion: 'token:h1' }); + // A row stored with no version is deleted unpinned. + expect(deletes[1]).not.toHaveProperty('parentVersion'); + + // The conflict the delete door throws is the item's refusal, with its code. + const raced = stubHost([flowRow('f1', 'h1')]); + raced.host.facade.deleteMetaItem.mockRejectedValueOnce( + refusal('Conflict on flow/f1: the version token sent is not the current version', 409, 'METADATA_CONFLICT')); + const refused = await move(raced.host, [{ type: 'flow', name: 'f1' }]); + expect(refused.outcome).toBe('refused'); + expect(refused.refused.map((r) => `${r.name}:${r.code}`)).toEqual(['f1:METADATA_CONFLICT']); + expect(raced.host.saveMetaItem).not.toHaveBeenCalled(); + }); + + it('after a rollback, every item the transaction touched is put back in the process: registry, projector and signal', async () => { + const { host } = stubHost([flowRow('f1'), flowRow('f2')]); + host.saveMetaItem + .mockResolvedValueOnce({ success: true }) + .mockRejectedValueOnce(refusal("Flow 'f2' is invalid.", 422, 'VALIDATION_ERROR')); + const answer = await move(host, [{ type: 'flow', name: 'f1' }, { type: 'flow', name: 'f2' }]); + expect(answer.outcome).toBe('refused'); + expect(answer.refused).toEqual([{ type: 'flow', name: 'f2', code: 'VALIDATION_ERROR', error: "Flow 'f2' is invalid." }]); + + // The registry is written back at the package-less address, for both. + const rewrites = host.applyRegistryWriteThrough.mock.calls.map((c: any[]) => c[0]); + expect(rewrites.map((w: any) => `${w.name}@${w.packageId}<-${w.reboundFrom?.packageId}`).sort()) + .toEqual([`f1@null<-${TARGET}`, `f2@null<-${TARGET}`]); + // The projector and the signal run again: deleted at the target, restored loose. + const projected = host.runMutationProjector.mock.calls.map((c: any[]) => `${c[0].name}:${c[0].state}`); + expect(projected).toEqual(['f2:deleted', 'f2:active', 'f1:deleted', 'f1:active']); + const signalled = host.emitMetadataMutation.mock.calls.map((c: any[]) => c[0]); + expect(signalled.map((s: any) => `${s.name}:${s.state}`)).toEqual(['f2:deleted', 'f2:active', 'f1:deleted', 'f1:active']); + const restoredF1 = host.runMutationProjector.mock.calls.map((c: any[]) => c[0]).find((p: any) => p.name === 'f1' && p.state === 'active'); + expect(restoredF1.body).toMatchObject({ name: 'f1' }); + }); + + it('a refusal with no code of its own is MOVE_FAILED, its declared sentence quoted', async () => { + const { host } = stubHost([flowRow('f1')]); + host.saveMetaItem.mockRejectedValueOnce(refusal('The flow cannot be saved here.', 400)); + const answer = await move(host, [{ type: 'flow', name: 'f1' }]); + expect(answer.outcome).toBe('refused'); + expect(answer.refused).toEqual([{ type: 'flow', name: 'f1', code: 'MOVE_FAILED', error: 'The flow cannot be saved here.' }]); + }); + + it('a fault that is not a refusal is answered as a 500 fault, its code and text filtered, never as an item\'s refusal', async () => { + const { host } = stubHost([flowRow('f1')]); + host.saveMetaItem.mockRejectedValueOnce(Object.assign(new Error('SQLITE_BUSY: database is locked at /var/db'), { code: 'SQLITE_BUSY' })); + const err: any = await move(host, [{ type: 'flow', name: 'f1' }]).then(() => undefined, (e) => e); + expect(err?.status).toBe(500); + expect(err.code).toBe('INTERNAL_ERROR'); + expect(err.message).toContain("Nothing was moved into package 'com.probe.zeta': the move of flow 'f1' failed"); + expect(err.message).not.toContain('SQLITE_BUSY'); + expect(err.message).not.toContain('/var/db'); + // The process is put back all the same. + expect(host.runMutationProjector.mock.calls.map((c: any[]) => `${c[0].name}:${c[0].state}`)).toEqual(['f1:deleted', 'f1:active']); + }); + + it('a failed package commit is a fault of the commit, not of the last item', async () => { + const { host } = stubHost([flowRow('f1')]); + host.recordPackageCommit.mockRejectedValueOnce(refusal('commit refused', 422, 'VALIDATION_ERROR')); + const err: any = await move(host, [{ type: 'flow', name: 'f1' }]).then(() => undefined, (e) => e); + expect(err?.status).toBe(500); + expect(err.message).toContain('recording the package commit failed'); + }); + + it('an undo that fails answers a 500 naming what did not go back, never `refused`', async () => { + // A runtime that cannot roll back: every landed step is undone by hand. + const { host, put } = stubHost([flowRow('f1'), flowRow('f2')], { rollback: false }); + host.saveMetaItem + .mockResolvedValueOnce({ success: true }) + .mockRejectedValueOnce(refusal("Flow 'f2' is invalid.", 422, 'VALIDATION_ERROR')); + put.mockRejectedValueOnce(new Error('disk full')); + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + try { + const err: any = await move(host, [{ type: 'flow', name: 'f1' }, { type: 'flow', name: 'f2' }]).then(() => undefined, (e) => e); + expect(err?.status).toBe(500); + expect(err.code).toBeUndefined(); + expect(err.message).toContain('undoing what had already moved failed for flow/f2'); + expect(err.message).not.toContain('flow/f1,'); + } finally { + error.mockRestore(); + } + // f1 went back: removed from the target, put back loose, the process replayed loose. + const undoDeletes = host.facade.deleteMetaItem.mock.calls.map((c: any[]) => c[0]).filter((d: any) => d.packageId === TARGET); + expect(undoDeletes.map((d: any) => d.name)).toEqual(['f2', 'f1']); + expect(host.runMutationProjector.mock.calls.map((c: any[]) => `${c[0].name}:${c[0].state}`)).toEqual(['f1:active']); + }); +}); diff --git a/packages/metadata-protocol/src/protocol-package-move-in.ts b/packages/metadata-protocol/src/protocol-package-move-in.ts index 065df279a22..b56a70c58e5 100644 --- a/packages/metadata-protocol/src/protocol-package-move-in.ts +++ b/packages/metadata-protocol/src/protocol-package-move-in.ts @@ -34,23 +34,35 @@ * reservation; and the selection as a set — a moved item that names a loose * item the selection leaves behind would be read from a package caller that * never resolves a bare name to an environment item (ADR-0150 D3 (a)), so it - * is refused naming what it leaves behind. + * is refused naming what it leaves behind. A dry run answers here: it calls + * no door, because the doors' side effects in the running process (the + * mutation projectors, the mutation signal, the registry) are not covered by + * a store rollback. So a dry run is phase 0's judgement, not the save + * door's, and a `would_move` can still meet a save-door refusal. * 1. Objects, each through the delete door (storage kept) and the save door, * OUTSIDE the transaction: an object's save runs its storage sync, which is * DDL, and DDL inside the driver transaction waits forever on the lock the * transaction holds (measured on SQLite; `publishPackageDrafts` defers the * same DDL past its transaction for the same reason). A later refusal undoes - * them, newest first. A dry run judges objects in phase 0 alone. + * them, newest first. * 2. Every other item's delete and save inside ONE `engine.transaction()`, the * package commit recorded inside it too. Any refusal rolls them back and - * undoes phase 1. A dry run runs the same writes and always rolls back. + * undoes phase 1. * 3. On a runtime that cannot roll back (`engineCanRollBack`), a refusal undoes - * every step already taken, newest first; a dry run there answers phase 0's - * judgement alone, because only a rollback makes a write invisible. + * every step already taken, newest first. * - * After any rollback the registry is put back from the restored rows: the save - * and delete doors mutate the in-memory registry as they go, and that cannot - * roll back with the store. + * Each delete names the version phase 0 read, so a write that lands on a + * selected item after phase 0 answers `METADATA_CONFLICT` instead of being + * lost under the phase-0 body. + * + * After a rollback or an undo, the running process is put back too: the save + * and delete doors ran the registry write-through, the awaited mutation + * projector and the mutation signal as they went, and none of that rolls back + * with the store. So for every item touched, the registry is written back + * through at the package-less address, and the projector and the signal run + * again at both addresses (the target's as deleted, the package-less one as + * restored), as the doors would for those writes. An undo that fails is not a + * refusal: the door answers a fault naming what it could not restore. */ import { isPlatformRecordRow } from '@objectstack/metadata'; @@ -68,6 +80,8 @@ import { REFERENCE_SITES } from './reference-sites.js'; import { resolveCallerPackageAddress } from './protocol-exact-qualifier.js'; import { retireOverlayCacheOnRollback } from './meta-overlay-cache.js'; import { extensionFieldSuffixRefusalError, judgeExtensionFieldSuffix } from './protocol-extension-field-suffix.js'; +import { clientFacingFailureCode, clientFacingFailureText, declaresClientRefusal } from './protocol-client-failures.js'; +import { mutationEventPackage, projectorEventPackage } from './protocol-mutation-package.js'; import type { ProtocolHost } from './protocol-host.js'; /** What the door is asked, after the route parsed the body. */ @@ -82,6 +96,7 @@ export interface MoveIntoPackageRequest { type MoveHost = Pick { readonly package_id?: string | null; readonly member?: string | null; readonly metadata?: unknown; + /** The stored body's content hash: the version a write against this row names. */ + readonly checksum?: string | null; } /** One selected item, judged loose, with its rows. */ @@ -122,9 +141,6 @@ interface LooseItem { /** The ADR-0150 D6 faces: these types are listed to AI clients by a derived name. */ const AI_FACE_TYPES: ReadonlySet = new Set(['tool', 'skill', 'agent', 'action']); -/** The sentinel a dry run throws to roll its transaction back. */ -const DRY_RUN_ROLLBACK = Symbol('move-in dry run'); - /** Whether a stored row is bound to no package (null, empty, or the legacy `sys_metadata` sentinel). */ function isPackageLessRow(row: { package_id?: unknown }): boolean { return row.package_id == null || row.package_id === '' || row.package_id === 'sys_metadata'; @@ -143,8 +159,24 @@ function keyOf(item: { type: string; name: string; member?: string | null }): st return `${item.type}/${item.name}${item.member ? `#${item.member}` : ''}`; } -/** The refusal an error thrown by a door becomes: the door's own code and words. */ +/** + * The refusal an error thrown by a door becomes: the door's own code and words, + * filtered as `publishPackageDrafts` filters them — a code outside the + * catalogue becomes the standard code for its status, and only a declared + * client refusal's sentence is quoted. A refusal with no code is `MOVE_FAILED`. + */ function refusalOf(item: { type: string; name: string; member?: string }, e: unknown): MoveIntoPackageRefusedItemParsed { + return { + type: item.type, + name: item.name, + ...(item.member ? { member: item.member } : {}), + code: clientFacingFailureCode(e) ?? 'MOVE_FAILED', + error: clientFacingFailureText(e, `The move of ${item.type} '${item.name}' was refused.`), + }; +} + +/** A phase-0 refusal from one of the save door's own judges, which this door asked itself: its code and words as built. */ +function judgedRefusalOf(item: { type: string; name: string; member?: string }, e: unknown): MoveIntoPackageRefusedItemParsed { const err = e as { code?: unknown; message?: unknown } | undefined; return { type: item.type, @@ -155,6 +187,15 @@ function refusalOf(item: { type: string; name: string; member?: string }, e: unk }; } +/** A fault the door answers as one (a 5xx), its sentence and code filtered as {@link refusalOf} filters them. */ +function moveFault(message: string, cause: unknown): Error { + const fault = new Error(message) as Error & { status?: number; code?: string }; + fault.status = 500; + const code = clientFacingFailureCode(cause); + if (code && !declaresClientRefusal(cause)) fault.code = code; + return fault; +} + /** Only the namespace a package's manifest declares (`undefined` for none). */ function namespaceOf(host: Pick, packageId: string): string | undefined { const ns = (host.engine as { registry?: { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } } | undefined) @@ -254,7 +295,7 @@ export class ProtocolPackageMoveInFacet { const probe = items[0] ?? { type: 'flow', name: '_' }; const unbound = host.uninstalledNamedBaseRefusal({ type: probe.type, name: probe.name, packageId: target }); if (unbound) { - for (const item of items) refuse(refusalOf(item, unbound)); + for (const item of items) refuse(judgedRefusalOf(item, unbound)); return answerRefused(); } if (!host.isWritablePackage(target)) { @@ -286,13 +327,13 @@ export class ProtocolPackageMoveInFacet { // this move hands over; any other owner refuses it. const layer = host.classifyObjectContribution(item.name, target); if (layer.kind === 'mismatch' && layer.ownerPackageId !== 'sys_metadata') { - refuse(refusalOf(item, host.overlayPackageMismatchError(item.name, target, layer.ownerPackageId))); + refuse(judgedRefusalOf(item, host.overlayPackageMismatchError(item.name, target, layer.ownerPackageId))); continue; } const body = bodyOf(item.active ?? item.draft); if (body) { const suffix = judgeExtensionFieldSuffix({ packageId: target, objects: { [item.name]: { ...body, name: item.name } } }); - if (suffix.length > 0) refuse(refusalOf(item, extensionFieldSuffixRefusalError(suffix))); + if (suffix.length > 0) refuse(judgedRefusalOf(item, extensionFieldSuffixRefusalError(suffix))); } } @@ -346,10 +387,11 @@ export class ProtocolPackageMoveInFacet { const namespace = namespaceOf(host, target); const moved = items.map((item) => movedAnswer(item, namespace)); - const canRollBack = engineCanRollBack(host.engine); - if (request.dryRun && !canRollBack) { + // A dry run is phase 0's judgement: it calls no door (see the header). + if (request.dryRun) { return { outcome: 'would_move', targetPackageId: target, moved, refused: [] }; } + const canRollBack = engineCanRollBack(host.engine); const objects = items.filter((i) => i.type === 'object'); const others = items.filter((i) => i.type !== 'object'); @@ -363,12 +405,18 @@ export class ProtocolPackageMoveInFacet { const row = state === 'active' ? item.active : item.draft; const body = bodyOf(row); if (!row || !body) continue; + // The version phase 0 read: a write that landed since answers + // `METADATA_CONFLICT` rather than being lost under this body. + const parentVersion = typeof row.checksum === 'string' && row.checksum !== '' + ? await host.receiptVersion(row.checksum) + : undefined; await host.facade.deleteMetaItem({ type: item.type, name: item.name, state, packageId: null, dropStorage: false, + ...(parentVersion ? { parentVersion } : {}), ...(item.member ? { member: item.member } : {}), ...(request.actor ? { actor: request.actor } : {}), }); @@ -399,41 +447,57 @@ export class ProtocolPackageMoveInFacet { })), }); commitId = commit?.commitId; - if (request.dryRun) throw DRY_RUN_ROLLBACK; }; const landedObjects = () => landed.filter((l) => l.item.type === 'object'); - let transacted = false; + /** The phase-2 steps a rollback removed from the store, for the process to be put back after it. */ + let rolledBack: Array<{ item: LooseItem; state: 'active' | 'draft' }> = []; try { // ── Phase 1: objects, outside the transaction (their storage sync is DDL) ── - if (!request.dryRun) { - for (const item of objects) await moveItem(item); - } + for (const item of objects) await moveItem(item); const objectSteps = landed.length; // ── Phase 2: the rest, in one transaction ───────────────────── - transacted = true; const engine = host.engine; if (engineCanRollBack(engine)) { try { await retireOverlayCacheOnRollback(engine, () => engine.transaction(() => run())); } catch (e: unknown) { // Rolled back in storage: what the transaction wrote is gone. - landed.splice(objectSteps); + rolledBack = landed.splice(objectSteps); throw e; } } else { await run(); } } catch (e: unknown) { + const unrestored: string[] = []; if (canRollBack) { - if (transacted) await ProtocolPackageMoveInFacet.restoreRegistry(host, others, target); - await ProtocolPackageMoveInFacet.undoLanded(host, landedObjects(), target, request.actor); + await ProtocolPackageMoveInFacet.restoreAfterRollback(host, rolledBack, target); + unrestored.push(...await ProtocolPackageMoveInFacet.undoLanded(host, landedObjects(), target, request.actor)); } else { - await ProtocolPackageMoveInFacet.undoLanded(host, landed, target, request.actor); + unrestored.push(...await ProtocolPackageMoveInFacet.undoLanded(host, landed, target, request.actor)); + } + const cause = current; + const said = cause + ? `the move of ${cause.type} '${cause.name}' ${declaresClientRefusal(e) ? 'was refused' : 'failed'}` + : 'recording the package commit failed'; + if (unrestored.length > 0) { + throw moveFault( + `Moving loose items into package '${target}' stopped (${said}: ` + + `${clientFacingFailureText(e, 'no detail can be quoted')}), and undoing what had already moved ` + + `failed for ${unrestored.join(', ')}. Each of those may now be stored in neither place, or in ` + + `package '${target}': read it, and re-save it from its history ` + + '(GET /meta/TYPE/NAME/history) where it is missing. Every other item is loose, as before.', + e, + ); } - if (e === DRY_RUN_ROLLBACK) { - return { outcome: 'would_move', targetPackageId: target, moved, refused: [] }; + // A thrown fault is answered as a fault, never as an item's refusal. + if (!cause || !declaresClientRefusal(e)) { + throw moveFault( + `Nothing was moved into package '${target}': ${said} ` + + `(${clientFacingFailureText(e, 'no detail can be quoted')}). Every item is loose, as before; try again.`, + e, + ); } - const cause = current ?? items[0]!; refuse(refusalOf(cause, e)); return answerRefused(); } @@ -442,60 +506,107 @@ export class ProtocolPackageMoveInFacet { /** * After a rollback the store holds every loose row again, but the delete - * and save doors already moved the in-memory registry: put each item back - * at its package-less address, from its restored body. + * and save doors already changed the running process: for each step the + * rollback removed, write the item back through the registry at its + * package-less address, and run the projector and the signal again at both + * addresses ({@link replayRestored}). */ - static async restoreRegistry(host: MoveHost, items: readonly LooseItem[], target: string): Promise { - for (const item of items) { - const body = bodyOf(item.active); - if (!item.active || !body) continue; + static async restoreAfterRollback( + host: MoveHost, + steps: ReadonlyArray<{ item: LooseItem; state: 'active' | 'draft' }>, + target: string, + ): Promise { + for (const { item, state } of [...steps].reverse()) { + const row = state === 'active' ? item.active : item.draft; + const body = bodyOf(row); + if (!row || !body) continue; try { - const [entry] = host.storedOverlayEntries({ type: item.type }, [item.active as never]); - await host.applyRegistryWriteThrough({ - type: item.type, - name: entry?.name ?? item.name, - item: entry?.data ?? body, - packageId: null, - organizationId: null, - reboundFrom: { packageId: target }, - }); + if (state === 'active') { + const [entry] = host.storedOverlayEntries({ type: item.type }, [row as never]); + await host.applyRegistryWriteThrough({ + type: item.type, + name: entry?.name ?? item.name, + item: entry?.data ?? body, + packageId: null, + organizationId: null, + reboundFrom: { packageId: target }, + }); + } + await ProtocolPackageMoveInFacet.replayRestored(host, item, state, body, target, true); } catch (err: any) { console.error( `[Protocol] moveIntoPackage: the move of ${item.type}/${item.name} into '${target}' was rolled back ` - + `in storage, but the registry could not be put back: ${err?.message ?? err}. Until the next restart ` - + 'the running process may serve the item at its package address although no row binds it there. ' + + `in storage, but the running process could not be put back: ${err?.message ?? err}. Until the next ` + + 'restart it may serve the item at its package address although no row binds it there. ' + 'Fix: restart the server; the boot registers the item from its stored row.', ); } } } + /** + * The projector and the signal for a step put back: at the target's + * address as deleted (when the target row was removed by no door, i.e. + * after a rollback), then at the package-less address as the restored + * state, with its body. Each projector re-reads the store at the address + * it is handed, so the order leaves it serving the package-less row. + */ + static async replayRestored( + host: MoveHost, + item: LooseItem, + state: 'active' | 'draft', + body: Record, + target: string, + targetRemovedByRollback: boolean, + ): Promise { + const member = item.member ? { member: item.member } : {}; + if (targetRemovedByRollback) { + await host.runMutationProjector({ + type: item.type, name: item.name, state: 'deleted', organizationId: null, + ...projectorEventPackage(item.type, target), + }); + host.emitMetadataMutation({ + type: item.type, name: item.name, state: 'deleted', organizationId: null, ...member, + ...mutationEventPackage(target), + }); + } + await host.runMutationProjector({ + type: item.type, name: item.name, state, organizationId: null, body, + ...projectorEventPackage(item.type, null), + }); + host.emitMetadataMutation({ + type: item.type, name: item.name, state, organizationId: null, ...member, + ...mutationEventPackage(null), + }); + } + /** * Undo each step no transaction covered, newest first — every step on a * runtime that cannot roll back, the objects' steps on one that can: - * remove the row written into the target, put the loose row back as it was - * stored, then put the registry back at the package-less address. + * remove the row written into the target (the delete door answers a + * success with nothing removed when the save never wrote it), put the loose + * row back as it was stored, then put the running process back at the + * package-less address. Answers the steps it could not undo, as + * `TYPE/NAME`; a step whose target-side delete fails stops there, so the + * loose row is never put back beside a target row still stored. */ static async undoLanded( host: MoveHost, landed: ReadonlyArray<{ item: LooseItem; state: 'active' | 'draft' }>, target: string, actor: string | undefined, - ): Promise { + ): Promise { const repo = host.getOverlayRepo(); + const unrestored: string[] = []; for (const { item, state } of [...landed].reverse()) { const row = state === 'active' ? item.active : item.draft; const body = bodyOf(row); try { - try { - await host.facade.deleteMetaItem({ - type: item.type, name: item.name, state, packageId: target, dropStorage: false, - ...(item.member ? { member: item.member } : {}), - ...(actor ? { actor } : {}), - }); - } catch { - // The save never wrote it: nothing to remove. - } + await host.facade.deleteMetaItem({ + type: item.type, name: item.name, state, packageId: target, dropStorage: false, + ...(item.member ? { member: item.member } : {}), + ...(actor ? { actor } : {}), + }); // `runtime-only`: the loose row is an item no package ships, put // back where it was. The default intent (`override-artifact`) is // refused on a type with no overlay channel, an object among them @@ -525,14 +636,17 @@ export class ProtocolPackageMoveInFacet { reboundFrom: { packageId: target }, }); } + if (body) await ProtocolPackageMoveInFacet.replayRestored(host, item, state, body, target, false); } catch (err: any) { + unrestored.push(`${item.type}/${item.name}`); console.error( - `[Protocol] moveIntoPackage: the refused move of ${item.type}/${item.name} into '${target}' could ` + `[Protocol] moveIntoPackage: the stopped move of ${item.type}/${item.name} into '${target}' could ` + `not be undone (a write no transaction covered): ${err?.message ?? err}. The item may now be ` - + 'stored in neither place, or in the target, although the answer says nothing moved. Fix: ' + + 'stored in neither place, or in the target; the door answers a fault naming it. Fix: ' + `re-save ${item.type}/${item.name} from its history (GET /meta/${item.type}/${item.name}/history).`, ); } } + return unrestored; } } diff --git a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts index ba54784cc3d..d3ed3733835 100644 --- a/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts +++ b/packages/metadata-protocol/src/protocol.object-registry-write-through-spelling.test.ts @@ -78,7 +78,7 @@ // `'view'`: it heals the old-shape `view` row a // `form` save, publish or delete re-saved, so no // stored spelling reaches it. -// 9. `restoreRegistry` (#38150) passes the item's type as the move-in +// 9. `restoreAfterRollback` (#38150) passes the item's type as the move-in // door folded it through `canonicalMetaType` // when it judged the selection: it puts each // moved item back at its package-less address diff --git a/packages/qa/dogfood/test/package-move-in.dogfood.test.ts b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts index c40168a9ec9..84eb89c9784 100644 --- a/packages/qa/dogfood/test/package-move-in.dogfood.test.ts +++ b/packages/qa/dogfood/test/package-move-in.dogfood.test.ts @@ -21,7 +21,11 @@ * the permission-set owner, `__c`), each refused with the save door's own * code. * - A `.custom` pair item and a served overlay are not loose, and are refused. - * - `dryRun` writes nothing. + * - `dryRun` calls no door, and a refused move puts the process back: after + * either, the flow still answers at `_env/NAME` and not at `NAMESPACE/NAME`, + * and a loose permission set still grants what it grants. + * - Each selected item's type is judged as a write of it (403 with its code), + * and the body's refusal answers 400 `VALIDATION_ERROR`. * - The `_env` address after a move, measured: 409 naming the new holder. * * The loose rows are a FIXTURE: inserted with the system context and read by @@ -49,6 +53,10 @@ const GHOST = 'com.probe.ghost'; const OWNER = 'com.probe.owner'; const CRM = 'com.example.crm'; const SHIPPED_FLOW = 'crm_convert_lead_wizard'; +/** A loose permission set granting `manage_metadata` and nothing else; the author persona holds it. */ +const AUTHOR_SET = 'probe_meta_author'; +const AUTHOR = 'move-in-author@dogfood.test'; +const PLAIN = 'move-in-plain@dogfood.test'; const flowBody = (name: string) => ({ name, label: name, type: 'autolaunched', @@ -74,6 +82,9 @@ const FIXTURE: ReadonlyArray = {}; const boot = (databaseFile: string) => bootStack(crmStack, { databaseFile }); @@ -121,6 +133,28 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou return answer; }; const get = async (path: string) => (await stack.apiAs(token, 'GET', path)).status; + const moveAs = async (as: string, packageId: string, body: unknown) => { + const res = await stack.apiAs(as, 'POST', `/packages/${encodeURIComponent(packageId)}/move-in`, body); + return { status: res.status, json: (await res.json()) as any }; + }; + /** The author persona's resolved system permissions. */ + const authorPermissions = async () => { + const r = await stack.apiAs(tok[AUTHOR], 'GET', '/auth/me/permissions'); + expect(r.status).toBe(200); + const body = (await r.json()) as any; + return ((body?.data ?? body)?.systemPermissions ?? []) as string[]; + }; + /** The flow answers at its environment address and not at the target's: the process serves it loose. */ + const servedLoose = async (name: string) => { + await vi.waitFor(async () => { + expect(await get(`/automation/_env/${name}`)).toBe(200); + expect(await get(`/automation/${NAMESPACE}/${name}`)).not.toBe(200); + }, { timeout: 15_000, interval: 250 }); + // And it stays so once the engine has followed every signal. + await new Promise((resolve) => setTimeout(resolve, 1_000)); + expect(await get(`/automation/_env/${name}`)).toBe(200); + expect(await get(`/automation/${NAMESPACE}/${name}`)).not.toBe(200); + }; beforeAll(async () => { dir = mkdtempSync(join(tmpdir(), 'dogfood-38150-')); @@ -146,6 +180,11 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou stack = await boot(dbFile); ql = await stack.kernel.getServiceAsync('objectql'); token = await stack.signIn(); + tok[PLAIN] = await stack.signUp(PLAIN); + tok[AUTHOR] = await stack.signUp(AUTHOR); + const authorId = (await ql.findOne('sys_user', { where: { email: AUTHOR }, context: SYSTEM_CTX }))?.id; + expect(authorId, 'the author persona is provisioned').toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: authorId, permission_set: AUTHOR_SET }, { context: SYSTEM_CTX }); }, 360_000); afterAll(async () => { @@ -187,7 +226,7 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou ]); }); - it('dryRun answers would_move with what would change, and writes nothing', async () => { + it('dryRun answers would_move with what would change, calls no door, and leaves the process serving the item loose', async () => { const r = await move(TARGET, { items: [{ type: 'flow', name: 'probe_dry_flow' }], dryRun: true }); expect(r.status, JSON.stringify(r.json)).toBe(200); const answer = MoveIntoPackageResponseSchema.parse(r.json.data); @@ -199,6 +238,61 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou }]); expect(await stored('probe_dry_flow')).toEqual(['flow/probe_dry_flow@loose:active']); expect(await get('/automation/probe_dry_flow')).toBe(200); + await servedLoose('probe_dry_flow'); + }); + + it('a refused move puts the process back: the flow moved before the refusal still answers loose', async () => { + // The flow moves inside the transaction; the permission set after it is + // refused by the save door, and the transaction rolls back. + const answer = refusedAnswer(await move(TARGET, { + items: [{ type: 'flow', name: 'probe_refused_flow' }, { type: 'permission', name: 'probe_perm_owner' }], + })); + expect(answer.refused.map((x) => `${x.name}:${x.code}`)).toEqual(['probe_perm_owner:VALIDATION_ERROR']); + expect(await stored('probe_refused_flow')).toEqual(['flow/probe_refused_flow@loose:active']); + await servedLoose('probe_refused_flow'); + }); + + it('a refused move puts the process back: a loose permission set moved before the refusal still grants', async () => { + expect(await authorPermissions(), 'the loose set grants before any move').toContain('manage_metadata'); + const answer = refusedAnswer(await move(TARGET, { + items: [{ type: 'permission', name: AUTHOR_SET }, { type: 'permission', name: 'probe_perm_owner' }], + })); + expect(answer.refused.map((x) => `${x.name}:${x.code}`)).toEqual(['probe_perm_owner:VALIDATION_ERROR']); + expect(await stored(AUTHOR_SET)).toEqual([`permission/${AUTHOR_SET}@loose:active`]); + expect(await authorPermissions(), 'the loose set still grants after the refusal').toContain('manage_metadata'); + }); + + it('a caller without manage_metadata is refused 403 PERMISSION_DENIED, nothing stored', async () => { + const r = await moveAs(tok[PLAIN], TARGET, { items: [{ type: 'flow', name: 'probe_dry_flow' }] }); + expect(r.status, JSON.stringify(r.json)).toBe(403); + expect(r.json.error.code).toBe('PERMISSION_DENIED'); + expect(await stored('probe_dry_flow')).toEqual(['flow/probe_dry_flow@loose:active']); + }); + + it('each selected type is judged as a write of it: a datasource asks manage_platform_settings (403)', async () => { + expect(await authorPermissions()).not.toContain('manage_platform_settings'); + const r = await moveAs(tok[AUTHOR], TARGET, { items: [{ type: 'flow', name: 'probe_dry_flow' }, { type: 'datasource', name: 'probe_any_ds' }] }); + expect(r.status, JSON.stringify(r.json)).toBe(403); + expect(r.json.error.code).toBe('PERMISSION_DENIED'); + expect(String(r.json.error.message)).toContain('`manage_platform_settings`'); + expect(await stored('probe_dry_flow')).toEqual(['flow/probe_dry_flow@loose:active']); + }); + + it('each selected type is judged as a write of it: a knowledge source asks manage_knowledge_sources (403)', async () => { + expect(await authorPermissions()).not.toContain('manage_knowledge_sources'); + const r = await moveAs(tok[AUTHOR], TARGET, { items: [{ type: 'knowledge_source', name: 'probe_ks' }] }); + expect(r.status, JSON.stringify(r.json)).toBe(403); + expect(r.json.error.code).toBe('PERMISSION_DENIED'); + expect(String(r.json.error.message)).toContain('`manage_knowledge_sources`'); + expect(await stored('probe_ks')).toEqual(['knowledge_source/probe_ks@loose:active']); + }); + + it('a knowledge source is admitted for its new author as its save is: no knowledge service here, 503, nothing stored', async () => { + const r = await move(TARGET, { items: [{ type: 'knowledge_source', name: 'probe_ks' }] }); + expect(r.status, JSON.stringify(r.json)).toBe(503); + expect(r.json.error.code).toBe('SERVICE_UNAVAILABLE'); + expect(String(r.json.error.message)).toContain("knowledge_source 'probe_ks'"); + expect(await stored('probe_ks')).toEqual(['knowledge_source/probe_ks@loose:active']); }); it('A3 (#37468) and the set rule: flow, dataset and report move together and read at the package\'s address with no restart', async () => { @@ -314,6 +408,7 @@ describe('dogfood: POST /packages/:id/move-in, the move door (#38150)', { timeou it('a body the schema refuses answers 400 and names the member', async () => { const r = await move(TARGET, { items: [] }); expect(r.status).toBe(400); + expect(r.json.error.code).toBe('VALIDATION_ERROR'); expect(String(r.json.error.message)).toContain('items'); }); }); diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index cf415631593..fd2f231ddb6 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -50,6 +50,7 @@ import { walledCatalogWriteVerdict } from '@objectstack/metadata-core'; // [ADR-0161 K4, guard two] Source admission, asked for each knowledge source a // duplicate would copy (`refuseDuplicatedKnowledgeSources`). import { KNOWLEDGE_SOURCE_ADMISSION_SERVICE, authoredKnowledgeSourceRefusal } from '@objectstack/metadata-core'; +import { canonicalMetaUrlType } from '@objectstack/spec/shared'; import { isMissingTableError } from '@objectstack/types'; import { readEffectiveTenancyPosture } from './activation-gate.js'; // [#21727] ADR-0087 D1's protocol handshake and the brand predicate for its @@ -4106,10 +4107,75 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin ), }; } + // [ADR-0161 K4] What the door writes is the selection, so each + // selected item's type is admitted as a `/meta` write of it is: a + // `knowledge_source` asks `manage_knowledge_sources` and a + // `datasource` asks `manage_platform_settings` + // (`metaTypeWriteRefusal`, the one decision), before anything is + // read or written. The engine's own call is answered without it. + const moveCaller: any = _context?.executionContext; + if (!moveCaller?.isSystem) { + for (const item of declared.data.items) { + const typeRefusal = metaTypeWriteRefusal('POST', item.type, moveCaller); + if (!typeRefusal) continue; + return { + handled: true, + response: deps.error( + `Nothing was moved into package "${id}": moving ${item.type} '${item.name}' removes it from ` + + `its package-less address and saves it into the package. ${typeRefusal.message}`, + typeRefusal.status, + { code: typeRefusal.code }, + ), + }; + } + } const protocol = await resolveProtocol(deps, _context); if (!protocol || typeof protocol.moveIntoPackage !== 'function') { return catalogNotImplemented(deps, _context, 'packages_move_in_unsupported'); } + // [ADR-0161 K4, guard two] A knowledge source is saved again under + // the package with the caller as its author, so the author is + // admitted as the `/meta` save admits one: may they search what it + // indexes (`authoredKnowledgeSourceRefusal`, read off the stored body). + for (const item of declared.data.items) { + if (canonicalMetaUrlType(item.type) !== KNOWLEDGE_SOURCE_PACKAGE_TYPE || moveCaller?.isSystem || typeof protocol.getMetaItem !== 'function') continue; + let stored: unknown; + try { + stored = await protocol.getMetaItem({ type: item.type, name: item.name, ...(item.member ? { member: item.member } : {}) }); + } catch (e: any) { + // No such item: the protocol answers it `NOT_LOOSE`, and + // there is no body to admit. Any other failure refuses the + // move, as the duplicate door refuses an unreadable source. + if (e?.status === 404) continue; + return { + handled: true, + response: deps.error( + `Nothing was moved into package "${id}": knowledge_source '${item.name}' could not be read ` + + `(${clientFacingFailureText(e, 'the read failed')}), and a knowledge source is admitted for ` + + 'the caller before it moves. Try again.', + 503, + ), + }; + } + const body = (stored as { item?: unknown } | undefined)?.item ?? stored; + const refused = await authoredKnowledgeSourceRefusal({ + type: item.type, + item: body, + executionContext: moveCaller, + resolveKnowledgeService: () => + deps.resolveServiceOrLoud(_context, KNOWLEDGE_SOURCE_ADMISSION_SERVICE, _context.environmentId), + }); + if (refused) { + return { + handled: true, + response: deps.error( + `Nothing was moved into package "${id}": knowledge_source '${item.name}' — ${refused.message}`, + refused.status, + { code: refused.code }, + ), + }; + } + } try { const actor = resolvePackageWriteActor(_context); const result = await protocol.moveIntoPackage({ @@ -4118,8 +4184,8 @@ export async function handlePackagesRequest(deps: DomainHandlerDeps, path: strin ...(declared.data.dryRun ? { dryRun: true } : {}), ...(actor !== undefined ? { actor } : {}), }) as { outcome?: string; refused?: ReadonlyArray<{ type: string; name: string; code: string; error: string }> }; - // A refused move wrote nothing, and answers as the save door - // answers the same refusal: 422 with the first item's own code + // A refused move left every item loose (what had moved was + // moved back), and answers as the save door answers the same refusal: 422 with the first item's own code // in `error.code`. `error.details` is the whole move answer // (`MoveIntoPackageResponseSchema`, `outcome: 'refused'`), so a // caller reads every item's refusal, not only the first. diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 24297b1af75..b79b800457c 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -594,7 +594,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'POST /packages/:id/move-in', domain: '/packages', disposition: 'sdk', client: 'packages.moveIn', requestSchema: 'MoveIntoPackageRequestSchema', responseSchema: 'MoveIntoPackageResponseSchema', - note: 'Enveloped — the named schema is the `data`. A new route whose declaration is its contract: the body is parsed with `MoveIntoPackageRequestSchema` (strict; a body it refuses answers 400 VALIDATION_ERROR naming the member, nothing moved), the query set is closed and empty. Whole or nothing: every item goes through the delete door (storage kept) and the save door into the target inside one transaction, so a refusal writes nothing and answers 422 with the first item\'s own save-door code in `error.code` and the whole answer (`outcome: refused`, every item\'s refusal) in `error.details`; `dryRun` answers the same judgement with `outcome: would_move`. Gates as the package write doors: manage-metadata, the wall, the knowledge-source gate, a read-only package refused 422 before the protocol. Pinned in `qa/dogfood/test/package-move-in.dogfood.test.ts`, which drives THIS route and parses the payload through the response schema' }, + note: 'Enveloped — the named schema is the `data`. A new route whose declaration is its contract: the body is parsed with `MoveIntoPackageRequestSchema` (strict; a body it refuses answers 400 VALIDATION_ERROR naming the member, nothing moved), the query set is closed and empty. Whole or nothing: every item goes through the delete door (storage kept, the version the judgement read named) and the save door into the target; items other than objects run inside one transaction, objects one by one just before it, outside it, because an object\'s save syncs its storage. A refusal moves back what had moved (the registry and the mutation signal replayed at both addresses) and answers 422 with the first item\'s own save-door code in `error.code` and the whole answer (`outcome: refused`, every item\'s refusal) in `error.details`; a failure that is not a refusal, or an undo that does not complete, answers a 500 fault instead. `dryRun` answers the judgement made before any door runs, calling no door, with `outcome: would_move`. Gates as the package write doors: manage-metadata, the wall, the knowledge-source gate on the target, a read-only package refused 422 before the protocol; and each selected item\'s type is judged as a write of that type (403 for `datasource` without manage-platform-settings, `knowledge_source` without manage-knowledge-sources, and the stored knowledge source\'s own admission). Pinned in `qa/dogfood/test/package-move-in.dogfood.test.ts`, which drives THIS route and parses the payload through the response schema' }, { route: 'POST /packages/:id/duplicate', domain: '/packages', disposition: 'sdk', client: 'packages.duplicate', responseSchema: 'DuplicatePackageResponseSchema', note: 'Enveloped — the named schema is the `data`: `duplicatePackage`\'s declared return, transcribed describe-only. ⚠ `data.success` is the operation\'s verdict; the envelope `success` is transport-level and true even for a partial/empty duplicate (a console that read the envelope `success` reported a partial or empty duplicate as done). The SOURCE must be a writable base: a code-loaded or platform/marketplace source is refused 422 `DUPLICATE_SOURCE_NOT_A_BASE` (`requireDuplicableSource`, `domains/packages.ts`), BEFORE the protocol call and therefore before the target package record is minted — `duplicatePackage` installs that record ahead of its copy loop, so refusing any later still left a real, listed, empty shell package behind. ADR-0070 D4 is declared-and-not-built and its object is a BASE, so cloning a code package\'s items would EXTEND D4 rather than implement it; the unbuilt case refuses loudly instead of answering 200 with `copiedCount: 0`, which no caller could tell from a base that really is empty. An empty WRITABLE base still answers 200 / `copiedCount: 0` — that read happened and found nothing. Pinned in `domains/packages-readonly-gate.test.ts`. Conformance: spec `api/package-lifecycle.test.ts`' }, diff --git a/packages/spec/src/api/package-lifecycle.zod.ts b/packages/spec/src/api/package-lifecycle.zod.ts index ee7a95ec169..6f0df3b5791 100644 --- a/packages/spec/src/api/package-lifecycle.zod.ts +++ b/packages/spec/src/api/package-lifecycle.zod.ts @@ -399,8 +399,13 @@ export const MoveIntoPackageItemSchema = lazySchema(() => z.object({ * Every item goes through the save door into the target, so it is refused * with the save door's own code, and the selection is judged as a set first: * a moved item that names a loose item left behind is refused (ADR-0150 - * D3 (a)). Any refusal refuses the whole call and nothing is written. - * `dryRun: true` answers the same judgement and writes nothing. + * D3 (a)). Any refusal refuses the whole call: what had moved is moved back + * and every item stays loose, as before. If moving an item back fails, the + * call answers a fault naming the items that did not go back, never + * `refused`. + * `dryRun: true` answers the judgement made before any door runs (loose, + * target, the object judges, the set) and calls no door, so a save-door judge + * that runs only on the real move can still refuse it. */ export const MoveIntoPackageRequestSchema = lazySchema(() => z.object({ items: z.array(MoveIntoPackageItemSchema).min(1).describe( @@ -409,7 +414,9 @@ export const MoveIntoPackageRequestSchema = lazySchema(() => z.object({ + 'are not loose and are refused. Listed once each.', ), dryRun: z.boolean().optional().describe( - 'Judge the move and answer what it would do, writing nothing. Omitted or false, the move is made.', + 'Answer what the move would do from the judgement made before any door runs (loose, target, the object ' + + 'judges, the set), calling no door and writing nothing. A save-door judge runs only on the real move, so ' + + 'it can still refuse an item a dry run passed. Omitted or false, the move is made.', ), }).strict().describe( 'Body of `POST /packages/:id/move-in`: the selection of loose items to move into the package the path names.', @@ -425,7 +432,7 @@ export const MoveIntoPackageMovedItemSchema = lazySchema(() => z.object({ ), environmentAddress: z.string().optional().describe( 'The environment-qualified address the item answered at before the move (`_env/NAME`), present for a type ' - + 'addressed by package (ADR-0150 D5). After the move it no longer resolves: the item answers at ' + + 'addressed by package (ADR-0150 D5) when the target package declares a namespace. After the move it no longer resolves: the item answers at ' + '`qualifiedAddress` and, while it is the only holder of its name, at its bare name.', ), qualifiedAddress: z.string().optional().describe( @@ -467,8 +474,9 @@ export const MoveIntoPackageRefusedItemSchema = lazySchema(() => z.object({ */ export const MoveIntoPackageResponseSchema = lazySchema(() => z.object({ outcome: z.enum(['moved', 'would_move', 'refused']).describe( - '`moved`: every item moved. `would_move`: a dry run that would move every item; nothing was written. ' - + '`refused`: at least one item is refused, so nothing moved.', + '`moved`: every item moved. `would_move`: a dry run whose judgement passed every item; no door ran and ' + + 'nothing was written. `refused`: at least one item is refused, so what had moved was moved back and every ' + + 'item is loose, as before.', ), targetPackageId: z.string().describe('The package the items move into.'), moved: z.array(MoveIntoPackageMovedItemSchema).describe( @@ -480,7 +488,7 @@ export const MoveIntoPackageResponseSchema = lazySchema(() => z.object({ commitId: z.string().optional().describe('The package commit the move recorded (absent on a dry run or a refusal).'), }).strict().describe( 'Answer of the move door: what moved (or would move) and what each moved item\'s addresses become, or every ' - + 'refusal with nothing moved.', + + 'refusal with every item left loose.', )); /** From 7ab2d914d2f53faaaab87faadcc43c983db47207 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:35:31 +0000 Subject: [PATCH 13/14] test(metadata-protocol): the projector and signal censuses count the move-in door's two replays (#38150) Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- .../src/protocol.recovery-doors-emit-mutation.test.ts | 7 +++++-- .../src/protocol.recovery-doors-mutation-projector.test.ts | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts b/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts index cd19949ec8f..62f641d9f54 100644 --- a/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts +++ b/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts @@ -671,17 +671,20 @@ describe('[#14179] every announcing door goes through the choke point', () => { /** Every match of `pattern` in `protocol.ts` and every split module. */ const sitesOf = (pattern: RegExp) => [source, ...splitSources].flatMap((text) => text.match(pattern) ?? []); - it('has exactly seven `emitMetadataMutation` call sites — three original, three doors, four limbs', () => { + it('has exactly nine `emitMetadataMutation` call sites — three original, three doors, four limbs, two move-in replays', () => { // saveMetaItem · runPublishSideEffects · deleteMetaItem (repository) // + rollbackMetaItem // + revertCommit restore limb + revertCommit soft-remove limb // + deleteMetaItem (legacy raw-engine) + // + moveIntoPackage's replay of a stopped move, twice: the target's + // address as deleted, the package-less one as restored + // (`protocol-package-move-in.ts` `replayRestored`) [#38150] // A new door that reaches for the LOCAL-only fan-out instead would // leave this count untouched and lose the cluster half in silence, so // §5's second case counts that method's callers too. // [#29985] `host.` in a moved body is the same call (ruling E's rewrite set). const callSites = sitesOf(/\b(?:this|host)\.emitMetadataMutation\(/g); - expect(callSites).toHaveLength(7); + expect(callSites).toHaveLength(9); // Non-vacuity: the declaration is not one of them. expect(source.match(/private emitMetadataMutation\(/g) ?? []).toHaveLength(1); }); diff --git a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts index 9e7346896b1..791174c5503 100644 --- a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts +++ b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts @@ -508,14 +508,17 @@ describe('every projecting door goes through runMutationProjector', () => { /** Every match of `pattern` in `protocol.ts` and every split module. */ const sitesOf = (pattern: RegExp) => [source, ...splitSources].flatMap((text) => text.match(pattern) ?? []); - it('has exactly seven `this.runMutationProjector(` call sites — three original, four recovery-door sites', () => { + it('has exactly nine `this.runMutationProjector(` call sites — three original, four recovery-door sites, two move-in replays', () => { // saveMetaItem · runPublishSideEffects · deleteMetaItem (repository) // + rollbackMetaItem // + revertCommit restore limb + revertCommit soft-remove limb // + deleteMetaItem (legacy raw-engine) + // + moveIntoPackage's replay of a stopped move, twice: the target's + // address as deleted, the package-less one as restored + // (`protocol-package-move-in.ts` `replayRestored`) [#38150] // [#29985] `host.` in a moved body is the same call (ruling E's rewrite set). const callSites = sitesOf(/\b(?:this|host)\.runMutationProjector\(/g); - expect(callSites).toHaveLength(7); + expect(callSites).toHaveLength(9); // Non-vacuity: the declaration is not one of them. expect(source.match(/private async runMutationProjector\(/g) ?? []).toHaveLength(1); }); From 23ca5017e0fe81e2c756a7a839ee314916e6818a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:49:48 +0000 Subject: [PATCH 14/14] docs(permissions),test(metadata-protocol): the move-in door's system-caller reads are owned in the system-context register; the projector census pays the lint load at collection (#38150) The per-item type gate and the knowledge-source author admission on the move-in door are named by the rows that own their bypass (46 and 55), and the register is regenerated. The projector call-site test, edited here, imports @objectstack/lint at module top as its sibling emit test does. Claude-Session: https://claude.ai/code/session_01L9qibyHmxFV4bTFZ5BKnUz Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 6 +++--- .../src/protocol.recovery-doors-mutation-projector.test.ts | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 47686def9fe..4fb987ecf85 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -189,7 +189,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources` | +| 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save. Lose at the package move-in door: the same admission asked for the caller, for each selected knowledge source the move saves again under the package | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources`, `handlePackagesRequest` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -211,7 +211,7 @@ One of the largest consumers of the flag; | 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `handleActionsRequest`, `dispatchActionRequest`, `resumeActionRunRequest`, `handleAIRequest`, `handleAutomationRequest`, `handleMetadataRequest`, `handleSecurityRequest`, `handlePackagesRequest`, `handleAnalyticsRequest`, `handleI18nRequest`, `registerExternalDatasourceRoutes`, `refusePackageRequest` | | 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `handleMcpRequest` | | 54 | Package REST route capability gate bypassed | rest | Get: a marketplace publish over REST (`POST /packages/publish`, the one route the REST registrar mounts since #14503) without `manage_metadata`; the package read cohort (`studio.access` / `setup.access`) is enforced by the dispatcher `/packages` domain's own read gate, where the reads are served | `refusePackageRequest` | -| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability; and a write to a package that holds a knowledge source (the twelve doors that write an existing package) without `manage_knowledge_sources` beside it (ADR-0161 K4) | `requireManageMetadata`, `requireReadCapability`, `refuseKnowledgeSourcePackageWrite` | +| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability; and a write to a package that holds a knowledge source (the twelve doors that write an existing package) without `manage_knowledge_sources` beside it (ADR-0161 K4); and, on the move-in door, a selected `datasource` or `knowledge_source` moved without the capability its `/meta` write asks (`manage_platform_settings`, `manage_knowledge_sources`) | `requireManageMetadata`, `requireReadCapability`, `refuseKnowledgeSourcePackageWrite`, `handlePackagesRequest` | | 56 | Activation write / authoring refusals do not fire | runtime | Get: activation artifacts writable and authorable without the activation-authoring capability | `refuseUngrantedActivationWrite`, `refuseUngrantedActivationAuthoring` | | 55b | Walled environment-metadata refusal does not fire | metadata-core, rest, runtime | Get: under `isolated` / `group`, a write of the environment's metadata, of any type, at the `/meta` write doors (save, reset, publish, rollback) and `POST /meta/_migrate-stored` on both transports, at every `/packages` write door (create, the manifest `PATCH`, enable, disable, publish, `publish-drafts`, `discard-drafts`, `revert`, `rollback`, `commits/:commitId/revert`, `duplicate`, `adopt-orphans`, delete), at the `/automation` definition writes (create, update, delete, clone), at the permission-set clone door, at the import of a remote table as an object (the REST import route and the MCP `import_object` tool), at the open MCP server's draft save and discard (`save_metadata_draft`, `delete_metadata_draft`), and at the refresh of a federated datasource's cached catalog. Every other caller below the platform-operator rung is refused `403` there (ADR-0131 D3, D12 items 7–8, D11), because one organization's write would change what every organization resolves. The seeders, the package door and migrations write the environment's metadata this way. Under `single` the refusal is inert for every caller | `walledCatalogWriteVerdict`, `walledCatalogRefusal`, `refuseWalledCatalogPackageWrite`, `refuseWalledFlowDefinitionWrite`, `registerExternalDatasourceRoutes`, `federationService`, `openWriter` | | 57 | Automation run-state read, flow-authoring write, the paused-run caller gate (screen read and resume), the two operator run-lifecycle writes, and the elevated self-triggered start, the AI-service-account elevated start and the start-record check at every door that starts a flow by name all pass | runtime | Get: run state, flow writes, a paused run's screen and its resume with no grant and without being the run's starter — and cancelling or restoring a suspension without the platform-operator rung. The screen read and the resume ask one predicate, so this is one bypass for both. The lifecycle bypass is the in-process owner's door: plugin-approvals' revise-window recall (ADR-0044) cancels on behalf of a decision it already authorized and recorded. And starting a flow declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) through any door that starts a flow by name — the trigger route, an action of `type: 'flow'` (REST `/actions` and the MCP `run_action` bridge) and a declared endpoint of `type: 'flow'` — which every other caller, the guest principal included, is refused `403 PERMISSION_DENIED` (the maintainer's rulings, letters B and A) — and starting, through the same doors, a flow whose `requiredPermissions` the caller does not hold (ruling record 6377848497, letter A) — and starting, through the same doors, a flow declared `runAs: 'system'` as an AI service account (an agent acting for itself, with no `onBehalfOf`) where the action's `ai.exposed: true` opt-in is not in hand, which that account is refused `403 PERMISSION_DENIED` (ADR-0151 Non-goals, ruling record 6812617393, letter C; a trigger route and a declared endpoint carry no opt-in, so there it is always refused, and the refusal names the action door that admits it). And starting, through the same doors, a flow on a record key the caller's own scope does not deliver, which every other caller is refused with the action door's `404 RECORD_NOT_FOUND` before the run exists (and `400 VALIDATION_FAILED` for a key that is not one id, or for an elevated start that names no object). The three doors ask one check, so this is one bypass for all of them, and it is the in-process caller's, such as a job: inbound HTTP never carries the flag | `mayReadRunState`, `refuseUngrantedFlowWrite`, `isRunStarterOrRunStateReader`, `refuseUngrantedRunLifecycleWrite`, `flowStartRefusal`, `refuseUnreadableFlowStartRecords` | @@ -693,7 +693,7 @@ and CI refuses one that differs from what the tree produces. | `packages/runtime/src/domains/mcp.ts#membershipReachRefusal` | 1 | 62b | | `packages/runtime/src/domains/mcp.ts#resumeActionRunRequest` | 1 | 52 | | `packages/runtime/src/domains/meta.ts#handleMetadataRequest` | 5 | 50, 52 | -| `packages/runtime/src/domains/packages.ts#handlePackagesRequest` | 1 | 52 | +| `packages/runtime/src/domains/packages.ts#handlePackagesRequest` | 3 | 46, 52, 55 | | `packages/runtime/src/domains/packages.ts#refuseDuplicatedKnowledgeSources` | 1 | 46 | | `packages/runtime/src/domains/packages.ts#refuseKnowledgeSourcePackageWrite` | 1 | 55 | | `packages/runtime/src/domains/packages.ts#refuseWalledCatalogPackageWrite` | 1 | 55b | diff --git a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts index 791174c5503..be50cc93037 100644 --- a/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts +++ b/packages/metadata-protocol/src/protocol.recovery-doors-mutation-projector.test.ts @@ -64,6 +64,9 @@ */ import { describe, expect, it } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias): the +// save and delete doors reach it dynamically. +import '@objectstack/lint'; import { readdirSync, readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import {