diff --git a/.changeset/34655-flow-default-active.md b/.changeset/34655-flow-default-active.md new file mode 100644 index 00000000000..331b0593b36 --- /dev/null +++ b/.changeset/34655-flow-default-active.md @@ -0,0 +1,28 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-automation': minor +'@objectstack/runtime': patch +'@objectstack/metadata-protocol': patch +--- + +feat(spec, service-automation): a packaged flow can ship switched off for an administrator to turn on (`defaultActive: false`) + +Clause-②: yes (widening) — `FlowSchema` gains the optional `defaultActive` boolean. A flow that declares it was refused before as an unknown key; a packaged flow that declares it now registers. A flow authored in the environment that declares it is still refused, now with a sentence naming its `status` as its switch. Nothing that registered before is refused. +Metadata-protocol: added +Skills-docs: updated here — skills/objectstack-automation/SKILL.md (one paragraph under "A flow an installed package ships"), evals/flows-triggers-approvals.json (eval id 24) + +A package can now ship a flow switched off: declare `defaultActive: false` on the flow, beside `status: 'active'`. On an installation where no administrator has switched the flow, it is not armed and does not run, and `GET /api/v1/automation/_status` reports it `enabled: false`. An administrator turns it on with the packaged-flow switch (`POST /api/v1/automation/:name/toggle`, or the Enabled switch on a read-only package's flow in Studio), which writes an activation-ledger row (`sys_metadata_activation`). That row wins over the declared default in either state: a flow switched on stays on across a restart, an upgrade and a reinstall, and one switched off stays off. With no row the flow follows the package's own declaration for the version installed today, so an upgrade that changes it moves only installations nobody switched; a declared `.custom` override armed in the package's place does not change the default, whatever it declares. Absent or `true`, the flow ships on, as every packaged flow did before. A package that declares the key needs a platform at or above this release: an older one refuses the flow as an unknown key. + +`status` stays the author's switch: `obsolete` and `invalid` disarm the flow everywhere, and the packaged-flow switch does not override them. + +Only a flow a package ships has the packaged-flow switch, so: + +- registering a flow authored in the environment that declares `defaultActive` is refused, with a sentence saying its switch is its `status` (`'obsolete'` to keep it off, `'active'` to arm it). The automation write doors (`POST /api/v1/automation`, `PUT /api/v1/automation/:name`) answer `VALIDATION_FAILED`, 400, and store nothing; a dry run refuses the draft; the metadata door (`PUT /api/v1/meta/flow/:name`), which parses without registering, stores the row, the engine refuses to arm it, and `os migrate meta --stored` lists it at the key; +- `POST /api/v1/automation/:name/clone` drops `defaultActive` from the copy, which is written switched off by its own `status` as before; +- an unmanaged install copies `defaultActive: false` as `status: 'obsolete'` (unless the status already disarms the flow) and drops the key, so the copy arrives switched off. + +A name two packages ship is a package's flow too: each holder's body registers with the key, on every re-sync and upgrade, and the refusal above is only for a name no package ships. + +For hosts that compose the engine themselves, `AutomationEngine.setPackagedFlowDefaultSource(source)` and its `PackagedFlowDefaultSource` type are new public API. The automation plugin attaches the reader (it asks the metadata protocol for the package's own body); it is how the engine reads the package's default while a declared `.custom` override is armed in the package's place, and it is asked once per registration, not on every enablement read. `AutomationEngine.refreshPackagedFlowDefaults()` is new public API too: it asks the reader again for every armed body that is not the package's own, and re-arms or disarms each flow whose answer moved; the automation plugin calls it at every `metadata:reloaded` re-sync, so a hot upgrade that changes the declared default reaches a flow whose override body was not re-registered. A host composing the engine itself calls it after the set of installed packages changes. An engine composed without a reader reads the default only off an armed package body, so while an override is armed a flow its package ships off runs (fail-open): such an engine cannot see the package's body, and treating an unknown default as on keeps the behaviour every packaged flow had before this release instead of switching off a flow no package was seen to declare off. + +ADR-0126 §4 carries an amendment note: "absence of a row means the packaged default" now reads the default a packaged flow declares; the ledger's shape is unchanged. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index a75820fc6bd..596e2265f48 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -31,7 +31,12 @@ ledger (ADR-0126 §7.2). A flow authored in the deployment is not switched there. Its switch is its own `status`: `'obsolete'` disarms it and `'active'` arms it, published with the complete definition through `PUT /api/v1/automation/:name`. The toggle door refuses such a flow with -409 `RESOURCE_CONFLICT`, names that switch, and changes nothing. +409 `RESOURCE_CONFLICT`, names that switch, and changes nothing. It refuses +the same way a switch ON of a packaged flow whose own `status` disables it +(`'obsolete'` / `'invalid'`): the ledger row alone would leave the flow off +while the caller read it as on, so it answers 409 `RESOURCE_CONFLICT`, +names publishing the definition `'active'`, and writes nothing. A switch +OFF of such a flow is accepted and records the choice. **Endpoints** ``` @@ -174,6 +179,7 @@ const result = AutomationApiErrorCode.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | @@ -303,6 +309,7 @@ const result = AutomationApiErrorCode.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | @@ -858,6 +865,7 @@ const result = AutomationApiErrorCode.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | @@ -1170,6 +1178,7 @@ const result = AutomationApiErrorCode.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | @@ -1235,6 +1244,7 @@ const result = AutomationApiErrorCode.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | diff --git a/content/docs/references/automation/flow.mdx b/content/docs/references/automation/flow.mdx index bf34e28dbe0..3678b2f81e3 100644 --- a/content/docs/references/automation/flow.mdx +++ b/content/docs/references/automation/flow.mdx @@ -35,6 +35,7 @@ const result = FlowSchema.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | @@ -260,6 +261,7 @@ const result = FlowSchema.parse(data); | **errorMessage** | `string` | optional | Text for a terminal failure, carried on AutomationResult for every terminal run (not only screen flows); the screen-flow UI shows it as a toast instead of the raw error. A `{{ }}` template over the run's variables, rendered over the variables at the failure point. | | **version** | `integer` | optional (default: `1`) | Version number | | **status** | `Enum<'draft' \| 'active' \| 'obsolete' \| 'invalid'>` | optional (default: `"draft"`) | Deployment status | +| **defaultActive** | `boolean` | optional | Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator's choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author's switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key. | | **type** | `Enum<'autolaunched' \| 'record_change' \| 'schedule' \| 'screen' \| 'api'>` | ✅ | Flow type | | **variables** | `{ name: string; type: string; isInput?: boolean; isOutput?: boolean; … }[]` | optional | Flow variables | | **nodes** | `{ id: string; type: string; label: string; config?: Record; … }[]` | ✅ | Flow nodes | diff --git a/docs/adr/0126-packaged-metadata-customization-model.md b/docs/adr/0126-packaged-metadata-customization-model.md index ca376339b58..519b8fc4782 100644 --- a/docs/adr/0126-packaged-metadata-customization-model.md +++ b/docs/adr/0126-packaged-metadata-customization-model.md @@ -1,6 +1,6 @@ # ADR-0126: The platform customization model for packaged metadata — three regimes, one activation ledger -**Status**: **Amended** (2026-09-04) by [ADR-0131](./0131-total-organization-ownership-no-null-organization-id.md) D6 — maintainer, verbatim: 「所以 ADR-0126 不能简单的关掉」「hotcrm 是标准的软件包,客户安装之后能根据业务需求实现具体的定制」「同意」. The three regimes stand at **environment scope only**: O's per-organization reading is retired (ADR-0005 amended), C's activation ledger stays as tenant-less deployment state (D3's reserved `organization_id`, written NULL, is withdrawn — ADR-0131 D1 forbids a nullable tenant column), E stands; the unreleased implementation (#12185, #12190, #12296, #12348, #12419, framework half of #12491) ships in 17.3 with that column dropped. The install mode ADR-0131 D6 adds (managed = sealed definitions + these regimes; template = copied once, fully editable, refused on shared-DB multi-tenant) is the frame the regimes now sit in. · **Amended** (2026-10-14, ADR-0131 D2/D3/D13): the permission projection §4 and §8 name is retired by #15204 stage 8 (`66949b7729`, 2026-10-13), which unwired the ADR-0094 projector and retired the `sys_permission_set` row object; see the notes in §4 and §8. · **Superseded in part by [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md)** (2026-10-31) — D1 (§2 Regime C's "never an overlay read path", for a declared override), D4 wall 1 (§6 item 1's corollary against name-redirection, for the declared case only) and §7.1's "⛔ No same-name clone in a second package" (for a declared override from the paired `.custom` only): customization of a packaged item is a declared override in the paired `.custom` package, served at the base's name once real flow version pinning exists (ADR-0146 D2, D9); the lock, the ledger switch and the walled operator gate stand. §7.4's Setup surface moves to the item in Studio; of §9's first bullet the badge, the customization list and revert are chartered, diff-vs-base and the skip-report stay deferred. Original status line follows. +**Status**: **Amended** (2026-09-04) by [ADR-0131](./0131-total-organization-ownership-no-null-organization-id.md) D6 — maintainer, verbatim: 「所以 ADR-0126 不能简单的关掉」「hotcrm 是标准的软件包,客户安装之后能根据业务需求实现具体的定制」「同意」. The three regimes stand at **environment scope only**: O's per-organization reading is retired (ADR-0005 amended), C's activation ledger stays as tenant-less deployment state (D3's reserved `organization_id`, written NULL, is withdrawn — ADR-0131 D1 forbids a nullable tenant column), E stands; the unreleased implementation (#12185, #12190, #12296, #12348, #12419, framework half of #12491) ships in 17.3 with that column dropped. The install mode ADR-0131 D6 adds (managed = sealed definitions + these regimes; template = copied once, fully editable, refused on shared-DB multi-tenant) is the frame the regimes now sit in. · **Amended** (2026-10-14, ADR-0131 D2/D3/D13): the permission projection §4 and §8 name is retired by #15204 stage 8 (`66949b7729`, 2026-10-13), which unwired the ADR-0094 projector and retired the `sys_permission_set` row object; see the notes in §4 and §8. · **Superseded in part by [ADR-0146](./0146-studio-designs-setup-administers-one-editor-per-item-paired-customize-package.md)** (2026-10-31) — D1 (§2 Regime C's "never an overlay read path", for a declared override), D4 wall 1 (§6 item 1's corollary against name-redirection, for the declared case only) and §7.1's "⛔ No same-name clone in a second package" (for a declared override from the paired `.custom` only): customization of a packaged item is a declared override in the paired `.custom` package, served at the base's name once real flow version pinning exists (ADR-0146 D2, D9); the lock, the ledger switch and the walled operator gate stand. §7.4's Setup surface moves to the item in Studio; of §9's first bullet the badge, the customization list and revert are chartered, diff-vs-base and the skip-report stay deferred. Original status line follows. · **Amended** (2026-11-17, [#34655](https://github.com/objectstack-ai/objectstack/issues/34655)): a packaged flow may declare §4's packaged default off (`defaultActive: false`); see the note under §4. **Original status**: Proposed (2026-08-25) — awaiting the maintainer's hand-merge, which is itself the acceptance act for a governed surface (Prime Directive #14) **and the ruling that settles the tentative flow-instance directions in §7** (chartered on @@ -216,6 +216,27 @@ Uniqueness: one row per `(metadata_type, name, organization_id NULL-collapsed)`; means the packaged default — **active**. The ledger is written by the enable/disable actions and read at each runtime's own consult point; an empty ledger changes nothing anywhere. +> **Amendment note (2026-11-17, [#34655](https://github.com/objectstack-ai/objectstack/issues/34655)) — a packaged flow may ship switched off.** +> The packaged default above may be declared by the item, for `flow`: `defaultActive: false` on a flow a package ships +> (`packages/spec/src/automation/flow.zod.ts#FlowSchema`) makes its packaged default **off**. Absence of a row still means +> the packaged default, so on an installation where no administrator has switched the flow it is not armed and does not run. +> A row is still the installation's choice and wins over the declared default in either state: a flow an administrator +> switched on stays on across a restart, an upgrade and a reinstall, and one switched off stays off. An "on" row counts +> only when it names the package that holds the flow now: a legacy row naming no package, or one naming a package that +> no longer holds the name, does not switch a flow shipped off on (an "off" row of either kind still switches it off). +> With no row the flow follows the declaration of the package's own body for the version installed now, so an upgrade +> that changes it moves only installations nobody switched. The default is the package's: a declared `.custom` override +> (ADR-0146 D2) armed in the base's place does not change it in either direction, whatever it declares, and is switched +> by the same row (`packages/services/service-automation/src/engine.ts#packagedFlowDefault`). +> The default is read at the consult point and never written as a row at install, so a row keeps meaning a recorded choice +> (`packages/services/service-automation/src/flow-activation-projection.ts#FlowActivationProjection`). "An empty ledger +> changes nothing anywhere" holds for every item that declares no default, and the ledger's shape does not move (§9's line +> on `packages/spec` is about the ledger itself; this key is on the flow). Only a flow a package ships has the switch, so +> the engine refuses the key on a flow authored in the environment, whose switch is its `status` +> (`packages/services/service-automation/src/engine.ts#refuseUnpackagedDefaultActive`); a clone drops it +> (`packages/runtime/src/flow-clone.ts#FLOW_CLONE_DROPPED_KEYS`), and an unmanaged install copies `false` as +> `status: 'obsolete'` (`packages/metadata-protocol/src/package-unmanaged-install.ts#copyUnmanagedFlowSwitch`). + **What the ledger is NOT:** - ⛔ **Not a definition store.** `sys_metadata` remains the **sole definition ledger** — the diff --git a/packages/metadata-protocol/src/package-unmanaged-flow-switch-34655.test.ts b/packages/metadata-protocol/src/package-unmanaged-flow-switch-34655.test.ts new file mode 100644 index 00000000000..913f98ae421 --- /dev/null +++ b/packages/metadata-protocol/src/package-unmanaged-flow-switch-34655.test.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34655, ADR-0126 §4 amendment] An unmanaged install copies a flow's + * `defaultActive` as the switch the copy has. The copy is the environment's + * own flow, switched by its `status`, and the automation engine refuses the + * key on such a flow, so a package that ships a flow switched off arrives + * switched off (`status: 'obsolete'`) and without the key. + */ + +// Pays the lint root's first load at collection, never inside a clocked case. +import './lint-root-preload.testkit.js'; +import { describe, expect, it } from 'vitest'; +import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; +import { copyUnmanagedFlowSwitch, planUnmanagedImport } from './package-unmanaged-install.js'; +import { overlaySchemaDeclaredKey } from './protocol.js'; + +function flow(name: string, extra: Record = {}): Record { + return { + name, + label: name, + type: 'record_change', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'crm_quote', triggerType: 'record-after-update' } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + ...extra, + }; +} + +function crmBody(flows: Record[]): Record { + return { + id: 'com.example.crm', + namespace: 'crm', + version: '4.0.0', + type: 'app', + name: 'CRM', + scope: 'cloud', + objects: [{ + name: 'crm_quote', + label: 'Quote', + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' } }, + }], + flows, + translations: [], + i18n: { defaultLocale: 'en' }, + }; +} + +const plan = (body: Record) => + planUnmanagedImport(body, { + isRuntimeCreatable: (type: string) => + DEFAULT_METADATA_TYPE_REGISTRY.find((e) => e.type === type)?.allowRuntimeCreate ?? true, + loadOrderOf: (type: string) => + DEFAULT_METADATA_TYPE_REGISTRY.find((e) => e.type === type)?.loadOrder ?? Number.MAX_SAFE_INTEGER, + protectionDeclarationOf: (type: string) => overlaySchemaDeclaredKey(type, 'protection'), + }); + +function flowItem(p: ReturnType, name: string) { + return p.items.find((item) => item.type === 'flow' && item.name === name)?.body; +} + +describe('#34655 — an unmanaged install copies `defaultActive` as the copy\'s status', () => { + it('a flow shipped switched off is copied switched off, as `status: \'obsolete\'`, without the key', () => { + const p = plan(crmBody([flow('draft_contract', { defaultActive: false })])); + const body = flowItem(p, 'draft_contract'); + expect(body).toBeDefined(); + expect(body).not.toHaveProperty('defaultActive'); + expect(body?.status).toBe('obsolete'); + }); + + it('a flow shipped on keeps its declared status, without the key', () => { + const p = plan(crmBody([flow('on_flow', { defaultActive: true })])); + const body = flowItem(p, 'on_flow'); + expect(body).not.toHaveProperty('defaultActive'); + expect(body?.status).toBe('active'); + }); + + it('a status that already disarms the flow is kept', () => { + expect(copyUnmanagedFlowSwitch('flow', flow('f', { defaultActive: false, status: 'invalid' }))).toEqual( + flow('f', { status: 'invalid' }), + ); + }); + + it('a flow with no status declared and shipped off is copied `obsolete`', () => { + const { status: _none, ...noStatus } = flow('f'); + expect(copyUnmanagedFlowSwitch('flow', { ...noStatus, defaultActive: false })).toEqual({ ...noStatus, status: 'obsolete' }); + }); + + it('CONTROL: a flow without the key, another type, and a value that is not a boolean are handed on as the same body', () => { + const plain = flow('plain'); + expect(copyUnmanagedFlowSwitch('flow', plain)).toBe(plain); + const other = { name: 'x', defaultActive: false }; + expect(copyUnmanagedFlowSwitch('view', other)).toBe(other); + const malformed = flow('bad', { defaultActive: 'no' }); + expect(copyUnmanagedFlowSwitch('flow', malformed)).toBe(malformed); + + const p = plan(crmBody([plain])); + expect(flowItem(p, 'plain')).toEqual(plain); + }); +}); diff --git a/packages/metadata-protocol/src/package-unmanaged-install.ts b/packages/metadata-protocol/src/package-unmanaged-install.ts index c62a93d37e9..0c105612c10 100644 --- a/packages/metadata-protocol/src/package-unmanaged-install.ts +++ b/packages/metadata-protocol/src/package-unmanaged-install.ts @@ -146,7 +146,11 @@ export interface UnmanagedImportItem { name: string; /** The manifest key it came from. */ key: string; - /** The body as the package declared it, less its protection lock in either spelling ({@link stripUnmanagedImportLock}). */ + /** + * The body as the package declared it, less its protection lock in either + * spelling ({@link stripUnmanagedImportLock}), and a flow's + * `defaultActive` copied as its `status` ({@link copyUnmanagedFlowSwitch}). + */ body: Record; /** The view names a container expands into (empty for every other item). */ expands: readonly string[]; @@ -285,6 +289,30 @@ export function stripUnmanagedImportLock( }; } +/** + * [#34655, ADR-0126 §4] A flow's `defaultActive`, copied as the switch the + * copy has. The key is the default of the packaged-flow switch (the + * activation ledger), and a copy is the environment's own flow, switched by + * its `status`: the engine refuses the key on such a flow. So the copy keeps + * what the package shipped, in the copy's own switch: + * - `defaultActive: false` → `status: 'obsolete'` (switched off, as Studio's + * switch writes it), unless the status already disarms the flow + * (`obsolete` / `invalid`), which is kept; + * - `defaultActive: true` → dropped, the status as declared. + * + * A value that is not a boolean is handed on untouched, so the save door + * judges the body as the package declared it and refuses it. Returns the SAME + * body when there is nothing to copy. + */ +export function copyUnmanagedFlowSwitch(type: string, body: Record): Record { + if (type !== 'flow' || typeof body.defaultActive !== 'boolean') return body; + const { defaultActive, ...rest } = body; + if (defaultActive === false && rest.status !== 'obsolete' && rest.status !== 'invalid') { + rest.status = 'obsolete'; + } + return rest; +} + /** One reason a body cannot be imported, naming the key that carries it. */ export interface UnmanagedImportFinding { key: string; @@ -563,7 +591,8 @@ export function planUnmanagedImport( item.type, item.name, item.body, options.protectionDeclarationOf(item.type), ); if (stripped) strippedLocks.push(stripped); - return body === item.body ? item : { ...item, body }; + const copied = copyUnmanagedFlowSwitch(item.type, body); + return copied === item.body ? item : { ...item, body: copied }; }); // [#30794] ⭐ THE RENAME RUNS AFTER THE VIEW CONTAINERS ARE EXPANDED, through diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index c8f606b6802..f6c0f2ae79a 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -388,8 +388,10 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // prompt projection for a skill written for the in-product agents only. // [#34374] `hook` 23 → 24: the declared texts, `texts`, a hook's // sentences written into records in the organization's language. + // [#34655] `flow` 23 → 24: `defaultActive`, the default of the + // packaged-flow switch (a package ships the flow switched off). const CARD_PROPERTY_COUNTS: Record = { - agent: 24, app: 24, dashboard: 21, dataset: 17, field: 83, flow: 23, + agent: 24, app: 24, dashboard: 21, dataset: 17, field: 83, flow: 24, hook: 24, object: 50, page: 28, position: 14, report: 24, skill: 17, tool: 14, }; diff --git a/packages/runtime/src/flow-clone-default-active-34655.test.ts b/packages/runtime/src/flow-clone-default-active-34655.test.ts new file mode 100644 index 00000000000..615f749460e --- /dev/null +++ b/packages/runtime/src/flow-clone-default-active-34655.test.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34655, ADR-0126 §4 amendment] A clone drops `defaultActive`: the key is + * the default of the switch only a flow a package ships has, the copy is a + * writable package's flow switched by its own `status`, and the engine + * refuses the key on such a flow. + */ + +import { describe, expect, it } from 'vitest'; +import { cloneFlowDefinition, FLOW_CLONE_DROPPED_KEYS, FLOW_CLONE_STATUS } from './flow-clone.js'; + +const source = { + name: 'draft_contract', + label: 'Draft contract', + type: 'record_change', + status: 'active', + defaultActive: false, + nodes: [{ id: 'start', type: 'start', label: 'Start', config: {} }], + edges: [], +}; + +describe('#34655 — a clone of a packaged flow shipped off', () => { + it('drops `defaultActive` and is written switched off by its own status', () => { + const clone = cloneFlowDefinition(source, { name: 'draft_contract_copy', label: 'Copy' }); + expect(clone).not.toHaveProperty('defaultActive'); + expect(clone.status).toBe(FLOW_CLONE_STATUS); + expect(FLOW_CLONE_DROPPED_KEYS).toContain('defaultActive'); + }); + + it('CONTROL: every other facet is copied', () => { + const clone = cloneFlowDefinition(source, { name: 'draft_contract_copy', label: 'Copy' }); + expect(clone.nodes).toEqual(source.nodes); + expect(clone.type).toBe(source.type); + expect(source.defaultActive).toBe(false); + }); +}); diff --git a/packages/runtime/src/flow-clone.ts b/packages/runtime/src/flow-clone.ts index b8a2fbdd1f7..6177ab627b9 100644 --- a/packages/runtime/src/flow-clone.ts +++ b/packages/runtime/src/flow-clone.ts @@ -170,12 +170,20 @@ export const FLOW_CLONE_MUTATED_FIELDS = ['name', 'label', 'status'] as const; * base does not ship, and the save gate refuses it (`403 NOT_OVERRIDABLE`). * New similar writes the pair's own item: it copies what the source serves * (the override's definition) and overrides nothing. + * + * [#34655, ADR-0126 §4] `defaultActive` is named for `protection`'s reason: + * it is the default of the switch only a flow a PACKAGE ships has (the + * activation ledger), and the engine refuses it on any other flow. The copy + * is a writable package's flow, switched by its own `status`, which the clone + * already sets ({@link FLOW_CLONE_STATUS}), so dropping it moves nothing: a + * copy that kept it would be refused over a key the admin never sent. */ export const FLOW_CLONE_DROPPED_KEYS: readonly string[] = Object.freeze([ ...METADATA_READ_DECORATIONS, ...Object.keys(MetadataProtectionFields), 'protection', ...Object.keys(OverrideDeclarationFields), + 'defaultActive', ]); /** diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 23bef28bcbb..8e95758edef 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2768,6 +2768,14 @@ export interface FlowContender { */ export type PackagedFlowSource = (name: string, packageId?: string) => string | undefined; +/** + * [#34655, ADR-0126 §4] The `defaultActive` package `packageId`'s own flow + * `name` declares, as the loader's set holds it, or `undefined` when it + * declares none (or the set holds no such body). See + * {@link AutomationEngine.setPackagedFlowDefaultSource}. + */ +export type PackagedFlowDefaultSource = (name: string, packageId: string) => boolean | undefined; + /** * [ADR-0150 D3] A reader over the ONE package-scoped resolver: which item the * bare flow name `name` means for a caller of package `callerPackageId` @@ -3109,6 +3117,13 @@ export class AutomationEngine implements IAutomationService { { flow: name, holders }, ); }, + // [#34655, ADR-0126 §4] With no row deciding, the package's default: + // a flow shipped `defaultActive: false` is off until an administrator + // switches it on. Read off the package's own body for the version + // installed now, so an upgrade that changes the default moves an + // installation no one switched, and a `.custom` override does not + // move it ({@link packagedFlowDefault}). + shipsOff: (key) => this.packagedFlowDefault(key) === false, }); /** * The durable ledger behind {@link flowLedgerDisabled}. `null` until a host @@ -3124,6 +3139,22 @@ export class AutomationEngine implements IAutomationService { * no flow a managed package loaded. */ private packagedFlowSource?: PackagedFlowSource; + /** [#34655] The reader over the loader's bodies' defaults — see {@link setPackagedFlowDefaultSource}. */ + private packagedFlowDefaultSource?: PackagedFlowDefaultSource; + /** + * [#34655, L2 N9] What {@link packagedFlowDefaultSource} answered for an + * armed body, so {@link isFlowEnabled} never reads the loader's set: + * keyed by the body {@link registerFlow} armed, which is a new object on + * every registration, so a registration asks again. A re-sync does not + * always re-register (L2 S4: the `metadata:reloaded` re-sync keeps a body + * the metadata-mutation sync armed from the same stored row, and keeps + * the body it had when a re-registration throws), and the answer depends + * on the loader's set, not on the body. So the map is replaced whenever + * either reader is attached and at every re-sync + * ({@link refreshPackagedFlowDefaults}), which also re-judges the flows + * whose answer moved. + */ + private packagedFlowDefaults = new WeakMap(); /** * [ADR-0150 D3] The reader that answers which item a bare flow name means * for a caller — see {@link setFlowNameResolver}. `undefined` until a host @@ -6124,6 +6155,21 @@ export class AutomationEngine implements IAutomationService { */ setPackagedFlowSource(source: PackagedFlowSource | undefined): void { this.packagedFlowSource = source; + this.packagedFlowDefaults = new WeakMap(); + } + + /** + * [#34655, ADR-0126 §4] Attach the reader over the bodies THE LOADER'S + * SET holds: the `defaultActive` package `packageId`'s own flow `name` + * declares. Hosts call this at start(), beside {@link setPackagedFlowSource}; + * the automation plugin asks the metadata protocol at question time + * (`packagedFlowDefaultReader`). It is how the package's default is read + * while a declared `.custom` override is armed in the base's place + * ({@link packagedFlowDefault}). + */ + setPackagedFlowDefaultSource(source: PackagedFlowDefaultSource | undefined): void { + this.packagedFlowDefaultSource = source; + this.packagedFlowDefaults = new WeakMap(); } /** @@ -6260,6 +6306,138 @@ export class AutomationEngine implements IAutomationService { return this.packagedFlowOwner(name) !== undefined; } + /** + * [#34655, ADR-0126 §4] Refuse a body that declares `defaultActive` for a + * flow no package ships. The key is the default of the packaged-flow + * switch (the activation ledger), and a flow authored in this deployment + * has no such switch: its switch is its own `status`, so the key could + * only be a declaration the engine does not honour. + * + * A flow is packaged when any package's loader set holds its name + * ({@link isShippedFlowName}: the loader's own answer, a name two + * packages hold included); every other flow is the environment's. Judged by NAME, never by the arm a + * registration names, because it is one of the {@link registrationChecks} + * (#23317): {@link registerFlow} throws it, {@link dryRun} refuses a draft + * for it, and the stored pass ({@link canonicalizeStoredFlow}) lists a + * stored row it would refuse, all three asking the same question. A + * package's declared `.custom` override is served at the base's name, so + * it passes; the default it carries is not read ({@link packagedFlowDefault}). + * + * Registration refuses it as it refuses every check: `registerFlow` throws + * an `Error`, which the automation write doors (`registerAndSaveFlow` in + * `@objectstack/runtime`) answer `VALIDATION_FAILED` / 400 with nothing + * stored. The metadata door (`PUT /api/v1/meta/flow/:name`) parses + * without registering, so it stores such a row; the engine then refuses + * to arm it, and the stored pass names it. + */ + private refuseUnpackagedDefaultActive(flowName: string, flow: FlowParsed): RegistrationCheckRefusal | undefined { + if (flow.defaultActive === undefined || this.isShippedFlowName(flowName, flow)) return undefined; + const why = + `'${flowName}' declares defaultActive, which is the default of the switch an administrator turns a ` + + `PACKAGED flow on and off with, and '${flowName}' was authored in this deployment, not shipped by a ` + + `package. A flow authored here is switched by its own status: remove defaultActive, and publish ` + + `it with status 'obsolete' to keep it off or 'active' to arm it.`; + return { + message: `Flow ${why}`, + sites: [{ path: 'flows[0].defaultActive', from: JSON.stringify(flow.defaultActive), detail: `the flow ${why}` }], + }; + } + + /** + * [#34655, L2 S3] Does ANY package's loader set hold a flow `name`? The + * question {@link refuseUnpackagedDefaultActive} asks — not "is there ONE + * owner": {@link packagedFlowOwner} answers none for a bare name two + * packages hold (ADR-0150 D4), and a package's body re-registered under + * such a name (a re-sync, a hot upgrade, a third holder arriving) is + * still a package's. Every answer is the loader's own, asked per package + * ({@link packagedFlowSlotOwner}) of each package that may hold it: the + * packages whose slots hold the name now, and the package the body names + * itself as (`_packageId`). The stamp is only which package to ASK; a + * stamp naming a package that ships no such flow answers no. + */ + private isShippedFlowName(name: string, flow: FlowParsed): boolean { + if (this.isPackagedFlow(name)) return true; + const bare = this.flowSlots.slot(name)?.name ?? name; + const stamped = (flow as { _packageId?: unknown })._packageId; + const candidates = new Set(typeof stamped === 'string' && stamped !== '' ? [stamped] : []); + for (const slot of this.flowSlots.slotsOf(bare)) if (slot.packageId !== null) candidates.add(slot.packageId); + return [...candidates].some((packageId) => this.packagedFlowSlotOwner(bare, packageId) !== undefined); + } + + /** + * [#34655, ADR-0126 §4, seat ruling on S2] The `defaultActive` the + * PACKAGE declares for the flow held under `key`, or `undefined` for none + * (and for a flow no package ships). Read off the package's own body: + * the armed body when the loader's body is what is armed, else the body + * the loader's set holds for the slot's package + * ({@link setPackagedFlowDefaultSource}). So a declared `.custom` override + * does not change the default, in either direction: an override that + * omits the key does not arm a flow its package ships off, and one that + * writes `false` does not switch off a flow its package ships on. The + * administrator's switch (the activation ledger) decides either way. + * With no reader attached, only an armed loader's body answers. + * + * [L2 N9] The reader's answer is asked once per armed body + * ({@link packagedFlowDefaults}), not on every {@link isFlowEnabled}, + * and asked again after each change to the loader's set + * ({@link refreshPackagedFlowDefaults}). + */ + private packagedFlowDefault(key: string): boolean | undefined { + const armed = this.flows.get(key); + if (!armed) return undefined; + if (this.flowArms.get(armed)?.source === 'package') return armed.defaultActive; + const source = this.packagedFlowDefaultSource; + if (source === undefined) return undefined; + const asked = this.packagedFlowDefaults.get(armed); + if (asked !== undefined) return asked.value; + const owner = this.packagedFlowOwner(key); + const value = owner === undefined ? undefined : source(this.flowSlots.slot(key)?.name ?? key, owner); + this.packagedFlowDefaults.set(armed, { value }); + return value; + } + + /** + * [#34655, L2 S4] The loader's set may have changed (a package installed, + * upgraded or removed): forget every default {@link packagedFlowDefault} + * cached, and send each held flow whose armed body is NOT the loader's + * own (a declared `.custom` override, a `runtime` body under a held name) + * back through the arming gate when its enablement moved. Returns the + * keys it moved. + * + * The cache is keyed by the armed body, and a re-sync does not always + * re-register: the automation plugin's `metadata:reloaded` re-sync keeps + * the body the metadata-mutation sync armed from the same stored row, and + * keeps the body it had when a re-registration throws. An override's + * stored body does not change when its base is upgraded, so without this + * the default read from the previous version's body would stay until the + * next registration of that flow or a restart: a flow the new version + * ships off would keep running, and one it ships on would stay off. The + * plugin calls this at every re-sync; a body {@link rollbackFlow} puts + * back is asked again too, since the map it was cached in is gone. + * + * A loader-armed flow reads its own body's declaration and is never + * cached, so it is not re-judged here: its re-registration is what moves + * it. An activation ledger row decides before any default is read, so a + * flow an administrator switched does not move. + */ + refreshPackagedFlowDefaults(): string[] { + const before = new Map(); + for (const [key, armed] of this.flows) { + if (this.flowArms.get(armed)?.source !== 'package') before.set(key, this.isFlowEnabled(key)); + } + this.packagedFlowDefaults = new WeakMap(); + const moved: string[] = []; + for (const [key, wasEnabled] of before) { + if (this.isFlowEnabled(key) === wasEnabled) continue; + if (wasEnabled) this.deactivateFlowTrigger(key); + else this.activateFlowTrigger(key); + moved.push(key); + } + // [#20725, ADR-0126 §7.3] The callers of a subflow that moved, through the same gate. + for (const key of moved) this.rejudgeSubflowCallers(key); + return moved; + } + /** * [ADR-0150 D3] Attach the reader over the one package-scoped resolver * ({@link FlowNameResolver}). The automation plugin calls this at `init()` @@ -6832,8 +7010,17 @@ export class AutomationEngine implements IAutomationService { * {@link registerFlow}. Returns the names it disarmed so the host can say * so in its bootstrap audit. * + * [#34655] A row switching a flow ON is offered to the arming gate + * ({@link activateFlowTrigger}, idempotent, still declined by a disarming + * `status`), so a flow its package ships off that an administrator + * switched on is armed after a restart on a host whose trigger was + * registered before the pull. The return value names only what it + * disarmed. + * * An empty ledger — the stock-boot case — disarms nothing and rebinds - * nothing, which is §4's "an empty ledger changes nothing anywhere". + * nothing, which is §4's "an empty ledger changes nothing anywhere" for + * every flow that declares no default; a flow shipped + * `defaultActive: false` stays unarmed, its package's default. */ hydrateFlowActivations(): Promise { // The body lives in ./flow-definitions.ts (#25222). @@ -6842,6 +7029,7 @@ export class AutomationEngine implements IAutomationService { get flowActivationStore() { return readFlowActivationStore(); }, flowLedgerDisabled: this.flowLedgerDisabled, flows: this.flows, + activateFlowTrigger: (...a) => this.activateFlowTrigger(...a), deactivateFlowTrigger: (...a) => this.deactivateFlowTrigger(...a), rejudgeSubflowCallers: (...a) => this.rejudgeSubflowCallers(...a), flowSlotKeysOf: (...a) => this.flowSlotKeysOf(...a), @@ -6855,7 +7043,9 @@ export class AutomationEngine implements IAutomationService { * * `flowStatusDisabled` is the authoring state (`obsolete` / `invalid`), * owned by the definition. `flowLedgerDisabled` is the installation's - * activation choice (ADR-0126 §4), owned by `sys_metadata_activation`. + * activation choice (ADR-0126 §4), owned by `sys_metadata_activation`; + * with no row deciding, it is the package's default, which a packaged + * flow may declare off (`defaultActive: false`, #34655). * Either one disarms; neither can override the other, because they answer * different questions and an "override" would mean one silently undoing a * decision it does not own. @@ -6879,7 +7069,16 @@ export class AutomationEngine implements IAutomationService { * (AGENTS.md "Degradation log levels"). */ private describeDisabledFlow(flowName: string): string { - if (this.flowLedgerDisabled.has(flowName)) { + if (this.flowLedgerDisabled.offByDefault(flowName)) { + // [#34655] No row: the package ships it off and no administrator + // has switched it on here. + this.logger.info( + `FLOW_DISABLED: packaged flow '${flowName}' refused — its package ships it switched off ` + + '(defaultActive: false) and the activation ledger (sys_metadata_activation) holds no row ' + + 'switching it on.', + { flow: flowName, refusal: 'FLOW_DISABLED' }, + ); + } else if (this.flowLedgerDisabled.has(flowName)) { this.logger.info( `FLOW_DISABLED: packaged flow '${flowName}' refused — it is switched off in the activation ledger ` + '(sys_metadata_activation, ADR-0126 §7.2).', @@ -10638,6 +10837,7 @@ export class AutomationEngine implements IAutomationService { validateDecisionModes: (...a) => this.validateDecisionModes(...a), validateFlowExpressions: (...a) => this.validateFlowExpressions(...a), validateApiTriggerSecret: (...a) => this.validateApiTriggerSecret(...a), + refuseUnpackagedDefaultActive: (...a) => this.refuseUnpackagedDefaultActive(...a), }; return registrationChecks.call(host, { advisory }); } diff --git a/packages/services/service-automation/src/flow-activation-projection.ts b/packages/services/service-automation/src/flow-activation-projection.ts index 72958026aa4..ac387b7ea9c 100644 --- a/packages/services/service-automation/src/flow-activation-projection.ts +++ b/packages/services/service-automation/src/flow-activation-projection.ts @@ -48,6 +48,14 @@ export interface FlowActivationProjectionReaders { * Reported once per name by the projection. */ readonly reportPackagelessOverShared?: (overlay: { name: string }) => void; + /** + * [#34655, ADR-0126 §4] Does the flow the engine files under `key` ship + * switched off (`defaultActive: false`)? Read only when no row decides + * for the flow ({@link FlowActivationProjection.has}): a row is an + * administrator's choice and wins over the package's default. Absent, + * every flow ships switched on, as before the key. + */ + readonly shipsOff?: (key: string) => boolean; } export class FlowActivationProjection { @@ -78,7 +86,27 @@ export class FlowActivationProjection { constructor(private readonly readers: FlowActivationProjectionReaders) {} /** - * Is the flow `name` switched off by a ledger row? + * Is the flow `key` switched off for this installation? The row that + * decides for it ({@link rowVerdict}) when there is one, else the + * package's default ({@link FlowActivationProjectionReaders.shipsOff}, + * #34655): with no row, a flow shipped `defaultActive: false` is off. + */ + has(key: string): boolean { + return this.rowVerdict(key) ?? this.readers.shipsOff?.(key) === true; + } + + /** + * [#34655] Is the flow `key` off only because its package ships it off — + * no row decides for it, so no administrator has switched it here? + */ + offByDefault(key: string): boolean { + return this.rowVerdict(key) === undefined && this.readers.shipsOff?.(key) === true; + } + + /** + * Does a ledger row decide whether the flow `key` is switched off, and + * which way? `undefined` when no row decides: the package's default + * does ({@link has}). * * - The row of the package that ships the name decides, in either state. * - Else a row naming no package binds to the name's one holder (ADR-0150 @@ -93,12 +121,12 @@ export class FlowActivationProjection { * - When no reader can say which package ships the name, every * switched-off row of the name switches it off. */ - has(key: string): boolean { + private rowVerdict(key: string): boolean | undefined { const slot = this.readers.slotOf?.(key); - if (slot?.shared) return this.hasShared(slot.name, slot.packageId); + if (slot?.shared) return this.sharedRowVerdict(slot.name, slot.packageId); const name = slot?.name ?? key; const packages = this.rows.get(name); - if (!packages || packages.size === 0) return false; + if (!packages || packages.size === 0) return undefined; const holder = this.readers.holderOf(name); if (holder !== undefined && packages.has(holder)) return packages.get(holder) === true; if (packages.get('') === true) return true; @@ -113,7 +141,7 @@ export class FlowActivationProjection { } return true; } - return false; + return undefined; } /** @@ -122,13 +150,14 @@ export class FlowActivationProjection { * naming no package that switches the name off keeps this slot off too: * it binds to one holder and nothing says which, so it fails closed for * every holder without a row of its own, and is reported once. A row of - * another package keys that package's slot only. + * another package keys that package's slot only, so with neither the slot + * has no row deciding for it (`undefined`). */ - private hasShared(name: string, packageId: string | null): boolean { + private sharedRowVerdict(name: string, packageId: string | null): boolean | undefined { const packages = this.rows.get(name); - if (!packages || packages.size === 0) return false; + if (!packages || packages.size === 0) return undefined; if (packageId !== null && packages.has(packageId)) return packages.get(packageId) === true; - if (packages.get('') !== true) return false; + if (packages.get('') !== true) return undefined; if (!this.packagelessBinding.has(name) && !this.packagelessSharedReported.has(name)) { this.packagelessSharedReported.add(name); this.readers.reportPackagelessOverShared?.({ name }); @@ -143,7 +172,7 @@ export class FlowActivationProjection { * has only ever read over one holder, and where the holder has no row of * its own. When it has one, that row is its switch, and the package-less * row is left as it is: once the name is shared, it keeps every other - * holder without a row of its own off ({@link hasShared}). + * holder without a row of its own off ({@link sharedRowVerdict}). */ canBindPackageless(name: string, packageId: string): boolean { const packages = this.rows.get(name); diff --git a/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts b/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts index 173caa883d4..06808b2768f 100644 --- a/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts +++ b/packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts @@ -46,7 +46,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { SysMetadataActivation } from '@objectstack/platform-objects'; import { defineStack } from '@objectstack/spec'; import type { AutomationContext } from '@objectstack/spec/contracts'; -import { AutomationServicePlugin } from './plugin.js'; +import { AutomationServicePlugin, packagedFlowDefaultReader } from './plugin.js'; import type { AutomationEngine, FlowTrigger, FlowTriggerBinding } from './engine.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -83,13 +83,13 @@ const pluginManifest = (id: string) => ({ name: 'crm', }); -/** The shipping package: one object and the base flow over it. */ -const shippingStack = () => +/** The shipping package: one object and the base flow over it (`base`: more keys on that flow). */ +const shippingStack = (base: Record = {}) => defineStack( { manifest: pluginManifest(BASE), objects: [{ name: TICKET, label: 'Ticket', fields: { title: { name: 'title', label: 'Title', type: 'text' } } }], - flows: [ticketFlow('BASE')], + flows: [ticketFlow('BASE', base)], } as never, { strict: false }, ) as Record; @@ -183,6 +183,7 @@ async function boot( start: (ql: ObjectQL, automation: AutomationEngine) => Promise, second: Second = 'none', ledger = false, + base: Record = {}, ) { const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never); kernels.push(kernel); @@ -210,7 +211,7 @@ async function boot( const manifests = ctx.getService<{ register(m: unknown): Promise }>('manifest'); const registerStack = (stack: Record) => manifests.register({ ...(stack.manifest as object), ...stack }); if (second === 'before') await registerStack(otherStack()); - if (!second.startsWith('installed-both')) await registerStack(shippingStack()); + if (!second.startsWith('installed-both')) await registerStack(shippingStack(base)); if (second === 'after') await registerStack(otherStack()); if (second.startsWith('installed-')) { ctx.hook('kernel:ready', async () => { @@ -238,17 +239,18 @@ async function measuredBoot( rows: readonly Row[], start: (ql: ObjectQL, automation: AutomationEngine) => Promise, second: Second = 'none', + base: Record = {}, ) { const dir = mkdtempSync(join(tmpdir(), 'qa-28717-')); dirs.push(dir); const file = join(dir, 'store.db'); const first = await boot(file, async (ql) => { for (const row of rows) await ql.insert('sys_metadata', storedRow(row), { context: SYS } as never); - }); + }, 'none', false, base); await first.kernel.shutdown(); kernels.splice(kernels.indexOf(first.kernel), 1); const warn = vi.spyOn(ObjectLogger.prototype, 'warn'); - const measured = await boot(file, start, second); + const measured = await boot(file, start, second, false, base); const collisionCalls = warn.mock.calls .filter(([message]) => String(message).includes('Flow name collision') && String(message).includes(`'${FLOW}'`)); const collisions = collisionCalls.map(([message]) => String(message)); @@ -312,6 +314,22 @@ describe('[#28717] a declared .custom flow override is armed from the first boot expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('BASE'); }); + it('[#34655, L2 N8] the base ships `defaultActive: false`: the armed override, which omits the key, stays off — read through the real protocol', async () => { + let armedAtPull: string | undefined; + const { fired, automation, kernel } = await measuredBoot(['override'], async (ql, engine) => { + armedAtPull = ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label; + await insertTicket(ql, 'shipped off'); + }, 'none', { defaultActive: false }); + expect(armedAtPull).toBe('OVERRIDE'); + // The package's own body, as the protocol's every-shipper read serves it (no mock: the duck-typed + // `shippedArtifactsOf` that `packagedFlowDefaultReader` asks). + const read = packagedFlowDefaultReader({ getService: (name: string) => kernel.getService(name) } as never); + expect(read(FLOW, BASE)).toBe(false); + expect(read(FLOW, PAIR), 'control: the pair ships no body of its own').toBeUndefined(); + expect(automation.getFlowRuntimeStates().find((s) => s.name === FLOW)).toMatchObject({ enabled: false }); + expect(fired).toEqual([]); + }); + it('control: with only the override, it is armed from the boot pull with no receipt and no warning (#28412)', async () => { let armedAtPull: string | undefined; const { fired, automation, collisions } = await measuredBoot(['override'], async (ql, engine) => { diff --git a/packages/services/service-automation/src/flow-default-active-34655.test.ts b/packages/services/service-automation/src/flow-default-active-34655.test.ts new file mode 100644 index 00000000000..cd264124813 --- /dev/null +++ b/packages/services/service-automation/src/flow-default-active-34655.test.ts @@ -0,0 +1,655 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34655, ADR-0126 §4 amendment] A packaged flow ships switched OFF with +// `defaultActive: false`: with no activation-ledger row it is not armed and +// does not run; an administrator's toggle writes a row, and the row wins over +// the declared default across a restart and an upgrade. Only a flow a package +// ships has that switch, so the key is refused on a flow authored in the +// environment. + +import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import { AutomationEngine } from './engine.js'; +import type { FlowTrigger, FlowTriggerBinding } from './engine.js'; +import { InMemoryFlowActivationStore } from './flow-activation-store.js'; +import { registerSubflowNode } from './builtin/subflow-node.js'; +import { AutomationServicePlugin, packagedFlowDefaultReader } from './plugin.js'; +import type { AutomationContext } from '@objectstack/spec/contracts'; + +function createTestLogger(): any { + const l: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + l.child = () => l; + return l; +} + +const RECORD_START = { objectName: 'quote', triggerType: 'record-after-update' }; + +/** A record-change flow a code package ships (the loader's stamps). */ +function packagedFlow(name: string, extra: Record = {}, nodes?: unknown[], edges?: unknown[]) { + return { + name, + label: name, + type: 'record_change', + status: 'active', + nodes: nodes ?? [ + { id: 'start', type: 'start', label: 'Start', config: RECORD_START }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: edges ?? [{ id: 'e1', source: 'start', target: 'end' }], + _packageId: 'crm', + ...extra, + }; +} + +/** The same body with no package stamps: a flow authored in this environment. */ +function environmentFlow(name: string, extra: Record = {}) { + const { _packageId: _dropped, ...body } = packagedFlow(name, extra); + return body; +} + +/** What a caller reads for a packaged flow switched off for the deployment. */ +const TURNED_OFF_SENTENCE = + 'This flow is turned off for this deployment. An administrator can turn it on again ' + + "in its package's Automations in Studio, or copy it there under a new name."; + +function recordingTrigger(type: string) { + const bound = new Set(); + const trigger: FlowTrigger = { + type, + start(binding: FlowTriggerBinding, _cb: (ctx: AutomationContext) => Promise) { + bound.add(binding.flowName); + }, + stop(flowName: string) { + bound.delete(flowName); + }, + }; + return { trigger, isBound: (n: string) => bound.has(n) }; +} + +/** + * The loader's set: the flows package `crm` ships, whatever the bodies carry + * (production: the automation plugin's `packagedFlowReader`). Asked before a + * body is filed, so it is a set of its own, never read off the engine's map. + */ +const SHIPPED_BY_CRM = new Set(['draft_contract', 'on_explicit', 'on_absent', 'retired', 'child', 'parent']); + +/** The boot pull's arm for a body package `crm`'s loader registered. */ +const PULL = { source: 'package', packageId: 'crm' } as const; + +/** One installation: a fresh engine over `store`, the record-change trigger registered. */ +function boot(store: InMemoryFlowActivationStore = new InMemoryFlowActivationStore()) { + const logger = createTestLogger(); + const engine = new AutomationEngine(logger); + engine.setPackagedFlowSource((name) => (SHIPPED_BY_CRM.has(name) ? 'crm' : undefined)); + engine.setFlowActivationStore(store); + const recordChange = recordingTrigger('record_change'); + engine.registerTrigger(recordChange.trigger); + return { engine, store, logger, isBound: recordChange.isBound }; +} + +function stateOf(engine: AutomationEngine, name: string) { + return engine.getFlowRuntimeStates().find((s) => s.name === name); +} + +describe('#34655 — a packaged flow declared `defaultActive: false` ships switched off', () => { + it('a fresh install (no ledger row) neither arms nor runs it, and the status read says so', async () => { + const { engine, store, isBound } = boot(); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + + expect(await engine.hydrateFlowActivations()).toEqual([]); + expect(await store.list()).toEqual([]); + expect(isBound('draft_contract')).toBe(false); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false, bound: false, status: 'active' }); + + const refused = await engine.execute('draft_contract'); + expect(refused.success).toBe(false); + expect(refused.code).toBe('FLOW_DISABLED'); + expect(refused.error).toBe(TURNED_OFF_SENTENCE); + }); + + it('the refusal log names the shipped default, not a ledger row', async () => { + const { engine, logger } = boot(); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + + await engine.execute('draft_contract'); + + const lines = logger.info.mock.calls.map((c: unknown[]) => String(c[0])).filter((m: string) => m.startsWith('FLOW_DISABLED')); + expect(lines).toEqual([ + "FLOW_DISABLED: packaged flow 'draft_contract' refused — its package ships it switched off " + + '(defaultActive: false) and the activation ledger (sys_metadata_activation) holds no row switching it on.', + ]); + }); + + it("an administrator's toggle on writes the row, arms it and runs it", async () => { + const { engine, store, isBound } = boot(); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await engine.hydrateFlowActivations(); + + await engine.toggleFlow('draft_contract', true); + + expect(await store.list()).toEqual([{ name: 'draft_contract', packageId: 'crm', active: true }]); + expect(isBound('draft_contract')).toBe(true); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true, bound: true }); + expect((await engine.execute('draft_contract')).success).toBe(true); + }); + + it('the switched-on state survives a restart, the trigger registered after the pull and the ledger read (the stock boot order)', async () => { + const first = boot(); + first.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await first.engine.toggleFlow('draft_contract', true); + + const engine = new AutomationEngine(createTestLogger()); + engine.setPackagedFlowSource((name) => (SHIPPED_BY_CRM.has(name) ? 'crm' : undefined)); + engine.setFlowActivationStore(first.store); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await engine.hydrateFlowActivations(); + const recordChange = recordingTrigger('record_change'); + engine.registerTrigger(recordChange.trigger); + + expect(recordChange.isBound('draft_contract')).toBe(true); + expect((await engine.execute('draft_contract')).success).toBe(true); + }); + + it('the switched-on state survives an uninstall and a reinstall: a boot without the package leaves the row, and the reinstall reads it', async () => { + // The ledger store has no delete (`metadata-activation-store.ts`), and + // nothing on the uninstall path writes it; here the boot WITHOUT the + // package plays the uninstall, over the same durable store. + const first = boot(); + first.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await first.engine.toggleFlow('draft_contract', true); + const row = await first.store.list(); + expect(row).toEqual([expect.objectContaining({ name: 'draft_contract', active: true })]); + + const uninstalled = new AutomationEngine(createTestLogger()); + uninstalled.setFlowActivationStore(first.store); + await uninstalled.hydrateFlowActivations(); + expect(await first.store.list()).toEqual(row); + + const reinstalled = boot(first.store); + reinstalled.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await reinstalled.engine.hydrateFlowActivations(); + expect(reinstalled.isBound('draft_contract')).toBe(true); + expect((await reinstalled.engine.execute('draft_contract')).success).toBe(true); + }); + + it('the switched-on state survives a restart on a host whose trigger was registered before the pull', async () => { + const first = boot(); + first.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await first.engine.hydrateFlowActivations(); + await first.engine.toggleFlow('draft_contract', true); + + const restarted = boot(first.store); + restarted.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + expect(await restarted.engine.hydrateFlowActivations()).toEqual([]); + + expect(restarted.isBound('draft_contract')).toBe(true); + expect((await restarted.engine.execute('draft_contract')).success).toBe(true); + }); + + it('the switched-on state survives an upgrade that changes the body and still declares the default off', async () => { + const { engine, isBound } = boot(); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await engine.hydrateFlowActivations(); + await engine.toggleFlow('draft_contract', true); + + // The upgrade re-registers the new version's body (a hot install, or the next boot's pull). + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false, version: 2, description: 'v2' }), PULL); + + expect(isBound('draft_contract')).toBe(true); + expect((await engine.execute('draft_contract')).success).toBe(true); + }); + + it('a flow switched back off stays off across a restart, whatever the default', async () => { + const first = boot(); + first.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + await first.engine.toggleFlow('draft_contract', true); + await first.engine.toggleFlow('draft_contract', false); + expect(await first.store.list()).toEqual([{ name: 'draft_contract', packageId: 'crm', active: false }]); + + // The next version ships it on; the administrator's row still decides. + const restarted = boot(first.store); + restarted.engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: true, version: 2 }), PULL); + expect(await restarted.engine.hydrateFlowActivations()).toEqual(['draft_contract']); + expect(restarted.isBound('draft_contract')).toBe(false); + expect((await restarted.engine.execute('draft_contract')).code).toBe('FLOW_DISABLED'); + }); + + it('with no row, an upgrade that changes the declared default moves the installation, both ways', async () => { + const { engine, isBound } = boot(); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + expect(isBound('draft_contract')).toBe(false); + + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { version: 2 }), PULL); + expect(isBound('draft_contract')).toBe(true); + expect((await engine.execute('draft_contract')).success).toBe(true); + + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false, version: 3 }), PULL); + expect(isBound('draft_contract')).toBe(false); + expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED'); + }); + + it('CONTROL: `defaultActive: true` and an absent key ship the flow on, as every packaged flow before the key', async () => { + const { engine, isBound } = boot(); + engine.registerFlow('on_explicit', packagedFlow('on_explicit', { defaultActive: true }), PULL); + engine.registerFlow('on_absent', packagedFlow('on_absent'), PULL); + expect(await engine.hydrateFlowActivations()).toEqual([]); + + for (const name of ['on_explicit', 'on_absent']) { + expect(isBound(name)).toBe(true); + expect((await engine.execute(name)).success).toBe(true); + } + }); + + it("`status` stays the author's: an `obsolete` flow a row switches on still does not arm", async () => { + // The row is placed directly, the shape an earlier boot leaves; what + // the toggle door answers for such a flow is not this key's. + const store = new InMemoryFlowActivationStore(); + await store.setActive({ name: 'retired', packageId: 'crm', active: true }); + const { engine, isBound } = boot(store); + engine.registerFlow('retired', packagedFlow('retired', { defaultActive: false, status: 'obsolete' }), PULL); + await engine.hydrateFlowActivations(); + + expect(isBound('retired')).toBe(false); + expect(stateOf(engine, 'retired')).toMatchObject({ enabled: false }); + expect((await engine.execute('retired')).code).toBe('FLOW_DISABLED'); + }); + + it('a packaged caller of a subflow that ships off is held unarmed until the subflow is switched on', async () => { + const { engine, isBound } = boot(); + registerSubflowNode(engine, { logger: createTestLogger(), getService: () => undefined } as any); + engine.registerFlow('child', packagedFlow('child', { defaultActive: false, type: 'autolaunched' }, [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'end', type: 'end', label: 'End' }, + ]), PULL); + engine.registerFlow('parent', packagedFlow('parent', {}, [ + { id: 'start', type: 'start', label: 'Start', config: RECORD_START }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: 'child' } }, + { id: 'end', type: 'end', label: 'End' }, + ], [ + { id: 'e1', source: 'start', target: 'call' }, + { id: 'e2', source: 'call', target: 'end' }, + ]), PULL); + + expect(isBound('parent')).toBe(false); + + await engine.toggleFlow('child', true); + expect(isBound('parent')).toBe(true); + expect((await engine.execute('parent')).success).toBe(true); + }); +}); + +describe('#34655 — `defaultActive` is refused on a flow authored in the environment', () => { + for (const value of [false, true]) { + // The engine throws a plain Error, as every registration refusal does; + // the write doors answer it VALIDATION_FAILED / 400 (`registerAndSaveFlow`). + it(`refuses \`defaultActive: ${value}\` on a flow no package ships, naming its status as its switch, filing nothing`, async () => { + const { engine } = boot(); + let thrown: unknown; + try { + engine.registerFlow('my_flow', environmentFlow('my_flow', { defaultActive: value })); + } catch (e) { + thrown = e; + } + expect(thrown).toBeInstanceOf(Error); + expect((thrown as Error).message).toBe( + "Flow 'my_flow' declares defaultActive, which is the default of the switch an administrator turns a " + + "PACKAGED flow on and off with, and 'my_flow' was authored in this deployment, not shipped by a " + + 'package. A flow authored here is switched by its own status: remove defaultActive, and publish ' + + "it with status 'obsolete' to keep it off or 'active' to arm it.", + ); + expect(await engine.getFlow('my_flow')).toBeNull(); + expect(stateOf(engine, 'my_flow')).toBeUndefined(); + }); + } + + it('CONTROL: the same environment flow without the key registers and runs', async () => { + const { engine, isBound } = boot(); + engine.registerFlow('my_flow', environmentFlow('my_flow')); + expect(isBound('my_flow')).toBe(true); + expect((await engine.execute('my_flow')).success).toBe(true); + }); + + it('the key is judged by NAME against the loader\'s set, never by the arm: a package arm for a name no package ships is refused too', () => { + const { engine } = boot(); + expect(() => engine.registerFlow( + 'unlisted_flow', + environmentFlow('unlisted_flow', { defaultActive: false }), + PULL, + )).toThrow(/^Flow 'unlisted_flow' declares defaultActive/); + expect(stateOf(engine, 'unlisted_flow')).toBeUndefined(); + }); + + it('CONTROL: a name the loader\'s set holds keeps the key, whatever arm registers it', () => { + const { engine } = boot(); + expect(() => engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }))).not.toThrow(); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true }); + }); + + it('a dry run refuses an environment draft declaring the key, with what registration throws (#23317: one check list)', async () => { + const { engine } = boot(); + const draft = environmentFlow('my_flow', { defaultActive: false }); + let registerError: unknown; + try { engine.registerFlow('my_flow', draft); } catch (e) { registerError = e; } + expect(registerError).toBeInstanceOf(Error); + await expect(engine.dryRun(draft, { userId: 'usr_maker' })).rejects.toThrow((registerError as Error).message); + }); + + it('the stored pass lists a stored environment row declaring the key, at the key, and none without it', () => { + const { engine } = boot(); + const { todos } = engine.canonicalizeStoredFlow('my_flow', environmentFlow('my_flow', { defaultActive: true })); + expect(todos.map((t) => t.path)).toEqual(['flows[0].defaultActive']); + expect(todos[0]!.reason).toContain("'my_flow' declares defaultActive"); + expect(engine.canonicalizeStoredFlow('my_flow', environmentFlow('my_flow')).todos).toEqual([]); + expect(engine.canonicalizeStoredFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false })).todos).toEqual([]); + }); +}); + +describe('#34655 (L2 S3) — a name two packages hold keeps the key: the check asks whether ANY package holds it', () => { + /** Each name's loader sets, as the plugin's reader answers them (one owner by name; each package's own question). */ + function bootCoHeld(loaderSets: Record) { + const booted = boot(); + booted.engine.setPackagedFlowSource((name, packageId) => { + const holders = loaderSets[name] ?? []; + if (packageId !== undefined) return holders.includes(packageId) ? packageId : undefined; + return holders.length === 1 ? holders[0] : undefined; + }); + return booted; + } + /** Package `packageId`'s own body of `name`, armed in its own slot as precedence arms a co-held name. */ + const ship = (engine: AutomationEngine, packageId: string, name: string, extra: Record = {}) => + engine.registerFlow(name, packagedFlow(name, { _packageId: packageId, ...extra }), { source: 'package', packageId, holder: packageId }); + + it('both holders, a re-sync and a third holder register with the key, true and false', () => { + const { engine } = bootCoHeld({ co_held: ['crm', 'erp', 'hr'] }); + expect(engine.packagedFlowOwner('co_held'), 'control: the bare name has no ONE owner').toBeUndefined(); + expect(() => ship(engine, 'crm', 'co_held', { defaultActive: false })).not.toThrow(); + expect(() => ship(engine, 'erp', 'co_held', { defaultActive: true })).not.toThrow(); + // The `metadata:reloaded` re-sync / a hot upgrade re-registers a holder's body. + expect(() => ship(engine, 'crm', 'co_held', { defaultActive: false, version: 2 })).not.toThrow(); + expect(() => ship(engine, 'hr', 'co_held', { defaultActive: false })).not.toThrow(); + expect(engine.getFlowRuntimeStates().filter((s) => s.name === 'co_held')).toHaveLength(3); + }); + + it('a dry run and the stored pass agree: no refusal for a co-held name', async () => { + const { engine } = bootCoHeld({ co_held: ['crm', 'erp'] }); + ship(engine, 'crm', 'co_held', { defaultActive: false }); + ship(engine, 'erp', 'co_held'); + const body = packagedFlow('co_held', { _packageId: 'erp', defaultActive: true }); + expect(engine.canonicalizeStoredFlow('co_held', body).todos).toEqual([]); + const dry = await engine.dryRun(body, { userId: 'usr_maker' }).then(() => undefined, (e: Error) => e.message); + expect(dry ?? '').not.toContain('declares defaultActive'); + }); + + it('CONTROL: the refusal still stands when no package holds the name, whatever package the body names itself as', () => { + const { engine } = bootCoHeld({ co_held: ['crm', 'erp'] }); + const forged = packagedFlow('loose_flow', { _packageId: 'crm', defaultActive: false }); + expect(() => engine.registerFlow('loose_flow', forged)).toThrow(/^Flow 'loose_flow' declares defaultActive/); + expect(engine.canonicalizeStoredFlow('loose_flow', forged).todos.map((t) => t.path)).toEqual(['flows[0].defaultActive']); + }); +}); + +describe('#34655 (seat ruling on S2) — a declared `.custom` override does not move the package\'s default', () => { + /** The pair's declared override, as the boot pull arms it in the base's place. */ + const OVERRIDE = { source: 'override', packageId: 'crm.custom' } as const; + + /** One installation whose loader holds `crm`'s own bodies with these defaults. */ + function bootWithLoaderDefaults(defaults: Record) { + const booted = boot(); + booted.engine.setPackagedFlowDefaultSource((name, packageId) => (packageId === 'crm' ? defaults[name] : undefined)); + return booted; + } + + it('the package ships it off and nobody switched it: an override that omits the key still does not arm', async () => { + const { engine, isBound } = bootWithLoaderDefaults({ draft_contract: false }); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE); + + expect(isBound('draft_contract')).toBe(false); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false }); + expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED'); + + await engine.toggleFlow('draft_contract', true); + expect(isBound('draft_contract')).toBe(true); + }); + + it('the package ships it on: an override that writes `false` does not switch it off, and the administrator still can', async () => { + const { engine, isBound } = bootWithLoaderDefaults({ on_absent: undefined }); + engine.registerFlow('on_absent', packagedFlow('on_absent', { defaultActive: false }), OVERRIDE); + + expect(isBound('on_absent')).toBe(true); + expect(stateOf(engine, 'on_absent')).toMatchObject({ enabled: true }); + + await engine.toggleFlow('on_absent', false); + expect(isBound('on_absent')).toBe(false); + }); + + it('CONTROL: with the loader\'s body armed, its own declaration is the default', () => { + const { engine, isBound } = bootWithLoaderDefaults({}); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL); + expect(isBound('draft_contract')).toBe(false); + }); + + it('(L2 N9) the loader\'s set is asked once per armed body, not on every enablement read', async () => { + const { engine } = boot(); + const reader = vi.fn((name: string, packageId: string) => (packageId === 'crm' && name === 'draft_contract' ? false : undefined)); + engine.setPackagedFlowDefaultSource(reader); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE); + const asked = reader.mock.calls.length; + expect(asked).toBe(1); + for (let i = 0; i < 5; i++) { + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false }); + expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED'); + } + expect(reader).toHaveBeenCalledTimes(asked); + // A re-registration (the re-sync after an upgrade) asks again, once. + reader.mockImplementation(() => undefined); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized', version: 2 }), OVERRIDE); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true }); + expect(reader).toHaveBeenCalledTimes(asked + 1); + }); + + it('(L2 S4) a change to the loader\'s set reaches a held override with no ledger row, both ways', async () => { + const defaults: Record = { draft_contract: false }; + const { engine, isBound } = bootWithLoaderDefaults(defaults); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE); + expect(isBound('draft_contract')).toBe(false); + + // The base is upgraded to ship it on; the held override body is not re-registered. + defaults.draft_contract = undefined; + expect(engine.refreshPackagedFlowDefaults()).toEqual(['draft_contract']); + expect(isBound('draft_contract')).toBe(true); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true, bound: true }); + expect((await engine.execute('draft_contract')).success).toBe(true); + + // And back to off. + defaults.draft_contract = false; + expect(engine.refreshPackagedFlowDefaults()).toEqual(['draft_contract']); + expect(isBound('draft_contract')).toBe(false); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false }); + expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED'); + }); + + it('(L2 S4) CONTROL: the refresh moves nothing a ledger row or the loader\'s own body decides', async () => { + const defaults: Record = { draft_contract: undefined, on_absent: undefined }; + const { engine, isBound } = bootWithLoaderDefaults(defaults); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE); + await engine.toggleFlow('draft_contract', false); + engine.registerFlow('on_absent', packagedFlow('on_absent', { defaultActive: false }), PULL); + expect(isBound('draft_contract')).toBe(false); + expect(isBound('on_absent')).toBe(false); + + // The reader flips both; the row decides the override, the loader's body decides its own flow. + defaults.draft_contract = true; + defaults.on_absent = true; + expect(engine.refreshPackagedFlowDefaults()).toEqual([]); + expect(isBound('draft_contract')).toBe(false); + expect(isBound('on_absent')).toBe(false); + }); + + it('(L2 N13) a body rolled back from the history reads the default of the set installed now', async () => { + const defaults: Record = { draft_contract: false }; + const { engine } = bootWithLoaderDefaults(defaults); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'v1' }), OVERRIDE); + engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'v2', version: 2 }), OVERRIDE); + const [first] = engine.getFlowVersionHistory('draft_contract').map((h) => h.version); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false }); + + defaults.draft_contract = undefined; + engine.refreshPackagedFlowDefaults(); + engine.rollbackFlow('draft_contract', first); + expect(((await engine.getFlow('draft_contract')) as { description?: string } | null)?.description).toBe('v1'); + expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true }); + }); +}); + +describe('#34655 (L2 S4) — a hot upgrade that flips the base\'s default reaches an override the mutation sync armed', () => { + const BASE = 'com.acme.crm'; + const FLOW = 'draft_contract'; + /** The pair's declared override, as the protocol's view serves it in the base's slot. */ + const served = (label: string) => + packagedFlow(FLOW, { label, _packageId: BASE, overrides: { package: BASE, basedOn: '1.0.0' } }); + + /** + * The automation plugin over a protocol stand-in: the view serves the + * override, the loader's set holds the base's own body with `baseDefault`, + * and the test raises the mutation signal and `metadata:reloaded`. No + * activation ledger: no row decides. + */ + async function bootComposition(baseDefault: boolean | undefined) { + const state = { view: [served('OVERRIDE')], baseDefault }; + const listeners: Array<(evt: { type: string; name: string; state: string; organizationId?: string | null }) => void> = []; + const captured: { ctx?: PluginContext } = {}; + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use({ + name: 'fake-composition', + version: '1.0.0', + async init(ctx: PluginContext) { + captured.ctx = ctx; + const register = (ctx as unknown as { registerService(n: string, s: unknown): void }).registerService; + register('objectql', { registry: { listItems: () => [], getObject: () => undefined } }); + register('protocol', { + packagedArtifactOwner: (r: { type: string; name: string }) => (r.type === 'flow' && r.name === FLOW ? BASE : undefined), + shippedArtifactsOf: (type: string, name: string) => + type === 'flow' && name === FLOW + ? [packagedFlow(FLOW, { + label: 'BASE', + _packageId: BASE, + ...(state.baseDefault === undefined ? {} : { defaultActive: state.baseDefault }), + })] + : [], + async getMetaItemsForExecution(q: { type: string }) { + return { items: q.type === 'flow' ? state.view : [] }; + }, + onMetadataMutation(listener: (typeof listeners)[number]) { + listeners.push(listener); + return () => listeners.splice(listeners.indexOf(listener), 1); + }, + }); + }, + } as Plugin); + kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' })); + await kernel.bootstrap(); + const engine = kernel.getService('automation'); + const recordChange = recordingTrigger('record_change'); + engine.registerTrigger(recordChange.trigger); + const armedLabel = async () => ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label; + return { + kernel, + engine, + isBound: recordChange.isBound, + registrations: () => engine.getFlowVersionHistory(FLOW).length, + /** A direct active save of the override (no reload): the mutation sync arms it and marks its slot. */ + async saveOverride(label: string) { + state.view = [served(label)]; + listeners.forEach((l) => l({ type: 'flow', name: FLOW, state: 'active', organizationId: null })); + await vi.waitFor(async () => expect(await armedLabel()).toBe(label)); + }, + /** A hot upgrade of the base package: its own body's declaration moves, then the reload. */ + async upgradeBase(next: boolean | undefined) { + state.baseDefault = next; + await captured.ctx!.trigger('metadata:reloaded', { changed: [`app/${BASE}`] }); + }, + }; + } + + it('the base moves from on to off: the override stops', async () => { + const c = await bootComposition(undefined); + try { + await c.saveOverride('OVERRIDE-2'); + expect(c.isBound(FLOW)).toBe(true); + const registrations = c.registrations(); + + await c.upgradeBase(false); + expect(c.registrations(), 'the re-sync kept the body the mutation sync armed').toBe(registrations); + expect(c.isBound(FLOW)).toBe(false); + expect(stateOf(c.engine, FLOW)).toMatchObject({ enabled: false }); + expect((await c.engine.execute(FLOW)).code).toBe('FLOW_DISABLED'); + } finally { + await c.kernel.shutdown(); + } + }); + + it('the base moves from off to on: the override starts', async () => { + const c = await bootComposition(false); + try { + await c.saveOverride('OVERRIDE-2'); + expect(c.isBound(FLOW)).toBe(false); + const registrations = c.registrations(); + + await c.upgradeBase(true); + expect(c.registrations(), 'the re-sync kept the body the mutation sync armed').toBe(registrations); + expect(c.isBound(FLOW)).toBe(true); + expect(stateOf(c.engine, FLOW)).toMatchObject({ enabled: true, bound: true }); + expect((await c.engine.execute(FLOW)).success).toBe(true); + } finally { + await c.kernel.shutdown(); + } + }); + + it('CONTROL: a reload that leaves the base\'s declaration as it was moves nothing', async () => { + const c = await bootComposition(false); + try { + await c.saveOverride('OVERRIDE-2'); + const registrations = c.registrations(); + + await c.upgradeBase(false); + expect(c.registrations()).toBe(registrations); + expect(c.isBound(FLOW)).toBe(false); + expect((await c.engine.execute(FLOW)).code).toBe('FLOW_DISABLED'); + } finally { + await c.kernel.shutdown(); + } + }); +}); + +describe('#34655 — packagedFlowDefaultReader reads the package\'s own body off the loader\'s set', () => { + const ctxWith = (protocol: unknown) => ({ + getService: (name: string) => { + if (name !== 'protocol' || protocol === undefined) throw new Error(`service '${name}' not found`); + return protocol as never; + }, + }); + + it("answers the declaration of THAT package's body, not another shipper's", () => { + const shippedArtifactsOf = vi.fn(() => [ + { name: 'draft_contract', _packageId: 'other', defaultActive: true }, + { name: 'draft_contract', _packageId: 'crm', defaultActive: false }, + ]); + const read = packagedFlowDefaultReader(ctxWith({ shippedArtifactsOf })); + expect(read('draft_contract', 'crm')).toBe(false); + expect(read('draft_contract', 'other')).toBe(true); + expect(shippedArtifactsOf).toHaveBeenCalledWith('flow', 'draft_contract'); + }); + + it('CONTROL: no declaration, no such body, a non-boolean, no protocol or no reader answer none', () => { + const read = packagedFlowDefaultReader(ctxWith({ + shippedArtifactsOf: (_type: string, name: string) => + [{ name: 'f', _packageId: 'crm' }, { name: 'g', _packageId: 'crm', defaultActive: 'no' }].filter((a) => a.name === name), + })); + expect(read('f', 'crm')).toBeUndefined(); + expect(read('f', 'other')).toBeUndefined(); + expect(read('g', 'crm')).toBeUndefined(); + expect(packagedFlowDefaultReader(ctxWith(undefined))('f', 'crm')).toBeUndefined(); + expect(packagedFlowDefaultReader(ctxWith({}))('f', 'crm')).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/flow-definitions.ts b/packages/services/service-automation/src/flow-definitions.ts index d82d74740f6..8515f70b491 100644 --- a/packages/services/service-automation/src/flow-definitions.ts +++ b/packages/services/service-automation/src/flow-definitions.ts @@ -471,7 +471,7 @@ export function withdrawFlow(this: Pick): Promise { +export async function hydrateFlowActivations(this: Pick): Promise { if (!this.flowActivationStore) return []; const rows = await this.flowActivationStore.list(); const disabled: string[] = []; @@ -506,7 +506,23 @@ export async function hydrateFlowActivations(this: Pick, + this: Pick, { advisory }: { advisory: boolean }, ): ReadonlyArray<(flowName: string, flow: FlowParsed) => RegistrationCheckRefusal | undefined> { return [ @@ -253,6 +254,11 @@ export function registrationChecks( // save for the whole backoff ladder. Refused here, naming the node // and the background path. A plain function: it reads no engine state. (flowName, flow) => validateAfterSaveInlineRetry(flowName, flow), + // [#34655, ADR-0126 §4] `defaultActive` is the default of the + // packaged-flow switch, so a flow no package ships may not declare + // it: its switch is its own `status`. Judged by name against the + // loader's set, the question the toggle door asks. + (flowName, flow) => this.refuseUnpackagedDefaultActive(flowName, flow), ]; } diff --git a/packages/services/service-automation/src/index.ts b/packages/services/service-automation/src/index.ts index 96aa8405848..ae3a4156997 100644 --- a/packages/services/service-automation/src/index.ts +++ b/packages/services/service-automation/src/index.ts @@ -74,6 +74,9 @@ export type { // method is barrel-reachable, so a host building a custom composition // needs the name to hand it the loader's set. PackagedFlowSource, + // [#34655] The reader `AutomationEngine.setPackagedFlowDefaultSource` + // takes, for the same reason: the package's own `defaultActive`. + PackagedFlowDefaultSource, // [ADR-0150 D3] The reader `AutomationEngine.setFlowNameResolver` takes — // barrel-reachable through that method, for a host composing its own // registry over the one package-scoped resolver. diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 172ba8ca75a..02ab3709496 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -1465,6 +1465,32 @@ export function packagedFlowReader(ctx: Pick): (nam }; } +/** + * [#34655, ADR-0126 §4] The engine's reader over the BODIES the loader's set + * holds: the `defaultActive` package `packageId`'s own flow `name` declares, + * through the protocol's `shippedArtifactsOf` (the every-shipper read + * `packagedFlowReader` judges a package's own question by, and reached the + * same way, by duck type at question time). `undefined` when the package's + * body declares none, when the protocol cannot be asked, and when the set + * holds no body of that package: the flow then ships on, as every packaged + * flow did before the key. + */ +export function packagedFlowDefaultReader(ctx: Pick): (name: string, packageId: string) => boolean | undefined { + return (name, packageId) => { + let protocol: { shippedArtifactsOf?: (type: string, name: string) => unknown[] } | undefined; + try { + protocol = ctx.getService('protocol'); + } catch { + return undefined; + } + if (typeof protocol?.shippedArtifactsOf !== 'function') return undefined; + const own = protocol.shippedArtifactsOf('flow', name) + .find((artifact) => (artifact as { _packageId?: unknown } | null)?._packageId === packageId); + const declared = (own as { defaultActive?: unknown } | undefined)?.defaultActive; + return typeof declared === 'boolean' ? declared : undefined; + }; +} + /** * [ADR-0150 D3] The engine's reader over the one package-scoped resolver: * `resolvePackageScopedName` from `@objectstack/objectql`, asked of the @@ -2280,6 +2306,10 @@ export class AutomationServicePlugin implements Plugin { // its locked-base verdict reads — never the stamps on a definition. // See `packagedFlowReader`. this.engine.setPackagedFlowSource(packagedFlowReader(ctx)); + // [#34655, ADR-0126 §4] The default a package's own flow declares, + // read off the loader's body, so a `.custom` override armed in its + // place does not move it. See `packagedFlowDefaultReader`. + this.engine.setPackagedFlowDefaultSource(packagedFlowDefaultReader(ctx)); // [ADR-0150 D3] Which item a bare flow name means, for a caller of a // package or of none, is the one package-scoped resolver's answer over @@ -6186,6 +6216,14 @@ export class AutomationServicePlugin implements Plugin { } } this.syncedFlowNames = freshNames; + // [#34655, L2 S4] A reload may have changed the loader's set (a hot + // upgrade of a base package), and the loop above keeps some bodies it + // did not re-register: a winner the mutation sync armed from this same + // stored row, and one whose re-registration threw. A declared + // override's stored body does not change with its base, so the + // package default the engine read for it must be read again here, not + // only when a body is registered. + this.engine.refreshPackagedFlowDefaults(); // [#21725] Every mark is spent: from here on this re-sync's // registrations are the ones the engine holds. this.mutationArmedFlows.clear(); diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 00dc072a003..3019499f8f7 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -384,6 +384,7 @@ "api/CreateFlowRequest:_packageId", "api/CreateFlowRequest:_packageVersion", "api/CreateFlowRequest:_provenance", + "api/CreateFlowRequest:defaultActive", "api/CreateFlowRequest:description", "api/CreateFlowRequest:edges", "api/CreateFlowRequest:errorHandling", diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index 7fe59977225..b63428f4a1a 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -191,6 +191,7 @@ "automation/Flow:_packageId", "automation/Flow:_packageVersion", "automation/Flow:_provenance", + "automation/Flow:defaultActive", "automation/Flow:description", "automation/Flow:edges", "automation/Flow:errorHandling", diff --git a/packages/spec/liveness/flow.json b/packages/spec/liveness/flow.json index 0291e4bc1ee..b7f31c04bf1 100644 --- a/packages/spec/liveness/flow.json +++ b/packages/spec/liveness/flow.json @@ -40,6 +40,12 @@ "evidence": "packages/services/service-automation/src/engine.ts#registerFlow (`this.flowStatusDisabled.set(name, flowStatus === 'obsolete' || flowStatus === 'invalid')` — the authoring state is read ONCE, at registration); packages/services/service-automation/src/engine.ts#isFlowEnabled (composes that bit with the durable ledger bit; every trigger and execute path asks this one predicate)", "note": "RE-VERIFIED 2026-07 (#3686 preview-claim sweep): the prior `live` verdict cited only a metadata-admin PREVIEW panel, which echoes what the author typed. Verdict stands, evidence replaced: it is genuinely engine-consumed since 497bda853. The previously cited FlowPreview line number did not even contain a status read. 2026-08-28: RE-ANCHORED (commit 8f10a79f7) and REPOINTED — the sharpest in-range rot in this batch. The parsable half of the citation, `:1382`, had come to rest on `private flowLedgerDisabled = new Set();` — the ADJACENT map, not this key's — while commit 15249270f had meanwhile SPLIT the single `flowEnabled` map into `flowStatusDisabled` (this key) and `flowLedgerDisabled` (the durable toggle), composed by `isFlowEnabled`. A pointer landing on a plausible line in the right class is the failure mode a line bound cannot reach. The other three positions (`:1387`, `:1704`, `:3097`) were bare line suffixes with no path and resolved to nothing at all. Re-closed by hand against 8cb96ec41." }, + "defaultActive": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidence": "packages/services/service-automation/src/flow-activation-projection.ts#FlowActivationProjection (`has` falls back to the `shipsOff` reader when no activation-ledger row decides; the engine wires that reader to the armed body's `defaultActive === false`); packages/services/service-automation/src/engine.ts#isFlowEnabled (every trigger and execute path asks this one predicate); packages/services/service-automation/src/engine.ts#refuseUnpackagedDefaultActive (refused on a flow no package ships)", + "note": "#34655 (ADR-0126 §4 amendment note): the default of the packaged-flow switch. A ledger row (an administrator's toggle) wins over it in either state; with no row the flow follows the armed body's declaration. A clone drops it (packages/runtime/src/flow-clone.ts FLOW_CLONE_DROPPED_KEYS) and an unmanaged install copies `false` as `status: 'obsolete'` (packages/metadata-protocol/src/package-unmanaged-install.ts copyUnmanagedFlowSwitch)." + }, "runAs": { "status": "live", "proof": "packages/qa/dogfood/test/flow-runas.dogfood.test.ts#flow-runas-identity", diff --git a/packages/spec/liveness/state-counts/flow.md b/packages/spec/liveness/state-counts/flow.md index b1518465765..b607b895de5 100644 --- a/packages/spec/liveness/state-counts/flow.md +++ b/packages/spec/liveness/state-counts/flow.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `flow` | 41 | 0 | 0 | 0 | 2 | 43 | +| `flow` | 42 | 0 | 0 | 0 | 2 | 44 | diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index 8ee39653e71..d1a044400d7 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -33,7 +33,12 @@ import { DroppedFieldsEventSchema } from '../data/data-engine.zod'; * there. Its switch is its own `status`: `'obsolete'` disarms it and * `'active'` arms it, published with the complete definition through * `PUT /api/v1/automation/:name`. The toggle door refuses such a flow with - * 409 `RESOURCE_CONFLICT`, names that switch, and changes nothing. + * 409 `RESOURCE_CONFLICT`, names that switch, and changes nothing. It refuses + * the same way a switch ON of a packaged flow whose own `status` disables it + * (`'obsolete'` / `'invalid'`): the ledger row alone would leave the flow off + * while the caller read it as on, so it answers 409 `RESOURCE_CONFLICT`, + * names publishing the definition `'active'`, and writes nothing. A switch + * OFF of such a flow is accepted and records the choice. * * @example Endpoints * ``` diff --git a/packages/spec/src/automation/flow-default-active-34655.test.ts b/packages/spec/src/automation/flow-default-active-34655.test.ts new file mode 100644 index 00000000000..ecba6256702 --- /dev/null +++ b/packages/spec/src/automation/flow-default-active-34655.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import { FlowSchema } from './flow.zod'; + +// [#34655, ADR-0126 §4 amendment] `defaultActive` — the default of the +// packaged-flow switch. Optional with no materialized default, so a flow that +// does not declare it parses exactly as before the key. + +const base = { + name: 'draft_contract', + label: 'Draft contract', + type: 'record_change' as const, + status: 'active' as const, + nodes: [{ id: 'start', type: 'start', label: 'Start', config: { objectName: 'quote', triggerType: 'record-after-update' } }], + edges: [], +}; + +describe('FlowSchema.defaultActive (#34655)', () => { + it('accepts `false` and `true` and keeps the declared value', () => { + expect(FlowSchema.parse({ ...base, defaultActive: false }).defaultActive).toBe(false); + expect(FlowSchema.parse({ ...base, defaultActive: true }).defaultActive).toBe(true); + }); + + it('CONTROL: a flow that does not declare it parses with no `defaultActive` key at all', () => { + const parsed = FlowSchema.parse(base); + expect(parsed).not.toHaveProperty('defaultActive'); + }); + + it('refuses a value that is not a boolean, at the key', () => { + const result = FlowSchema.safeParse({ ...base, defaultActive: 'off' }); + expect(result.success).toBe(false); + expect(result.error?.issues.map((i) => i.path.join('.'))).toEqual(['defaultActive']); + }); +}); diff --git a/packages/spec/src/automation/flow.zod.ts b/packages/spec/src/automation/flow.zod.ts index 33b7f8b04ad..18cec6b4649 100644 --- a/packages/spec/src/automation/flow.zod.ts +++ b/packages/spec/src/automation/flow.zod.ts @@ -1167,6 +1167,42 @@ export const FlowSchema = lazySchema(() => strictObject( /** Metadata & Versioning */ version: z.number().int().default(1).describe('Version number'), status: z.enum(['draft', 'active', 'obsolete', 'invalid']).default('draft').describe('Deployment status'), + /** + * [#34655, ADR-0126 §4] Whether a flow a PACKAGE ships starts switched on + * where it is installed. `false` ships it switched OFF: on an installation + * whose administrator has never switched it, it is not armed and does not + * run, and an administrator turns it on with the packaged-flow switch + * (`POST /api/v1/automation/:name/toggle`, Studio's Enabled switch on a + * read-only package's flow). Absent or `true`: on, as every packaged flow + * has always been. + * + * This is the default of the installation's switch, not a second switch. + * The switch's state is the activation ledger (`sys_metadata_activation`): + * a row there is an administrator's choice and wins over this key, so a + * flow an administrator turned on stays on across a restart, an upgrade + * and a reinstall, and one turned off stays off. (An "on" row counts only + * when it names the package that holds the flow now; a legacy row naming no + * package, or one naming a package that no longer holds it, leaves a flow + * shipped off switched off.) With no row the flow follows this key, so a + * later version of the package that changes it moves an installation + * nobody switched. + * + * The default is the PACKAGE's: the key is read off the package's own body. + * A declared `.custom` override armed in the package's place does not + * change it in either direction, whatever the override declares; it is + * switched by the same switch. + * + * `status` stays the AUTHOR's: `obsolete` / `invalid` disarm the flow for + * every installation, and no switch overrides that. Ship a flow an + * administrator may turn on as `status: 'active', defaultActive: false`. + * + * Only a flow a package ships has that switch. A flow authored in the + * environment is switched by its `status`: registering one that declares + * `defaultActive` is refused, a dry run of one is refused, and the stored + * pass lists a stored one. A clone of a packaged flow drops the key, and an + * unmanaged install copies `defaultActive: false` as `status: 'obsolete'`. + */ + defaultActive: z.boolean().optional().describe('Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator\'s choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author\'s switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key.'), /** Trigger Type */ type: z.enum(['autolaunched', 'record_change', 'schedule', 'screen', 'api']).describe('Flow type'), diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 2c198f73171..40b387602a9 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1974,7 +1974,12 @@ export interface IAutomationService { * (ADR-0126 §7.2). A flow authored in the deployment is not this switch's: * the automation service refuses it with `RESOURCE_CONFLICT` / 409 and * changes nothing. That flow's switch is its own `status` (`'obsolete'` / - * `'active'`), published through {@link registerFlow}. + * `'active'`), published through {@link registerFlow}. A packaged flow + * whose own `status` disables it (`'obsolete'` / `'invalid'`) is refused + * the same way when switched ON — `RESOURCE_CONFLICT` / 409, nothing + * written — because the ledger row alone would leave it off while the + * caller read it as on; publishing its definition `'active'` arms it. + * Switching such a flow OFF is accepted and records the choice. * * `caller` names who made the request, so the activation-ledger row the * switch writes, and the audit row that write produces, attribute it to diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index a8c74bb6597..4af17854fbe 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -816,6 +816,14 @@ const LEDGER: ReadonlyArray = [ key: 'overrides', why: 'declared, not enforced yet — liveness verdict `planned`: the override declaration (ADR-0146 D2) parses, is stored and travels through export, but no door admits or serves it until the write gate and the effective read land. Studio writes it when it saves a customization into `.custom`; a hand-filled control is not how it is authored', }, + // #34655 — the default of the packaged-flow switch (ADR-0126 §4 amendment). + { + kind: 'omit', + type: 'flow', + path: ROOT_PATH, + key: 'defaultActive', + why: "a package's declaration, refused on every flow this form saves — the schema says a flow authored in the environment is switched by `status` and may not declare this key. The automation engine refuses it at registration on a flow no installed package ships, which is every flow the form writes, so a control would offer a value the save door always rejects. Like `skill.mcpPrompt`, its meaning also lives in its absence (unset ships the flow on, with no schema default), which a switch would draw as off. Authored in package source; an administrator's on/off for a packaged flow is the activation toggle, not this key", + }, { kind: 'omit', type: 'email_template', diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 726d77d9c9e..b83e0b1a685 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -634,7 +634,24 @@ export const CEILINGS = new Map([ // priced text is 27611 bytes -> ceil(27611 / 4) = 6903; the ceiling moves +42, // the measured remainder only. Pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(27611 / 4) - ['skills/objectstack-automation/SKILL.md', 6903], + // 6903 -> 6992 (2026-11-17, card #34655, its Done-when "Document it in the + // automation skill", ruled into the same PR by the area): one paragraph under + // "A flow an installed package ships" teaches `defaultActive: false` — the + // flow ships unarmed (`_status` `enabled: false`) until an administrator turns + // the packaged-flow switch on, that choice outlives restart / upgrade / + // reinstall, `status: 'obsolete'` disarms past the switch, and a flow + // authored in the deployment is refused the key. Raise path the standing + // ruling 「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B). + // NOTHING PAID DOWN: the file was read whole for a restatement of the + // activation switch, its default or `status` as a switch and none exists — + // the paragraph points at the switch the preceding paragraph introduces + // rather than restating it. Arithmetic in priced bytes (stamp line + // excluded), against `main`'s 27611 (headroom 0): the diff adds 357 bytes + // and removes none, so the LANDED priced text is 27968 bytes -> + // ceil(27968 / 4) = 6992; the ceiling moves +89, the measured addition only. + // Pinned AT the measurement. + // ceil(($(wc -c < skills/objectstack-automation/SKILL.md) - 20) / 4) == ceil(27968 / 4) + ['skills/objectstack-automation/SKILL.md', 6992], // 13783 -> 13892 (2026-08-31 app-repo-principles raise, see the block above). // The invariant-vs-transition-gate choice, placed in the field-conditional-rule // bullet list where the tool is actually picked. Both wrong picks are silent: diff --git a/skills/objectstack-automation/SKILL.md b/skills/objectstack-automation/SKILL.md index 8144f0f9378..3fec47e76a8 100644 --- a/skills/objectstack-automation/SKILL.md +++ b/skills/objectstack-automation/SKILL.md @@ -56,6 +56,12 @@ A flow *beside* it is "new similar": `POST /api/v1/automation/:name/clone` package-less; a flow holding a `secret` / `signingSecret` is refused (`409`): author it anew. +A package ships a flow **switched off** with `defaultActive: false` (beside +`status: 'active'`): unarmed (`_status` `enabled: false`) until an administrator +turns that switch on, which then outlives restart, upgrade and reinstall. +`status: 'obsolete'` disarms past the switch; a flow authored in the deployment +is refused the key (its switch is `status`). + ### Flow Node Types Built-in (plugins register more): diff --git a/skills/objectstack-automation/evals/flows-triggers-approvals.json b/skills/objectstack-automation/evals/flows-triggers-approvals.json index 71a8c84a220..0b28e98650d 100644 --- a/skills/objectstack-automation/evals/flows-triggers-approvals.json +++ b/skills/objectstack-automation/evals/flows-triggers-approvals.json @@ -420,6 +420,21 @@ "STACK_TRIGGER_CAPABILITY_REQUIRED" ] } + }, + { + "id": 24, + "prompt": "Our `crm` package adds a `record-after-update` flow on `crm_quote` that drafts a contract once a quote is accepted. Some customers will want it, others not, so it must arrive switched off and an administrator should be able to turn it on per deployment, and keep it on through our later upgrades. How do I declare that?", + "expected_output": "Declare `defaultActive: false` on the flow, beside `status: 'active'`. On an installation where no administrator has switched it, the flow is not armed and does not run (`GET /api/v1/automation/_status` reports `enabled: false`). An administrator turns it on with the packaged-flow switch, `POST /api/v1/automation/:name/toggle` with `{ enabled: true }`; that choice wins over the declared default and survives a restart, an upgrade and a reinstall. Not `status: 'obsolete'`, which disarms the flow everywhere and which the switch does not override, and not a flow the deployment authors itself, which is refused the key (its switch is its `status`).", + "files": [], + "assertions": { + "must_contain": [ + "defaultActive: false", + "toggle" + ], + "must_not_contain": [ + "isActive" + ] + } } ] }