From 3a0f5b8a70e143994a82dc58218d34027ca0cd8e Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 30 Sep 2026 02:31:21 +1000 Subject: [PATCH] docs(eda): ratify args evaluation-failure semantics (J6) An args value that cannot be evaluated aborts its playbook run: the action and every later action in that playbook do not run, other playbooks matching the event still run, and the task is unaffected. J3's skip-and-continue rule stays specific to `when`, because a predicate has a meaningful false and data does not. Ratified now that the action runner is the production consumer, and locked by a call-site test that fails if the rule is weakened to a skip. Drop the stale "unbuilt decisions" header line, since J1, J2 and the Result schema declarations have shipped. --- docs/data/generated/dev-docs.json | 2 +- docs/prds/playbook-expression-syntax.md | 11 ++++++-- internal/domain/eda/playbook/playbook.go | 4 +-- internal/domain/eda/playbook/run_test.go | 35 ++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 6 deletions(-) diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index 085903101..72253cb22 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -406,7 +406,7 @@ "url": "/dev/prds/playbook-expression-syntax/", "title": "Playbook data-flow and condition syntax", "section": "PRDs", - "body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\nUnbuilt decisions: `archie-core-t2db.25` (J1 action ids),\n`archie-core-t2db.26` (J2 args as CEL),\n`archie-core-t2db.27` (Result schemas declared to CEL).\n\n**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression\nmechanism covers both an action's `when` condition and its `args` values.\n\n## The requirement, stated directly\n\nA playbook action is gated and parametrised by runtime data: (a) a condition\ndeciding whether the action runs; (b) a later action's `args` values referencing\nan earlier action's `Result` and the triggering event's fields. Both are **CEL\nexpressions**, evaluated against one evaluation context. There is no separate\ninterpolation syntax: CEL reads nested maps and fields natively, so `args`\nvalues that need data are written as CEL, and only plain literal args remain\nplain YAML scalars.\n\nBoth halves are read-only: expressions may read context values and compute a\nresult from them, never mutate, never call host functions, never perform I/O.\nCEL enforces this structurally (no side effects, linear evaluation when macros\nare bounded, cost-limited).\n\n```yaml\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build finished\"' # literal\n when: 'event.label == \"bugfix\"' # gate on event field\n - position: module\n kind: log\n args:\n message: '\"done: \" + string(actions.build.result.written)'\n when: \"actions.build.result.written == true\"\n```\n\n## Trust boundary of the expression\n\nA playbook YAML is **operator-installed, in-process, daemon-privileged** -- the\nsame tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's\ntrust-boundary section): loaded from a configured directory at startup, never\nfrom a webhook body or task worktree. The schema-by-example flow uses live\nevents to _design against_; the saved playbook is operator-authored file content\nin an operator-configured location.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not attacker\n input; no sandboxing against a hostile expression string is required. If a\n future playbook source is less trusted (auto-generated bindings from\n unauthenticated captures), that is the playbook-file trust tier moving -- the\n loader's acceptance check is the right place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook body, prior\n results through the same pipeline). Robustness against hostile data is\n required: no panic on wrong-typed/missing fields, no unbounded cost on\n deep/cyclic maps, bounded evaluation time. CEL provides this structurally\n (cost limits, linear non-Turing-complete evaluation, error values instead of\n panics -- verified in the vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)\nas the repo's conditional-logic precedent. That is the wrong precedent for\nplaybook conditions because this document's premise is: **YAML is pure\norchestration data; Yaegi is where imperative logic lives** (Problem section;\nmodule-position.md's \"no generic hook\" section). Yaegi snippets in YAML would\nmove imperative logic into the data layer -- the inversion this design exists to\nprevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data, not\nprograms**. CEL is non-Turing-complete and side-effect-free, so it cannot become\na program; a condition that needs real logic gets a Module kind (Yaegi),\nreferenced by the action, not a stronger expression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an `any`\npayload; it exists to keep static implementation contracts typed. Evaluating CEL\nagainst runtime `map[string]any` is **not the same problem**: the rule concerns\n_implementation contracts_ (static operations a capability family exposes), not\n_runtime data values_ (legitimately dynamic -- an event payload's shape is\nunknown until it arrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the playbook\nengine family, not a new capability contract. Stated once.\n\n## Minimum viable evaluation context (what expressions see)\n\nOne flat context, namespaced from the playbook run, built at dispatch time:\n\n| Name | Type | Source |\n| --------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `event` | `map(string, dyn)` | The triggering event's decoded payload (webhook body / forge issue / schedule tick). Field access via `event.\u003cfield\u003e`, map access via `event[\"field\"]`, presence via `has(event.\u003cfield\u003e)`. |\n| `actions` | per-playbook object type | Previous actions' results, one field per declared action `id` (`actions.\u003cid\u003e`), each field typed `{ result: \u003cKindResult\u003e }` so a later action reads an earlier one's `Result` struct (`actions.\u003cid\u003e.result.\u003cfield\u003e`) with field-level checking. The current action and later actions are not present. |\n\nExpressions may also read literal-only state (numbers, strings, booleans)\ndirectly. CEL's `has()` macro covers the missing-key case (`has(event.labels)`\n-\u003e bool), which replaces any bespoke `has`/ `contains` operator.\n\n`actions.\u003cid\u003e.result` is the kind's hand-written `Result` struct:\n`ModuleRegistry.DecodeResult` converts `Module.Invoke`'s flat `map[string]any`\n(`archie-core-t2db.13`) back into that struct before a later expression reads\nit, so the checker and the run read the same typed value.\n\nJudgement call J1: `action` id is a required field on every action that later\nactions reference; ids are validated at load (unique, stable-identifier-shaped),\nand a `when`/`args` expression referencing an unknown `actions.\u003cid\u003e` is a **load\nfailure**, not a runtime miss -- the same reject-at-load rule as collisions (see\nbelow).\n\n## Load-time validation (consistent with the collision rule)\n\nThe collision-handling rule is: schema defines the accepted message; anything\noutside it is rejected at load, logged plainly, reported to the caller -- never\ndeferred to runtime. Expressions are validated the same way, at playbook load:\n\n- **Syntax**: every `when` and every CEL-typed `args` value is parsed and\n checked by CEL's checker when the playbook is loaded. A syntax or type error\n is a reported load failure (the playbook is dropped and the error goes to the\n caller), not a runtime surprise.\n- **Context conformance**: with the context declared to CEL (`event` as\n `map(string, dyn)`, `actions` as a per-playbook object type with one typed\n field per declared id), unknown top-level identifiers are rejected at compile\n time. Field-level typing inside `dyn` values is deferred to runtime by CEL's\n design (verified: `data.items.lenght` with `data` dyn compiles clean and\n errors at eval) -- so the loader declares as much type as the schema provides\n (the action kinds' generated `Result` structs become CEL type declarations at\n load, giving field-level rejection for result reads), and `event` stays `dyn`\n because its shape is unknown by design (schema-by-example).\n- **Names**: unknown `actions.\u003cid\u003e` references and unknown roots are\n compile-time/lint-visible errors (J1).\n\nThis means the lint tool and the daemon share one checker -- same single-source\nargument as the playbook loaders.\n\n## Candidate comparison\n\n| Candidate | Maintenance | Safety surface | Cost (measured) | Verdict |\n| ------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------ |\n| **CEL (cel.dev/cel-go)** | Actively maintained (google/cel, monthly releases) | Non-Turing-complete, linear eval, `CostLimit`/`CostTracking`/`ParserRecursionLimit`, no side effects, error values not panics | **+13.0MB** (2.34MB -\u003e 15.25MB) | **Chosen** |\n| `expr-lang/expr` v1.17.8 | Actively maintained | Side-effect-free, `DisableAllBuiltins`, depth limits (CVE fixed w/ tests) | +3.9MB (2.34MB -\u003e 6.28MB) | Not chosen: two safety CVEs this cycle; smaller ecosystem; no protobuf/type-model fit with future schema-gen |\n| `gval` v1.2.3 | Maintained, slower | No builtin-restriction surface; extras (ternary/`??`) not wanted | +3.0MB (2 transitive deps) | Not chosen |\n| `govaluate` | **ARCHIVED** (author archived 2024) | n/a | n/a | Not chosen: dead |\n| `starlark-go` | Maintained (Bazel) | Turing-complete with step limits | large (full language) | Not chosen: whole-language surface |\n\n## Vetting record\n\nSource reviewed at HEAD:\n\n- **Repo hygiene**: clean. No binaries/media in tree (the only non-source\n artifacts are expected generated protobuf files); 16-line `.gitignore`.\n- **Hard-boundary correctness**: the place correctness is hard for an expression\n evaluator is bounding evaluation and surviving hostile input. Dedicated\n regression tests exist and pass at HEAD: `TestCostLimit`, `TestCostTracking*`,\n `TestParserRecursionLimit`, and a large conformance suite. Verified by\n execution: evaluation against a 2000-deep nested map under `CostLimit`\n completes in ~10 microseconds and returns an error value for a missing key --\n no panic, no unbounded walk.\n- **Dependency footprint**: antlr (parser), protobuf + genproto (CEL's type\n model), `cel.dev/expr` (CEL spec types), yaml.v3. All mainstream, canonical,\n vendored widely by Google-adjacent projects. No runtime-impure third-party\n code; the REPL-only deps (readline, tview, tcell) are not in the library\n import graph.\n- **Security record**: no advisories on record for `cel.dev/cel-go` (GitHub\n Advisory Database).\n- **Module path**: migrated to `cel.dev/cel-go` (v0.32.0 is current); the old\n `cel.dev/cel-go/cel` path is the pre-migration identity. Pin `cel.dev/cel-go`.\n- **Binary size cost**: +13.0MB is the largest of the candidates (measured:\n baseline 2.34MB -\u003e 15.25MB with CEL). Accepted because: the daemon already\n embeds a large Yaegi runtime; CEL's type model is the load-bearing win\n (compile-time rejection of result-path typos, matching the reject-at-load\n rule); and the alternative bespoke grammar would re-implement CEL's checker to\n get the same guarantee. Flagged for sign-off: if 13MB is unacceptable for a\n specific deployment target, the fallback is a bespoke grammar with a\n re-implemented subset of this checker -- a strictly worse trade.\n\n## Why bespoke was not sufficient\n\nA bespoke grammar for the shipped cases (path read + comparison + bool\ncomposition) is small, but the load-time-validation requirement makes the\ncomparison: the reject-at-load rule requires _field-level_ static checking of\nresult paths against generated `Result` schemas, which is CEL's type-checker's\njob. Re-implementing that on a hand-rolled grammar means re-implementing a type\nsystem -- more code than the grammar itself, with worse diagnostics, no\nconformance suite, and no community surface for future expression needs (even\ndeclarative ones). The bespoke option only wins on binary size, and the size\ncost of CEL is measured and bounded.\n\n## Judgement calls (flagged for sign-off)\n\n- **J1 -- `id` required on referenced actions, unknown id = load failure.**\n Matches the reject-at-load rule. Alternative considered: an alternative is\n positional `actions[0]` access, which breaks on reorder; named is the\n operator-friendlier shape.\n- **J2 -- every `args` value is evaluated as a CEL expression.** No split\n between \"literal args\" and \"expression args\": a plain string value is a CEL\n string literal, a number is a CEL number literal, and any value that reads\n context data is written in CEL. One mechanism, no interpolation marker, no\n second syntax to learn. Alternative considered: cEL string literals must be\n quoted inside YAML (e.g. `message: '\"build finished\"'`), which is slightly\n noisy for mostly-literal args; accepted for uniformity -- the linter catches\n quoting mistakes at load.\n- **J3 -- condition failure semantics.** A condition that errors at runtime\n (missing/wrong-typed field) evaluates to **false**: the action is skipped,\n logged, run continues. This is the simplest candidate consistent with gap 1's\n bias against clever recovery; gap 1 (`archie-core-t2db.18`) commits\n stop-on-first-failure, so per-action control is not coming and J3 stands.\n Alternative considered: cEL separates false from error; we treat evaluation\n error as false + log.\n- **J4 -- `event` stays `dyn` (schema-by-example).** Load-time we cannot know\n event field types; declaring them typed would reject valid plays. Result reads\n get field-level checking via generated schema declarations. Alternative\n considered: when schema-by-example ships, tighten event field declarations\n from captured samples.\n- **J5 -- cost limit default.** A `CostLimit` at load time (e.g. 100,000) is\n applied to every expression; the linter and daemon use the same value so they\n agree. Alternative considered: exact number is a constant to tune at first\n use.\n\n## Interaction with the execution-time gaps\n\nThis resolution does not resolve the execution-time gaps (both are resolved\nseparately: gap 1 by `archie-core-t2db.18`, gap 2 by the gap-2 decision).\nConditions make gap 1 concrete (condition-failure vs. action-failure semantics,\nJ3) and CEL's read-only result access makes gap 2's keying derivation readable\n(an idempotency key expression can read event fields) -- both flagged as the\ngaps' first real exercise. Gap 2's exercise is subsequently solved by that\ndecision: the answer is a fixed structural derivation, and idempotency keys are\ndeliberately NOT CEL expressions (see the \"No CEL in the key\" passage).\n\n## Implementation placement (for the follow-up slice)\n\n- New `internal/domain/eda/expr` package: builds the CEL environment (context\n declarations, generated `Result` schema types as CEL type declarations, cost\n limit), compiles/validates playbook expressions at load, evaluates them at\n dispatch. Domain layer; no infrastructure imports; owned by the playbook\n engine family. One new dependency: `cel.dev/cel-go` (pinned), `go.mod`\n otherwise unchanged.\n- Consumption: the playbook event coordinator (open question 4's loader)\n evaluates `when` before dispatch and evaluates `args` values before\n `Module.Invoke`; the lint tool (`archie-core-t2db.12`) shares the same\n compile/validate path for author-time diagnostics.\n- Schema integration: action kinds' generated `Result`/`Args` structs\n (`archie-core-t2db.13`'s `logextract` pattern) are declared to CEL at load so\n `actions.\u003cid\u003e.result.\u003cfield\u003e` type-checks; `args` expressions type-check\n against the target kind's `Args` schema before the playbook is accepted.\n" + "body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\n\n**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression\nmechanism covers both an action's `when` condition and its `args` values.\n\n## The requirement, stated directly\n\nA playbook action is gated and parametrised by runtime data: (a) a condition\ndeciding whether the action runs; (b) a later action's `args` values referencing\nan earlier action's `Result` and the triggering event's fields. Both are **CEL\nexpressions**, evaluated against one evaluation context. There is no separate\ninterpolation syntax: CEL reads nested maps and fields natively, so `args`\nvalues that need data are written as CEL, and only plain literal args remain\nplain YAML scalars.\n\nBoth halves are read-only: expressions may read context values and compute a\nresult from them, never mutate, never call host functions, never perform I/O.\nCEL enforces this structurally (no side effects, linear evaluation when macros\nare bounded, cost-limited).\n\n```yaml\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build finished\"' # literal\n when: 'event.label == \"bugfix\"' # gate on event field\n - position: module\n kind: log\n args:\n message: '\"done: \" + string(actions.build.result.written)'\n when: \"actions.build.result.written == true\"\n```\n\n## Trust boundary of the expression\n\nA playbook YAML is **operator-installed, in-process, daemon-privileged** -- the\nsame tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's\ntrust-boundary section): loaded from a configured directory at startup, never\nfrom a webhook body or task worktree. The schema-by-example flow uses live\nevents to _design against_; the saved playbook is operator-authored file content\nin an operator-configured location.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not attacker\n input; no sandboxing against a hostile expression string is required. If a\n future playbook source is less trusted (auto-generated bindings from\n unauthenticated captures), that is the playbook-file trust tier moving -- the\n loader's acceptance check is the right place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook body, prior\n results through the same pipeline). Robustness against hostile data is\n required: no panic on wrong-typed/missing fields, no unbounded cost on\n deep/cyclic maps, bounded evaluation time. CEL provides this structurally\n (cost limits, linear non-Turing-complete evaluation, error values instead of\n panics -- verified in the vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)\nas the repo's conditional-logic precedent. That is the wrong precedent for\nplaybook conditions because this document's premise is: **YAML is pure\norchestration data; Yaegi is where imperative logic lives** (Problem section;\nmodule-position.md's \"no generic hook\" section). Yaegi snippets in YAML would\nmove imperative logic into the data layer -- the inversion this design exists to\nprevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data, not\nprograms**. CEL is non-Turing-complete and side-effect-free, so it cannot become\na program; a condition that needs real logic gets a Module kind (Yaegi),\nreferenced by the action, not a stronger expression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an `any`\npayload; it exists to keep static implementation contracts typed. Evaluating CEL\nagainst runtime `map[string]any` is **not the same problem**: the rule concerns\n_implementation contracts_ (static operations a capability family exposes), not\n_runtime data values_ (legitimately dynamic -- an event payload's shape is\nunknown until it arrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the playbook\nengine family, not a new capability contract. Stated once.\n\n## Minimum viable evaluation context (what expressions see)\n\nOne flat context, namespaced from the playbook run, built at dispatch time:\n\n| Name | Type | Source |\n| --------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `event` | `map(string, dyn)` | The triggering event's decoded payload (webhook body / forge issue / schedule tick). Field access via `event.\u003cfield\u003e`, map access via `event[\"field\"]`, presence via `has(event.\u003cfield\u003e)`. |\n| `actions` | per-playbook object type | Previous actions' results, one field per declared action `id` (`actions.\u003cid\u003e`), each field typed `{ result: \u003cKindResult\u003e }` so a later action reads an earlier one's `Result` struct (`actions.\u003cid\u003e.result.\u003cfield\u003e`) with field-level checking. The current action and later actions are not present. |\n\nExpressions may also read literal-only state (numbers, strings, booleans)\ndirectly. CEL's `has()` macro covers the missing-key case (`has(event.labels)`\n-\u003e bool), which replaces any bespoke `has`/ `contains` operator.\n\n`actions.\u003cid\u003e.result` is the kind's hand-written `Result` struct:\n`ModuleRegistry.DecodeResult` converts `Module.Invoke`'s flat `map[string]any`\n(`archie-core-t2db.13`) back into that struct before a later expression reads\nit, so the checker and the run read the same typed value.\n\nJudgement call J1: `action` id is a required field on every action that later\nactions reference; ids are validated at load (unique, stable-identifier-shaped),\nand a `when`/`args` expression referencing an unknown `actions.\u003cid\u003e` is a **load\nfailure**, not a runtime miss -- the same reject-at-load rule as collisions (see\nbelow).\n\n## Load-time validation (consistent with the collision rule)\n\nThe collision-handling rule is: schema defines the accepted message; anything\noutside it is rejected at load, logged plainly, reported to the caller -- never\ndeferred to runtime. Expressions are validated the same way, at playbook load:\n\n- **Syntax**: every `when` and every CEL-typed `args` value is parsed and\n checked by CEL's checker when the playbook is loaded. A syntax or type error\n is a reported load failure (the playbook is dropped and the error goes to the\n caller), not a runtime surprise.\n- **Context conformance**: with the context declared to CEL (`event` as\n `map(string, dyn)`, `actions` as a per-playbook object type with one typed\n field per declared id), unknown top-level identifiers are rejected at compile\n time. Field-level typing inside `dyn` values is deferred to runtime by CEL's\n design (verified: `data.items.lenght` with `data` dyn compiles clean and\n errors at eval) -- so the loader declares as much type as the schema provides\n (the action kinds' generated `Result` structs become CEL type declarations at\n load, giving field-level rejection for result reads), and `event` stays `dyn`\n because its shape is unknown by design (schema-by-example).\n- **Names**: unknown `actions.\u003cid\u003e` references and unknown roots are\n compile-time/lint-visible errors (J1).\n\nThis means the lint tool and the daemon share one checker -- same single-source\nargument as the playbook loaders.\n\n## Candidate comparison\n\n| Candidate | Maintenance | Safety surface | Cost (measured) | Verdict |\n| ------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------ |\n| **CEL (cel.dev/cel-go)** | Actively maintained (google/cel, monthly releases) | Non-Turing-complete, linear eval, `CostLimit`/`CostTracking`/`ParserRecursionLimit`, no side effects, error values not panics | **+13.0MB** (2.34MB -\u003e 15.25MB) | **Chosen** |\n| `expr-lang/expr` v1.17.8 | Actively maintained | Side-effect-free, `DisableAllBuiltins`, depth limits (CVE fixed w/ tests) | +3.9MB (2.34MB -\u003e 6.28MB) | Not chosen: two safety CVEs this cycle; smaller ecosystem; no protobuf/type-model fit with future schema-gen |\n| `gval` v1.2.3 | Maintained, slower | No builtin-restriction surface; extras (ternary/`??`) not wanted | +3.0MB (2 transitive deps) | Not chosen |\n| `govaluate` | **ARCHIVED** (author archived 2024) | n/a | n/a | Not chosen: dead |\n| `starlark-go` | Maintained (Bazel) | Turing-complete with step limits | large (full language) | Not chosen: whole-language surface |\n\n## Vetting record\n\nSource reviewed at HEAD:\n\n- **Repo hygiene**: clean. No binaries/media in tree (the only non-source\n artifacts are expected generated protobuf files); 16-line `.gitignore`.\n- **Hard-boundary correctness**: the place correctness is hard for an expression\n evaluator is bounding evaluation and surviving hostile input. Dedicated\n regression tests exist and pass at HEAD: `TestCostLimit`, `TestCostTracking*`,\n `TestParserRecursionLimit`, and a large conformance suite. Verified by\n execution: evaluation against a 2000-deep nested map under `CostLimit`\n completes in ~10 microseconds and returns an error value for a missing key --\n no panic, no unbounded walk.\n- **Dependency footprint**: antlr (parser), protobuf + genproto (CEL's type\n model), `cel.dev/expr` (CEL spec types), yaml.v3. All mainstream, canonical,\n vendored widely by Google-adjacent projects. No runtime-impure third-party\n code; the REPL-only deps (readline, tview, tcell) are not in the library\n import graph.\n- **Security record**: no advisories on record for `cel.dev/cel-go` (GitHub\n Advisory Database).\n- **Module path**: migrated to `cel.dev/cel-go` (v0.32.0 is current); the old\n `cel.dev/cel-go/cel` path is the pre-migration identity. Pin `cel.dev/cel-go`.\n- **Binary size cost**: +13.0MB is the largest of the candidates (measured:\n baseline 2.34MB -\u003e 15.25MB with CEL). Accepted because: the daemon already\n embeds a large Yaegi runtime; CEL's type model is the load-bearing win\n (compile-time rejection of result-path typos, matching the reject-at-load\n rule); and the alternative bespoke grammar would re-implement CEL's checker to\n get the same guarantee. Flagged for sign-off: if 13MB is unacceptable for a\n specific deployment target, the fallback is a bespoke grammar with a\n re-implemented subset of this checker -- a strictly worse trade.\n\n## Why bespoke was not sufficient\n\nA bespoke grammar for the shipped cases (path read + comparison + bool\ncomposition) is small, but the load-time-validation requirement makes the\ncomparison: the reject-at-load rule requires _field-level_ static checking of\nresult paths against generated `Result` schemas, which is CEL's type-checker's\njob. Re-implementing that on a hand-rolled grammar means re-implementing a type\nsystem -- more code than the grammar itself, with worse diagnostics, no\nconformance suite, and no community surface for future expression needs (even\ndeclarative ones). The bespoke option only wins on binary size, and the size\ncost of CEL is measured and bounded.\n\n## Judgement calls (flagged for sign-off)\n\n- **J1 -- `id` required on referenced actions, unknown id = load failure.**\n Matches the reject-at-load rule. Alternative considered: an alternative is\n positional `actions[0]` access, which breaks on reorder; named is the\n operator-friendlier shape.\n- **J2 -- every `args` value is evaluated as a CEL expression.** No split\n between \"literal args\" and \"expression args\": a plain string value is a CEL\n string literal, a number is a CEL number literal, and any value that reads\n context data is written in CEL. One mechanism, no interpolation marker, no\n second syntax to learn. Alternative considered: cEL string literals must be\n quoted inside YAML (e.g. `message: '\"build finished\"'`), which is slightly\n noisy for mostly-literal args; accepted for uniformity -- the linter catches\n quoting mistakes at load.\n- **J3 -- condition failure semantics.** A condition that errors at runtime\n (missing/wrong-typed field) evaluates to **false**: the action is skipped,\n logged, run continues. This is the simplest candidate consistent with gap 1's\n bias against clever recovery; gap 1 (`archie-core-t2db.18`) commits\n stop-on-first-failure, so per-action control is not coming and J3 stands.\n Alternative considered: cEL separates false from error; we treat evaluation\n error as false + log.\n- **J4 -- `event` stays `dyn` (schema-by-example).** Load-time we cannot know\n event field types; declaring them typed would reject valid plays. Result reads\n get field-level checking via generated schema declarations. Alternative\n considered: when schema-by-example ships, tighten event field declarations\n from captured samples.\n- **J5 -- cost limit default.** A `CostLimit` at load time (e.g. 100,000) is\n applied to every expression; the linter and daemon use the same value so they\n agree. Alternative considered: exact number is a constant to tune at first\n use.\n- **J6 -- `args` failure semantics.** An `args` value that cannot be evaluated\n aborts its playbook run: the action and every later action in that playbook do\n not run, because data has no false value to fall back on and an action run\n without its arguments is a silent one. Other playbooks matching the same event\n still run, and the task is unaffected: a playbook run never changes routing.\n The daemon log reports the failure, naming the task, the playbook and the\n action; no task event is written. Alternative considered: mirroring J3,\n rejected because a predicate has a meaningful false and data does not.\n\n## Interaction with the execution-time gaps\n\nThis resolution does not resolve the execution-time gaps (both are resolved\nseparately: gap 1 by `archie-core-t2db.18`, gap 2 by the gap-2 decision).\nConditions make gap 1 concrete (condition-failure vs. action-failure semantics,\nJ3) and CEL's read-only result access makes gap 2's keying derivation readable\n(an idempotency key expression can read event fields) -- both flagged as the\ngaps' first real exercise. Gap 2's exercise is subsequently solved by that\ndecision: the answer is a fixed structural derivation, and idempotency keys are\ndeliberately NOT CEL expressions (see the \"No CEL in the key\" passage).\n\n## Implementation placement (for the follow-up slice)\n\n- New `internal/domain/eda/expr` package: builds the CEL environment (context\n declarations, generated `Result` schema types as CEL type declarations, cost\n limit), compiles/validates playbook expressions at load, evaluates them at\n dispatch. Domain layer; no infrastructure imports; owned by the playbook\n engine family. One new dependency: `cel.dev/cel-go` (pinned), `go.mod`\n otherwise unchanged.\n- Consumption: the playbook event coordinator (open question 4's loader)\n evaluates `when` before dispatch and evaluates `args` values before\n `Module.Invoke`; the lint tool (`archie-core-t2db.12`) shares the same\n compile/validate path for author-time diagnostics.\n- Schema integration: action kinds' generated `Result`/`Args` structs\n (`archie-core-t2db.13`'s `logextract` pattern) are declared to CEL at load so\n `actions.\u003cid\u003e.result.\u003cfield\u003e` type-checks; `args` expressions type-check\n against the target kind's `Args` schema before the playbook is accepted.\n" }, { "url": "/dev/prds/pr-review-agent/", diff --git a/docs/prds/playbook-expression-syntax.md b/docs/prds/playbook-expression-syntax.md index 1d7ce1998..60d1277c2 100644 --- a/docs/prds/playbook-expression-syntax.md +++ b/docs/prds/playbook-expression-syntax.md @@ -4,9 +4,6 @@ **Date:** 2026-09-03 **Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db` **Beads issue:** `archie-core-t2db.14` (expression environment). -Unbuilt decisions: `archie-core-t2db.25` (J1 action ids), -`archie-core-t2db.26` (J2 args as CEL), -`archie-core-t2db.27` (Result schemas declared to CEL). **Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression mechanism covers both an action's `when` condition and its `args` values. @@ -222,6 +219,14 @@ cost of CEL is measured and bounded. applied to every expression; the linter and daemon use the same value so they agree. Alternative considered: exact number is a constant to tune at first use. +- **J6 -- `args` failure semantics.** An `args` value that cannot be evaluated + aborts its playbook run: the action and every later action in that playbook do + not run, because data has no false value to fall back on and an action run + without its arguments is a silent one. Other playbooks matching the same event + still run, and the task is unaffected: a playbook run never changes routing. + The daemon log reports the failure, naming the task, the playbook and the + action; no task event is written. Alternative considered: mirroring J3, + rejected because a predicate has a meaningful false and data does not. ## Interaction with the execution-time gaps diff --git a/internal/domain/eda/playbook/playbook.go b/internal/domain/eda/playbook/playbook.go index 150fc89f6..1f5409747 100644 --- a/internal/domain/eda/playbook/playbook.go +++ b/internal/domain/eda/playbook/playbook.go @@ -735,8 +735,8 @@ func evalContext(input DispatchInput) expr.Context { // // Asymmetry with `when`: `when` is a predicate, so an evaluation error is // false (J3: skip + log); `args` is data, so an evaluation error has no -// meaningful substitute and is returned to the caller to abort the dispatch. -// Ratifying that rule against a real consumer is tracked by archie-core-1h05. +// meaningful substitute and is returned to the caller to abort the playbook run +// (J6, docs/prds/playbook-expression-syntax.md). func (s *Store) EvalArgs(a Action, input DispatchInput) (map[string]any, error) { if s == nil { return map[string]any{}, nil diff --git a/internal/domain/eda/playbook/run_test.go b/internal/domain/eda/playbook/run_test.go index 8d599dfc0..225bdffe8 100644 --- a/internal/domain/eda/playbook/run_test.go +++ b/internal/domain/eda/playbook/run_test.go @@ -124,6 +124,41 @@ func TestRunStopsThePlaybookOnAnInvokeError(t *testing.T) { } } +// TestRunAbortsThePlaybookOnAnArgsEvaluationFailure pins J6 +// (docs/prds/playbook-expression-syntax.md): an args value that cannot be +// evaluated stops its playbook before the action runs, unlike a `when` that +// errors, which skips the action and continues (J3). The error names the +// playbook and the action whose args failed. +func TestRunAbortsThePlaybookOnAnArgsEvaluationFailure(t *testing.T) { + mods := &recordingModules{ModuleRegistry: module.New()} + store := loadRunStore(t, mods, ` +trigger: + kind: bug +actions: + - id: first + position: module + kind: log + args: { message: 'event.absent' } + - id: second + position: module + kind: log + args: { message: '"second"' } +`) + + err := store.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), bugInput()) + if err == nil { + t.Fatal("Run(args evaluation failure) = nil, want the playbook aborted") + } + for _, want := range []string{"pb.yaml", "first", "evaluate args"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("Run error = %q, want it to contain %q", err.Error(), want) + } + } + if len(mods.messages) != 0 { + t.Fatalf("invoked messages = %q, want none: the playbook aborts before the first action runs", mods.messages) + } +} + func TestRunIgnoresNonMatchingAndWorkflowPlaybooks(t *testing.T) { mods := &recordingModules{ModuleRegistry: module.New()} store := loadRunStore(t, mods, twoLogActions)