diff --git a/.claude/hooks/replaced-history-guard.sh b/.claude/hooks/replaced-history-guard.sh
index a0e15dbf..4546dc56 100755
--- a/.claude/hooks/replaced-history-guard.sh
+++ b/.claude/hooks/replaced-history-guard.sh
@@ -21,18 +21,23 @@ REPLACED_ROOT=1c2098c131ea654c850dccd2c7c627dab2e26f4a
input=$(cat)
+# One shell word in the JSON input: bare, in single quotes, or in double quotes (JSON-escaped:
+# \"...\"). Quoted, it may contain spaces, and it is taken whole.
+word='(\\"[^"]*\\"|'\''[^'\'']*'\''|[^[:space:];&|"'\''\\][^[:space:];&|"'\'']*)'
+
# `git push`, also after global options (`git -C dir push`, `git -c k=v push`).
printf '%s' "$input" |
- grep -Eq 'git(([[:space:]]+-[Cc][[:space:]]+[^[:space:]]+)|([[:space:]]+--?[A-Za-z][-A-Za-z]*(=[^[:space:]]+)?))*[[:space:]]+push([[:space:]]|$|["'\'';&|)])' ||
+ grep -Eq 'git(([[:space:]]+-[Cc][[:space:]]+('"$word"'|[^[:space:]]+))|([[:space:]]+--?[A-Za-z][-A-Za-z]*(=[^[:space:]]+)?))*[[:space:]]+push([[:space:]]|$|["'\'';&|)])' ||
exit 0
root=$(cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null && pwd -P) || exit 0
-# The repository: `git -C
`, else a leading `cd `, else the project. JSON-escaped
-# backslashes (Windows paths) become slashes; paths with spaces are not recognised (-> the project).
-dir=$(printf '%s' "$input" | grep -Eo 'git[[:space:]]+-C[[:space:]]+[^[:space:];&|]+' | head -n 1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//')
-[ -n "$dir" ] || dir=$(printf '%s' "$input" | grep -Eo '"command":[[:space:]]*"cd[[:space:]]+[^[:space:];&|]+' | head -n 1 | sed -E 's/^"command":[[:space:]]*"cd[[:space:]]+//')
-dir=$(printf '%s' "$dir" | sed 's#\\\\#/#g' | tr -d '"'\')
+# The repository: `git -C `, else a leading `cd `, else the project. A path that does not
+# resolve is let through below, so a quoted one must be taken whole, quotes and all, then unquoted.
+# JSON-escaped backslashes (Windows paths) become slashes; a line break ends a bare path.
+dir=$(printf '%s' "$input" | grep -Eo "git[[:space:]]+-C[[:space:]]+$word" | head -n 1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//')
+[ -n "$dir" ] || dir=$(printf '%s' "$input" | grep -Eo "\"command\":[[:space:]]*\"cd[[:space:]]+$word" | head -n 1 | sed -E 's/^"command":[[:space:]]*"cd[[:space:]]+//')
+dir=$(printf '%s' "$dir" | sed -e 's/^\\"\(.*\)\\"$/\1/' -e "s/^'\(.*\)'\$/\1/" -e 's#\\\\#/#g' -e 's/\\n.*//')
if [ -n "$dir" ]; then
dir=$(cd "$dir" 2>/dev/null && pwd -P) || exit 0
case "$dir/" in
diff --git a/.gitignore b/.gitignore
index a4c6f414..5638753e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -146,7 +146,11 @@ cython_debug/
custom/dapr/components/rabbitmq-pubsub.yaml
# Secrets
+# Both names: the framework loads '.secrets.toml' (DEFAULT_SETTINGS_FILES) and asbs
+# scaffolds that name, while 'secrets.toml' is the older name still found in the wild.
+# Named exactly rather than '.secrets.*', which would also hide the committed example.
**/secrets.toml
+**/.secrets.toml
.env.rabbitmq
uv.lock
@@ -160,3 +164,6 @@ uv.lock
ARCHITECTURE_DECISIONS.md
+
+# Private, machine-local Claude Code instructions
+CLAUDE.local.md
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..c7668808
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,276 @@
+# AGENTS.md
+
+Architecture, component patterns, testing conventions and **design rules** for this repository,
+shared across every AI assistant and every human working in it. `CLAUDE.md` holds the commands
+and the per-feature process; this file holds what the code has to be like and why.
+
+Each rule below states the rule, the reason, and **the failure it prevents**. That last part is
+not decoration: a rule without its failure is advice, and advice gets argued away by the next
+person with a deadline. Most of these were bought with a defect -- either one that shipped or one
+found by probing -- and the failure line is the receipt.
+
+If a rule and the code disagree, one of them is wrong and it is worth finding out which before
+writing anything. If a rule and a specification disagree, see *The spec wins on precedence, not
+on correctness* below.
+
+---
+
+## Where things are
+
+`src/blueprint/agents/` is the framework; `src/blueprint/agent_generator/` is the `asbs`
+scaffolder that generates projects against it. Inside the framework:
+
+| Path | What lives there |
+|---|---|
+| `app_builder.py` | The declaration API. `with_*` records; `build()` constructs, wires and returns the `FastAPI` app |
+| `agent_group.py` | Several agents in one process: named declarations in, one application out |
+| `group_config.py` | Which agents *this* process runs, resolved from the environment and the group file |
+| `entrypoint.py` | `python -m blueprint.agents.entrypoint` -- the container's command |
+| `component/` | `Component` (registry name, namespace, config view, executor), `Registry`, `namespace.py` |
+| `handler/` | `EventHandlerBase`, the `HandlerChain`, dispatch and deduplication |
+| `services/` | `ServiceBase`, the eventing services, and the infrastructure services (caches) |
+| `io/api/` | `RestApiBase`, the actuators (`/health`, `/info`, `/status`), the eventing endpoints, schedulers |
+| `clients/` | `ClientBase`, `IOClientBase` (NATS, Dapr), the AI clients |
+| `agent/` | `AgentRuntime` and `AgentBuilder` -- an LLM runtime and its fluent declaration |
+| `config/` | `Config` (Dynaconf), the logging manager |
+| `models/` | Pydantic models: events, configuration, API payloads, status |
+
+Prose for users lives in `src/blueprint/agent_generator/docs/`:
+`src/blueprint/agent_generator/docs/concepts/architecture.md` for the assembly model,
+`src/blueprint/agent_generator/docs/concepts/event-processing.md` for the dispatch pipeline,
+`src/blueprint/agent_generator/docs/concepts/configuration.md` for settings,
+`src/blueprint/agent_generator/docs/guides/` for deployment, testing and the CLI. Specifications and plans are in
+`docs/specs/` and `docs/plans/`; a feature's changelog beside its plan is the running record of
+what was done and why.
+
+---
+
+## Component patterns
+
+A project's component is an ordinary class extending one base:
+
+| Base | For |
+|---|---|
+| `EventHandlerBase` | Reacting to an event. Declares its topics, decides whether it can handle a delivery, handles it |
+| `ServiceBase` | Business logic with no transport of its own |
+| `RestApiBase` | HTTP endpoints, declared with the `@RestApiBase.get/post/...` decorators |
+| `SchedulerBase` | Recurring work, either from an in-process timer or from an external tick |
+| `ClientBase` / `IOClientBase` | Talking to something outside the process |
+| `HealthCheckerBase` | One entry in the readiness payload. Not a `Component` |
+
+What every one of them has in common:
+
+- **The constructor takes what its author wrote, and nothing the framework added.**
+ `super().__init__()` is enough. A component is never handed a namespace, a registry or a
+ configuration object -- it reads them from `self`.
+- **`self.registry`, `self.config` and `self.executor` answer for the component's own agent.**
+ A lookup written as `self.registry.get_service(OrderService)` finds this agent's service, and
+ `self.config.get("model_name")` reads this agent's value, with no namespace at the call site.
+- **Collaborators are resolved in `on_startup`, not in `__init__`.** Nothing is constructed until
+ `build()` runs, and within that pass the order is the declaration order, so a component's
+ collaborator may not exist yet while it is being constructed.
+- **`on_startup` / `on_shutdown` are the lifecycle.** The application's lifespan drives them; a
+ component that opens something in the first closes it in the second.
+- **`should_register=False`** is for a component nobody looks up -- the actuator API, the eventing
+ endpoints. It keeps a second registry entry per agent from existing.
+
+**The acknowledgement contract, for handlers:** a normal return acknowledges the delivery; a
+raised exception does not. `NO_HANDLER_FOUND` acknowledges too -- an event nobody declared is not
+a failure of this process. `ProcessingResult` describes the outcome and never controls delivery.
+*Failure:* if a result object could nak, two independent concerns -- "what happened" and "should
+the broker send this again" -- would be encoded in one value, and a handler returning a failure
+result would silently loop the broker.
+
+---
+
+## Design rules
+
+Every rule below that a machine can check is checked by `tests/unit/agents/test_design_rules.py`,
+one section per rule, each failure message naming the rule it enforces. Prose alone has already
+failed here once: this file was cited by `CLAUDE.md` for months while it did not exist, so the
+guards -- including the one that checks that a cited file exists -- are what keep the rest of this
+document true.
+
+### Construction and assembly
+
+**Collect, then wire.** A declaration API records; nothing is constructed, registered or
+connected until `build()`. *Failure:* a component constructed during accumulation exists before
+any namespace does and belongs to the root for ever -- which is what forced a second builder
+class to exist for three phases, until deferred wiring removed the reason for it.
+
+**One declaration surface.** Adding a capability is one edit: a `with_*` method on `AppBuilder`.
+A second class whose only job is to defer construction is the smell that was removed, not a
+pattern to copy. *Failure:* four places to edit, three of which fail *silently* -- the capability
+is simply absent from that surface, and only in the deployment shape nobody tested.
+
+**A builder is single-use, and says so.** *Failure:* a second `build()` surfaces
+`Component.configure`'s "already set" error, which names neither the builder nor the second call
+and sends the reader into framework internals.
+
+**Group policy belongs to the collector.** The host refuses what a group cannot honour, at
+assembly, naming the agent and the fix -- a group, and `build(config)` (what `create_app()` calls),
+because a declaration served alone is the shape a group hosts. Only the old
+`AppBuilder(config)...build()` shape stays permissive. *Failure:* restrictions scattered into
+the builder punish the single-agent case for constraints that only a group has.
+
+### Namespaces and isolation
+
+**A component never learns it is in a group.** The namespace is ambient, read by
+`Component.__init__` from the scope in force; it is never a constructor parameter of a project's
+component, and never enumerable from anything a component can reach. *Failure:* an agent that can
+read its neighbours can be written to depend on them, and regrouping then breaks it in
+production.
+
+**Isolation is structural where it can be, audited where it cannot.** Separate stores beat a
+shared store with a key prefix; where walling something off would break a supported use, log the
+access and name the reader instead. *Failure:* a prefix has to be applied correctly at every call
+site, and the one site that forgets is a silent cross-agent read.
+
+**A lookup never falls back across agents.** Components resolve namespace-then-root, deliberately;
+caches do not resolve at all outside the declaring agent. *Failure:* two agents that both asked
+for `sessions` silently share one store, and only in production.
+
+**An omitted namespace on the root registry means every namespace, not the root.** Framework code
+that dispatches or resolves per agent names its namespace explicitly, even where it looks
+redundant. *Failure:* a root dispatch runs every agent's handlers, or `build()` sees only root
+handlers and silently short-staffs a grouped process.
+
+**Entering a scope for the root is not a no-op.** `namespace_scope("")` *sets* the root, so code
+that constructs on behalf of a namespace it was handed uses the guarded form
+(`construction_scope`). *Failure:* replaying one agent's declarations resets every component of
+every agent back to the root, silently.
+
+**An agent's failure is attributed, whatever the pod does about it.** A degraded agent drives
+`blueprint.namespace.up = 0` and an ERROR event naming it, its group and its pod, independently of
+readiness. *Failure:* grouping removes the pod restart that used to be the alert, so nineteen
+agents go on answering while the twentieth has silently stopped and nothing says so. Guarded by
+`test_namespace_supervisor.py`.
+
+**Every detached task carries a done-callback that logs its exception with the agent.** A bare
+`create_task` or `ensure_future` is a violation. *Failure:* the exception surfaces as asyncio's
+"Task exception was never retrieved", at an unpredictable time and attributed to nobody. Guarded
+by `test_design_rules.py::TestEveryDetachedTaskIsWatched`.
+
+**The probe decides where traffic goes; it never decides who is woken.** `readiness_policy` may
+keep a degraded agent from taking the pod out of rotation; it never suppresses that agent's signal,
+and it never stops it being taken off its topics. *Failure:* a deployment that chose `critical` to
+avoid a noisy probe would also have switched off the alerting for the agents it stopped gating on.
+
+### Names and values that leave the process
+
+**A name that crosses the process boundary is validated, never repaired.** Queue groups, JetStream
+durables, subjects, cache names, namespaces, environment-variable prefixes. *Failure:* silent
+rewriting breaks an external dependency with nothing in the logs to debug -- a spaced `app_name`
+becomes a subject the CronJob author cannot know they must match.
+
+**Two components of one class collide on the derived registry name.** A name is qualified with
+its agent automatically, so a collision means two of one class in one agent, or two explicit
+names that clash. Give one an explicit `name=`. *Failure:* the second registration raises at
+startup, or -- worse, before names were qualified -- replaced the first.
+
+**A check answerable at the call stays at the call.** *Failure:* an error reported several
+`with_*` calls later, or at `build()`, names the wrong line and the author looks for the mistake
+where it is not.
+
+### Declarations and defaults
+
+**An empty declaration means everything, not nothing.** `get_handled_event_types() -> []` is the
+wildcard bucket. *Failure:* treating an empty set as authoritative silences the application, and
+an unhandled event acknowledges -- so the deliveries vanish rather than piling up where somebody
+would see them.
+
+**A key whose absence changes behaviour is required, not defaulted.** `scheduler_mode` and
+`idempotency_ttl` have no default because neither value is safe to inherit. `must_exist=True`
+beside a `default=` is a lie: Dynaconf fills the default and the validator then passes.
+*Failure:* a deployment gets a behaviour nobody chose -- every replica running every tick, or a
+deduplication window shorter than the broker's redelivery window.
+
+### Configuration and logging
+
+**Configuration is injected before any component exists**, and is read through the component's
+own scoped view. There is **no public read path to the unscoped loader**: `Component.config` is a
+view, and the class-level accessor was deleted. *Failure:* a component reads a neighbour's or the
+process's value under a name that means "mine", and the bug appears only once a second agent
+exists.
+
+**Configuration isolation is audited, not enforced.** Reading the raw settings tree from a scoped
+view logs a WARNING naming the reader, rather than raising. *Failure (of the alternative):*
+legitimate framework reads break, and the ones that matter are not the ones a wall would catch.
+
+**A key that describes the process cannot be set per agent.** One process has one port, one
+environment, one prefix, one event bus and one logging configuration. Such a key in an agent's
+own settings file is dropped and reported. *Failure:* the author sets a value that is read by
+nothing and reported by nothing, and the pod does something other than what the file says.
+
+**Logging is configured by the application**, never by library code, a constructor, or at import
+time. Modules get `getLogger(__name__)` and emit; the application attaches handlers, once.
+*Failure:* N scoped configurations each build a logging manager, each re-attaches filters, and
+the last one to load decides the whole process's level.
+
+### Versioning and releases
+
+**The version is the git tag; the repository is never bumped by hand.** `.github/workflows/publish.yml`
+extracts the version from the tag and rewrites `pyproject.toml` at build time. A change adds a
+`CHANGELOG.md` entry under `[Unreleased]` and touches no version string. *Failure:* a
+hand-edited version disagrees with the tag that published it, and the artefact on the index
+cannot be traced back to a commit.
+
+---
+
+## Testing conventions
+
+- **`tests/unit` needs nothing running, and a test that needs something running lives in
+ `tests/integration`.** The `integration` marker is applied **by location**, from
+ `tests/integration/conftest.py`, so the directory and the marker cannot drift apart and nobody
+ has to remember a decorator. What that cannot enforce, and a review must, is the other half:
+ a test needing nothing is in the wrong directory even though the marker will be attached to it.
+ *Failure:* the split was enforced three ways at once and agreed with itself in none of them --
+ CI selected by directory, three tests carried the marker by hand, and `tests/integration` sat
+ red and unread for a year (#80).
+- **A test that reaches for a service it does not need is not offline, it is lucky.** Its result
+ then depends on what happens to be listening on the developer's machine. Turn the reach off
+ explicitly -- `health_check_dapr = false` is there for exactly this -- rather than relying on
+ the connection being refused.
+- **Every package under `tests/unit/agents/` has a `TESTS.md`** listing each file, the class
+ under test, and what is covered; the one at the top level covers the files that sit directly in
+ it. It is updated with the tests, not after them. (`tests/unit/agent_generator/`,
+ `tests/unit/examples/` and `tests/integration/` have none yet.)
+- **Probe against real objects.** Every real defect this framework's grouping work surfaced was
+ found by testing against a real `Registry`, a real `Config` and a real cache rather than a
+ mock. *Failure:* a mock registry answers every lookup and hides resolution bugs by
+ construction -- six ownership tests passed against a `MagicMock` while the code could not have
+ worked.
+- **Assert on the observable thing, not on the call.** Paths from `app.openapi()`, names from the
+ registry, values from `config.get`, files on disk. A test that asserts a mock was called with
+ certain arguments passes when the arguments are wrong for the caller.
+- **A test says what it pins down.** The docstring is the reason the case exists, and for a
+ regression it names the failure. `test_that_it_works` is not a name.
+- **The frozen compatibility suite is frozen.** `tests/unit/agents/test_frozen_compatibility.py`
+ exercises what existing projects already do. **Never edit it to accommodate an API change**: if
+ it needs editing, a break shipped, and the break is the finding.
+- **A guard test states the rule it enforces in its failure message.** Someone hitting it should
+ learn the rule from the failure, not from this file. The guards for the design rules above live
+ in `tests/unit/agents/test_design_rules.py`; a rule that is not mechanically checkable says so
+ there, so that its absence is not read as an oversight.
+
+---
+
+## How the work is done
+
+**No unused code in the framework.** Git history is where removed work belongs. *Failure:* a
+plausible unused abstraction misleads the next reader into building on something nothing has ever
+exercised -- a renderer written and deleted before it was committed cost less than one left in
+place would have.
+
+**Probe, do not assume**, and say which it was. "Verified by probe" and "read from the code" are
+different claims, and a report that blurs them cannot be checked.
+
+**The spec wins on precedence, not on correctness.** Where a specification and this repository
+disagree, the specification decides what ships -- but challenge a requirement's premise before
+building it, and record every departure, with its argument, in the feature's changelog. *Failure:*
+a requirement is implemented as written although its premise is false (a key that is "read by
+nothing" turns out to be read per agent), or quietly diverged from, and nobody can tell which.
+
+**Report the code, not the wrapper.** A change is reported by walking through what the production
+code now does -- the functions, the branches, the call sites -- and showing the lines that matter.
+"Tests pass and lint is clean" is the wrapper around a change, not the change.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96ef88c2..3fbe268e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,1013 @@
# Changelog
+## [Unreleased]
+
+**Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather
+than an architectural commitment. An agent's code is identical whether it runs alone or beside
+nineteen others; only what starts the process differs. A standalone agent is unaffected by almost
+all of this — see **Breaking** for the exceptions, which are listed in the order you are likely to
+hit them.
+
+Full migration path, including the one decision to get right before the first deploy:
+[`guides/multi-agent-setup.md`](src/blueprint/agent_generator/docs/guides/multi-agent-setup.md). The normative spec is
+`docs/specs/2026-08-28-multi-agent-grouping.md`.
+
+### Breaking
+
+- **In a group, the NATS publish endpoint and scheduler triggers move, and each agent is one
+ Swagger group.** Grouped agents only; a standalone agent's paths and tags do not change.
+ - `/api//events/{topic}` becomes `/api//nats/events/{topic}`.
+ - `/api///trigger` becomes `/api//scheduler//trigger`.
+ - Cache endpoints stay at `/api//cache/*`.
+ - Every operation of a grouped agent is tagged with exactly the agent's name, replacing declared
+ tags and tagging untagged ones. In the 0.9.0 alphas an agent was split into `.` groups
+ interleaved with other agents', and its untagged routes sat under "default" beside everyone
+ else's.
+ - `nats`, `cache` and `scheduler` under `/api//` are reserved: a grouped agent's own route
+ starting with one now fails startup, naming the class and the route. Rename it or set
+ `path_prefix`.
+
+ Clients and scripts calling a grouped agent's NATS publish endpoint or scheduler trigger need the
+ new paths. Nothing broker-side changes.
+- **Removed unused internals:** the empty module `blueprint.agents.models.event_routing`, and the
+ example-domain models `AnalysisRequest` and `AnalysisResponse` in `blueprint.agents.models.result`,
+ which nothing in the framework used and the package did not export.
+- **`blueprint.events.unhandled` and `blueprint.events.duplicate` carry `agent`, not
+ `namespace`,** and are recorded on the agent's own meter. They were created at import on the
+ global meter, so they reported under the root's resource for every agent, with a label no other
+ metric uses. The root is labelled ``, as everywhere else. Dashboards on the old label need
+ the new one.
+- **`nats_use_jetstream = true` is enforced against the server; there is no fallback to Core
+ NATS.** The server is asked for the account's JetStream information on connecting. If it does not
+ offer JetStream, the agent fails: at startup through the startup failure policy, later (broker
+ unreachable at startup) by shutting the process down for the root or a critical agent and marking
+ a non-critical one down. The previous fallback rarely triggered, and when it did it dropped
+ durable consumers and acknowledgements without anyone deciding it.
+- **JetStream consumer settings are opt-in again.** The framework set `ack_wait` 300 s,
+ `max_ack_pending` 16 and `max_deliver` 5 on every consumer it created, overriding the server's
+ defaults for deployments that had configured nothing. `nats_ack_wait`, `nats_max_ack_pending` and
+ `nats_max_deliver` are now applied only when set; unset, the server's default stands (NATS: 30 s,
+ 1000, unlimited). With `nats_max_deliver` unset, a message that keeps failing is retried without
+ limit and never dead-lettered, as in 0.8 -- set it to bound retries. Consumers that already
+ exist keep their settings, and an unset key is not reported as a difference.
+- **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now
+ `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`):
+ the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly,
+ or implements `ClientBase`, is affected -- handlers are not. A one-argument callback now fails
+ with a `TypeError` on the first message.
+- **`nats_url` has no default outside development.** With `event_bus = "nats"` and no `nats_url`,
+ a process whose `app_environment` is anything but `"development"` now fails startup naming the
+ key -- a standalone or critical agent before the port is bound, a non-critical agent of a group
+ by being marked down. It used to connect to `nats://localhost:4222`, which in a pod reaches
+ nothing and retried forever while the pod reported healthy. Development keeps the localhost
+ fallback, with a WARNING. A broker in the same pod needs `nats_url` set explicitly.
+- **A process in development mode logs a WARNING at startup** that it is not suitable for
+ production. `app_environment` defaults to `"development"`, so a deployment that sets nothing now
+ says so in its own log.
+- **`root` is required in `agents.toml`.** Every entry of a map written for a 0.9.0 alpha needs
+ one line added; a map without it refuses to start rather than guessing. For an image that copied
+ one agent to `/app`, that is `root = "."`.
+- **The standalone image does not run the group entry point** (the 0.9.0 alphas' did). It serves
+ `src.main:create_app` directly. An existing project keeps working: `uvicorn src.main:app` is
+ still served for a pre-split `main.py`, and a project that wants the old command can keep it.
+- **`agents.toml` inside an agent is refused unconditionally**, with no exception for an agent
+ mapped at the image root. That shape only existed in the 0.9.0 alphas, to let a standalone agent
+ be a group of one, which it no longer has to be.
+- **`asbs setup` writes no `agents.toml` into an agent** (the 0.9.0 alphas did). The map says which
+ agents an *image* contains, which is a packaging decision -- an agent carrying one is an agent
+ that knows whether it is running alone. The single-agent `Dockerfile` reads no map either: it
+ serves `create_app()` at the root. An agent scaffolded by an alpha should delete the file; in a
+ group it is refused.
+- **The `src//main.py` group layout is retired.** An agent is now the same directory alone
+ or in a group -- `/settings.toml` beside `/src/` -- which is what lets it move
+ between repositories untouched. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so
+ nothing stable depended on the old shape.
+- **`AgentMapPartGenerator` is gone.** It generated a file that is no longer written; its
+ `agent_namespace` helper moved to `PartGeneratorBase`.
+
+1. **`scheduler_mode` is required.** A project that registers a scheduler and does not set it fails
+ at `build()`, with an error naming both values and what each costs. `"in_process"` keeps 0.8's
+ in-process timer and is the smallest migration (it now claims each tick, see 13); `"event"` is
+ the one that fixes #73.
+ Defaulting the key would either keep firing a timer per replica or silently stop ticking a
+ service with no broker, and neither is safe to inherit.
+2. **A subject-unsafe `app_name` or `nats_queue_group` now fails at startup** instead of being
+ rewritten or reaching the broker. `app_name = "Health Monitor"` with an event-mode scheduler used
+ to derive `Health_Monitor.scheduler.`; the rewrite was invisible to whoever wrote the
+ `CronJob`, so the symptom was a tick that never arrived. Rename to a subject-safe value, or pass
+ `topic=` explicitly.
+3. **A scoped `Config`'s dotted key no longer resolves against the whole tree.** `_scoped_get` used
+ to fall back from `.` to the raw key, and since an agent's section is
+ `[default.]`, that let one agent read another's settings. The fallback is now an allowlist
+ of the four prefixes the framework itself owns (`cache`, `event_publishing`, `runtimes`,
+ `runtime`). A project reading its *own custom* nested key through a scoped view now gets an error
+ naming the rule; flat keys and `Config.settings` are unaffected.
+4. **A registry view that names another agent is refused.** `get_component(..., namespace="other")`
+ and `get_cache(..., namespace="other")` raise on a scoped view. Every in-framework caller passes
+ its own namespace or holds the application registry, so nothing internal is affected.
+5. **A scoped `Config`'s telemetry `service.name` is the agent's name.** Affects a project using
+ `Config(agent_scope=...)`, which has shipped since April. A repo with `foo.app_name = "Foo
+ Service"` and no `foo.otel_service_name` sees `service.name` change from `Foo Service` to `foo`.
+ Migration is one line: set `.otel_service_name` to whatever the dashboards key on. A
+ project that passes no `agent_scope` is unaffected.
+6. **Cache keys moved, twice -- for named caches and for agents in a group.** A cache is now
+ private to the agent that declared it, keyed on `(namespace, name)` with its own subdirectory
+ and Redis prefix. Such a cache upgrading with persistent Redis or a mounted disk cache sees its
+ old entries as **absent** — a cold cache, not an error. **A standalone agent's default cache is
+ unaffected:** its directory, Redis prefix and keys are unchanged, so it keeps its entries. A
+ group still needs exactly one writable mount, since an agent's store is a subdirectory of
+ `cache.cache_dir`. If any cache entry is load-bearing rather than an optimisation, migrate it
+ deliberately.
+7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`,
+ `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one
+ declaration surface; `AgentGroup` collects named declarations into a process. Passing an
+ already-built component instance (`with_service(MyService())`) still works in the old
+ `AppBuilder(config)...build()` shape, and is refused by `build(config)` -- what `create_app()`
+ calls -- and in a group: pass the class, or a zero-argument factory.
+8. **`ClientBase.subscribe` changed from `(topic, callback)` to `(topic_callbacks)`**, and
+ `EventHandlingBase.subscribe` and `POST /nats/subscribe/{topic}` are removed. This affects
+ third-party transport implementations; both in-repo clients are updated.
+9. **On grouped Dapr, one delivery is fanned out in-process to every agent that declared the
+ topic, and the single acknowledgement the sidecar receives is their combination** — so a retry
+ asked for by one agent redelivers to all of them. The sidecar fetches the subscription document
+ from one fixed path, which is why there is one endpoint at the root that routes rather than one
+ document per agent. Set `idempotency_enabled` for grouped Dapr, or keep handlers
+ repeat-tolerant. Single-agent Dapr and NATS are both unaffected.
+10. **`Registry.update_component_name` refuses a name that is already taken** instead of overwriting
+ it. Anything relying on the overwrite was losing a component silently.
+11. **`asbs setup` now scaffolds `.secrets.toml`**, the name `DEFAULT_SETTINGS_FILES` actually loads;
+ it used to write `secrets.toml`, which nothing read. This is a change to the *scaffolder* only —
+ the framework's file list is untouched, so no existing deployment changes. `asbs validate`
+ reports an undotted file as the rename it needs. An already-scaffolded project should rename its
+ file.
+12. **`Component.shared_config` is now private (`Component._shared_config`)**, with
+ `Component.reset_shared_state()` as the one supported way to clear it. The old attribute was
+ public and writable but read by nothing outside `_ComponentMeta`, so hiding it looked like
+ code-only cleanup. It is not: a test suite that rebuilds its `AppBuilder` app once per test case
+ and resets state between cases with the old `Component.shared_config = None` now silently
+ no-ops, since the real state lives on `_shared_config` — `Component.configure()`'s "already set"
+ guard then trips starting from the second test in the run, with an error that does not name this
+ rename. **Any project resetting shared state between test cases must switch to
+ `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which
+ stays public and is otherwise unaffected. A project that never resets shared state between
+ builds is unaffected.
+13. **A scheduler tick runs in one replica, not in every one.** Before, every replica -- and every
+ worker -- ran its own timer and each ran every tick. Now `scheduler_mode = "event"` delivers the
+ tick through the queue group to one replica, and `"in_process"` claims each tick in the cache so
+ one replica runs it -- across replicas only on a Redis cache, since a disk cache's claim holds
+ within one process. A deployment that relied on every replica running a tick in parallel -- a
+ per-pod cleanup, say -- now runs it once per tick; register the cache per pod, or do the per-pod
+ work outside the scheduler. Without a registered cache, `"in_process"` still runs every tick in
+ every replica, and says so with a WARNING at startup where it used to log an INFO.
+14. **A Core NATS event reaches one replica, not every one.** Subscriptions now join a queue group
+ (`nats_queue_group`, else `app_name`); before, every replica received and processed every event.
+ A deployment that relied on each replica seeing each event now sees each event once.
+15. **`Config()` no longer configures logging.** Constructing a `Config` used to set up the root
+ logger; library code must not, so `AppBuilder` does it now. A script or test that builds only a
+ `Config` and relied on its logging setup has to configure logging itself.
+16. **`Config.settings` is read-only.** It was a plain attribute; assigning to it now raises
+ `AttributeError`. Replacing the settings tree underneath a running configuration bypasses every
+ agent's view of it and is not supported.
+17. **Metrics a project records itself are now exported.** With OpenTelemetry enabled, the framework
+ registers a global `MeterProvider` that exports over OTLP. Before, it registered none, so a
+ counter a project created through `metrics.get_meter(...)` was silently discarded; the same
+ unchanged code now reaches the collector, which can add series -- and cost -- to a metrics
+ backend. A project that registered its own `MeterProvider` first keeps it: the SDK refuses a
+ second one and the framework's is not installed.
+18. **A broker fault no retry can fix fails the agent, critical or not, and can fail liveness.** A
+ durable that filters another subject, a stream the server refuses to create or widen, a grant the
+ account lacks, and on a named connection a refused login or deliver subject used to be retried for
+ ever (a named connection's missing grant every 60 s) while the agent consumed nothing -- and a
+ JetStream grant refused to the agent's own connection, found by the health poll before startup,
+ left the agent paused as degraded for good, with nothing logged. Now each is logged CRITICAL
+ with what to change and never retried. At startup the start fails, whatever
+ `critical_agents` says; after startup `GET /health/live` answers `503` naming the agent and the
+ reason (it was always `200`), so Kubernetes restarts the pod, and the root or a critical agent
+ also ends the process as before. A degraded agent whose fault may heal still never fails
+ liveness. A named connection in this state reads `failed`. New exception classes, all
+ subclasses of `DeterministicTransportError`: `DurableConflictError` (replaces
+ `JetStreamBindingError` for the clash), `StreamConflictError`, `JetStreamPermissionError`,
+ `TenancyError`; `JetStreamUnavailableError` is one too. A missing binding-mode stream is still
+ retried (Known issues).
+19. **An orphaned agent takes the pod out, whatever `readiness_policy` says.** An agent latched down
+ -- its startup failed and recovery retries it, or its transport failed for good -- now gates
+ readiness under `"critical"` and `"any"` too: it consumes nothing for a reason that is not
+ transient. And an agent whose resume after a degradation keeps failing, or whose connection loop
+ gave up (`event_client_max_retries`), fails liveness until it consumes again, logged CRITICAL: it
+ reported healthy while paused, so readiness read UP while nothing was consumed.
+20. **A failed JetStream delivery comes back after a delay.** A `RetryableHandlerError`, any
+ unexpected exception and `nats_handler_timeout` used to nak for immediate redelivery, so every
+ attempt was used up within a few hundred milliseconds -- measured: 5 attempts in 0.3 s -- and a
+ backend restart or a 5xx outlasted them all. The new `nats_nak_delay` (agent scope) defaults to
+ 1 s, 5 s, 15 s, 30 s, then 60 s per redelivery; `0` restores the old behaviour. A degraded
+ agent still hands its buffered deliveries back at once.
+21. **The NATS publish route refuses a tenant's subject.** With a connection source,
+ `POST .../events/{topic}` answers 403 for a subject the source claims for the agent or a tenant
+ binding filters or delivers to: the route has no authentication, and an event put into a
+ tenant's stream ran under that tenant's identity. `operator_routes_enabled = false` (process
+ scope) leaves the publish route and the cache routes out altogether.
+
+### Added
+
+- **`examples/site_readings`: named connections end to end.** One agent, two sites, each its own
+ NATS account, supplied by a `ConnectionSource` (claims, a per-connection subject prefix, `validate`,
+ `run_scope`), with the example broker, a provisioning script and offline tests.
+- **A JetStream run knows which attempt it is.** The handler context carries `nats_delivery_attempt`
+ (1-based) and `nats_max_deliver` (`None` when unlimited) on the default and on named connections,
+ so a service can close open work on the last attempt instead of leaving it open. Core NATS
+ deliveries carry neither key.
+- **`HandlerResult.skipped(reason)`.** A handler that is responsible for an event but finds it needs
+ nothing returns it: the chain stops (no later handler is asked, unlike `None`), the delivery is
+ acknowledged, nothing is published, the reason is logged at INFO and the event is counted as
+ `blueprint.events.skipped` rather than as unhandled. The run reports the new
+ `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason as message.
+- **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a
+ readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`,
+ `reconnecting`, `retrying` (with the last error, redacted), `failed` (a tenancy fault no retry
+ fixes, see Breaking 18) or `paused`, and any permission violation,
+ plus the gauge `blueprint.nats.connection.bound` and the counter
+ `blueprint.nats.connection.permission_violations` (attributes `agent`, `connection`). The new agent-scope
+ key decides whether the entry can fail: `"never"` (default), `"any"` (one bound) or `"all"` (every one
+ bound); another value fails startup. In every mode a named connection feeds readiness only and never
+ pauses the agent, so its other connections keep delivering. A paused agent whose default connection
+ comes back re-evaluates readiness at once instead of at the next health interval.
+- **Named connections change at runtime.** A connection source that defines `watch(notify)` tells every
+ agent's client when its connections change; the client binds a new connection, replaces a changed one
+ (new link bound before the old one is retired) and retires a removed one: drained, its runs given
+ `subscription_change_grace` seconds, the rest revoked -- never settled, `publish` refused with the new
+ `DeliveryRevokedError`, not cancelled. A change never interleaves with a pause, and no consumer is
+ deleted. A permission the broker refuses is retried every 60 s with an ERROR instead of at full pace.
+- **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for
+ every agent with `--group`), with file and line: such code keeps a run going past
+ `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway.
+- **`ConnectionSource.claims(agent, subjects)` and `nats_unclaimed_subjects`.** The source says which
+ subjects belong to named connections, independently of which connections exist; those never go to
+ the agent's default connection, so a fresh deployment without a tenant subscribes nothing there. A
+ subject not claimed fails startup unless `nats_unclaimed_subjects = "default_connection"` allows it.
+- **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes.
+- **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent,
+ connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run
+ is always allowed; further runs also need a slot of **`nats_extra_runs_per_process`** (process scope,
+ number or percentage of the process's pairs, unset unlimited). With every slot taken the subscription stops taking
+ messages; keep `nats_max_ack_pending` near replicas x this value.
+- **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent.
+- **`nats_handler_timeout`** (seconds, unset by default): the longest one run may take. At the limit the
+ run is cancelled and nak'd for redelivery after `nats_nak_delay`; a `TimeoutError` of the handler's own is an
+ ordinary failure. Unset, a run is never cut.
+- **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under
+ one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`,
+ so no existing path moves.
+- **The migration docs name absolute `src` imports as a pitfall.** `from src.x import Y` works for
+ an agent served on its own and fails in a group, where a non-critical agent is then skipped with
+ one ERROR line and its routes are missing from `/docs`. The `blueprint-migration` skill and
+ `guides/multi-agent-migration.md` now carry the cause, the log line, the fix (relative imports,
+ which keep working standalone) and a `grep` that finds them. `asbs validate --group` reports
+ them as a warning, with file and line.
+- **Handlers see the subject a NATS message was delivered on**, as `context["nats_subject"]`
+ (`NATS_SUBJECT_CONTEXT_KEY`), beside `nats_topic`, which is the subscription and may be a
+ wildcard. It comes from the broker, not the event, so a tenant can be derived from the subject the
+ broker checked rather than from the publisher-controlled `tenantid`.
+- **NATS credentials from their own keys.** `nats_user`/`nats_password`, `nats_token`,
+ `nats_creds_file` and `nats_nkey_seed` are passed to the connection, so an account under
+ tenant-scoped auth no longer has to put its credentials inside `nats_url`. At most one method may
+ be configured; a half-set login, a creds file that is not there, or two methods at once fail
+ startup. `nats_inbox_prefix` replaces `_INBOX` for accounts not permitted `_INBOX.>`. All are read
+ per agent, so each agent of a group can have its own account. The dependency on `nats-py` is now
+ `nats-py[nkeys]`, which creds files and nkey seeds need.
+- **A `blueprint-migration` Claude Code skill**, installed by `asbs claude`: moving an existing
+ single-agent project into a group -- the files it touches, the mistakes that break it, and how
+ `asbs validate --group` checks it. The migration guide was previously reachable only from inside
+ `blueprint-multi-agent`. `asbs claude` now lists the skills and agents it installed by reading
+ them from the package, rather than from a hand-kept list that would have left any new skill
+ unannounced.
+- **A standalone agent declares nothing group-related.** `asbs setup` writes a `create_app()`
+ factory beside the declaration, and the generated Dockerfile serves it with
+ `uvicorn src.main:create_app --factory` -- no agent map, no group, no namespace. A group of one
+ is still a group, and requiring an agent to declare itself one in order to run alone is what put
+ the group's own file inside the agent. The same directory is still hosted by a group image
+ without changing a line; its components simply gain that agent's namespace, and with it the
+ `/api/` route prefix.
+- **`.dockerignore`**, written by both `asbs setup` and `asbs setup --group`. Not tidy-up: the
+ group image copies the whole `agents/` tree, because which agents a process runs is decided at
+ startup rather than at build time -- and Docker's build context is the filesystem, not the
+ repository, so `**/.secrets.toml` being in `.gitignore` did nothing to keep real keys out of a
+ layer.
+- **`asbs setup --group` writes a `pyproject.toml`** as well. The group Dockerfile's builder stage
+ installs from one, so without it the image could not be built.
+- **The declaration rules apply to `create_app` too.** A component registered as an already-built
+ instance is refused when a *host* builds a declaration -- `create_app()` or a group -- because an
+ agent that works standalone only because nobody checked is an agent that fails the day it joins a
+ group. The older shape, `AppBuilder(config)` built in place, stays permissive and keeps working.
+- **`root` in the agent map**, required per agent, relative to the directory `agents.toml` is in.
+ Stated rather than derived: a root guessed from where a declaration happens to sit is right for
+ one layout and silently wrong for every other, and nesting an agent at any depth now costs
+ nothing. A missing `root`, one that escapes the image, one that is not a directory, and two
+ agents sharing one are each refused at startup, naming the agent.
+- **Misplaced files are refused, not ignored** (`blueprint.agents.layout`). One table of artefacts
+ with a single legal location, enforced at group assembly and reported by `asbs validate
+ --group`: `settings.toml` and `.secrets.toml` beside `src/`, `agents.toml` at the image root.
+ `Dockerfile` is deliberately absent from it -- an agent may own one while living in a group
+ repository. Adding an artefact is one tuple.
+- **`asbs setup --group`** writes the image's files -- an empty agent map, the process settings
+ and a group Dockerfile -- and creates no agent.
+- **`asbs validate --group`** validates an image: every `root`, each agent's layout, misplaced
+ files, process-wide keys left in an agent, and which `settings.toml` each agent actually reads.
+- **`asbs dev --name`** serves an agent directory under the namespace a group image would give it,
+ writing the one-agent map outside the project for that run. Without `--name`, an agent directory
+ is served alone at the root through its `create_app()`; it needs no `agents.toml`.
+
+- **The documentation ships inside the package.** The user-facing guides moved from the repository
+ root to `src/blueprint/agent_generator/docs/` and are now installed with the wheel, so a
+ developer or an AI assistant working in a consuming project can read them with no network access.
+ Previously `README.md` became the wheel's `METADATA` while the 21 documentation pages it links to
+ stayed behind in the repository, and every one of those links resolved to nothing once installed.
+- **`asbs docs`** locates the packaged documentation: `asbs docs` lists every page, `asbs docs
+ ` prints the path to one, `asbs docs --cat` prints its contents, and `--root`
+ prints the directory. A bare page name is accepted when it is unambiguous.
+- **Seven Claude Code skills**, installed by `asbs claude` alongside the two that already existed:
+ `blueprint-cli`, `blueprint-config`, `blueprint-events`, `blueprint-multi-agent`,
+ `blueprint-testing`, `blueprint-deployment` and `blueprint-troubleshooting`. Each carries the
+ rules that are expensive to get wrong and points at the packaged page for the rest, rather than
+ restating it -- the docs stay the single source of truth.
+
+- **Agent grouping.** `agents.toml` names the agents an image contains and the module each
+ declaration lives in; `BLUEPRINT_AGENTS`, or `BLUEPRINT_GROUP` plus a mounted
+ `BLUEPRINT_GROUP_CONFIG` file, decides which of them a given process runs;
+ `python -m blueprint.agents.entrypoint` resolves, builds and serves them. Each hosted agent owns
+ its handlers, agent runtime, REST routes (`/api/`), AI client, thread pool, caches and
+ broker connection; the port, the health endpoint and the process are shared.
+ `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process.
+- **Agents in one process are isolated, and the barrier is enforced rather than conventional.** An
+ agent resolves its own components, caches and configuration plus the root's shared ones. Reaching
+ a neighbour by its registry key, by an explicit `namespace=` on a view, by a dotted configuration
+ key, or by sharing one declaration's mutable argument between two agents is refused or reported
+ absent. `Config.settings` remains the documented escape hatch and logs a WARNING naming the agent.
+- **An agent's identity is stable across regrouping** (spec C1): its NATS queue group, JetStream
+ durable, cache partition, OpenTelemetry `service.name`, registry prefix and REST prefix all derive
+ from the agent's own name and never from the group or the pod.
+- **Per-agent observability.** `service.name` per agent, `blueprint_namespace_up{agent}`, a
+ readiness entry and health checks attributed per agent, `blueprint.scheduler.tick_age_seconds`,
+ `blueprint.events.dead_lettered`, `blueprint.events.unhandled` and `blueprint.events.duplicate`.
+- **`CacheService.claim`** — set-if-absent: atomic on Redis (`SET NX EX`), and on disk (`add`)
+ atomic within one process only. This is the compare-and-set primitive the deduplication work
+ flagged as missing.
+- **Named caches.** `with_cache(name=...)`, `/cache/*` endpoints take `?name=`, and `/readiness`
+ gains a `cache:` entry per named cache.
+- **Opt-in event deduplication** — `idempotency_enabled` and a required `idempotency_ttl`. Off by
+ default; a failed dispatch releases its claim so the nak's redelivery still runs.
+- **`nats_publish_mode`** (`"core"` / `"jetstream"`) separates publishing from durable consumption,
+ with `nats_publish_subjects` for subjects not already in `event_publishing.topic_mapping`. Unset,
+ it follows `nats_use_jetstream`, so nothing existing changes.
+- **`run_app`**, so a project can serve itself from its own settings.
+- **Scaffolding**: `asbs setup` now writes a `pyproject.toml` and two tests, so
+ `asbs setup` → `pytest` → `asbs validate` closes; `asbs validate` reports what a project has not
+ said about grouping and about idempotency; the CLI no longer crashes on a Windows console.
+- New config keys: `event_client_drain_timeout`, `dapr_pubsub_name`,
+ `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`,
+ `event_publishing_enabled`, `nats_publish_mode`, `nats_publish_subjects`. All default to current
+ behaviour except `scheduler_mode`, which is required — see **Breaking**.
+- `pyyaml>=6.0` is now a declared dependency (it reads the group file). Already present in every
+ environment via `uvicorn[standard]`, so no installed set changes.
+
+### Changed
+
+- **One `main.py` pattern in every document, skill and agent prompt: the template's.** `src/main.py`
+ is a declaration (`agent = AppBuilder()...`, unbuilt `AgentBuilder`, components as classes) with
+ a `create_app()` for running it alone. The docs showed three patterns, including `.with_config()`,
+ `.with_api()` and `AgentBuilder().with_name()`, which do not exist, and a built `AgentRuntime`
+ that a group refuses.
+- **Handlers translate, services decide -- in the scaffold and every document.** The handler
+ template no longer says "this is where the main business logic is implemented":
+ `can_handle_event` routes on the envelope only, `handle_event` extracts the payload, makes one
+ service call and returns the answer (`HandlerResult`, `HandlerResult.skipped(reason)` or `None`);
+ idempotency belongs to the service; handlers never call the LLM. The chain semantics are stated
+ as the code has them: the first result that is not `None` ends the chain (the docs said a
+ `HandlerResult` let later handlers run).
+- **The examples follow the handler and service rules.** One handler per event type making one
+ service call (`webhook_relay`, `order_event_pipeline`), APIs that translate request DTOs into
+ domain models (`document_summarizer`, `inventory_api`), a scheduler with one service call
+ (`health_monitor`), no `assert` in production code, and the template's model file names
+ (`dto.py`, `domain_models.py`).
+- **`asbs validate` checks the NATS delivery keys** that otherwise fail only at startup:
+ `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`,
+ `nats_connections_readiness`, `nats_unclaimed_subjects`, and the form and module of
+ `nats_connection_source` (the factory is not called).
+- **`docs/guides/cli-reference.md` is an index**, with one page per command under `guides/cli/`
+ (`setup`, `create`, `validate`, `dev`, `claude`, plus `naming` and `auto-registration`). It was a
+ single 1,023-line page, which meant reading about one flag cost the whole file.
+- **Migrating an existing agent into a group is its own page**,
+ `guides/multi-agent-migration.md`, split out of `guides/multi-agent-setup.md`.
+- **`README.md` links are absolute.** Relative links do not resolve on the PyPI project page or in
+ the installed `METADATA`. The CI badge pointed at an unrelated repository.
+
+### Fixed
+
+- **`asbs validate` no longer fails an image build on an unset `nats_url`.** Outside development
+ it reported one as an issue, and an image that validates while it is built has no `nats_url` yet:
+ the deployment injects it when the container starts. It is a notice now, as `event_bus` is; the
+ process still refuses to start without one.
+
+- **Readiness follows a healthy start within seconds.** The periodic health check is an
+ APScheduler job, and APScheduler dropped a run that started more than 1 s late; every dropped run
+ kept the verdict of the first startup moment -- AI clients "not initialized", agents paused --
+ for another interval: measured 96 to 217 s after a start. A late run now runs, and runs missed
+ meanwhile are folded into one.
+
+- **Under Dapr, a shared topic is warned about when `idempotency_enabled` is `"false"`.** The
+ startup check for a topic two agents declare read the raw value, and the string `"false"` an
+ environment variable can deliver counts as true, so an agent that does not deduplicate went
+ unmentioned. It is read like the handler chain reads it now. `asbs validate` applies the runtime's
+ own functions for this and six other startup rules instead of restating them.
+
+- **`app_environment` reads the environment that was loaded.** Written inside `[default]` it selects
+ nothing, yet `Config.get("app_environment")` answered its value: a process that loaded
+ `[development]` ran its production checks (`nats_url` required) -- or, the other way round, its
+ development fallbacks. It now answers the loaded environment, and startup logs a WARNING when the
+ settings say otherwise.
+
+- **With deduplication on, an event cut off by `nats_handler_timeout` is no longer lost.** The run
+ is cancelled and nak'd, but the dedup marker was released only for an `Exception`, and
+ cancellation is not one. The redelivery found the marker, was skipped as a duplicate and
+ acknowledged, and the event was never processed. The same happened to a handler that swallowed
+ the cancellation, to a run cancelled by a shutdown, and to a failure after the handler returned
+ (a scalar return value that is not a valid `HandlerResult`). A delivery now keeps its marker only
+ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the
+ redelivery acknowledged unrun; now the redelivery runs to completion.
+
+- **A group named only by its group file is the deployment group** (S19). A group file that declares
+ one group needs no `BLUEPRINT_GROUP`, but the name reached neither the NATS connection name, the
+ telemetry resource's `deployment.group` nor the supervisor's log lines, which read only the
+ variable: they said ``. They now carry the resolved name.
+
+- **`diskcache-rs` 0.4.10 is the minimum, and a disk cache's claim is documented as per-process**
+ (S23). 0.4.9 and earlier refused a second process the cache directory ("Database already open").
+ 0.4.10 lets several open it, but its set-if-absent is not atomic between them: four processes
+ claiming one key at once each won in 297 of 300 rounds. A disk cache's claim therefore holds
+ within one process: replicas sharing a cache directory (or `uvicorn --workers N` run by hand) can
+ both win one deduplication marker or one in-process tick, and a claim across replicas needs
+ Redis. The docs no longer say "a disk cache on a shared volume".
+
+- **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused
+ or changed:
+ - A health check of the application's own under a built-in name (`cache`, a client's name)
+ replaced the built-in in 0.8 and failed the build here. It replaces it again, with a WARNING.
+ Two checks of the application's own under one name are still refused.
+ - A handler instance passed after a handler class of the same priority failed the build. Every
+ declared handler now registers in declaration order, as 0.8 did, whether passed as a class or
+ as an instance.
+ - A `SessionsJobHandler` subclass that widened `can_handle_event` was only offered its own job
+ type, which it declared automatically. It declares nothing now when it overrides the selector,
+ and is offered every event as in 0.8.
+
+- **asyncio debug mode is off unless `event_loop_debug` is set** (S21). It was on by default in
+ development -- the default environment -- so an application that never set one paid for debug
+ mode on every coroutine. The watchdog runs instead. The value is read as a boolean: `"false"`
+ from an environment variable means false, and a value that is no boolean fails startup.
+
+- **Shutdown runs to the end past a failed step** (N1). A startup recovery task that had ended by
+ raising re-raised while shutdown cancelled it, and a failing actuator shutdown raised out of the
+ lifespan; either skipped every later step. Both are logged and shutdown goes on.
+
+- **A JetStream consumer that filters another subject is no longer bound.** Root topic
+ `orders-created` and agent `orders` on topic `created` derive the same durable name
+ (`orders-created-durable`). Whichever started second bound the other's consumer with only a
+ drift warning, and received that topic's messages in its own handler. It now refuses to bind:
+ the subscription fails with an error naming the consumer, its filter and the topic, and the
+ connection retries. Rename one of the topics.
+
+- **The "Created JetStream consumer" line is logged when `nats_ack_wait` is unset.** It formatted
+ the unset value with `%.1f`, so the line was lost to a logging error; it now reads
+ `ack_wait server default`. A delivery whose run could not be started no longer keeps its run slot.
+
+- **A group's telemetry is no longer cut off at shutdown.** All agents share one span processor
+ and one metric exporter, and the first provider to shut down closed them for every other: the
+ remaining agents' final metrics were dropped ("Exporter already shutdown"). They are now closed by
+ the last provider, and the application's shutdown flushes every provider after its components
+ have stopped -- agents first, the root last. Measured against a collector: 2 of 4 final metric
+ points arrived before, 4 of 4 now.
+
+- **In a group, `OTEL_SERVICE_NAME` no longer names every agent alike.** The agents keep their own
+ name as `service.name`; the variable names the root's telemetry, as standalone. Startup logs a
+ WARNING naming the value. A `service.name` in `OTEL_RESOURCE_ATTRIBUTES` without
+ `OTEL_SERVICE_NAME` now fails the start of a group, for the same reason; standalone it is used as
+ declared.
+- **An agent's own `otel_service_name` reaches its telemetry.** `[] otel_service_name` was
+ resolved for the agent and then ignored: its resource always carried the agent's name. It is the
+ agent's `service.name` now. The root's `otel_service_name` still never applies to an agent.
+
+- **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.**
+ The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one
+ handler made to it reached the next. A delivery one agent acknowledged and another terminated
+ answered `SUCCESS` with the terminating agent's reason. Startup now warns about a topic two agents
+ declare while one of them runs without `idempotency_enabled`, since a retry asked for by one
+ redelivers to all of them.
+
+- **The `topic` label of the event counters is bounded under Dapr.** `blueprint.events.unhandled`,
+ `.duplicate` and `.skipped` took the topic from the request path, so posts to `/events/`
+ minted one time series each. A topic the agent did not declare is now counted as ``
+ (every topic, with `dapr_declarative_subscriptions = true`); the real one stays in the log line.
+ The DROP answer for an unparseable body is limited to the delivery route `/events/{topic}`: another
+ route of a `DaprEventing` subclass answers a malformed body with 422 again.
+
+- **A slow cache no longer holds up every delivery of the process.** The dedup claim and release, and
+ the in-process scheduler's tick claim, ran on the event loop, so a Redis that stopped answering
+ stalled every agent for as long as the call blocked. They now run in a worker thread. **The minimum
+ redis-py is now 8.0**, the release that bounds every call by a 5 s default; before it the default
+ was no timeout at all. New, opt-in: `cache.redis_socket_timeout`. Measured with the Redis container
+ paused and a 2 s timeout: the event loop's longest gap was 0.06 s (before: 2.02 s), and the claim
+ failed open after 2 s. Startup now warns when deduplication runs without a heartbeat -- NATS with
+ `nats_heartbeat_enabled = false`, and Dapr -- where a redelivery of a running event is skipped as a
+ duplicate.
+
+- **Scaffolded images select the production environment, and the group image turns healthy.** The
+ generated Dockerfiles set `DYNACONF_ENVIRONMENT`, which selects nothing, so every image ran the
+ `development` section; they now set `DYNACONF_APP_ENVIRONMENT` (`production`, and `development` in
+ the dev stage). **Existing projects: rename the variable in your Dockerfile** -- the image then
+ loads `[production]`, with no localhost broker fallback. The group image's health check used `curl`,
+ which its slim base does not have, and is now a Python one. `asbs setup` checks the agent's name
+ before writing anything, `asbs create service` writes a service that imports, and the messages
+ about what `asbs dev` serves without `--name` (the agent alone, at the root namespace) are correct.
+
+- **`/status/env` no longer leaks what its masking missed, and no longer fails on `${PORT}`.** A URL
+ password holding `/`, `?` or `#` was partly returned, a token in a query string, an `AccountKey=` in
+ a connection string and every value of a section under a secret-named key (`credentials`) were
+ returned in clear, and keys such as `sentry_dsn` or `db_pass` were not recognised; a URL with a
+ non-numeric port answered 500. Measured over HTTP: seven placeholder secrets in the response
+ before, none now; status 200 with `${PORT}` (before: 500).
+
+- **Clearing the root Redis cache no longer clears every agent's.** Every named and agent cache nests
+ under the default store's key prefix, and its `clear()` deleted everything under it -- with
+ `key_prefix = ""`, the whole database. Its `list_namespaces()` listed the nested stores as its own
+ namespaces. The default store now touches only keys of its own form, and a clear without a prefix
+ warns. The key layout is unchanged. Measured on Redis 7: two agents' caches and a foreign key survive
+ a root clear (before: all gone, the database empty without a prefix).
+
+- **Crontabs read the same in both scheduler modes, or fail startup.** The day of the week is
+ apscheduler's count -- `0` = Monday ... `6` = Sunday -- so `in_process` firing days do not move. `7` is
+ refused (it was accepted in `event` mode and failed only when the timer was built), and **an `event`-mode
+ scheduler whose crontab gives the day of the week by number (`1-5`, `*/2`) now fails startup**: the
+ external cron counts `0` as Sunday, so the number named a different day there. Write names
+ (`mon-fri`). The crontab is now checked when the scheduler is wired in both modes. New, opt-in:
+ `scheduler_timezone` for the `in_process` timer; unset keeps the host's local time.
+
+- **A scheduler whose startup failed is no longer reported as recovered.** It was marked started before
+ its timer existed, so the startup retry found it "already started" and cleared the agent's latch
+ with no timer running.
+
+- **Every scheduler's `blueprint.scheduler.tick_age_seconds` is exported.** A second scheduler of one
+ agent created a second gauge of the same name, which the SDK drops, so only the first was reported.
+ Measured with two in-process schedulers: two points (before: one).
+
+- **`asbs validate` checks schedulers as the runtime does.** It accepts `scheduler_mode` written as the
+ runtime reads it (`"Event"`), counts environment overrides, refuses an `event_bus` that cannot deliver
+ a tick, reports a missing `event_bus` as a notice (it is a process-wide key and may be set elsewhere),
+ and `--group` runs the scheduler checks per agent.
+
+- **`asbs validate` reads settings the way the process does, for one environment.** The target is
+ `--environment`, else `DYNACONF_APP_ENVIRONMENT` (or `_APP_ENVIRONMENT`), else
+ `production` -- what the scaffolded Dockerfiles set; use `--environment development` for what
+ `asbs dev` runs. A key set only in another environment's section counts as unset, and a key
+ written outside any section is warned about (the process loads none of them). Each agent's
+ `.secrets.toml` and `settings.toml` are layered as the runtime layers them, and `--group`
+ resolves the group file as the runtime does (`--group-config`, `--group-name`). Newly reported:
+ crontab and timezone errors, deduplication without a ttl or a cache, a missing `nats_url`
+ outside development, a non-boolean heartbeat or `event_loop_debug`, an empty agent map, and the
+ runtime's group-file refusals in its own words. Of 19 cases measured on fresh scaffolds where the
+ process refuses to start or warns, the validator used to report 1; it reports all 19.
+
+- **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the
+ scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route
+ `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and
+ `/api/orders/scheduler/nightly/trigger`, as the docs said. **Alpha users of grouped event-mode
+ schedulers: move the publishing `CronJob` to the new subject.** A standalone scheduler is unchanged.
+ An event-mode scheduler's tick handler now belongs to the scheduler's agent; it was registered at the
+ root, in the root's handler chain.
+
+- **The registry keeps agents apart where it did not.** A namespaced lookup's qualified key could be
+ another agent's (`orders` + `eu_ledger` is `orders_eu` + `ledger`); it now has to belong to the asking
+ agent. A view can no longer clear the registry, shut down the thread pools, rename or register
+ another agent's component, or take another agent's thread pool. A declaration shared by several
+ agents is now also refused when it carries state in a bound method or a closure.
+
+- **An agent's own `.secrets.toml` is read in a group.** Only its `settings.toml` was merged, although
+ the layout check, the guides and `asbs setup` said the secrets beside it are read. It is now merged
+ first, so a secret wins over the settings file, and none of its values is logged.
+
+- **Agent settings are resolved for the environment the process actually loaded.** With
+ `ENV_FOR_DYNACONF` set, the process loaded that environment while every agent's file was layered for
+ `app_environment`; and each agent kept its other environments' sections as keys (`production` in
+ development). Both now follow what Dynaconf loaded.
+
+- **An agent can no longer read or overwrite what is not its own through its name.** `cache`,
+ `event_publishing`, `runtimes` and `runtime` are refused as agent names (an agent's settings would
+ have landed in the shared section); merging an agent's settings onto a plain key of the same name
+ fails instead of replacing it; and a view refuses a bare key naming another agent, which returned that
+ agent's whole section.
+
+- **A group file that says something other than what it means now fails startup.** A name in
+ `critical_agents` (or `BLUEPRINT_CRITICAL_AGENTS`) that the group does not run made every agent
+ non-critical -- also when `BLUEPRINT_AGENTS` replaced the file's list, whose `critical_agents` still
+ applies. `agents: order` (a scalar) was read letter by letter, a group declared twice in one file
+ resolved to whichever came last, and a group whose agents were all skipped started with none and
+ reported ready. Each of these is now a `GroupConfigError` naming the problem.
+
+- **Named connections changed at runtime no longer leave an old link consuming.** A connection changed
+ twice before its new binding was bound, or changed and then removed, kept its original link
+ subscribed for good: only the not-yet-bound binding in between was retired. Measured on a broker
+ with one account per connection: the original link is now closed in both cases (before: still
+ open after 15 s).
+
+- **A named connection whose subscription the broker refuses is no longer reported as bound.** The
+ broker refuses a subscription asynchronously, so `subscribe()` returned and the connection read as
+ bound and was never retried. A bind now waits for the broker's round trip, and a refusal fails the
+ connection as a tenancy fault (Breaking 18). Measured when it was still retried: `retrying` with
+ `permission_denied` (before: `bound`).
+
+- **An operator's consumer with `idle_heartbeat` or `flow_control` works in binding mode.** Its status
+ messages reached the handler, were terminated as matching no subject, and an unanswered flow control
+ request stalls the consumer. Heartbeats are now dropped and flow control requests answered. A new
+ `tls` context alone no longer counts as a changed connection, which rebound every `tls://`
+ connection on every notify.
+
+- **A degraded agent whose resume fails is no longer left off its topics for good.** The supervisor
+ resumes an agent once, on the transition back to healthy, and a paused NATS client reports
+ healthy; a failed re-subscribe therefore left the agent paused with every check green, and nothing
+ tried again. The client now retries in the background -- from `event_client_retry_delay`, doubling
+ to 60 s, a WARNING per attempt -- drops what a failed attempt subscribed, and stops when the agent
+ is degraded again or shuts down. Measured: a resume failing on a stream that could not be recreated
+ consumed again 7 s after the obstacle was removed (before: still paused 36 s later).
+
+- **`event_bus = "sessions"` agents now stop consuming while degraded (C4).** The sessions job stream
+ is no transport client, so the supervisor never paused it: a degraded agent kept taking jobs. Its
+ stream is now closed while it is degraded and reopened when it recovers; a job that reaches it in
+ between is left pending for a healthy replica.
+
+- **A JetStream agent no longer gains a second subscription per topic on every reconnect.** nats-py
+ restores every subscription itself after a reconnect, the JetStream ones included; the client
+ subscribed again on top, and the extra subscriptions were unknown to pause, drain and shutdown. A
+ degraded agent therefore kept consuming through them: after one broker restart, a paused agent ran
+ all 10 of 10 events sent to it. A reconnect now re-checks the stream and the consumers (recreating
+ them if the broker lost them) and subscribes nothing. Measured: subscriptions 2 before and 2 after
+ a restart (4 before the fix), 0 runs while paused, every event run once after a restart and after a
+ broker that lost its storage.
+
+- **An agent started before its broker no longer hangs in startup.** With reconnects unlimited (the
+ default, `nats_max_reconnect_attempts = -1`) nats-py retried the first connect inside itself for
+ ever, so startup never returned and `event_client_max_retries` was never consulted. The first
+ connect now fails after two attempts, the retry loop takes over, and reconnects of an established
+ connection stay unlimited. An agent that connects while it is paused re-evaluates its health at once
+ instead of one health interval later. Measured: startup returned after 5.6 s (before: not within
+ 120 s), and the agent consumed once the broker was up.
+
+- **A delivery that reaches a paused agent is nak'd instead of run** (JetStream), so it redelivers to a
+ healthy replica; Core NATS, which cannot nak, still handles what the drain lets through.
+
+- **With deduplication on, one named connection's event no longer suppresses another's.** The dedup
+ key was the event's `source` and `id` only, so the same producer behind two connections -- two data
+ sources emitting the same ids for different data -- had the second connection's event skipped as a
+ duplicate and acknowledged. A delivery from a named connection now adds the connection's name to
+ the key; the default connection keeps the old key, so existing markers still match. Measured on a
+ broker with one account per connection: before, the second connection's event was skipped; now
+ both run, and a repeat on the same connection is still skipped.
+
+- **Logs and Dapr answers no longer carry payload values or credentials.** A delivery that is not a
+ valid CloudEvent was logged with pydantic's rendering of the error, which quotes every offending
+ input value: under Dapr (`Discarding unparseable delivery`), under NATS (`Discarding unparseable
+ message`, also in 0.8) and for a malformed inner event of a `com.dapr.event.sent` envelope, which
+ was additionally logged in full when it had no `type`. These lines now name each field and error
+ type only (`body.id: string_type`). The Dapr answer for an exception that is not a `HandlerError`
+ carries its type name as `reason` (`"ValueError"`), no longer its text; a `HandlerError`'s
+ `reason` is unchanged. The NATS connection lines (a failed attempt, a permanent failure, an error
+ on a named connection) redact the URL and the connection's password, token and nkey seed, and the
+ permanent-failure line no longer adds a traceback. Measured with a placeholder secret in the
+ payload, against JetStream and the Dapr endpoint: before, it was in 1 to 4 log records per
+ scenario and in the Dapr answer; now in none.
+
+- **`/health/ready` no longer waits for a running health poll.** The cached answer was read under the
+ lock the poll holds while it awaits every check, so a slow check -- a NATS connect up to its 10 s
+ timeout -- delayed every readiness probe with it. Measured with a 4 s check: up to 3.9 s per probe
+ before, under 0.1 s now.
+- **A NATS connection that gave up reconnecting comes back, with its subscriptions.**
+ `nats_max_reconnect_attempts` now defaults to unlimited (was 5, about 10 s of outage), and a
+ connection that closes anyway restarts the client's retry loop, which connects and resubscribes;
+ a health check no longer opens a bare connection that subscribes to nothing.
+- **NATS deliveries are no longer handled strictly one at a time.** nats-py gives each subscription
+ one task that awaits its callback, and the callback ran the whole handler -- so an agent handled
+ one event per subscription and process at a time, however much of the run was spent waiting on a
+ model. Each delivery now runs as its own task, up to the new `nats_max_concurrent_runs` per agent,
+ shared by its subscriptions; unset, each subscription still runs one delivery at a time, the
+ previous behaviour. Measured against a real broker with 2 s handlers: 5 events
+ took 10 s before and 4 s with the key at 4.
+- **A long JetStream run is no longer redelivered while it still runs.** The delivery is reported
+ `in_progress` every third of the bound consumer's `ack_wait` until it is settled. Measured: one
+ 7 s run under a 3 s `ack_wait` ran three times before, once now.
+
+- **Successful health probes are left out of the access log, as documented.** `HealthCheckFilter`
+ looked for `" 200 "` in uvicorn's access line, but uvicorn ends that line with the status code,
+ so the filter never matched and every `/health/live` and `/health/ready` probe was logged. It now
+ parses the line, drops 2xx responses on those two paths (with or without a query string), and
+ keeps everything else -- a failed or redirected probe is still logged. Visible wherever
+ `uvicorn.access` logs at INFO: the grouped image's `python -m blueprint.agents.entrypoint`, which
+ calls `uvicorn.run(app, log_level=...)` after the app is built and so resets that logger's level,
+ and any deployment with `suppress_noisy_loggers = false`.
+- **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since
+ the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a
+ group cannot depend on where it runs; it now applies only to an agent's view in a group.
+- **`OTEL_RESOURCE_ATTRIBUTES` is honoured.** The framework set `service.name`, `deployment.group`
+ and `service.instance.id` in code, which the OpenTelemetry SDK lets win over the environment, so
+ a value a deployment declared was silently replaced -- `service.name` included, since 0.8. A key
+ declared in `OTEL_RESOURCE_ATTRIBUTES` or `OTEL_SERVICE_NAME` is now used exactly as declared;
+ the framework fills only what was left out. A standalone agent's resource carries no
+ `deployment.group` (it was ``), and no placeholder instance id when the pod is unknown.
+- **A standalone agent's `/health/ready` has its original shape again.** The body gained `policy`
+ and a `namespaces` section keyed `""`, which describe the agents of a group. They now appear
+ only when the process hosts a group; a standalone agent gets `status` and `components`, as before.
+ The same holds for `/status/env`: its `namespaces` breakdown appears only in a group (the new
+ `envvar_prefix` field stays), and its log line is the 0.8.1 one for a standalone agent.
+- **A standalone agent's NATS connection is named after its pod alone.** It was named
+ `..`, implying a namespace and a group that do not exist for it. Before the
+ namespace feature it sent no name; now it sends the pod (or host) name, and none if that cannot
+ be determined. Agents in a group keep `..`.
+- **A standalone agent logs what it logged before the namespace feature.** Log lines and error
+ messages that existed in 0.8.1 had been reworded for groups, with `` standing in for a
+ standalone agent's empty namespace -- e.g. `Eventing component startup completed`,
+ `No handler in namespace '' processed event`, the NATS connect and subscribe lines, the
+ cache registration lines, `Health check failed for …`, `Readiness probe failed: …`, the
+ configuration and OpenTelemetry lines, and the registry's "no cache" and "already exists"
+ errors. A standalone agent emits the 0.8.1 wording again; a grouped process keeps the new one.
+- **A handler failure is logged once.** The handler chain and `EventProcessingService` each logged
+ it at ERROR before re-raising, and the transport edge logged it again with its disposition --
+ up to three copies per failure. Only the edge logs it now. `DaprClient.publish`, `NATSClient.connect`
+ and `Config.validate` stop logging before raising, too.
+- **The documented health-check example reported a failing check.** `HealthCheckerBase`'s example
+ returned `status="UP"`, but readiness counts anything other than `"healthy"` as failing;
+ `SessionsServiceHealthChecker` returned `UP`/`DOWN` and so always counted as down. Both now use
+ `"healthy"`/`"unhealthy"`.
+- **Stale documentation:** the health package README described three classes that do not exist
+ (rewritten); `components/services.md` said `ServiceBase` has no abstract methods (it has two);
+ the `RestApiBase` and `EventHandlerBase` docstring examples did not run; `namespace_of` and the
+ registry's log line described code that has moved on.
+- **`opentelemetry-instrumentation-httpx` is a declared dependency.** `telemetry.py` imports it,
+ and it was installed only because something else happened to pull it in.
+- **Scaffolding fixes.** The generated `Dockerfile` copied a `README.md` that nothing generates, so
+ `docker build` on a fresh project failed; the generated `settings.toml` chose `scheduler_mode =
+ "in_process"`, defeating its deliberate lack of a default, and carried an internal model host;
+ `asbs validate` told an agent to add an `agents.toml`, which an agent must not carry, and now
+ points at the image's map instead (as a notice); `asbs setup` said a standalone agent's routes
+ were under `/api/`; the generator called `sys.exit(1)` from library code on an invalid
+ config and now raises `ValueError`. The unreferenced `assistant_integrations/CLAUDE.md` is no
+ longer packaged.
+- **`SessionsJobHandler` no longer grows without bound.** Its replay guard kept every finished
+ job's id for the life of the process. It now remembers an id for an hour and at most 10,000 ids
+ (`SEEN_TTL_SECONDS`, `SEEN_MAX_ENTRIES`, overridable per subclass).
+- **REST request bodies are no longer logged.** `RestApiBase._process_resource` put the whole
+ payload into the `extra` of an INFO line, so personal data and secrets in a request body reached
+ the logs. Only the payload's type is logged now.
+- **A REST request keeps one request id.** `process_event` replaced the id the REST layer had
+ created, logged and returned as the RFC 7807 `traceId`, so processing ran under a second id that
+ matched nothing the caller saw. A caller's id is now kept.
+- **The vLLM request timeout has its own key.** It was taken from `model_max_tokens`, so 4096
+ tokens meant a 68-minute HTTP timeout and 5 tokens a 5-second one. `model_timeout` (seconds,
+ default 60 for vLLM) sets it now, and applies to the OpenAI client too when set.
+- **The Dapr routing key reaches the sidecar.** It was sent as an HTTP header, which Dapr's publish
+ API does not read; it is now the `metadata.routingKey` query parameter.
+- **One declaration with an `AgentBuilder` can serve several agents of a group.** A group replays
+ a declaration once per agent, and `AgentBuilder.build()` is single-use, so the second agent failed
+ with "AgentBuilder.build() has already been called". Each agent now builds from its own copy of
+ the builder, with its own tool list.
+- **`AgentBuilder.with_result_type()` and `with_deps_type()` take effect.** Both were stored and
+ never passed to the agent, so a structured-output agent returned plain `str` and the documented
+ `result.output.` failed. They are now passed as `output_type` and `deps_type`. Giving the
+ same value to `build()` as a keyword as well is refused.
+- **Event deduplication claims atomically.** The handler chain checked for the marker with
+ `exists()` and then wrote it with `set()`, so two replicas handed the same event at the same moment
+ both passed the check and both dispatched. It now uses the cache's `claim()`, which already
+ existed for the scheduler's tick claim -- atomic across replicas on Redis, and within one process
+ on a disk cache.
+- **A handler result that fails to publish fails the delivery.** `publish_handler_event` caught
+ every exception and logged a WARNING, so the inbound event was acknowledged and the handler's
+ output was lost. The failure now naks the event -- the handler runs again on redelivery -- and the
+ dedup marker is released so the redelivery is not skipped. Result events get a deterministic id
+ (UUIDv5 over agent, source event, type and position) instead of a random one, so a republished
+ result keeps its id and consumers can deduplicate it.
+- **An agent latched down at startup is shown as down in `/health/ready`.** The latch paused the
+ agent and set its gauge to 0, but readiness was computed from health checks alone, so the probe
+ and the payload reported it `UP` with nothing failing. The payload now shows it `DOWN` with a
+ `reason`, and the readiness policy counts it. The poll also no longer skips everything when no
+ health check is registered, which had left both the verdict and resumption unevaluated.
+- **An agent latched down at startup recovers without a restart.** Its failed components are
+ retried every `startup_retry_interval_seconds` (default 30), in start order; when all have
+ started the latch is released and health checks decide. It never ends the process. `on_startup`
+ must therefore be safe to call again after it raised.
+- **A non-critical agent marked down at startup no longer consumes events anyway.** When its
+ client failed `on_startup`, the agent was paused before its eventing endpoint subscribed, and the
+ subscribe path ignored the pause -- so the latched-down agent connected and took events it could
+ not process. A paused client now registers its topics and waits; it connects and subscribes only
+ if the agent is released.
+- **Credentials inside `nats_url` no longer reach the log or `/health`.** The connect log line
+ printed the URL verbatim, and the NATS health message printed the parsed URL including
+ `user:password@`. Both now show `***@host:port`.
+- **An environment override of a key an agent's own `settings.toml` also sets now wins in a group.**
+ `DYNACONF___KEY` was compared against the agent file's keys case-sensitively -- Dynaconf
+ upper-cases what it loads, the file keeps lower case -- so the override was never seen: a list
+ was concatenated with the file's, a scalar was replaced by the file's value, and the key was
+ reported as merged. Keys are now matched case-insensitively, at every nesting level.
+- **Both scaffolded `Dockerfile`s declared a `HEALTHCHECK` against a route that does not exist.**
+ `curl -f http://localhost:8000/health` -- but `ActuatorApi` serves `/health/live` and
+ `/health/ready`, and nothing at `/health`. `curl -f` fails on the 404, so every container built
+ from a scaffold reported `unhealthy` for its whole life: compose's `depends_on:
+ service_healthy` never released, and anything reading Docker's health state saw a permanently
+ failing container that was in fact serving traffic. Both now probe `/health/live`, which is what
+ the deployment guide has always shown. A generated-project test holds the path.
+
+- **`asbs validate --group` contradicted the runtime about where an agent's `root` points.** The
+ runtime resolves every `root` against the **image root** -- the directory the process runs in --
+ and `BLUEPRINT_AGENT_MAP` may put the map anywhere, so a repository keeping `deploy/agents.toml`
+ with its agents at the top runs correctly. The validator resolved each `root` against whichever
+ directory the map sat in, so it reported that layout as `... is not a directory` under the
+ verdict "would stop this image starting" -- a false statement about a working image, whose
+ correct reading is to break a layout that worked. The two coincide only where the map is at the
+ image root, which is what `asbs setup --group` writes, so no test caught it. The command now
+ takes the directory argument as the image root and `--agent-map PATH` (or `BLUEPRINT_AGENT_MAP`)
+ as where the map is; a relative path resolves against the image root, as at runtime. The error
+ for an absent map names the flag. Present since `root` became required in 0.9.0a4.
+- **An agent settings file that scoped keys under the agent's own name merged into nothing.**
+ `[default.]` in that agent's own `settings.toml` nested to `..*` once the
+ file was merged under the agent's namespace, so every key in it was unreachable -- and the
+ failure surfaced far from the cause, as `No model name for runtime agent '_agent'
+ configured`, naming the agent rather than the file. Found migrating a real project. It is now
+ refused at merge, naming the section and the fix, and `asbs validate --group` reports it without
+ starting anything. Plain `[default]` serves both shapes: standalone resolves it because a scoped
+ lookup falls back to the root key.
+- **A grouped agent's own `settings.toml` was never read.** The group looked for it beside the
+ *declaration module* -- inside `src/` -- while every scaffolded project writes it beside `src/`,
+ so the file existed, looked right, and was never opened. Nothing failed: the agent ran on the
+ group's defaults and said so nowhere. It is now read from the directory the agent map states.
+- **Prompts resolved against the process working directory.** One directory for a whole group, so
+ it was right for at most one agent; the others found nothing, or found a neighbour's prompt of
+ the same name. Each agent's configuration view now reports its own directory as the package
+ root, so `/src/prompts` resolves exactly as it does standalone.
+- **A scaffolded agent no longer ships process-wide keys.** `log_level` and `log_format` were
+ written into every agent's `settings.toml`, so every group one joined dropped them with a
+ warning about a file the scaffolder itself wrote. They are now commented out, with the reason.
+
+- **`pytest` and `pytest-asyncio` are no longer runtime dependencies.** They were listed in
+ `[project.dependencies]`, so every consumer installed the test suite's tooling in production.
+ They remain in the `ci` extra.
+
+- **⚠️ The environment a project selects is now actually the one that loads** (#89). `Config`
+ passed the resolved `app_environment` to Dynaconf as `current_env=`, which is a *derived*
+ property reporting the active environment, not the parameter that selects one. That parameter
+ is `env=`. The resolved environment was therefore never applied: a deployment could log
+ `Loading configuration properties for environment: production` and read every value from the
+ default section, with nothing anywhere disagreeing. Verified against dynaconf 3.3.5 — with two
+ sections that differ, `current_env=` returns the default's value and `env=` returns
+ production's.
+
+ **This is a behavioural change, and it is not opt-in.** A project that declares a non-default
+ `app_environment` *and* has a matching `[]` section has been silently running the
+ default section; on upgrade it starts getting the section it always asked for. If that section
+ is stale — written once, never exercised, never corrected because it never took effect — the
+ values in it go live on upgrade. **Check your non-default sections before upgrading.** A
+ project with no `app_environment`, or with no section for it, is unaffected.
+
+ Note `app_environment` is read by the first configuration pass, which loads with
+ `environments=False` and so sees **top-level keys only** — the same shape `envvar_prefix`
+ requires. Declared inside a section it is invisible to that pass and selects nothing, before
+ this fix or after; set it at the top level of `settings.toml`, or as `_APP_ENVIRONMENT`
+ in the environment. Pinned by `TestTheResolvedEnvironmentIsTheOneLoaded`, whose cases fail
+ against the old keyword.
+- **`/status/env` no longer returns credentials in clear** (#91). Config masking matched whole keys
+ only, so anything with a prefix or suffix around the secret word came back readable. Present since
+ `4e6421b`, unrelated to grouping. An agent-scoped actuator also now reports its own scope rather
+ than the whole tree.
+- **Dapr declared topics actually subscribe** (#81). `GET /dapr/subscribe` served nothing usable and
+ answered 422 to the sidecar. A project that overrides `get_subscribed_topics()` will see Dapr
+ behaviour change by design — declared topics went from subscribing to nothing to subscribing.
+- **Resilient broker startup and subscription readiness** (#28). Connection and subscription setup
+ run asynchronously with background retry, `/health/live` succeeds while retrying,
+ `/health/ready` stays unhealthy until subscriptions are established, and NATS and Dapr behave
+ consistently. Configurable via `event_client_max_retries` and `event_client_retry_delay`.
+- **Schedulers no longer fire duplicate cron ticks under multiple replicas or workers** (#73).
+ `scheduler_mode = "event"` delivers the tick as an ordinary event, so the queue group picks one
+ replica; `"in_process"` claims each tick in the shared cache so one replica runs it (across
+ replicas, a Redis cache: a disk cache's claim holds within one process).
+- **Schedulers no longer start twice** (#43), on both causes: a second `build()` pass no longer
+ starts a second timer, and `SchedulerBase` sitting in the REST-API lifespan loop as well as the
+ scheduler loop no longer creates two `AsyncIOScheduler` instances per scheduler. The manual
+ trigger route is now registered before `include_router` copies it, so it is actually served.
+- **`AgentBuilder` no longer needs a `Config` at construction and builds no model during `__init__`**
+ (#4). The AI client and model are resolved in `build()`, against the agent's own configuration view.
+- **The unit/integration test split is enforced** (#80). `tests/integration/` was not run by CI and
+ sat at 28 failures asserting on examples that had been removed.
+- **A handler's published result is no longer silently lost under JetStream.** The client declared
+ no publishable subjects, so `js.publish` waited for an acknowledgement no stream would send, timed
+ out, and was swallowed as a WARNING while a Core NATS listener still saw the message. Found
+ against a real broker.
+- **`AgentRuntime` is constructed with its name and registered like every other component.** It
+ registered itself under the bare name, so two agents in a group sharing a runtime name collided on
+ one registry key. This also made a freshly scaffolded project fail to start with
+ `TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name'`.
+- **A scaffolded project starts, tests and validates.** Its settings file wrote `[default.logging]`
+ and `[default.observability]` tables the framework never reads; `asbs create agent` wrote
+ `[default.runtimes..models]` where the framework reads `model_settings`; `asbs create` wrote
+ absolute imports into files using relative ones; `asbs create handler` could die mid-command on a
+ Windows console leaving the project half-edited; and `asbs setup` printed
+ `pip install -e .` without writing a `pyproject.toml`.
+- **`token_metrics_enabled` is actually read.** `get_observability_config()` never passed it, so the
+ per-call token and latency metrics stayed on however the key was set.
+- **`GET /cache/stats` no longer returns 500**, and the four overlapping cache documents are one,
+ rewritten against the code.
+- **Five bundled examples declared an `app_name` the broker refuses**; `webhook_relay` was broken
+ outright. All renamed, and a test now holds every example's `app_name` to the subject alphabet.
+- Events that match no handler are counted rather than flagged, acknowledged rather than redelivered
+ to `max_deliver`; a critical error drops on Dapr and terms on NATS; an unparseable body drops
+ instead of answering 422; in-flight handlers drain before the connection closes; JetStream
+ consumers share load via a deliver group; and what the framework gives up on is republished to
+ `.dead-letter` before being termed.
+
+### Deprecated
+
+- **JetStream consumers created before 0.9.** 0.8 left each durable delivering to a random inbox
+ with no deliver group, so only one replica can consume from it. Such a consumer is still found
+ under its name and used exactly as it is -- it is never recreated, which would replay or gap --
+ but it is logged at startup as `DEPRECATED` and will not be supported in a future release.
+ Delete it during a maintenance window; the framework then recreates it so that every replica
+ shares it.
+
+### Known issues
+
+- Generating the `CronJob` for `scheduler_mode = "event"` is deliberately deferred, so the publisher
+ must be written by hand.
+- No CI gate enforces that an environment's group declaration covers the in-image agent map;
+ `asbs validate` reports it locally.
+- The memory number this feature exists to produce — marginal RSS per additional hosted agent — has
+ not been measured (#32, #35, #36).
+- **#75** (supervisord multi-agent-per-host vs. Kubernetes per-agent Pod) is materially answered by
+ the spec: grouping makes the choice a deployment parameter and Kubernetes runs one Deployment per
+ group. The ADR the issue asks for is still outstanding.
+- Dead letters accumulate on `.dead-letter` with no consumer; draining it is an
+ operational task the framework does not perform.
+- `size` in the cache statistics counts TTL metadata entries, so a cache holding two values reports
+ `4`. Documented as-is rather than changed, because a reported metric is somebody's dashboard.
+- **A named connection whose binding names a stream that does not exist is retried, not refused.**
+ It reads `retrying` in `.nats_client:connections` and stops nothing else. With
+ `manage_consumer = false` the client sends no JetStream request, so a missing consumer is not
+ detected at all: the binding reads as bound and receives nothing. Whether either becomes fatal --
+ at once, or after a grace period for provisioning -- is still open.
+- **A disk cache's claim holds within one process only.** Two processes on one cache directory --
+ replicas sharing a cache directory, or `uvicorn --workers N` run by hand -- can both win one
+ deduplication marker or one in-process tick, with no error raised (diskcache-rs 0.4.10). A claim
+ across replicas needs Redis. How this is resolved -- an OS file lock around the claim, or a startup
+ warning -- is still open.
+
+### Upgrading a standalone agent from 0.8
+
+What the broker sees change when an agent that ran on 0.8 starts on this version, with
+`nats_use_jetstream = true`:
+
+- **Existing durables are reused**, found under the same name for a topic without `.`, `*`, `>` or
+ whitespace (`orders` -> `orders-durable`), and announced as deprecated (above). For a topic with a
+ dot the name is now `orders_created-durable`; 0.8's `orders.created-durable` is a name the broker
+ refuses, so no such consumer can exist to be orphaned.
+- **`nats_durable_name` with several topics fails startup.** 0.8 gave all of them one consumer, of
+ which only the first topic's subscription worked.
+- **The stream is widened, never narrowed.** 0.8 created it over `.>` and never touched
+ it again; this version adds every subscribed topic, the dead-letter subject and, when publishing
+ through JetStream, the publish subjects.
+- **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each
+ message reaches one replica instead of every one.
+- **A failed JetStream delivery is redelivered after a delay**, not at once: `nats_nak_delay`
+ defaults to 1 s, 5 s, 15 s, 30 s, then 60 s per redelivery, so with `nats_max_deliver = 5` a
+ failing message is dead-lettered after about 50 s instead of a fraction of a second.
+ `nats_nak_delay = 0` restores 0.8's immediate redelivery (Breaking 20).
+
+What the code sees change:
+
+- **Components are constructed by `build()`, not by the `with_*()` call.** `with_handler(MyHandler)`
+ records the class; `build()` constructs it, in declaration order. Code that looked a component up
+ in the registry between a `with_*()` call and `build()` finds nothing, and an error a constructor
+ raises -- a missing configuration key, say -- is raised by `build()`. In 0.8's
+ `AppBuilder(config)...build()` shape an instance passed to `with_*()` is the caller's own and is
+ used as it is; `build(config)` and a group refuse instances (Breaking 7).
+
+### Rolling back to 0.8
+
+What does not go back by itself when a deployment returns to 0.8:
+
+- **JetStream durables.** This version creates each durable with a deliver subject
+ `_DELIVER.` and a deliver group; 0.8 subscribes with `js.subscribe(..., durable=...)` and
+ no queue, which does not bind to such a consumer. Delete the consumers this version created
+ before starting 0.8 -- messages still pending on them are lost with them. A durable of a dotted
+ topic (`orders_created-durable`) has no 0.8 counterpart and is simply left behind.
+- **Cache entries** written under the new keys (named caches, agents in a group) are invisible to
+ 0.8, which reads its old keys. A standalone agent's default cache keeps its keys either way.
+- **REST paths and Swagger groups** of grouped agents (`/api//nats/...`,
+ `/api//scheduler/...`) do not exist in 0.8; callers and probes that moved have to move
+ back. A standalone agent's paths are the same in both.
+- **Metric labels.** Dashboards moved to `agent` on `blueprint.events.unhandled` and
+ `.duplicate` -- and to the `` topic label under Dapr -- see 0.8's `namespace` label
+ and per-topic series again.
+
## [0.8.2] - 2026-10-06
### Added
@@ -225,7 +1234,7 @@ default_ttl = 3600 # 1 hour default TTL
### Added
- New `/info` actuator endpoint exposing app name, version, and all dependency versions.
-- [ServiceInfo](/src/blueprint/agents/models/status.py:8:0-25:5) model for structured `/info` responses.
+- `ServiceInfo` model (`src/blueprint/agents/models/status.py`) for structured `/info` responses.
- Actuator links (`/info`, `/status/env`, `/status/llm`, `/status/build`) in root `/` metadata.
- Supporting classes in component registry in addition to names
- Fetching an unregistered component now throws an exception
diff --git a/CLAUDE.md b/CLAUDE.md
index f554efbf..5f42b50b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2,7 +2,13 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
-See `AGENTS.md` for architecture, component patterns, and testing conventions shared across all AI assistants.
+See `AGENTS.md` for the architecture, the component patterns, the testing conventions and the **design rules** --
+each with the failure it prevents -- shared across all AI assistants and every human working here.
+
+## Language
+
+This repository is written entirely in English: code, identifiers, comments, docstrings, log and error messages,
+documentation, specs, plans, changelogs, commit messages and pull-request descriptions.
## Dev Commands
@@ -10,17 +16,25 @@ See `AGENTS.md` for architecture, component patterns, and testing conventions sh
# Install in editable mode with dev deps
uv pip install -e ".[dev]"
-# Run all tests (bare pytest not in PATH — always use uv run)
+# Run everything CI runs: tests/unit needs nothing running (bare pytest is not in PATH)
+uv run pytest tests/unit
+
+# Everything, including tests/integration, which needs the services it names
uv run pytest tests/
-# Skip integration tests (no external services needed)
+# Everything that needs no external service. tests/integration is marked by location
+# (tests/integration/conftest.py), so this deselects the whole directory rather than the
+# three tests that happened to carry the decorator.
uv run pytest tests/ -m "not integration"
+# Only the tests that need services running
+uv run pytest tests/ -m integration
+
# Run a single test
uv run pytest tests/unit/agents/app_builder/test_app_builder.py::TestClass::test_name -v
# Run tests with coverage
-uv run pytest tests/ --cov=blueprint.agents --cov-report=html
+uv run pytest tests/unit --cov=blueprint.agents --cov-report=html
# Lint / format / type-check
ruff check src/ tests/
@@ -63,6 +77,77 @@ cp dist/* ~/local-pypi/
uv pip install --no-cache-dir --find-links file:///home/pajoma/pypi/ avs-blueprint-agents==
```
+---
+
+## Multi-Agent Grouping
+
+- **Spec (normative):** `docs/specs/2026-08-28-multi-agent-grouping.md` -- invariants C1-C7, API
+ surface, config reference, acceptance criteria. Where any other document disagrees with the
+ spec, the spec wins.
+- **Implementation plan:** `docs/plans/2026-08-28-multi-agent-grouping.md` -- prerequisites P0-P6
+ (blocking defects) and phases 0-10.
+- **Follow-up plan -- grouped HTTP surface:** `docs/plans/2026-09-28-grouped-http-surface.md` --
+ one Swagger tag per agent, reserved path segments (`nats`, `cache`, `scheduler`), steps 0-4.
+ Spec sec. 11.2. Standalone tags and paths never change.
+
+**Work this feature in reviewable steps.** Make one change, then stop and report what changed and
+why before starting the next. Do not chain phases together, and do not chain the work items within
+a phase, into a single unreviewed run -- each step is meant to be looked at before the next one
+begins. This rule applies to every prerequisite and phase in that plan, and only to this feature.
+
+**Record every change in the feature changelog.** `docs/plans/2026-08-28-multi-agent-grouping-changelog.md`
+is updated as part of each change, not reconstructed at the end: it is the running record of what
+was done and why, and it becomes the pull-request description. Smaller fixes found along the way
+belong in it too -- they are the ones most easily lost.
+
+**Explain new code, not just its arrival.** When a change introduces real implementation -- new
+behaviour, new control flow, a new abstraction -- report what was built and how it works, not only
+which files changed and whether the checks passed. Formatting and lint fixes, type annotations,
+tests and documentation need no walkthrough.
+
+**Report the production code in detail, and report it first.** The walkthrough is about
+`src/`: name each function, branch and call site that changed, show the lines that matter, and say
+what the code now does that it did not do before and what breaks if it is removed. A list of files
+touched, a summary of intent, or "tests pass and lint is clean" is not a report of the code -- that
+is the wrapper around it. Tests, documentation and the changelog are listed, not walked through:
+they are how the change is verified and recorded, not the change itself.
+
+This is not satisfied by having reported the code in an earlier message. **Every message that
+reports a step as done carries the walkthrough**, including the one that follows a background test
+run finishing -- that message reports the step, so it repeats the code detail rather than shrinking
+to a status line. Err towards showing the actual changed lines: a paraphrase of what a function now
+does is weaker than the function.
+
+The rule has been missed repeatedly, so treat it as a checklist item before writing any completion
+message: *have I shown the changed code, not described it?*
+
+Read the spec before changing `component/registry.py`, `app_builder.py`, `handler/`,
+`services/eventing/`, `io/api/eventing/`, `clients/io/nats_client.py`, the schedulers or
+telemetry: those paths carry invariants that are not visible from the code.
+
+---
+
+## Commits
+
+Commit messages follow **Conventional Commits** -- `.pre-commit-config.yaml` runs the commitizen
+hook at the `commit-msg` stage, so the subject line must be `(): ` with
+a type from `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`,
+`revert`. A prefix like `P0:` is not a type and will be rejected once the hook is installed.
+
+Install every hook stage, not just the default one:
+
+```bash
+pre-commit install
+pre-commit install --hook-type commit-msg
+pre-commit install --hook-type pre-push
+```
+
+End every commit message with the repo's trailer:
+
+```
+Co-Authored-By: Claude Opus 5 (1M context)
+```
+
## Project names
This repository is public and used by many projects. The names of projects, products, customers,
diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md
index d69db65a..9f4390de 100644
--- a/CONTRIBUTE.md
+++ b/CONTRIBUTE.md
@@ -56,13 +56,16 @@ This installs:
### Run All Tests
```bash
-python pytest tests/
+python -m pytest tests/
```
### Run Tests with Coverage
+`--cov` comes from `pytest-cov`, which no extra of this package installs:
+
```bash
-python pytest tests/ --cov=blueprint.agents --cov-report=html
+pip install pytest-cov
+python -m pytest tests/ --cov=blueprint.agents --cov-report=html
```
This generates an HTML coverage report in `htmlcov/index.html`.
@@ -70,7 +73,7 @@ This generates an HTML coverage report in `htmlcov/index.html`.
### Run Tests for a Specific Module
```bash
-python pytest tests/unit/test_agent_builder.py
+python -m pytest tests/unit/agents/agent/test_agent_builder.py
```
### Run Tests in Watch Mode (with pytest-watch)
@@ -96,7 +99,7 @@ pytest tests/ -v
### Run a Specific Test
```bash
-pytest tests/unit/test_agent_builder.py::TestAgentBuilder::test_with_model_sets_model_name -v
+pytest tests/unit/agents/agent/test_agent_builder.py::TestFluentSetters::test_with_tool_appends -v
```
## Building the Package Locally
@@ -142,7 +145,7 @@ You should see entries like:
blueprint/agents/__init__.py
blueprint/agents/agent/__init__.py
blueprint/agents/agent/agent_builder.py
-blueprint/agents/api/__init__.py
+blueprint/agents/app_builder.py
blueprint/agents/config/__init__.py
...
```
@@ -206,16 +209,34 @@ mypy src/
black src/ tests/ && ruff check src/ tests/ && mypy src/
```
-## Pre-commit & Pre-push Hooks
+## Commit Messages
+
+Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/): a subject line
+of `(): `, where the type is one of `feat`, `fix`, `docs`, `style`,
+`refactor`, `perf`, `test`, `build`, `ci`, `chore` or `revert`. The commitizen hook configured in
+`.pre-commit-config.yaml` checks this at the `commit-msg` stage, so it only runs if you install
+that stage (see below).
+
+```
+fix(eventing): join a queue group on Core NATS subscriptions
+
+Without queue= every replica received every message, so two replicas
+doubled every side effect.
+```
+
+## Pre-commit, Commit-msg & Pre-push Hooks
-Set up both commit and push hooks:
+Install all three hook stages -- `pre-commit install` on its own installs only the first, which
+leaves the commit-message check inactive:
```bash
pre-commit install
+pre-commit install --hook-type commit-msg
pre-commit install --hook-type pre-push
```
- **Pre-commit** runs linting and formatting checks on staged files before each commit.
+- **Commit-msg** validates the commit message against Conventional Commits.
- **Pre-push** runs the unit test suite before pushing, so CI won't fail on basic issues.
## Troubleshooting
@@ -270,7 +291,7 @@ Publishing is handled by the CI/CD pipeline. See `.github/workflows/publish.yml`
If you encounter issues, please:
-1. Check the [Troubleshooting Guide](docs/guides/troubleshooting.md) for known issues
+1. Check the [Troubleshooting Guide](src/blueprint/agent_generator/docs/guides/troubleshooting.md) for known issues
2. Review the test output carefully for error messages
3. Open an issue on GitHub with details about your environment and the error
diff --git a/README.md b/README.md
index fb85d48d..61d90d2d 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
[](https://pypi.org/project/avs-blueprint-agents/)
[](https://www.python.org/downloads/)
-[](LICENSE)
-[](https://github.com/2SpeakAI/blueprint-agents/actions)
+[](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/LICENSE)
+[](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/actions)
**A Python framework for building production-ready AI agent microservices with event-driven architecture.**
@@ -14,9 +14,10 @@ Blueprint Agents gives you a component-based toolkit for building intelligent mi
## Key Features
- **Component Architecture** -- Five composable base classes (`EventHandlerBase`, `ServiceBase`, `RestApiBase`, `AgentRuntime`, `SchedulerBase`) assembled via a fluent `AppBuilder`
-- **Event-Driven Processing** -- CloudEvents v1.0 with chain-of-responsibility handlers, Dapr and NATS pub/sub support
+- **Event-Driven Processing** -- CloudEvents v1.0 with chain-of-responsibility handlers, Dapr and NATS pub/sub support; on NATS, concurrent runs per agent with JetStream heartbeats and run timeouts, and named connections (several brokers or accounts per agent, supplied by a connection source)
- **LLM Integration** -- AI agents powered by [Pydantic AI](https://ai.pydantic.dev/) with structured outputs, tool calling, and multi-model support (OpenAI, vLLM)
- **Built-in Observability** -- OpenTelemetry tracing, metrics, and structured logging out of the box
+- **Multi-Agent Grouping** -- Run one agent per process, or host several in one process, as a *deployment* choice: the agent's code is identical either way
- **CLI Scaffolding** -- Generate complete project structures and individual components with the `asbs` CLI
- **Deployment Ready** -- Docker, Kubernetes with Helm charts, health checks, and CI/CD patterns included
@@ -28,16 +29,24 @@ Blueprint Agents gives you a component-based toolkit for building intelligent mi
# Install the framework
pip install avs-blueprint-agents
-# Scaffold a new project
+# Scaffold a new project -- asbs setup writes into the current directory
+mkdir my-agent && cd my-agent
asbs setup my-agent
# Start developing
-cd my-agent
pip install -e .
asbs dev
```
-Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`.
+Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`,
+and this agent's routes under `/api` -- served alone, at the root. `asbs dev --name my_agent`
+serves it under the namespace a group image would give it, with its routes under `/api/my_agent`.
+
+`asbs setup` writes your project's `main.py` as a **declaration** -- an `AppBuilder` that is never
+built -- and a `create_app()` that builds it. It writes no `agents.toml`: that map belongs to an
+image that hosts several agents. That is what lets the same project run on its own and be hosted
+alongside other agents without changing a line. See
+[Running one agent, or several](#running-one-agent-or-several).
---
@@ -57,27 +66,43 @@ uv add avs-blueprint-agents
### Alpha Release (TestPyPI)
-To install the latest alpha version for testing, add the TestPyPI index to your `pyproject.toml`:
+Alpha builds are published to TestPyPI. **TestPyPI must be used for this package only** -- it also
+carries stale copies of common dependencies (an ancient `fastapi`, an `apscheduler` too old for
+this package), and any setup that lets the resolver reach them for *dependencies* fails.
+
+With uv, name the index for this one package and nothing else:
```toml
[[tool.uv.index]]
name = "test-pypi"
url = "https://test.pypi.org/simple/"
-priority = "supplemental"
-```
+explicit = true # only for packages that name it below
-Then install:
+[tool.uv.sources]
+avs-blueprint-agents = { index = "test-pypi" }
+```
```bash
-uv add avs-blueprint-agents
+uv add "avs-blueprint-agents==0.9.0a1"
```
-Or with pip:
+`explicit = true` is the load-bearing part: without it uv applies its default `first-index`
+strategy, pins every dependency to the first index that happens to contain it, and the resolution
+fails on TestPyPI's old `apscheduler`. That is deliberate protection against dependency confusion,
+not something to work around with `--index-strategy unsafe-best-match`.
+
+**pip has no equivalent** -- no index priority and no per-package source, so `--extra-index-url`
+merges both indexes and the broken copies stay reachable whichever order the flags are in. Fetch
+the package alone, then install it with dependencies resolved from PyPI:
```bash
-pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ avs-blueprint-agents
+pip download --no-deps --index-url https://test.pypi.org/simple/ "avs-blueprint-agents==0.9.0a1" -d ./dl
+pip install --index-url https://pypi.org/simple/ ./dl/avs_blueprint_agents-0.9.0a1-py3-none-any.whl
```
+Pin the exact alpha version in both cases: PyPI carries the newer stable release, and an unpinned
+install resolves to that instead.
+
### From Source
```bash
@@ -93,30 +118,37 @@ pip install -e ".[dev]"
Blueprint Agents uses five composable component types, wired together with the `AppBuilder`:
```python
-from blueprint.agents import AppBuilder, AgentBuilder, Config
-
-from src.handlers.order_handler import OrderHandler
-from src.services.order_service import OrderService
-from src.api.routes import OrderApi
+from blueprint.agents import AppBuilder
-config = Config(settings_files=["settings.toml", "secrets.toml"])
+from .handlers.order_handler import OrderHandler
+from .services.order_service import OrderService
+from .api.routes import OrderApi
-app = (
- AppBuilder(config)
+agent = (
+ AppBuilder()
.with_handler(OrderHandler)
.with_service(OrderService)
- .with_rest_api(OrderApi())
+ .with_rest_api(OrderApi)
.with_cache()
- .build()
)
```
+Two things about that chain are worth knowing up front:
+
+- **Nothing is constructed yet.** Every `with_*` call records a declaration; `build()` constructs
+ it. Leaving `build()` out is what lets the deployment decide the configuration and the namespace
+ each component is built in.
+- **Pass classes, not instances.** `with_rest_api(OrderApi)` rather than `with_rest_api(OrderApi())`.
+ An instance created on the `with_*` line exists before any namespace does, so it belongs to the
+ process root for ever. A group refuses them, and so do `agent.build(config)` and the
+ `create_app()` that calls it; only the old `AppBuilder(config)...build()` shape still accepts them.
+
### The Five Components
| Component | Base Class | Purpose |
|-----------|-----------|---------|
-| **Event Handler** | `EventHandlerBase` | Process CloudEvents via chain-of-responsibility with priority ordering |
-| **Service** | `ServiceBase` | Encapsulate business logic with full registry access |
+| **Event Handler** | `EventHandlerBase` | Route CloudEvents (priority chain) and translate each into one service call; returns a result, `HandlerResult.skipped(reason)` or `None` |
+| **Service** | `ServiceBase` | All business logic, including whether an event needs work; runs the agents |
| **REST API** | `RestApiBase` | Define HTTP endpoints with `@get()`, `@post()`, `@put()`, `@delete()`, `@patch()` decorators |
| **Agent** | `AgentRuntime` | Run LLM agents with structured outputs, tool calling, and prompt management |
| **Scheduler** | `SchedulerBase` | Execute cron-based background tasks with auto-registered trigger endpoints |
@@ -134,17 +166,85 @@ on_shutdown() --> Clean up resources, close connections
---
+## Running one agent, or several
+
+**How many agents share a process is a deployment parameter, not an architectural commitment.**
+The declaration in your project's `main.py` is the same either way; only what starts the
+process differs.
+
+| Shape | What starts it |
+|---|---|
+| Standalone, a module-level `app` you built yourself | `uvicorn src.main:app` |
+| Standalone, a declaration built by a factory | `uvicorn src.main:create_app --factory` |
+| Hosted -- one agent, or twenty | `python -m blueprint.agents.entrypoint` |
+
+### Standalone
+
+Unchanged, and still fully supported. Build the declaration yourself and serve it:
+
+```python
+config = Config(settings_files=["settings.toml", ".secrets.toml"])
+app = agent.build(config) # the declaration from "How It Works"
+```
+
+A standalone agent runs at the **root namespace**: its registry names, REST paths (`/api/...`),
+NATS queue group, JetStream durable and OpenTelemetry `service.name` are exactly what they were
+before this existed. Nothing reads `agents.toml` unless you run the entry point.
+
+### Hosted in a group
+
+Name each agent, its directory (`root`, relative to the image root) and the module its
+declaration lives in, in the image's `agents.toml`. Both keys are required:
+
+```toml
+[agents.orders]
+root = "agents/orders"
+module = "agents.orders.src.main:agent"
+
+[agents.billing]
+root = "agents/billing"
+module = "agents.billing.src.main:agent"
+```
+
+The image contains those agents; the **deployment** decides which of them a given process runs:
+
+```bash
+docker run -e BLUEPRINT_AGENTS=orders,billing my-image # both in one process
+docker run -e BLUEPRINT_AGENTS=orders my-image # a group of one
+```
+
+Each hosted agent gets its own handlers, agent runtime, REST routes, AI client, thread pool,
+caches and broker connection. The port, the health endpoint and the process are shared. Agents in
+one process are **isolated**: an agent resolves its own components, caches and configuration and
+the root's shared ones, and the framework refuses any attempt to reach a neighbour's.
+
+A group of one gives today's process isolation; a group of twenty gives the shared-interpreter
+memory profile. Moving an agent between groups changes neither its broker-side consumer identity
+nor its telemetry identity.
+
+> **The agent's name in `agents.toml` is its identity everywhere else** -- registry prefix, NATS
+> queue group, part of the JetStream durable, cache partition, OpenTelemetry `service.name` and
+> the REST prefix `/api/`. Renaming it after the first deploy is a consumer migration, not a
+> rename. Choose it before you ship.
+
+Other group settings: `BLUEPRINT_GROUP_CONFIG` and `BLUEPRINT_GROUP` select a named group from a
+mounted file, and `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process.
+See the [Multi-Agent Setup guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md) for the full reference and the
+migration path for an existing single-agent project.
+
+---
+
## Examples
-Explore complete, runnable examples in the [`examples/`](examples/) directory:
+Explore complete, runnable examples in the [`examples/`](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/) directory:
| Example | Description | Components Used |
|---------|-------------|-----------------|
-| [**inventory_api**](examples/inventory_api/) | Product inventory CRUD REST API | RestApiBase, ServiceBase, Cache |
-| [**order_event_pipeline**](examples/order_event_pipeline/) | E-commerce order processing with Dapr pub/sub | EventHandlerBase, ServiceBase, Dapr |
-| [**document_summarizer**](examples/document_summarizer/) | LLM-powered document summarization with structured output | AgentRuntime, AgentBuilder, Tools |
-| [**webhook_relay**](examples/webhook_relay/) | Webhook ingestion and normalization pipeline with NATS | EventHandlerBase, NATS, Cache |
-| [**health_monitor**](examples/health_monitor/) | System health monitoring with scheduled checks | SchedulerBase, ServiceBase, Cache |
+| [**inventory_api**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/inventory_api/) | Product inventory CRUD REST API | RestApiBase, ServiceBase, Cache |
+| [**order_event_pipeline**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/order_event_pipeline/) | E-commerce order processing with Dapr pub/sub | EventHandlerBase, ServiceBase, Dapr |
+| [**document_summarizer**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/document_summarizer/) | LLM-powered document summarization with structured output | AgentRuntime, AgentBuilder, Tools |
+| [**webhook_relay**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/webhook_relay/) | Webhook ingestion and normalization pipeline with NATS | EventHandlerBase, NATS, Cache |
+| [**health_monitor**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/health_monitor/) | System health monitoring with scheduled checks | SchedulerBase, ServiceBase, Cache |
---
@@ -172,7 +272,7 @@ cache_dir = ".cache/my-agent"
default_ttl = 3600
```
-**secrets.toml** (never commit this file):
+**.secrets.toml** (never commit this file):
```toml
[default.runtimes.my_agent]
@@ -218,7 +318,7 @@ job_timeout_seconds = 300
No `SessionsBus`, `SessionsApiClient`, or `SessionKeyProvider` references in service `main.py` — `AppBuilder.build()` wires them automatically.
-See the [Configuration Reference](docs/concepts/configuration.md) for all available settings.
+See the [Configuration Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/configuration.md) for all available settings.
---
@@ -227,17 +327,20 @@ See the [Configuration Reference](docs/concepts/configuration.md) for all availa
The `asbs` CLI scaffolds projects and components:
```bash
-asbs setup # Create a new project
+asbs setup # Create a new agent, in the current directory
+asbs setup --group # Create an image's files (agent map, group Dockerfile)
asbs create handler [--event-type ] # Add an event handler
asbs create service # Add a business service
asbs create api # Add a REST API
asbs create agent # Add an AI agent
asbs create scheduler [--cron ] # Add a scheduler
-asbs validate # Validate project structure
-asbs dev [--port ] # Run development server
+asbs validate [--group] # Validate one agent, or a whole image
+asbs dev [--name ] [--port ] # Run development server
+asbs docs [] [--cat] # Locate the bundled documentation
+asbs claude # Install the Claude Code files into a project
```
-See the full [CLI Reference](docs/guides/cli-reference.md).
+See the full [CLI Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/cli-reference.md).
---
@@ -249,39 +352,53 @@ Blueprint Agents services deploy as standard Python containers:
- **Kubernetes** -- Helm charts with Dapr sidecar injection, health probes, and ConfigMap/Secret management
- **CI/CD** -- GitHub Actions workflows for linting, testing, and publishing
-See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions.
+See the [Deployment Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/deployment.md) for detailed instructions.
---
## Documentation
+**The documentation ships with the package.** Every page below is installed alongside the code, so
+a developer -- or an AI assistant working in your project -- can read it without network access:
+
+```bash
+asbs docs # list every page
+asbs docs guides/multi-agent-setup # print the path to one page
+asbs docs reference/configuration-keys --cat # print its contents
+```
+
+`asbs claude` additionally installs Claude Code skills that route to the right page for the task at
+hand. The links below are the same pages on GitHub, for browsing.
+
### Getting Started
-- [Getting Started Guide](docs/getting-started.md) -- Installation, first project, and walkthrough
+- [Getting Started Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/getting-started.md) -- Installation, first project, and walkthrough
+- [Multi-Agent Setup](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md) -- Running several agents in one process
+- [Multi-Agent Migration](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md) -- Moving an existing agent into a group
### Core Concepts
-- [Architecture](docs/concepts/architecture.md) -- Component model, registry, and lifecycle
-- [Event Processing](docs/concepts/event-processing.md) -- CloudEvents, handler chain, Dapr/NATS
-- [Configuration](docs/concepts/configuration.md) -- Settings, secrets, and environment variables
-- [Caching](docs/concepts/caching.md) -- Persistent disk cache with TTL and namespaces
-- [Observability](docs/concepts/observability.md) -- OpenTelemetry tracing, metrics, and logging
+- [Architecture](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/architecture.md) -- Component model, registry, and lifecycle
+- [Event Processing](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/event-processing.md) -- CloudEvents, handler chain, Dapr/NATS
+- [Configuration](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/configuration.md) -- Settings, secrets, and environment variables
+- [Caching](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/caching.md) -- Disk and Redis caches, TTL, namespaces, and per-agent isolation
+- [Observability](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/observability.md) -- OpenTelemetry tracing, metrics, and logging
### Component Guides
-- [Event Handlers](docs/components/event-handlers.md)
-- [Services](docs/components/services.md)
-- [REST APIs](docs/components/rest-apis.md)
-- [Agents](docs/components/agents.md)
-- [Schedulers](docs/components/schedulers.md)
+- [Event Handlers](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/event-handlers.md)
+- [Services](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/services.md)
+- [REST APIs](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/rest-apis.md)
+- [Agents](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/agents.md)
+- [Schedulers](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/schedulers.md)
### Operations
-- [CLI Reference](docs/guides/cli-reference.md)
-- [Testing Guide](docs/guides/testing.md)
-- [Deployment Guide](docs/guides/deployment.md)
-- [Troubleshooting](docs/guides/troubleshooting.md)
+- [CLI Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/cli-reference.md)
+- [Testing Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/testing.md)
+- [Deployment Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/deployment.md)
+- [Troubleshooting](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/troubleshooting.md)
### Reference
-- [API Reference](docs/reference/api.md)
-- [Configuration Keys](docs/reference/configuration-keys.md)
-- [Data Models](docs/reference/models.md)
+- [API Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/api.md)
+- [Configuration Keys](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/configuration-keys.md)
+- [Data Models](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/models.md)
---
@@ -297,7 +414,7 @@ See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions.
## Contributing
-We welcome contributions! See [CONTRIBUTE.md](CONTRIBUTE.md) for guidelines on:
+We welcome contributions! See [CONTRIBUTE.md](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/CONTRIBUTE.md) for guidelines on:
- Setting up the development environment
- Running tests and linting
@@ -307,4 +424,4 @@ We welcome contributions! See [CONTRIBUTE.md](CONTRIBUTE.md) for guidelines on:
## License
-This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
+This project is licensed under the MIT License. See [LICENSE](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/LICENSE) for details.
diff --git a/docs/components/event-handlers.md b/docs/components/event-handlers.md
deleted file mode 100644
index 49e1d512..00000000
--- a/docs/components/event-handlers.md
+++ /dev/null
@@ -1,315 +0,0 @@
-# Event Handlers
-
-Event handlers process incoming CloudEvents using a chain-of-responsibility pattern. Each handler declares which events it can process, and the framework routes events through all registered handlers in priority order.
-
-## Import
-
-```python
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-```
-
-## Purpose
-
-Event handlers are the primary entry point for asynchronous event processing. When a CloudEvent arrives (via Dapr, NATS, or HTTP), the framework iterates through all registered handlers in priority order. Each handler is asked whether it can process the event via `can_handle_event()`; if it can, `handle_event()` is called. Handlers should be thin — delegate all domain logic to services.
-
-## Base Class
-
-```python
-from typing import Any
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-
-class MyHandler(EventHandlerBase):
-
- def __init__(self) -> None:
- super().__init__(priority=100) # Lower priority runs first
-
- async def on_startup(self) -> None:
- self._service = self.registry.get_service(MyService)
-
- async def on_shutdown(self) -> None:
- pass
-
- async def can_handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> bool:
- ...
-
- async def handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> Any | HandlerResult | list[HandlerResult] | None:
- ...
-```
-
-## Priority
-
-The `priority` argument controls execution order. Handlers with a **lower** numeric priority value are evaluated first. If two handlers share the same priority, ordering is non-deterministic.
-
-```python
-super().__init__(priority=10) # Runs early
-super().__init__(priority=100) # Default
-super().__init__(priority=500) # Runs late
-```
-
-## Abstract Methods
-
-### can_handle_event
-
-Determines whether this handler should process the given event. Return `True` to claim the event, `False` to skip it. Even if `False` is returned, the next handler still runs — returning `False` does not stop the chain.
-
-```python
-async def can_handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
-) -> bool:
- return event.type == "order.created"
-```
-
-### handle_event
-
-Performs the actual processing. Called only when `can_handle_event` returned `True`.
-
-```python
-async def handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
-) -> Any | HandlerResult | list[HandlerResult] | None:
- result = await self._order_service.process(event.data)
- return HandlerResult(data=result, event_type="order.processed")
-```
-
-## Return Value Semantics
-
-The return value of `handle_event` controls what happens next:
-
-| Return Value | Behavior |
-|---|---|
-| `None` | Passes control to the next handler in the chain. |
-| `HandlerResult` | Publishes a new CloudEvent downstream; passes control to the next handler. |
-| `list[HandlerResult]` | Publishes multiple CloudEvents; passes control to the next handler. |
-| Any other value | Stored internally for chaining; no event publication; passes to next handler. |
-
-Note: The handler chain always continues through all handlers that return `True` from `can_handle_event`. Returning a `HandlerResult` does not stop subsequent handlers.
-
-## Sharing Data Between Handlers via context
-
-The `context` dictionary is shared across all handlers processing the same event. A handler early in the chain (low priority) can write parsed or enriched data into `context`, and a later handler reads it — avoiding redundant work.
-
-```python
-# Handler at priority 5 -- runs first
-class NormalizerHandler(EventHandlerBase):
- def __init__(self) -> None:
- super().__init__(priority=5)
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "webhook.received"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None:
- # Parse once and store for downstream handlers
- normalized = self._service.normalize(event.data)
- context["normalized"] = normalized
- context["source"] = normalized.source
- return None # Pass to next handler
-
-
-# Handler at priority 20 -- runs after NormalizerHandler but double checked with filled context
-class EnricherHandler(EventHandlerBase):
- def __init__(self) -> None:
- super().__init__(priority=20)
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return context.get("normalized") and event.type == "webhook.received"
-
- async def handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> HandlerResult | None:
- # Read data written by the earlier handler
- normalized = context.get("normalized")
-
- enriched = self._service.enrich(normalized)
- return HandlerResult(event_type="webhook.processed", data=enriched)
-```
-
-## Published Event Types
-
-Optionally declare the event types this handler can produce. Used for documentation and subscription introspection.
-
-```python
-def get_published_event_types(self) -> tuple[str, str] | None:
- return ("order.processed", "order.error")
-```
-
-The tuple is `(success_type, error_type)`. Return `None` if the handler does not publish events.
-
-## Accessing Services
-
-Resolve service dependencies in `on_startup()`. Never in `__init__()`.
-
-```python
-from blueprint.agents.services.service_base import ServiceBase
-
-
-class OrderService(ServiceBase):
- async def process(self, order: dict) -> dict:
- ...
-
-
-class OrderHandler(EventHandlerBase):
-
- def __init__(self) -> None:
- super().__init__(priority=100)
- self._order_service: OrderService | None = None
-
- async def on_startup(self) -> None:
- self._order_service = self.registry.get_service(OrderService)
-
- async def on_shutdown(self) -> None:
- pass
-
- async def can_handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> bool:
- return event.type == "order.created"
-
- async def handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> HandlerResult | None:
- if self._order_service is None:
- return None
- result = await self._order_service.process(event.data)
- return HandlerResult(data=result, event_type="order.processed")
-```
-
-## Registration
-
-Register handlers with `AppBuilder` by passing the **class** or an instance of the class:
-
-```python
-from blueprint.agents import AppBuilder, Config
-
-config = Config(settings_files=["settings.toml", "secrets.toml"])
-app = (
- AppBuilder(config)
- .with_service(OrderService)
- .with_handler(OrderHandler)
- .build()
-)
-```
-
-Services must be registered before the handlers that depend on them.
-
-## Full Example
-
-```python
-from typing import Any
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-from blueprint.agents.services.service_base import ServiceBase
-
-
-class InvoiceService(ServiceBase):
- """Domain service for invoice processing."""
-
- async def on_startup(self) -> None:
- pass
-
- async def on_shutdown(self) -> None:
- pass
-
- async def generate_invoice(self, order_id: str, items: list[dict]) -> dict:
- return {"invoice_id": "INV-001", "order_id": order_id, "total": 99.99}
-
-
-class InvoiceHandler(EventHandlerBase):
- """Generates invoices when an order is confirmed."""
-
- def __init__(self) -> None:
- super().__init__(priority=50)
- self._invoice_service: InvoiceService | None = None
-
- async def on_startup(self) -> None:
- self._invoice_service = self.registry.get_service(InvoiceService)
-
- async def on_shutdown(self) -> None:
- pass
-
- def get_published_event_types(self) -> tuple[str, str] | None:
- return ("invoice.created", "invoice.error")
-
- async def can_handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> bool:
- return event.type == "order.confirmed"
-
- async def handle_event(
- self, event: GenericCloudEvent, context: dict[str, Any]
- ) -> HandlerResult | None:
- if self._invoice_service is None:
- return None
-
- order_data = event.data or {}
- order_id = order_data.get("order_id", "")
- items = order_data.get("items", [])
-
- try:
- invoice = await self._invoice_service.generate_invoice(order_id, items)
- return HandlerResult(data=invoice, event_type="invoice.created")
- except Exception as exc:
- return HandlerResult(
- data={"order_id": order_id, "error": str(exc)},
- event_type="invoice.error",
- )
-```
-
-## Testing
-
-Use a mock registry to unit test handlers in isolation.
-
-```python
-import pytest
-from unittest.mock import AsyncMock, MagicMock
-from blueprint.agents.models.events import GenericCloudEvent
-
-
-@pytest.fixture
-def mock_registry():
- registry = MagicMock()
- invoice_service = AsyncMock()
- invoice_service.generate_invoice.return_value = {
- "invoice_id": "INV-TEST",
- "order_id": "ORD-1",
- "total": 50.00,
- }
- registry.get_service.return_value = invoice_service
- return registry
-
-
-@pytest.fixture
-async def handler(mock_registry):
- h = InvoiceHandler()
- h._registry = mock_registry
- await h.on_startup()
- return h
-
-
-async def test_can_handle_matching_event(handler):
- event = GenericCloudEvent(id="1", type="order.confirmed", data={})
- assert await handler.can_handle_event(event, {}) is True
-
-
-async def test_ignores_unrelated_event(handler):
- event = GenericCloudEvent(id="2", type="user.created", data={})
- assert await handler.can_handle_event(event, {}) is False
-
-
-async def test_handle_event_returns_result(handler):
- event = GenericCloudEvent(
- id="3",
- type="order.confirmed",
- data={"order_id": "ORD-1", "items": [{"sku": "A", "qty": 2}]},
- )
- result = await handler.handle_event(event, {})
- assert result is not None
- assert result.event_type == "invoice.created"
- assert result.data["invoice_id"] == "INV-TEST"
-```
diff --git a/docs/concepts/cache-architecture.md b/docs/concepts/cache-architecture.md
deleted file mode 100644
index b1886d2e..00000000
--- a/docs/concepts/cache-architecture.md
+++ /dev/null
@@ -1,181 +0,0 @@
-# Cache Architecture
-
-This document describes the **pluggable cache architecture** introduced for centralised caching support. It explains the components, their responsibilities, and the design choices behind them.
-
-For end-user setup instructions, see [Caching — Getting Started](../guides/caching-getting-started.md). For a higher-level system overview with diagrams, see [Cache System Overview](./cache-system-overview.md).
-
----
-
-## Goals
-
-The architecture solves three problems:
-
-| Problem | Solution |
-|---|---|
-| Scaling out causes cache misses on every replica | Shared backend (Redis) so all replicas see the same cache |
-| Different deployments need different storage backends | Pluggable backend behind a single interface |
-| Existing single-replica services should not be forced to change | Local DiskCache stays the default |
-
-## Components
-
-```
- ┌─────────────────────────────────────┐
- │ CacheService (abstract interface) │
- │ │
- │ get / set / delete / exists │
- │ clear / hash / get_stats │
- └─────────────────────────────────────┘
- ▲ ▲
- │ │
- ┌───────────────┘ └───────────────┐
- │ │
- ┌──────────────────────┐ ┌──────────────────────┐
- │ DiskCacheService │ │ RedisCacheService │
- │ (default, local) │ │ (centralised) │
- │ │ │ │
- │ diskcache-rs │ │ redis-py 7.x │
- │ per-process file │ │ shared TCP client │
- └──────────────────────┘ └──────────────────────┘
-
- ▲
- │ creates the right one based on
- │ CacheConfig.backend
- │
- ┌─────────────────────────────────────┐
- │ CacheBackendFactory │
- │ .create(CacheConfig) → CacheService│
- └─────────────────────────────────────┘
- ▲
- │ reads from settings.toml
- │
- ┌─────────────────────────────────────┐
- │ Config.get_cache_config() │
- │ returns a CacheConfig (Pydantic) │
- └─────────────────────────────────────┘
- ▲
- │ wires the cache into the registry
- │
- ┌─────────────────────────────────────┐
- │ AppBuilder.with_cache() │
- │ → Component.shared_registry │
- │ .cache_service = … │
- └─────────────────────────────────────┘
- ▲
- │ pulled by every service / handler
- │ in their on_startup()
- │
- ┌───────────────┴────────────────┐
- │ │
- ┌──────────┐ ┌──────────┐
- │ ServiceA │ │ ServiceB │
- │ │ │ │
- │ self. │ │ self. │
- │ registry │ │ registry │
- │ .cache_ │ │ .cache_ │
- │ service │ │ service │
- └──────────┘ └──────────┘
-```
-
-### `CacheService` — the abstract interface
-`src/blueprint/agents/services/infrastructure/cache_service.py`
-
-Five operations every backend must implement: `get`, `set`, `delete`, `exists`, `clear`. Plus `hash` for normalised key generation, `get_stats` for the management API, and `list_namespaces` / `list_values` for the cache REST endpoints.
-
-Code that uses the cache only sees this interface — it never imports `DiskCacheService` or `RedisCacheService` directly.
-
-### `DiskCacheService` — local default
-Same file. Backed by `diskcache-rs` (a Rust-accelerated diskcache port). Persists to a directory on disk. Thread-safe via an optional `RLock`. **Default** — services that don't change anything continue to work exactly as before.
-
-### `RedisCacheService` — centralised, shared
-`src/blueprint/agents/services/infrastructure/redis_cache_service.py`
-
-Backed by `redis-py 7.x`. Uses Redis-native TTL via the `EX` argument on `SET`. Namespace + key are joined with `:` and prefixed by an optional `key_prefix` so multiple services can share one Redis instance without collisions.
-
-### `CacheBackendFactory` — Strategy selector
-`src/blueprint/agents/services/infrastructure/cache_backend_factory.py`
-
-A simple `@staticmethod` that returns a `DiskCacheService` or a `RedisCacheService` depending on `CacheConfig.backend`. This is where the **Strategy pattern** lives — it picks the concrete strategy at runtime based on configuration.
-
-### `CacheConfig` — typed configuration
-`src/blueprint/agents/models/config.py`
-
-Pydantic model. Holds: `backend`, `cache_dir`, `default_ttl`, `key_prefix`, `redis_url`, `redis_password`, `redis_db`, `redis_tls`, `fallback_to_local`. Read from `settings.toml` via Dynaconf in `Config.get_cache_config()`.
-
-### `AppBuilder.with_cache()` — wiring
-`src/blueprint/agents/app_builder.py`
-
-```python
-def with_cache(self, enabled: bool = True, enable_locking: bool = True) -> "AppBuilder":
- if enabled:
- cache_config = self._config.get_cache_config()
- cache_service = CacheBackendFactory.create(cache_config, enable_locking=enable_locking)
- Component.shared_registry.cache_service = cache_service
- return self
-```
-
-Calling `with_cache()` is the **only** thing a service author needs to do to opt in. The factory picks the backend, the registry stores the singleton, and every component can pull it from `self.registry.cache_service`.
-
----
-
-## Design choices
-
-### Why a Strategy pattern, not subclassing the cache?
-
-Because the **calling code** (services, handlers, agents) does not know — and should not know — which backend is in use. With Strategy:
-
-- Services depend only on `CacheService` (the interface).
-- Choosing backend is a one-line change in `settings.toml`.
-- New backends (Memcached, DynamoDB, …) can be added by implementing `CacheService` without touching any caller.
-
-### Why keep DiskCache as default?
-
-Two reasons:
-1. **No breaking changes** — every existing service that already used the cache keeps working.
-2. **Zero-dependency baseline** — single-replica deployments don't need Redis just to use the cache.
-
-### Why a single global registry instead of injecting the cache per service?
-
-Because `Component.shared_registry` is the existing mechanism for cross-component dependency lookup (services look up other services there too). Reusing it keeps the API uniform and the singleton guarantee enforced by the registry's "set once" check.
-
-### Why `key_prefix` AND `namespace`?
-
-Two layers of isolation, two scopes:
-- **`namespace`** is *per-call* (`cache.get(k, namespace="prices")`) — used by code to organise its own keys.
-- **`key_prefix`** is *per-instance* (configured once in `settings.toml`) — used to keep multiple services that share one Redis instance from colliding.
-
-A Redis key looks like `{key_prefix}:{namespace}:{hash(key)}`.
-
-### Why a sync redis-py client in async services?
-
-Redis operations are normally sub-millisecond and the cache is on the hot path. The sync client is simpler, well-tested, and the latency cost is negligible for typical agent workloads. If that ever becomes a bottleneck, an `AsyncRedisCacheService` can be added without changing any caller.
-
-### What about fallback when Redis is unreachable?
-
-Two failure modes are distinguished:
-1. **`redis` package not installed** — `CacheBackendFactory` falls back to `DiskCacheService` if `fallback_to_local=True`. This is a **real backend swap** — the app runs with disk thereafter.
-2. **Redis unreachable at startup or runtime** — `RedisCacheService` keeps trying Redis. With `fallback_to_local=True`, `on_startup()` does not raise; with `fallback_to_local=False`, it raises and the pod crashes (K8s restarts it).
-
-In case (2) the cache is not silently swapped to disk. Operations against an unreachable Redis return `None`/`False` and log warnings.
-
-To prevent a pod from silently serving cache misses while looking healthy to K8s, the framework registers a `CacheHealthChecker` for the readiness probe automatically when `with_cache()` is called:
-
-- `/health/ready` → returns **HTTP 503** with full diagnostic payload when Redis is unreachable
-- `/health/live` → unaffected (always 200) — the pod stays alive
-- Recovery is automatic — when Redis returns, the next health-check tick (≤ `health_check_interval_seconds`, default 30s) flips readiness back to UP and K8s re-adds the pod to the service pool
-
-For DiskCache, the health check is trivially UP (the local filesystem doesn't fail in the same way a network service does).
-
----
-
-## What's now possible with this architecture
-
-| Before | After |
-|---|---|
-| Each replica had its own DiskCache → cache misses after every restart and on every new replica | Replicas share a single Redis cache → warm cache survives restarts and scales horizontally |
-| Cache backend hard-coded into the framework | `settings.toml` switches backends; new backends slot in via `CacheService` |
-| Services that scaled out had to pin to one replica or accept duplicate work | Two replicas of the same service deduplicate work via the shared cache |
-| Two different services on the same Redis would collide on identical keys | `key_prefix` per service guarantees isolation |
-| No way to verify multi-instance behaviour without spinning up real replicas | `examples/shared_cache_demo/demo_multiprocess.py` proves cross-process sharing in 2 seconds |
-| No automated test for "two services in one app share cache via the registry" | `tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py` covers it |
-| `Config.get_cache_config()` only read 4 of 11 fields (backend/redis_* ignored) | All fields are read; Redis is reachable purely through `settings.toml` |
-| Redis outage → pod looks healthy to K8s, silently serves cache misses | Readiness probe flips to HTTP 503 within one health-check interval; K8s drops pod from service pool until Redis recovers |
diff --git a/docs/concepts/cache-system-overview.md b/docs/concepts/cache-system-overview.md
deleted file mode 100644
index 0deba1f1..00000000
--- a/docs/concepts/cache-system-overview.md
+++ /dev/null
@@ -1,232 +0,0 @@
-# Cache System Overview
-
-A diagram-led tour of how the cache is structured, where the **Strategy pattern** sits, and how data flows from a service call to a Redis key.
-
-For the design rationale, see [Cache Architecture](./cache-architecture.md). For setup steps, see [Caching — Getting Started](../guides/caching-getting-started.md).
-
----
-
-## Strategy pattern in one picture
-
-The cache is a textbook Strategy pattern. The **context** (the calling code) holds a reference to a **strategy** (a `CacheService`) and uses it through a fixed interface. The concrete strategy is selected once, at startup, by a factory that reads configuration.
-
-```
- ┌──────────────────────────────────────────────┐
- │ Context: any service, handler, or API │
- │ │
- │ self._cache = self.registry │
- │ .cache_service │
- │ │
- │ self._cache.set("k", v, namespace="ns") │
- │ self._cache.get("k", namespace="ns") │
- └──────────────────────┬───────────────────────┘
- │ uses
- ▼
- ┌──────────────────────────────────────────────┐
- │ Strategy interface: CacheService │
- │ │
- │ get(key, namespace) -> Any | None │
- │ set(key, value, namespace, ttl) -> None │
- │ delete(key, namespace) -> bool │
- │ exists(key, namespace) -> bool │
- │ clear(namespace) -> None │
- └────────┬─────────────────────────────┬───────┘
- │ implemented by │
- ▼ ▼
- ┌────────────────────────┐ ┌─────────────────────────┐
- │ ConcreteStrategy: │ │ ConcreteStrategy: │
- │ DiskCacheService │ │ RedisCacheService │
- │ │ │ │
- │ • diskcache-rs (Rust) │ │ • redis-py 7.x │
- │ • file-system, local │ │ • TCP, shared │
- │ • per-process │ │ • across processes │
- └────────────────────────┘ └─────────────────────────┘
- ▲ ▲
- │ │
- │ chooses one of these │
- │ │
- └──────────────┬──────────────┘
- │
- │ creates
- ┌─────────┴─────────────┐
- │ CacheBackendFactory │
- │ │
- │ if config.backend │
- │ == "redis": │
- │ RedisCacheService│
- │ else: │
- │ DiskCacheService │
- └─────────┬──────────────┘
- │ reads
- ▼
- ┌────────────────────────┐
- │ CacheConfig (Pydantic) │
- │ │
- │ backend, redis_url, │
- │ key_prefix, … │
- └─────────┬──────────────┘
- │ produced by
- ▼
- ┌────────────────────────┐
- │ Config.get_cache_ │
- │ config() │
- │ │
- │ reads [default.cache] │
- │ from settings.toml │
- │ via Dynaconf │
- └────────────────────────┘
-```
-
-**Why this matters**: a service that calls `self._cache.set(...)` has no idea — and does not need to know — whether that write goes to a local `.cache/` folder or to a Redis cluster on the other side of the world. Switching backends is a one-line change in `settings.toml`.
-
----
-
-## Lifecycle: from `AppBuilder.build()` to a Redis key
-
-The end-to-end timeline of one cache write, from app startup through the actual Redis command:
-
-```
- APP STARTUP
- ───────────
-
- AppBuilder(config) [1]
- .with_service(PricingService) [2]
- .with_service(RecommendationService) [3]
- .with_cache() [4]
- .build() [5]
-
-
- [4] with_cache() [5] build() → on_startup()
- ───────────── ────────────────────────
-
- Config.get_cache_config() For every component:
- ↓ component.on_startup()
- CacheConfig( ↓
- backend="redis", Pricing ← registry.cache_service
- redis_url="redis://...", Recommend ← registry.cache_service
- key_prefix="my-svc", (both get the SAME instance)
- ...
- )
- ↓
- CacheBackendFactory.create(cfg)
- ↓
- RedisCacheService(redis_url=..., key_prefix=...)
- ↓
- Component.shared_registry.cache_service = ↑
-
-
- APP RUNTIME
- ───────────
-
- PricingService.store_price("laptop", 49.99)
- ↓
- self._cache.set(
- "price:laptop",
- {"amount": 49.99},
- namespace="products",
- ttl=600
- )
- ↓
- RedisCacheService._full_key(...) → "my-svc:products:7f8a…"
- ↓
- json.dumps({"amount": 49.99}) → '{"amount": 49.99}'
- ↓
- redis_client.set(
- "my-svc:products:7f8a…", ← SET command on Redis
- '{"amount": 49.99}',
- ex=600 ← Redis-native TTL
- )
-
- RecommendationService.read_price("laptop")
- ↓
- self._cache.get("price:laptop", namespace="products")
- ↓
- RedisCacheService._full_key(...) → "my-svc:products:7f8a…" (same hash!)
- ↓
- redis_client.get("my-svc:products:7f8a…")
- ↓
- '{"amount": 49.99}' → json.loads() → {"amount": 49.99}
-```
-
-The key insight: both services produce the **same** Redis key from the same logical key, namespace, and prefix. That's how they see each other's writes through the registry.
-
----
-
-## Multi-process / multi-replica view
-
-This is the case the issue asks for. Two replicas of the same service running in two different processes (or two different pods) — both connected to one Redis:
-
-```
- ┌─────────────────────────────┐ ┌─────────────────────────────┐
- │ Replica A (PID 1234) │ │ Replica B (PID 5678) │
- │ │ │ │
- │ Component.shared_registry │ │ Component.shared_registry │
- │ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │
- │ │ cache_service: │ │ │ │ cache_service: │ │
- │ │ RedisCacheService │ │ │ │ RedisCacheService │ │
- │ │ (instance #A) │ │ │ │ (instance #B) │ │
- │ │ │ │ │ │ │ │
- │ │ key_prefix="my-svc" │ │ │ │ key_prefix="my-svc" │ │
- │ └─────────┬──────────────┘ │ │ └─────────┬──────────────┘ │
- │ │ │ │ │ │
- └─────────────┼────────────────┘ └─────────────┼────────────────┘
- │ TCP │ TCP
- │ │
- └────────────────┬───────────────────────┘
- ▼
- ┌──────────────────────┐
- │ Redis │
- │ │
- │ my-svc:ns:hash1 ───┐│
- │ ││ shared
- │ my-svc:ns:hash2 ───┘│
- │ │
- └──────────────────────┘
-```
-
-Each replica owns its own `RedisCacheService` Python object and its own TCP connection to Redis. They have **no shared memory and no shared Python objects**. The only shared state is Redis itself, which is exactly what makes the cache "centralised".
-
-This is what `examples/shared_cache_demo/demo_multiprocess.py` demonstrates programmatically (using two `multiprocessing.Process` workers to simulate the two replicas).
-
----
-
-## Data layout in Redis
-
-Every cache write goes through the same key formula:
-
-```
- ┌────────────────┬──────────────┬──────────────────────────────┐
- │ key_prefix │ namespace │ sha256(normalised key) │
- ├────────────────┼──────────────┼──────────────────────────────┤
- │ "my-svc" │ "products" │ "7f8a9c1e2b…" │
- └────────────────┴──────────────┴──────────────────────────────┘
- │ │ │
- └──────────────┴────────────────────┘
- │
- ▼
- "my-svc:products:7f8a9c1e2b…"
-```
-
-- **`key_prefix`** isolates whole services from each other (e.g. `payments-svc` vs. `inventory-svc`).
-- **`namespace`** isolates logical groups within one service (e.g. `prices` vs. `recommendations`).
-- **`hash`** is the SHA-256 of the key, after JSON-normalising it so that `["a", "b"]` and `["b", "a"]` produce the same hash, and `{"x": 1, "y": 2}` and `{"y": 2, "x": 1}` produce the same hash.
-
-The two-layer prefix system means **multiple services can share one Redis without ever colliding**, and within a service you can subdivide cleanly by namespace.
-
----
-
-## Component responsibilities at a glance
-
-| Component | Role | Knows about | Does NOT know about |
-|---|---|---|---|
-| `CacheService` | Interface every backend implements | – | Concrete backends |
-| `DiskCacheService` | Local disk-backed implementation | `diskcache-rs`, file system | Redis, Dynaconf, AppBuilder |
-| `RedisCacheService` | Redis-backed implementation | `redis-py`, key-prefix scheme | DiskCache, Dynaconf, AppBuilder |
-| `CacheBackendFactory` | Strategy selector | Both backends, `CacheConfig` | Settings files, AppBuilder |
-| `CacheConfig` | Typed Pydantic config model | Field shapes only | Dynaconf, AppBuilder, backends |
-| `Config.get_cache_config()` | Reads `[default.cache]` from settings | Dynaconf, `CacheConfig` | Backends, registry |
-| `AppBuilder.with_cache()` | Wires the cache into the registry | Factory, registry, `Config` | Backends |
-| `Component.shared_registry` | Singleton store, dependency lookup | `CacheService` (interface only) | Backends, settings |
-| Application services | Use the cache through `self.registry.cache_service` | The interface | Everything else |
-
-Each layer touches only the layers immediately above and below it. This is what makes the architecture extensible: add a new backend by implementing `CacheService` + extending the factory, and nothing else has to change.
diff --git a/docs/concepts/caching.md b/docs/concepts/caching.md
deleted file mode 100644
index 55af35f6..00000000
--- a/docs/concepts/caching.md
+++ /dev/null
@@ -1,347 +0,0 @@
-# Caching
-
-Blueprint Agents includes a built-in persistent key-value cache backed by diskcache-rs. The cache provides fast local storage with TTL expiration, namespace isolation, and a management REST API.
-
-## Enabling the Cache
-
-Enable caching by calling `.with_cache()` on the `AppBuilder`:
-
-```python
-from blueprint.agents import AppBuilder, Config
-
-config = Config(settings_files=["settings.toml", "secrets.toml"])
-
-app = (
- AppBuilder(config)
- .with_service(MyService)
- .with_handler(MyHandler)
- .with_cache()
- .build()
-)
-```
-
-Once enabled, the cache service is registered in the component registry and a management REST API is automatically mounted.
-
-## Accessing the Cache
-
-The cache is available through the component registry from `on_startup()` onward:
-
-```python
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import CloudEvent, HandlerResult
-
-
-class DeduplicationHandler(EventHandlerBase):
- priority = 1
-
- async def on_startup(self) -> None:
- self.cache = self.registry.cache_service
-
- def can_handle_event(self, event: CloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "document.received"
-
- async def handle_event(self, event: CloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- doc_id = event.subject
-
- # Check if already processed
- if await self.cache.get(doc_id, namespace="processed"):
- return None # Skip duplicate
-
- # Mark as processed with a 1-hour TTL
- await self.cache.set(doc_id, True, namespace="processed", ttl=3600)
-
- return HandlerResult(
- event_type="document.accepted",
- data=event.data,
- )
-```
-
-## Cache Operations
-
-### get(key, namespace)
-
-Retrieve a value by key within a namespace. Returns `None` if the key does not exist or has expired.
-
-```python
-value = await self.cache.get("user:12345", namespace="profiles")
-if value is None:
- # Cache miss -- fetch from source
- value = await self.fetch_profile(12345)
- await self.cache.set("user:12345", value, namespace="profiles", ttl=900)
-```
-
-### set(key, value, namespace, ttl)
-
-Store a value under a key. The `ttl` parameter specifies the time-to-live in seconds. If omitted, the `default_ttl` from configuration is used.
-
-```python
-# Cache for 30 minutes
-await self.cache.set("result:abc", {"score": 0.95}, namespace="results", ttl=1800)
-
-# Cache using the default TTL from settings.toml
-await self.cache.set("result:def", {"score": 0.87}, namespace="results")
-```
-
-### delete(key, namespace)
-
-Remove a specific key from a namespace.
-
-```python
-await self.cache.delete("user:12345", namespace="profiles")
-```
-
-### clear(namespace)
-
-Remove all entries in a namespace. Useful for bulk invalidation.
-
-```python
-# Purge all cached search results
-await self.cache.clear(namespace="search_results")
-```
-
-## TTL and Automatic Expiration
-
-Every cached entry can have an individual TTL (time-to-live) in seconds. Once the TTL elapses, the entry is no longer returned by `get()` and is eligible for eviction.
-
-```python
-# Short-lived cache for rate limiting (60 seconds)
-await self.cache.set(f"rate:{client_ip}", request_count, namespace="rate_limit", ttl=60)
-
-# Long-lived cache for expensive computations (24 hours)
-await self.cache.set(embedding_key, vector, namespace="embeddings", ttl=86400)
-```
-
-If no TTL is provided, the `default_ttl` value from `[default.cache]` in `settings.toml` is applied.
-
-## Namespace Isolation
-
-Namespaces partition the cache into logical segments. Different components can use separate namespaces without risk of key collisions.
-
-```python
-# Handler uses one namespace
-await self.cache.set("doc:1", metadata, namespace="documents")
-
-# Service uses a different namespace
-await self.cache.set("doc:1", embedding, namespace="embeddings")
-
-# No collision -- these are independent entries
-```
-
-Namespaces also allow targeted invalidation. Clearing one namespace does not affect others.
-
-## Key Hashing for Complex Keys
-
-The cache supports complex keys such as lists, dictionaries, and tuples. These are automatically hashed to produce a stable string key.
-
-```python
-# Dictionary key -- automatically hashed
-query_params = {"model": "gpt-4o", "prompt": "Summarize this document", "temperature": 0.3}
-cached_response = await self.cache.get(query_params, namespace="llm_responses")
-
-if cached_response is None:
- response = await self.call_llm(query_params)
- await self.cache.set(query_params, response, namespace="llm_responses", ttl=7200)
-
-# List key -- also automatically hashed
-chunk_ids = ["chunk-a", "chunk-b", "chunk-c"]
-await self.cache.set(chunk_ids, merged_result, namespace="merged_chunks")
-```
-
-## Cache Management REST API
-
-When the cache is enabled, the framework automatically registers a REST API for cache inspection and management at `/api/cache`.
-
-### Endpoints
-
-| Method | Path | Description |
-|---|---|---|
-| `GET` | `/api/cache/{namespace}/{key}` | Retrieve a cached value |
-| `PUT` | `/api/cache/{namespace}/{key}` | Set a cached value (JSON body) |
-| `DELETE` | `/api/cache/{namespace}/{key}` | Delete a cached entry |
-| `DELETE` | `/api/cache/{namespace}` | Clear an entire namespace |
-
-### Example Usage
-
-```bash
-# Retrieve a cached value
-curl http://localhost:8000/api/cache/profiles/user:12345
-
-# Set a cached value with a TTL
-curl -X PUT http://localhost:8000/api/cache/results/query:abc \
- -H "Content-Type: application/json" \
- -d '{"value": {"score": 0.95}, "ttl": 1800}'
-
-# Delete a specific key
-curl -X DELETE http://localhost:8000/api/cache/profiles/user:12345
-
-# Clear all entries in a namespace
-curl -X DELETE http://localhost:8000/api/cache/search_results
-```
-
-## Configuration
-
-Cache settings are defined in `settings.toml` under the `[default.cache]` section:
-
-```toml
-[default.cache]
-cache_dir = "/tmp/blueprint-cache"
-size_limit = 1073741824 # Maximum cache size in bytes (1 GB)
-eviction_policy = "least-recently-used" # Eviction strategy when size_limit is reached
-default_ttl = 3600 # Default TTL in seconds (1 hour)
-```
-
-### Configuration Fields
-
-| Field | Type | Description |
-|---|---|---|
-| `cache_dir` | `str` | Filesystem path where cache data is stored |
-| `size_limit` | `int` | Maximum total cache size in bytes |
-| `eviction_policy` | `str` | Strategy for removing entries when the cache is full |
-| `default_ttl` | `int` | Default time-to-live in seconds for entries without an explicit TTL |
-
-## Redis Backend
-
-For deployments where multiple service instances need to share cache state (e.g. horizontal scaling, blue/green deployments, multi-pod Kubernetes setups), Blueprint Agents ships with an optional Redis backend. Cache reads and writes flow through a central Redis server so every replica sees the same data.
-
-### Installation
-
-The Redis client is an optional extra. Install it explicitly:
-
-```bash
-pip install 'avs-blueprint-agents[redis]'
-```
-
-This pulls in `redis-py` with the `hiredis` parser for fast wire-protocol decoding. No code changes are required — the framework auto-selects the backend at startup based on `settings.toml`.
-
-### Configuration
-
-Switch backends by setting `backend = "redis"` and adding the connection fields:
-
-```toml
-[default.cache]
-backend = "redis" # "disk" (default) or "redis"
-default_ttl = 3600 # Default TTL in seconds (used by both backends)
-key_prefix = "inventory-api" # Prefix prepended to every cache key
-redis_url = "redis://localhost:6379/0" # Connection URL (host, port, db)
-redis_password = "secret" # Optional password
-redis_db = 0 # Database index (0–15 for default Redis)
-redis_tls = false # Set true for TLS (rediss://)
-fallback_to_local = false # If true: fall back to DiskCacheService when Redis is unreachable
-```
-
-### Field Reference
-
-| Field | Type | Description |
-|---|---|---|
-| `backend` | `str` | `"disk"` (default) or `"redis"`. Controls which cache implementation is instantiated. |
-| `key_prefix` | `str` | Global prefix prepended to every key in the form `{prefix}:{namespace}:{hash}`. Lets you safely share a single Redis database between multiple services without key collisions. Empty string disables prefixing. |
-| `redis_url` | `str` | Standard Redis URL (`redis://...` or `rediss://...` for TLS). Defaults to `redis://localhost:6379/0`. |
-| `redis_password` | `str \| None` | Password for Redis AUTH. Read this from a secrets file, never commit it. |
-| `redis_db` | `int` | Numeric database index. Default is `0`. |
-| `redis_tls` | `bool` | Enable TLS — equivalent to using `rediss://` in `redis_url`. |
-| `fallback_to_local` | `bool` | If `True`, the framework starts up with `DiskCacheService` when (a) the Redis extra is not installed or (b) the Redis server is unreachable on `on_startup()`. Useful for graceful degradation in non-production environments. |
-
-### Multi-Service Shared Redis
-
-When several microservices share one Redis cluster, set a unique `key_prefix` per service:
-
-```toml
-# Service A
-[default.cache]
-backend = "redis"
-key_prefix = "inventory-api"
-redis_url = "redis://shared-redis:6379/0"
-
-# Service B
-[default.cache]
-backend = "redis"
-key_prefix = "billing-api"
-redis_url = "redis://shared-redis:6379/0"
-```
-
-Each service's `clear()`, `list_namespaces()`, and `list_values()` calls only operate within its own prefix. `clear()` uses `SCAN` + `DELETE` (never `FLUSHDB`), so it never touches keys belonging to other services.
-
-### Graceful Degradation
-
-In development or non-critical environments, set `fallback_to_local = true` to keep the service running when Redis is unavailable:
-
-```toml
-[default.cache]
-backend = "redis"
-redis_url = "redis://localhost:6379/0"
-fallback_to_local = true
-```
-
-Behavior:
-- If the `redis` extra is not installed: factory returns a `DiskCacheService`.
-- If Redis is installed but unreachable on startup: `on_startup()` logs the failure and continues without raising.
-
-In production, leave `fallback_to_local = false` so startup fails loudly when the cache backend is misconfigured.
-
-## File-Based Locking
-
-The DiskCacheService uses file-based locking to ensure safe concurrent access across multiple processes or deployment replicas sharing the same `cache_dir`. This means multiple instances of the same service can safely read and write to a shared cache directory without corruption.
-
-```toml
-[default.cache]
-# Shared cache directory across replicas
-cache_dir = "/mnt/shared/blueprint-cache"
-```
-
-## Complete Example
-
-```python
-from blueprint.agents import AppBuilder, Config
-from blueprint.agents.services.service_base import ServiceBase
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import CloudEvent, HandlerResult
-
-
-class EmbeddingService(ServiceBase):
- async def on_startup(self) -> None:
- self.cache = self.registry.cache_service
- self.agent = self.registry.get_agent("embedder")
-
- async def get_embedding(self, text: str) -> list[float]:
- # Check cache first
- cached = await self.cache.get(text, namespace="embeddings")
- if cached is not None:
- return cached
-
- # Compute and cache
- embedding = await self.agent.run(text)
- await self.cache.set(text, embedding, namespace="embeddings", ttl=86400)
- return embedding
-
-
-class DocumentHandler(EventHandlerBase):
- priority = 10
-
- async def on_startup(self) -> None:
- self.embedding_svc = self.registry.get_service(EmbeddingService)
-
- def can_handle_event(self, event: CloudEvent) -> bool:
- return event.type == "document.received"
-
- async def handle_event(self, event: CloudEvent) -> HandlerResult:
- embedding = await self.embedding_svc.get_embedding(event.data["content"])
- return HandlerResult(
- event_type="document.embedded",
- data={"doc_id": event.subject, "embedding": embedding},
- )
-
- def get_published_event_types(self) -> list[str]:
- return ["document.embedded"]
-
-
-config = Config(settings_files=["settings.toml"])
-
-app = (
- AppBuilder(config)
- .with_service(EmbeddingService)
- .with_handler(DocumentHandler)
- .with_agent("embedder", EmbedderAgent)
- .with_cache()
- .build()
-)
-```
diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md
deleted file mode 100644
index 326c849a..00000000
--- a/docs/concepts/configuration.md
+++ /dev/null
@@ -1,235 +0,0 @@
-# Configuration
-
-Blueprint Agents uses a layered configuration system built on Dynaconf. Configuration is loaded from TOML files, with support for environment variable interpolation, environment-specific overrides, and structured sections for each framework subsystem.
-
-## Config Class
-
-The `Config` class is the entry point for all configuration. It accepts a list of settings files and merges them in order, with later files overriding earlier ones.
-
-```python
-from blueprint.agents import Config
-
-config = Config(settings_files=["settings.toml", "secrets.toml"])
-```
-
-The `Config` instance is passed to `AppBuilder` and automatically made available to all components via `self.config`.
-
-## File Structure
-
-### settings.toml
-
-The primary configuration file. All settings live under a `[default]` section (the Dynaconf default environment).
-
-```toml
-[default]
-app_name = "document-processor"
-log_level = "INFO"
-event_bus = "dapr"
-```
-
-### secrets.toml
-
-A separate file for sensitive values such as API keys, connection strings, and credentials. This file should be listed in `.gitignore` and never committed to version control.
-
-```toml
-[default]
-openai_api_key = "sk-..."
-database_connection_string = "postgresql://user:pass@host/db"
-```
-
-## Environment Variable Interpolation
-
-Any value in a TOML file can reference an environment variable using the `${ENV_VAR}` syntax. This is useful for deployment environments where secrets are injected through the platform.
-
-```toml
-[default]
-openai_api_key = "${OPENAI_API_KEY}"
-nats_url = "${NATS_URL}"
-database_url = "${DATABASE_URL}"
-```
-
-If the environment variable is not set, Dynaconf will raise an error at startup.
-
-## Configuration Sections
-
-### AI Runtime Configuration
-
-Each registered agent runtime has its own configuration block under `[default.runtimes.]`. The name must match the name used in `.with_agent(name, ...)`.
-
-```toml
-[default.runtimes.summarizer]
-model_provider = "openai"
-model_name = "gpt-4o"
-model_api_key = "${OPENAI_API_KEY}"
-model_max_tokens = 4096
-model_temperature = 0.3
-model_base_url = "https://api.openai.com/v1"
-
-[default.runtimes.classifier]
-model_provider = "anthropic"
-model_name = "claude-sonnet-4-20250514"
-model_api_key = "${ANTHROPIC_API_KEY}"
-model_max_tokens = 2048
-model_temperature = 0.0
-```
-
-### Cache Configuration
-
-Settings for the built-in disk cache service, under `[default.cache]`.
-
-```toml
-[default.cache]
-cache_dir = "/tmp/blueprint-cache"
-size_limit = 1073741824 # 1 GB in bytes
-eviction_policy = "least-recently-used"
-default_ttl = 3600 # seconds
-```
-
-See the [Caching](caching.md) concept document for full details.
-
-### Event Publishing Configuration
-
-Controls how events are published, including the default pub/sub component and topic-to-event-type mappings.
-
-```toml
-[default.event_publishing]
-default_pubsub_name = "pubsub"
-
-[default.event_publishing.topic_mapping]
-"document.received" = "documents-inbound"
-"document.summarized" = "documents-processed"
-"document.error" = "documents-errors"
-```
-
-See the [Event Processing](event-processing.md) concept document for full details.
-
-### Observability Configuration
-
-Settings for OpenTelemetry tracing and structured logging.
-
-```toml
-[default]
-otel_enabled = true
-otel_endpoint = "http://localhost:4317"
-otel_service_name = "document-processor"
-log_level = "INFO"
-```
-
-See the [Observability](observability.md) concept document for full details.
-
-## Accessing Configuration at Runtime
-
-All components inherit access to configuration through `self.config`, which is available from `on_startup()` onward.
-
-### General Access
-
-```python
-from blueprint.agents.services.service_base import ServiceBase
-
-
-class StorageService(ServiceBase):
- async def on_startup(self) -> None:
- # Read a single value
- db_url = self.config.get("database_url")
-
- # Read a value with a default
- timeout = self.config.get("request_timeout", 30)
-```
-
-### AI Runtime Configuration
-
-Use `get_ai_config()` to retrieve the full configuration block for a named runtime. This returns a structured object with all model-related settings.
-
-```python
-from blueprint.agents.services.service_base import ServiceBase
-
-
-class ModelService(ServiceBase):
- async def on_startup(self) -> None:
- ai_config = self.config.get_ai_config("summarizer")
-
- provider = ai_config.model_provider # "openai"
- model = ai_config.model_name # "gpt-4o"
- max_tokens = ai_config.model_max_tokens # 4096
- temperature = ai_config.model_temperature # 0.3
-```
-
-### Cache Configuration
-
-Use `get_cache_config()` to retrieve cache-related settings as a structured object.
-
-```python
-cache_config = self.config.get_cache_config()
-print(cache_config.cache_dir) # "/tmp/blueprint-cache"
-print(cache_config.size_limit) # 1073741824
-print(cache_config.eviction_policy) # "least-recently-used"
-print(cache_config.default_ttl) # 3600
-```
-
-## Validation
-
-Configuration is validated automatically when `AppBuilder.build()` is called. If required settings are missing or have invalid types, a `ConfigError` is raised with a descriptive message.
-
-```python
-from blueprint.agents import AppBuilder, Config
-
-config = Config(settings_files=["settings.toml"])
-
-try:
- app = AppBuilder(config).with_agent("summarizer", SummarizerAgent).build()
-except ConfigError as e:
- # e.g., "Missing required config: default.runtimes.summarizer.model_provider"
- print(f"Configuration error: {e}")
-```
-
-Validation checks include:
-
-- Required fields for each registered runtime (model_provider, model_name)
-- Valid event bus selection ("dapr" or "nats")
-- Topic mappings exist for all declared published event types
-- Cache configuration is present when `.with_cache()` is used
-
-## Full Example settings.toml
-
-```toml
-[default]
-app_name = "document-processor"
-log_level = "INFO"
-event_bus = "dapr"
-
-# Observability
-otel_enabled = true
-otel_endpoint = "http://localhost:4317"
-otel_service_name = "document-processor"
-
-# Event publishing
-[default.event_publishing]
-default_pubsub_name = "pubsub"
-
-[default.event_publishing.topic_mapping]
-"document.received" = "documents-inbound"
-"document.summarized" = "documents-processed"
-"document.error" = "documents-errors"
-
-# AI runtimes
-[default.runtimes.summarizer]
-model_provider = "openai"
-model_name = "gpt-4o"
-model_api_key = "${OPENAI_API_KEY}"
-model_max_tokens = 4096
-model_temperature = 0.3
-
-[default.runtimes.classifier]
-model_provider = "anthropic"
-model_name = "claude-sonnet-4-20250514"
-model_api_key = "${ANTHROPIC_API_KEY}"
-model_max_tokens = 2048
-model_temperature = 0.0
-
-# Cache
-[default.cache]
-cache_dir = "/tmp/blueprint-cache"
-size_limit = 1073741824
-eviction_policy = "least-recently-used"
-default_ttl = 3600
-```
diff --git a/docs/concepts/event-processing.md b/docs/concepts/event-processing.md
deleted file mode 100644
index 06a0e531..00000000
--- a/docs/concepts/event-processing.md
+++ /dev/null
@@ -1,319 +0,0 @@
-# Event Processing
-
-Blueprint Agents uses the CloudEvents v1.0 specification as its universal message format. Events flow through a handler chain where each handler can inspect, process, transform, or forward events to downstream consumers.
-
-## CloudEvent Model
-
-The framework provides a generic `CloudEvent[T]` model that wraps the standard CloudEvents attributes with a typed data payload.
-
-```python
-from blueprint.agents.models.events import CloudEvent, GenericCloudEvent
-```
-
-### Core Fields
-
-| Field | Type | Description |
-|---|---|---|
-| `id` | `str` | Unique event identifier (UUID by default) |
-| `type` | `str` | Event type identifier, e.g. `"document.received"` |
-| `source` | `str` | URI identifying the event producer |
-| `subject` | `str` | Subject of the event in context of the source |
-| `time` | `datetime` | Timestamp when the event was created |
-| `data` | `T` | The event payload, typed by the generic parameter |
-
-### GenericCloudEvent
-
-For cases where the data payload does not require a specific schema, use the pre-defined alias:
-
-```python
-# GenericCloudEvent is equivalent to CloudEvent[dict[str, Any]]
-event = GenericCloudEvent(
- type="document.received",
- source="/ingest/api",
- subject="doc-12345",
- data={"content": "The full document text...", "format": "plaintext"},
-)
-```
-
-### Typed Events
-
-For structured payloads, parameterize `CloudEvent` with a Pydantic model or dataclass:
-
-```python
-from pydantic import BaseModel
-from blueprint.agents.models.events import CloudEvent
-
-
-class DocumentPayload(BaseModel):
- content: str
- format: str
- word_count: int
-
-
-event: CloudEvent[DocumentPayload] = CloudEvent(
- type="document.received",
- source="/ingest/api",
- subject="doc-12345",
- data=DocumentPayload(content="...", format="plaintext", word_count=1500),
-)
-```
-
-## Handler Chain-of-Responsibility
-
-Event handlers form an ordered processing chain. When an event arrives, the framework iterates through registered handlers, asks each whether it can handle the event, and delegates processing to those that accept it.
-
-### Handler Priority
-
-Handlers are sorted by their `priority` attribute (lower values execute earlier). This determines the order in which handlers are consulted for each incoming event.
-
-```python
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import CloudEvent
-
-
-class ValidationHandler(EventHandlerBase):
- priority = 1 # Runs first
-
- def can_handle_event(self, event: CloudEvent) -> bool:
- return event.type == "document.received"
-
- async def handle_event(self, event: CloudEvent) -> None:
- if not event.data.get("content"):
- raise ValueError("Empty document content")
- # Return None to pass the event to the next handler
- return None
-
-
-class EnrichmentHandler(EventHandlerBase):
- priority = 10 # Runs after validation
-
- def can_handle_event(self, event: CloudEvent) -> bool:
- return event.type == "document.received"
-
- async def handle_event(self, event: CloudEvent) -> HandlerResult:
- enriched = await self.enrich(event.data)
- return HandlerResult(event_type="document.enriched", data=enriched)
-```
-
-### Handler Methods
-
-Every handler must implement two methods:
-
-- **`can_handle_event(event)`** -- Return `True` if this handler should process the given event. Called for every incoming event.
-- **`handle_event(event)`** -- Process the event and return a result that controls downstream behavior.
-
-## Return Values from handle_event
-
-The return value of `handle_event()` determines what happens after processing:
-
-### Return None -- Pass to Next Handler
-
-Returning `None` or not returning signals that the handler has finished its work (or declined to act) and the event should continue to the next handler in the chain.
-
-```python
-async def handle_event(self, event: CloudEvent) -> None:
- await self.log_event(event)
- return None # Continue chain
-```
-
-### Return HandlerResult -- Publish a Downstream Event
-
-Returning a `HandlerResult` causes the framework to publish a new event to the configured event bus.
-
-```python
-from blueprint.agents.models.events import HandlerResult
-
-
-async def handle_event(self, event: CloudEvent) -> HandlerResult:
- summary = await self.summarize(event.data["content"])
- return HandlerResult(
- event_type="document.summarized",
- data={"summary": summary, "original_id": event.id},
- )
-```
-
-### Return a List of HandlerResult -- Publish Multiple Events
-
-Returning a list publishes multiple downstream events, useful for fan-out patterns.
-
-```python
-async def handle_event(self, event: CloudEvent) -> list[HandlerResult]:
- chunks = self.split_document(event.data["content"])
- return [
- HandlerResult(
- event_type="chunk.created",
- data={"chunk": chunk, "index": i},
- )
- for i, chunk in enumerate(chunks)
- ]
-```
-
-### Return Any Other Value -- Internal Chaining
-
-Returning any other value passes it along internally within the handler chain without publishing to the event bus. This is useful for in-process data transformation between handlers.
-
-```python
-async def handle_event(self, event: CloudEvent) -> dict:
- # This result is available to the next handler but is not published
- return {"validated": True, "timestamp": datetime.utcnow().isoformat()}
-```
-
-## Declaring Published Event Types
-
-Each handler should declare the event types it may produce. The framework uses this metadata for validation and documentation.
-
-```python
-class DocumentHandler(EventHandlerBase):
- def get_published_event_types(self) -> list[str]:
- return ["document.summarized", "document.error"]
-```
-
-## Event Bus Configuration
-
-Blueprint Agents supports two event bus backends: Dapr and NATS. The choice is made in `settings.toml`.
-
-### Selecting the Event Bus
-
-```toml
-[default]
-event_bus = "dapr" # "dapr", "nats", or "sessions"
-```
-
-### Topic Mapping
-
-Map event types to topics so the framework knows where to publish each event:
-
-```toml
-[default.event_publishing]
-default_pubsub_name = "pubsub"
-
-[default.event_publishing.topic_mapping]
-"document.received" = "documents-inbound"
-"document.summarized" = "documents-processed"
-"document.error" = "documents-errors"
-```
-
-## Dapr Event Bus
-
-When `event_bus = "dapr"`, the framework integrates with the Dapr sidecar for pub/sub messaging.
-
-- **Receiving events**: The application exposes an HTTP endpoint at `/events/{topic}`. The Dapr sidecar delivers messages by calling this endpoint.
-- **Publishing events**: The framework publishes events through the Dapr sidecar HTTP API (`/v1.0/publish/{pubsub}/{topic}`).
-
-Dapr handles message delivery guarantees, retries, and dead-letter queues through its component configuration.
-
-```toml
-[default]
-event_bus = "dapr"
-
-[default.event_publishing]
-default_pubsub_name = "pubsub"
-
-[default.event_publishing.topic_mapping]
-"document.received" = "documents"
-```
-
-## NATS Event Bus
-
-When `event_bus = "nats"`, the framework connects directly to a NATS server.
-
-- **Receiving events**: The framework subscribes to NATS subjects mapped from topic names.
-- **Publishing events**: Messages are published directly to NATS subjects.
-- **JetStream**: Optional JetStream support provides persistence, replay, and at-least-once delivery guarantees.
-
-```toml
-[default]
-event_bus = "nats"
-nats_url = "nats://localhost:4222"
-
-[default.event_publishing]
-default_pubsub_name = "default"
-
-[default.event_publishing.topic_mapping]
-"document.received" = "documents.inbound"
-"document.summarized" = "documents.processed"
-```
-
-## Sessions Transport
-
-When `event_bus = "sessions"`, `AppBuilder.build()` wires three components automatically:
-
-1. `SessionsApiClient` — REST client for the sessions service
-2. `SessionKeyProvider` — session-key resolution with TTL cache
-3. `SessionsBus` — outbound SSE consumer that converts job notifications into CloudEvents and dispatches them through the handler chain
-
-`SessionsBus` has no inbound HTTP surface — there is no router to mount. Connection to the sessions service is established asynchronously after startup; the framework tolerates a sessions service that is unreachable at boot and retries in the background.
-
-> **Agent registration (sessions v0.4.0+):** Before opening the SSE job stream, `SessionsBus` calls
-> `POST /agents/register` to declare its `agent_id`, `agent_type`, and `capabilities` — the dispatch
-> source of truth. It re-registers before every reconnect attempt (idempotent), and on graceful
-> shutdown it drains in-flight jobs and unregisters (`DELETE /agents/{agent_id}`). Against a pre-v0.4.0
-> server the register call returns 404 and is skipped ("legacy, proceed without registration").
-
-> **Reconnect catch-up:** SSE only pushes jobs created *while connected*, so jobs created during a
-> restart, redeploy, or stream gap would otherwise be missed. On every (re)connect `SessionsBus`
-> reconciles in two ways: it resumes the stream with `Last-Event-ID` (the server replays missed
-> frames from its ring buffer on a same-process reconnect), and it runs a REST **catch-up** —
-> `GET /jobs?status=pending` for its capabilities — dispatching any pending jobs through the normal
-> handler path. Both feed the same idempotent handler, so a job that arrives via more than one route
-> is processed once. Catch-up is best-effort: a listing failure is logged and never disturbs the live
-> stream. A job stranded in `running` because its previous owner crashed is recovered server-side
-> (the sessions reaper re-pends it) and then redelivered by this catch-up.
-
-```toml
-[default]
-event_bus = "sessions"
-
-[default.sessions_service]
-base_url = "http://sessions:8000"
-agent_id = "my-agent"
-agent_type = "analyser"
-capabilities = ["analyse_documents"]
-api_key = "@format {env[SESSIONS_API_KEY]}"
-# Optional per-agent HS256 bearer. Sent as `Authorization: Bearer ` alongside
-# `X-Api-Key` on the gated routes only when set. See service-sessions#198/#326. Inject via
-# SESSIONS_AGENT_TOKEN, never commit it. To opt out, OMIT this line (or export an empty
-# SESSIONS_AGENT_TOKEN=) — keeping it with the env var undefined fails Dynaconf config load.
-agent_token = "@format {env[SESSIONS_AGENT_TOKEN]}"
-max_concurrent_jobs = 5
-job_timeout_seconds = 300
-```
-
-## Complete Handler Example
-
-```python
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import CloudEvent, HandlerResult
-
-
-class IngestionHandler(EventHandlerBase):
- priority = 5
-
- async def on_startup(self) -> None:
- self.storage = self.registry.get_service(StorageService)
- self.cache = self.registry.cache_service
-
- def can_handle_event(self, event: CloudEvent) -> bool:
- return event.type in ("document.received", "document.updated")
-
- async def handle_event(self, event: CloudEvent) -> HandlerResult | list[HandlerResult]:
- doc_id = event.subject
-
- # Check cache for deduplication
- cached = await self.cache.get(doc_id, namespace="ingested")
- if cached and event.type == "document.received":
- return None # Already processed, skip
-
- # Store the document
- await self.storage.save(doc_id, event.data)
- await self.cache.set(doc_id, True, namespace="ingested", ttl=3600)
-
- # Publish downstream
- return HandlerResult(
- event_type="document.stored",
- data={"doc_id": doc_id, "source": event.source},
- )
-
- def get_published_event_types(self) -> list[str]:
- return ["document.stored", "document.ingestion_error"]
-```
diff --git a/docs/concepts/observability.md b/docs/concepts/observability.md
deleted file mode 100644
index ac97ea16..00000000
--- a/docs/concepts/observability.md
+++ /dev/null
@@ -1,298 +0,0 @@
-# Observability
-
-Blueprint Agents provides built-in observability through OpenTelemetry tracing, structured logging, metrics collection, and health check endpoints. These capabilities are designed to work out of the box with minimal configuration while remaining extensible for advanced use cases.
-
-## OpenTelemetry Tracing
-
-The framework integrates with OpenTelemetry to produce distributed traces exported via the OTLP protocol. When enabled, traces capture the full request lifecycle including HTTP handling, event processing, and AI model invocations.
-
-### Configuration
-
-Enable tracing in `settings.toml`:
-
-```toml
-[default]
-otel_enabled = true
-otel_endpoint = "http://localhost:4317"
-otel_service_name = "document-processor"
-```
-
-| Field | Type | Description |
-|---|---|---|
-| `otel_enabled` | `bool` | Enable or disable OpenTelemetry tracing |
-| `otel_endpoint` | `str` | OTLP collector endpoint (gRPC) |
-| `otel_service_name` | `str` | Service name attached to all spans and metrics |
-
-### Automatic FastAPI Instrumentation
-
-When tracing is enabled, the framework automatically instruments the FastAPI application. Every incoming HTTP request generates a span with method, path, status code, and duration attributes. No additional code is required.
-
-### Automatic CloudEvent Attribute Extraction
-
-When an event handler processes a CloudEvent, the framework automatically extracts event metadata and attaches it to the active span:
-
-- `cloudevent.id` -- The unique event identifier
-- `cloudevent.type` -- The event type string
-- `cloudevent.source` -- The event source URI
-- `cloudevent.subject` -- The event subject
-
-This makes it straightforward to correlate traces with specific events in your observability backend.
-
-## The @traced() Decorator
-
-For custom spans on application-specific logic, use the `@traced()` decorator on any async method:
-
-```python
-from blueprint.agents.services.service_base import ServiceBase
-from blueprint.agents.observability import traced
-
-
-class EmbeddingService(ServiceBase):
- async def on_startup(self) -> None:
- self.model = self.registry.get_agent("embedder")
-
- @traced()
- async def compute_embedding(self, text: str) -> list[float]:
- # This method is wrapped in a span named "EmbeddingService.compute_embedding"
- return await self.model.run(text)
-
- @traced()
- async def batch_embed(self, texts: list[str]) -> list[list[float]]:
- results = []
- for text in texts:
- embedding = await self.compute_embedding(text)
- results.append(embedding)
- return results
-```
-
-The decorator creates a span named `{ClassName}.{method_name}` by default. Nested `@traced()` calls produce parent-child span relationships, giving full visibility into call hierarchies.
-
-### Custom Span Names
-
-Pass a name argument to override the default span name:
-
-```python
-@traced("embedding.compute")
-async def compute_embedding(self, text: str) -> list[float]:
- return await self.model.run(text)
-```
-
-## Metrics
-
-The framework automatically collects and exports metrics related to AI model usage and request processing.
-
-### Token Usage Metrics
-
-For every AI agent invocation, the following metrics are recorded:
-
-| Metric | Description |
-|---|---|
-| `ai.tokens.prompt` | Number of tokens in the prompt |
-| `ai.tokens.completion` | Number of tokens in the model response |
-| `ai.tokens.total` | Total tokens consumed (prompt + completion) |
-
-### Request Metrics
-
-| Metric | Description |
-|---|---|
-| `ai.request.latency` | Duration of the model request in milliseconds |
-| `ai.request.model_provider` | The provider used (e.g., "openai", "anthropic") |
-| `ai.request.model_name` | The specific model invoked (e.g., "gpt-4o") |
-
-These metrics are exported alongside traces through the configured OTLP endpoint and can be visualized in Grafana, Datadog, or any OpenTelemetry-compatible backend.
-
-## Structured Logging
-
-Blueprint Agents uses structured logging with correlation context. Log messages are formatted with key-value pairs that are queryable in log aggregation systems.
-
-### Formatting Convention
-
-Use `%s`-style string formatting in log statements, not f-strings. This allows log aggregators to group identical log patterns and enables lazy evaluation (the string is only formatted if the log level is active).
-
-```python
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class DocumentHandler(EventHandlerBase):
- async def handle_event(self, event: CloudEvent) -> HandlerResult:
- # Correct: %s-style formatting
- logger.info("Processing document %s from source %s", event.subject, event.source)
-
- # Incorrect: f-string formatting (defeats structured logging)
- # logger.info(f"Processing document {event.subject} from source {event.source}")
-
- result = await self.process(event)
- logger.debug("Processing complete for %s, result size: %d", event.subject, len(result))
-
- return HandlerResult(event_type="document.processed", data=result)
-```
-
-### Log Level Configuration
-
-Set the log level in `settings.toml`:
-
-```toml
-[default]
-log_level = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL
-```
-
-### Correlation Context
-
-When tracing is enabled, the active trace ID and span ID are automatically injected into log records. This allows you to correlate log entries with specific traces in your observability stack.
-
-## Health Checks
-
-The framework automatically registers health check endpoints on the FastAPI application. These endpoints follow standard conventions for container orchestration platforms such as Kubernetes.
-
-### Built-in Endpoints
-
-| Endpoint | Purpose | Description |
-|---|---|---|
-| `/health/live` | Liveness probe | Returns 200 if the process is running. Used by orchestrators to detect crashed processes. |
-| `/health/ready` | Readiness probe | Returns 200 if the application is ready to accept traffic. Checks that all components have completed startup. |
-| `/health/detailed` | Detailed status | Returns a JSON breakdown of each component's health status. Useful for debugging. |
-
-### Response Format
-
-The `/health/detailed` endpoint returns structured information about each component:
-
-```json
-{
- "status": "healthy",
- "components": {
- "EmbeddingService": {"status": "healthy"},
- "DocumentHandler": {"status": "healthy"},
- "summarizer": {"status": "healthy", "type": "agent"},
- "cache": {"status": "healthy", "entries": 1523}
- },
- "uptime_seconds": 3847
-}
-```
-
-### Custom Health Checkers
-
-Register custom health check logic using `.with_health_checker()` on the `AppBuilder`. This is useful for verifying connectivity to external dependencies.
-
-```python
-from blueprint.agents import AppBuilder, Config
-
-
-async def check_database(registry) -> dict:
- """Custom health check for database connectivity."""
- try:
- db = registry.get_service(DatabaseService)
- await db.ping()
- return {"status": "healthy", "latency_ms": 12}
- except Exception as e:
- return {"status": "unhealthy", "error": str(e)}
-
-
-async def check_external_api(registry) -> dict:
- """Custom health check for an external API."""
- try:
- client = registry.get_service(ExternalApiClient)
- await client.health_check()
- return {"status": "healthy"}
- except Exception as e:
- return {"status": "unhealthy", "error": str(e)}
-
-
-config = Config(settings_files=["settings.toml"])
-
-app = (
- AppBuilder(config)
- .with_service(DatabaseService)
- .with_service(ExternalApiClient)
- .with_handler(MyHandler)
- .with_health_checker("database", check_database)
- .with_health_checker("external_api", check_external_api)
- .build()
-)
-```
-
-Custom health checkers appear in the `/health/detailed` response and influence the `/health/ready` status. If any checker returns `"unhealthy"`, the readiness endpoint returns a 503 status code.
-
-## Complete Configuration Example
-
-```toml
-[default]
-app_name = "document-processor"
-log_level = "INFO"
-
-# OpenTelemetry
-otel_enabled = true
-otel_endpoint = "http://otel-collector:4317"
-otel_service_name = "document-processor"
-```
-
-## Complete Code Example
-
-```python
-import logging
-
-from blueprint.agents import AppBuilder, Config
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.services.service_base import ServiceBase
-from blueprint.agents.models.events import CloudEvent, HandlerResult
-from blueprint.agents.observability import traced
-
-logger = logging.getLogger(__name__)
-
-
-class AnalyticsService(ServiceBase):
- async def on_startup(self) -> None:
- self.agent = self.registry.get_agent("analyzer")
-
- @traced()
- async def analyze(self, content: str) -> dict:
- logger.info("Starting analysis, content length: %d", len(content))
- result = await self.agent.run(content)
- logger.info("Analysis complete, categories found: %d", len(result.get("categories", [])))
- return result
-
-
-class AnalyticsHandler(EventHandlerBase):
- priority = 10
-
- async def on_startup(self) -> None:
- self.analytics = self.registry.get_service(AnalyticsService)
-
- def can_handle_event(self, event: CloudEvent) -> bool:
- return event.type == "document.received"
-
- @traced()
- async def handle_event(self, event: CloudEvent) -> HandlerResult:
- logger.info("Handling event %s for subject %s", event.type, event.subject)
- result = await self.analytics.analyze(event.data["content"])
- return HandlerResult(
- event_type="document.analyzed",
- data={"doc_id": event.subject, "analysis": result},
- )
-
- def get_published_event_types(self) -> list[str]:
- return ["document.analyzed", "document.analysis_error"]
-
-
-async def check_model_health(registry) -> dict:
- try:
- agent = registry.get_agent("analyzer")
- await agent.health_check()
- return {"status": "healthy"}
- except Exception as e:
- return {"status": "unhealthy", "error": str(e)}
-
-
-config = Config(settings_files=["settings.toml", "secrets.toml"])
-
-app = (
- AppBuilder(config)
- .with_service(AnalyticsService)
- .with_handler(AnalyticsHandler)
- .with_agent("analyzer", AnalyzerAgent)
- .with_health_checker("analyzer_model", check_model_health)
- .with_cache()
- .build()
-)
-```
diff --git a/docs/guides/caching-getting-started.md b/docs/guides/caching-getting-started.md
deleted file mode 100644
index b70dad25..00000000
--- a/docs/guides/caching-getting-started.md
+++ /dev/null
@@ -1,208 +0,0 @@
-# Caching — Getting Started
-
-This guide walks a developer who is **already using `avs-blueprint-agents`** through enabling the centralised Redis cache for their service. Estimated time: 5 minutes once Redis is reachable.
-
-For the architectural background, see [Cache Architecture](../concepts/cache-architecture.md).
-
----
-
-## 1. Add the Redis extra to your project
-
-The `redis` Python package is shipped as an **optional extra** of `avs-blueprint-agents` so single-replica deployments don't pull in extra dependencies.
-
-In your project's `pyproject.toml`:
-
-```toml
-[project]
-dependencies = [
- "avs-blueprint-agents[redis]>=0.6.0",
- # ... your other dependencies
-]
-```
-
-If you use `requirements.txt`:
-
-```
-avs-blueprint-agents[redis]>=0.6.0
-```
-
-If you use `uv`:
-
-```bash
-uv add "avs-blueprint-agents[redis]"
-```
-
-What this pulls in: `redis>=5.0.0` with the `hiredis` C-parser for performance.
-
----
-
-## 2. Tell the blueprint which backend to use
-
-In your `settings.toml` (or whichever Dynaconf settings file you use):
-
-```toml
-[default.cache]
-backend = "redis" # was "disk" — switch here
-key_prefix = "my-service-name" # avoids collisions in shared Redis
-redis_url = "redis://localhost:6379/0" # full URL incl. db index
-default_ttl = 600 # seconds; null = no expiry
-
-# --- Optional ---
-# redis_password = "@format {env[REDIS_PASSWORD]}"
-# redis_db = 0
-# redis_tls = false # true → uses rediss:// scheme
-# fallback_to_local = false # true → fallback to DiskCache if Redis is down
-```
-
-**That's the only required change.** Your existing `AppBuilder().with_cache()` line picks up the new config automatically — no code change.
-
-### Required vs. optional fields
-
-| Field | Required? | Default | Notes |
-|---|---|---|---|
-| `backend` | yes (to switch) | `"disk"` | `"disk"` or `"redis"` |
-| `redis_url` | yes for Redis | `"redis://localhost:6379/0"` | Standard URL, `redis://[user[:password]]@host:port/db` |
-| `key_prefix` | recommended | `""` | Pick something distinctive per service — avoids collisions when multiple services share Redis |
-| `default_ttl` | optional | `3600` | Seconds; `null` means no TTL is set on writes that don't supply one |
-| `redis_password` | only if needed | `null` | Use Dynaconf env-var injection: `"@format {env[REDIS_PASSWORD]}"` |
-| `redis_db` | optional | `0` | Redis DB index; usually `0` |
-| `redis_tls` | only for TLS | `false` | When `true`, the connection upgrades to `rediss://` |
-| `fallback_to_local` | optional | `false` | Soft fallback when Redis is unreachable at startup |
-
----
-
-## 3. Use the cache from your services
-
-Nothing changes here. Every service / handler / API resolves the cache from the registry in `on_startup()`:
-
-```python
-from blueprint.agents.services.service_base import ServiceBase
-
-class MyService(ServiceBase):
- async def on_startup(self) -> None:
- self._cache = self.registry.cache_service
-
- async def on_shutdown(self) -> None:
- return None
-
- def remember(self, key: str, value: dict) -> None:
- self._cache.set(key, value, namespace="my-namespace")
-
- def recall(self, key: str) -> dict | None:
- return self._cache.get(key, namespace="my-namespace")
-```
-
-The `self._cache` you receive is the **same instance** for every service in this app — that's what makes "two agents writing to the same cache" work.
-
----
-
-## 4. Verify it works
-
-Run a real Redis (Docker is fine):
-
-```bash
-docker run -d --rm --name dev-redis -p 6379:6379 redis:alpine
-```
-
-Start your app:
-
-```bash
-python -m uvicorn src.main:app --port 8000
-```
-
-You should see in the log:
-
-```
-Adding component: redis_cache_service to registry
-Registering cache service: RedisCacheService
-RedisCacheService connected to redis://localhost:6379/0 (prefix='my-service-name')
-```
-
-Hit any endpoint that writes to the cache, then peek at Redis to see your keys:
-
-```bash
-docker exec dev-redis redis-cli KEYS "my-service-name:*"
-```
-
-You should see one or more keys like `my-service-name:my-namespace:`.
-
----
-
-## 5. Multiple replicas — the actual point of the feature
-
-The whole reason for switching to Redis is **shared state across replicas**. To prove it works in your setup:
-
-```bash
-# Terminal 1 — replica A
-python -m uvicorn src.main:app --port 8001
-
-# Terminal 2 — replica B (same code, same settings.toml, different port)
-python -m uvicorn src.main:app --port 8002
-
-# Write to replica A
-curl -X POST 'http://localhost:8001/your-write-endpoint?...'
-
-# Read on replica B — should return what A just wrote
-curl 'http://localhost:8002/your-read-endpoint'
-```
-
-If A's writes show up on B, you're done. If not, double-check `key_prefix` and `redis_url` are identical between the two replicas.
-
----
-
-## 6. Operations checklist
-
-Before you ship to production:
-
-- [ ] Use a managed Redis (or your platform's Redis service) — don't run `redis:alpine` in prod
-- [ ] Set `redis_password` via env var, not literally in `settings.toml`
-- [ ] Use TLS for any Redis that is not in the same VPC: `redis_tls = true`
-- [ ] Pick a `key_prefix` that includes the service name *and* environment (e.g. `payments-svc-prod`)
-- [ ] Decide on `fallback_to_local`: ON keeps the service up if Redis is down, OFF surfaces the issue immediately. Both are valid — choose the one that matches your operational posture
-- [ ] Set `default_ttl` so abandoned keys eventually disappear
-- [ ] Wire K8s probes to `/health/ready` (readiness) and `/health/live` (liveness) — the framework reflects Redis reachability via the readiness probe automatically
-
-### How the readiness probe interacts with Redis outages
-
-When `with_cache()` is called, a `CacheHealthChecker` is registered automatically and pings Redis on every health-check tick (default 30 s, configurable via `health_check_interval_seconds`).
-
-| Scenario | `/health/ready` | `/health/live` | K8s reaction |
-|---|---|---|---|
-| Redis healthy | `200 UP` with `cache: healthy` | `200 UP` | Pod in service pool, traffic flows |
-| Redis stops mid-flight | Within ≤ 30 s flips to `503 DOWN` with full diagnostic payload | stays `200 UP` | Pod removed from service pool, **not** killed |
-| Redis recovers | Within ≤ 30 s flips back to `200 UP` | stays `200 UP` | Pod re-added to service pool automatically |
-| `fallback_to_local=true`, Redis unreachable at startup | `503 DOWN` once first health tick runs | `200 UP` | Pod alive but won't take traffic until Redis returns |
-| `fallback_to_local=false`, Redis unreachable at startup | never reached (boot crashes) | never reached | CrashLoopBackOff → pager |
-
-A K8s `httpGet` probe on `/health/ready` only inspects the HTTP status code, so the 503 propagation is what makes the cache check actually take effect at the orchestration layer.
-
-Example K8s probe configuration:
-
-```yaml
-readinessProbe:
- httpGet:
- path: /health/ready
- port: 8000
- initialDelaySeconds: 10 # give the cache health check one tick
- periodSeconds: 10
- failureThreshold: 3 # tolerate one missed tick before pulling the pod
-livenessProbe:
- httpGet:
- path: /health/live
- port: 8000
- initialDelaySeconds: 10
- periodSeconds: 30
-```
-
----
-
-## Troubleshooting
-
-| Symptom | Cause | Fix |
-|---|---|---|
-| `ImportError: Redis backend requires 'avs-blueprint-agents[redis]'` | Forgot to install the extra | `pip install 'avs-blueprint-agents[redis]'` |
-| Log shows `DiskCacheService` instead of `RedisCacheService` | `settings.toml` not picked up — wrong path or wrong section | Confirm `[default.cache]` section, confirm `Config(settings_files=["settings.toml"])` finds the file |
-| `redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379` | Redis not running | `docker ps` to check; `docker run -d -p 6379:6379 redis:alpine` to start |
-| Two replicas don't see each other's keys | Different `key_prefix` between replicas | Identical `key_prefix` for replicas of the same service |
-| Two services collide on the same key | Same `key_prefix` for different services | Pick distinct `key_prefix` values per service |
-| `Component with name redis_cache_service already exists` (in tests) | A previous test already constructed a cache and the Component registry rejects duplicate names | Use the autouse fixture pattern from `tests/integration/test_shared_redis_cache.py` to clear the registry between tests |
diff --git a/docs/guides/cli-reference.md b/docs/guides/cli-reference.md
deleted file mode 100644
index e54b5eaf..00000000
--- a/docs/guides/cli-reference.md
+++ /dev/null
@@ -1,925 +0,0 @@
-# CLI Reference
-
-The `asbs` command-line tool is the primary interface for scaffolding, developing, and managing Blueprint Agents projects. It is installed automatically with the `avs-blueprint-agents` package.
-
-```bash
-pip install avs-blueprint-agents
-```
-
----
-
-## Naming Conventions and Auto-Registration
-
-All `asbs create` commands follow consistent naming conventions and automatically register components in `src/main.py`.
-
-### Input Flexibility
-
-The CLI accepts component names in multiple formats and normalizes them to proper class and file names:
-
-- **snake_case**: `order_placed` → `OrderPlacedHandler`
-- **CamelCase**: `OrderPlaced` → `OrderPlacedHandler`
-- **kebab-case**: `order-placed` → `OrderPlacedHandler`
-
-All formats are converted to proper class names without double suffixes (e.g., never `OrderPlacedHandlerHandler`).
-
-### Component Naming
-
-Each component type follows a consistent suffix pattern:
-
-| Component Type | Input | Class Name | File Name | Notes |
-|---|---|---|---|---|
-| **Handler** | `order_placed` | `OrderPlacedHandler` | `order_placed_handler.py` | Handles events |
-| **Service** | `invoice_processor` | `InvoiceProcessorService` | `invoice_processor_service.py` | Contains business logic |
-| **API** | `order_management` | `OrderManagementApi` | `order_management_api.py` | REST endpoints + models file |
-| **Agent** | `document_analyzer` | `DocumentAnalyzer` | `document_analyzer_agent.py` | No "Agent" suffix in class name |
-| **Scheduler** | `cleanup` | `CleanupScheduler` | `cleanup_scheduler.py` | Background tasks |
-
-### Name Normalization Examples
-
-The CLI handles various input formats correctly:
-
-#### Handler Examples
-```bash
-asbs create handler order_placed # Snake case input
-asbs create handler OrderPlaced # CamelCase input
-asbs create handler order-placed # Kebab-case input
-# All produce: OrderPlacedHandler in order_placed_handler.py
-```
-
-#### Service Examples
-```bash
-asbs create service user_manager
-asbs create service UserManager
-asbs create service user-manager
-# All produce: UserManagerService in user_manager_service.py
-```
-
-#### API Examples
-```bash
-asbs create api product_catalog
-asbs create api ProductCatalog
-asbs create api product-catalog
-# All produce: ProductCatalogApi in product_catalog_api.py
-# And: product_catalog_models.py (without the "_api" suffix)
-```
-
-#### Agent Examples
-```bash
-asbs create agent document_analyzer
-asbs create agent DocumentAnalyzer
-asbs create agent document-analyzer
-# All produce: DocumentAnalyzer (agent class, not DocumentAnalyzerAgent)
-# File: document_analyzer_agent.py
-# Builder function: build_document_analyzer_agent()
-```
-
-### Auto-Registration
-
-When you create a component, the CLI automatically:
-
-1. **Creates the component file** in the appropriate directory
-2. **Adds imports** to `src/main.py`
-3. **Registers with AppBuilder** in the chain
-
-If auto-registration fails (e.g., `src/main.py` not found), the CLI displays a clear error message with manual registration instructions.
-
-#### Example Auto-Registration Output
-
-```bash
-$ asbs create handler order_placed
-✓ Created handler: src/handlers/order_placed_handler.py
-✓ Auto-registered in src/main.py
- - Added import: from src.handlers.order_placed_handler import OrderPlacedHandler
- - Added registration: .with_handler(OrderPlacedHandler())
-```
-
----
-
-## asbs setup
-
-Scaffold a complete Blueprint Agents project with all required directories and configuration files.
-
-```bash
-asbs setup
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------------|------------------------------------|----------|
-| `project-name` | Name of the project to create | Yes |
-
-### Generated Project Structure
-
-```
-/
- src/
- main.py
- handlers/
- services/
- api/
- models/
- prompts/
- tests/
- unit/
- integration/
- settings.toml
- secrets.toml
- pyproject.toml
- Dockerfile
-```
-
-### Example
-
-```bash
-asbs setup my-ai-service
-```
-
-The generated `main.py` contains the minimal application bootstrap:
-
-```python
-from blueprint.agents import AppBuilder, Config
-
-app = AppBuilder(Config()).build()
-```
-
----
-
-## asbs create handler
-
-Generate a new event handler component by creating a subclass of `EventHandlerBase`.
-
-```bash
-asbs create handler [--event-type ] [--priority ]
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------|---------------------------------|----------|
-| `name` | Name of the handler to create | Yes |
-
-### Options
-
-| Flag | Description | Default |
-|-------------------------|----------------------------------------------------|-----------|
-| `--event-type ` | The event type this handler will respond to | (prompt) |
-| `--priority ` | Handler priority (lower numbers execute first) | `0` |
-
-### Naming
-
-Handler names are converted to `Handler` format:
-
-- Input: `order_placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py`
-- Input: `OrderPlaced` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py`
-- Input: `order-placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py`
-
-### Auto-Registration
-
-The created handler is automatically:
-- Imported in `src/main.py`
-- Registered with `.with_handler(OrderPlacedHandler())`
-
-If auto-registration fails, manual registration instructions are provided.
-
-### Examples
-
-#### Basic Handler
-
-```bash
-asbs create handler order_placed --event-type "order.placed"
-```
-
-Creates `src/handlers/order_placed_handler.py` with an `OrderPlacedHandler` class.
-
-#### Handler with Priority
-
-```bash
-asbs create handler high_priority_event --event-type "system.alert" --priority 5
-```
-
-Handlers with lower priority numbers execute first in the chain.
-
-#### Handler Generated Code
-
-The generated handler includes:
-
-```python
-from blueprint.agents.handler import EventHandlerBase
-
-class OrderPlacedHandler(EventHandlerBase):
- def __init__(self) -> None:
- super().__init__(priority=0)
-
- async def on_startup(self) -> None:
- # Initialize resources from registry
- pass
-
- async def on_shutdown(self) -> None:
- # Clean up resources
- pass
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "order.placed"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- # Return None to pass to next handler
- # Return HandlerResult(...) to publish and stop chain
- return None
-```
-
----
-
-## asbs create service
-
-Generate a new service component by creating a subclass of `ServiceBase`.
-
-```bash
-asbs create service
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------|---------------------------------|----------|
-| `name` | Name of the service to create | Yes |
-
-### Naming
-
-Service names are converted to `Service` format:
-
-- Input: `invoice_processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py`
-- Input: `InvoiceProcessor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py`
-- Input: `invoice-processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py`
-
-### Auto-Registration
-
-The created service is automatically:
-- Imported in `src/main.py`
-- Registered with `.with_service(InvoiceProcessorService())`
-
-### Examples
-
-#### Basic Service
-
-```bash
-asbs create service invoice_processor
-```
-
-Creates `src/services/invoice_processor_service.py` with an `InvoiceProcessorService` class.
-
-#### Service Generated Code
-
-The generated service includes:
-
-```python
-from blueprint.agents.services import ServiceBase
-
-class InvoiceProcessorService(ServiceBase):
- async def on_startup(self) -> None:
- # Initialize resources, fetch dependencies from registry
- # Example: self._cache = self.registry.cache_service
- # Example: self._agent = self.registry.get_agent("analyzer")
- pass
-
- async def on_shutdown(self) -> None:
- # Clean up resources
- pass
-
- async def process(self, data: dict) -> dict:
- """Process invoice data.
-
- Args:
- data: Invoice information
-
- Returns:
- Processing result
- """
- # TODO: Implement business logic
- pass
-```
-
----
-
-## asbs create api
-
-Generate a new REST API component by creating a subclass of `RestApiBase`, plus a models file with Request/Response classes.
-
-```bash
-asbs create api
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------|------------------------------|----------|
-| `name` | Name of the API to create | Yes |
-
-### Naming
-
-API names are converted to `Api` format with an accompanying models file:
-
-- Input: `order_management`
- - Class: `OrderManagementApi`
- - API File: `order_management_api.py`
- - Models File: `order_management_models.py`
-
-### Files Generated
-
-1. **API File** (`src/api/_api.py`)
- - REST API class with `.get()`, `.post()`, `.put()`, `.delete()` endpoints
- - Dependency injection via `self.registry.get_service(...)`
-
-2. **Models File** (`src/models/_models.py`)
- - Request and Response Pydantic models
- - Example: `OrderManagementRequest` and `OrderManagementResponse`
-
-### Auto-Registration
-
-The created API is automatically:
-- Imported in `src/main.py` (both models and API)
-- Registered with `.with_rest_api(OrderManagementApi())`
-
-### Examples
-
-#### Basic API
-
-```bash
-asbs create api order_management
-```
-
-Creates:
-- `src/api/order_management_api.py` with `OrderManagementApi` class
-- `src/models/order_management_models.py` with `OrderManagementRequest` and `OrderManagementResponse` classes
-
-#### API Generated Code
-
-The generated API includes:
-
-```python
-"""REST API for order_management operations."""
-
-from fastapi import HTTPException, status
-from blueprint.agents.io.api.rest_api_base import RestApiBase
-from src.models.order_management_models import OrderManagementRequest, OrderManagementResponse
-
-class OrderManagementApi(RestApiBase):
- async def on_startup(self) -> None:
- # Initialize dependencies from registry
- # Example: self._service = self.registry.get_service(OrderService)
- pass
-
- async def on_shutdown(self) -> None:
- pass
-
- @RestApiBase.get("/{item_id}", response_model=OrderManagementResponse)
- async def get_item(self, item_id: str) -> OrderManagementResponse:
- """Get item by ID."""
- # TODO: Implement get logic
- pass
-
- @RestApiBase.post("/", response_model=OrderManagementResponse)
- async def create_item(self, request: OrderManagementRequest) -> OrderManagementResponse:
- """Create new item."""
- # TODO: Implement create logic
- pass
-```
-
-The accompanying models file includes:
-
-```python
-from pydantic import BaseModel
-
-class OrderManagementRequest(BaseModel):
- """Request model for order_management operations."""
- # TODO: Add your request fields
- pass
-
-class OrderManagementResponse(BaseModel):
- """Response model for order_management operations."""
- # TODO: Add your response fields
- pass
-```
-
----
-
-## asbs create agent
-
-Generate an AI agent component with `AgentRuntime`, `AgentBuilder` boilerplate, system prompt, instruction prompt, and settings configuration.
-
-```bash
-asbs create agent
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------|--------------------------------|----------|
-| `name` | Name of the agent to create | Yes |
-
-### Naming
-
-Agent names are converted to `` format (no "Agent" suffix in class name, but used in builder function):
-
-- Input: `document_analyzer` → Function: `build_document_analyzer_agent()` → File: `document_analyzer_agent.py`
-- Input: `DocumentAnalyzer` → Function: `build_document_analyzer_agent()` → File: `document_analyzer_agent.py`
-
-### Files Generated
-
-1. **Agent Module** (`src/agents/_agent.py`)
- - `build__agent(config)` function that creates and configures the agent
- - Uses `AgentBuilder` with model config, prompts, and tools
-
-2. **System Prompt** (`src/prompts/_system.prompt`)
- - Static context for the agent
- - Example content already provided
-
-3. **Instruction Prompt** (`src/prompts/_instruction.prompt`)
- - Dynamic template with `{placeholders}` for runtime input
- - Example content already provided
-
-4. **Settings Configuration** (`settings.toml`)
- - `[default.runtimes.]` section with model configuration
- - Model provider, name, temperature, and token limits
-
-### Auto-Registration
-
-The created agent is automatically:
-- Imported in `src/main.py`
-- Agent instance created before `app =`
-- Registered with `.with_agent(_agent)`
-- Configuration added to `settings.toml`
-
-### Examples
-
-#### Basic Agent
-
-```bash
-asbs create agent document_analyzer
-```
-
-Creates:
-- `src/agents/document_analyzer_agent.py` with `build_document_analyzer_agent()` function
-- `src/prompts/document_analyzer_system.prompt` with system context
-- `src/prompts/document_analyzer_instruction.prompt` with instruction template
-- `[default.runtimes.document_analyzer]` section in `settings.toml`
-
-#### Agent Generated Code
-
-The generated agent builder includes:
-
-```python
-"""AgentRuntime for document_analyzer operations."""
-
-from blueprint.agents import AgentBuilder
-from blueprint.agents.base import AgentRuntime
-from blueprint.agents.config import Config
-
-
-def build_document_analyzer_agent(config: Config) -> AgentRuntime:
- """Build the document_analyzer agent.
-
- Args:
- config: Application configuration
-
- Returns:
- Configured AgentRuntime instance
- """
- agent = (
- AgentBuilder(config, runtime_name="document_analyzer")
- .with_model_from_config()
- .with_system_prompt("document_analyzer_system")
- .build(name="document_analyzer")
- )
-
- return agent
-```
-
-#### Settings Configuration
-
-Auto-generated in `settings.toml`:
-
-```toml
-[default.runtimes.document_analyzer]
-model_provider = "openai"
-model_name = "gpt-4o-mini"
-model_temperature = 0.7
-model_max_tokens = 2000
-```
-
-Override any defaults in your `settings.toml` after creation.
-
----
-
-## asbs create scheduler
-
-Generate a scheduled task component by creating a subclass of `SchedulerBase`.
-
-```bash
-asbs create scheduler [--cron ]
-```
-
-### Arguments
-
-| Argument | Description | Required |
-|----------|------------------------------------|----------|
-| `name` | Name of the scheduler to create | Yes |
-
-### Options
-
-| Flag | Description | Default |
-|------------------|--------------------------------------|---------------|
-| `--cron ` | Cron expression for the schedule | `0 * * * *` |
-
-### Naming
-
-Scheduler names are converted to `Scheduler` format:
-
-- Input: `cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py`
-- Input: `Cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py`
-- Input: `cleanup-task` → Class: `CleanupTaskScheduler` → File: `cleanup_task_scheduler.py`
-
-### Auto-Registration
-
-The created scheduler is automatically:
-- Imported in `src/main.py`
-- Registered with `.with_scheduler(CleanupScheduler())`
-
-### Cron Expressions
-
-Use standard 5-field cron syntax:
-
-```
-┌───────────── minute (0-59)
-│ ┌───────────── hour (0-23)
-│ │ ┌───────────── day of month (1-31)
-│ │ │ ┌───────────── month (1-12)
-│ │ │ │ ┌───────────── day of week (0-7, 0=Sunday)
-│ │ │ │ │
-│ │ │ │ │
-* * * * *
-```
-
-Common patterns:
-- `*/5 * * * *` - Every 5 minutes
-- `0 * * * *` - Every hour at minute 0
-- `0 2 * * *` - Daily at 2:00 AM
-- `0 8 * * 1-5` - Weekdays at 8:00 AM
-- `0 0 1 * *` - Monthly at midnight on the 1st
-
-### Examples
-
-#### Hourly Scheduler
-
-```bash
-asbs create scheduler metrics_collector
-```
-
-Creates `src/schedulers/metrics_collector_scheduler.py` with default hourly schedule.
-
-#### Custom Cron Schedule
-
-```bash
-asbs create scheduler daily_cleanup --cron "0 2 * * *"
-```
-
-Creates a scheduler that runs daily at 2:00 AM.
-
-#### Scheduler Generated Code
-
-The generated scheduler includes:
-
-```python
-"""Scheduler for cleanup operations."""
-
-import logging
-from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase
-
-logger = logging.getLogger(__name__)
-
-
-class CleanupScheduler(SchedulerBase):
- """Scheduler for cleanup operations."""
-
- def __init__(self) -> None:
- """Initialize the scheduler."""
- super().__init__(crontab="0 2 * * *")
-
- async def on_startup(self) -> None:
- """Initialize the scheduler."""
- # TODO: Get services from registry
- # Example: self._service = self.registry.get_service(CleanupService)
-
- async def on_shutdown(self) -> None:
- """Cleanup when shutting down."""
-
- async def tick(self) -> None:
- """Execute scheduled task."""
- try:
- # TODO: Implement your scheduled task here
- # Example: await self._service.cleanup()
- except Exception as e:
- logger.exception("Error during %s scheduler tick: %s", __name__, e)
- raise
-```
-
----
-
-## asbs validate
-
-Validate the project structure and configuration files. Checks for required directories, valid `settings.toml` entries, correct component registrations, and import consistency.
-
-```bash
-asbs validate
-```
-
-### Checks Performed
-
-- Required project directories exist (`src/`, `tests/`)
-- `settings.toml` contains required configuration keys
-- `secrets.toml` is present and not committed to version control
-- All referenced components can be imported
-- No duplicate component names
-- Port configuration is valid
-
-### Example
-
-```bash
-asbs validate
-```
-
-```
-[OK] Project structure is valid
-[OK] settings.toml configuration is valid
-[OK] secrets.toml is present
-[WARN] secrets.toml is not in .gitignore
-[OK] All components import successfully
-[OK] No duplicate component names detected
-```
-
----
-
-## asbs dev
-
-Run the application in development mode with hot reload enabled. Uses `uvicorn` under the hood.
-
-```bash
-asbs dev [--port ]
-```
-
-### Options
-
-| Flag | Description | Default |
-|------------------|----------------------------------|---------|
-| `--port ` | Port to bind the server to | `8000` |
-
-### Example
-
-```bash
-asbs dev --port 9000
-```
-
-```
-INFO: Blueprint Agents dev server starting...
-INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
-INFO: Started reloader process
-```
-
-The development server watches for file changes in the `src/` directory and automatically restarts when modifications are detected.
-
----
-
-## Auto-Registration Troubleshooting
-
-When `asbs create` commands run, they attempt to automatically register components in `src/main.py`. If this fails, the CLI provides clear guidance on manual registration.
-
-### Common Issues
-
-#### `src/main.py` Not Found
-
-**Error:**
-```
-⚠ Could not auto-register (src/main.py not found or invalid)
-```
-
-**Solution:**
-Ensure your project has the correct structure:
-```
-my_service/
-├── src/
-│ └── main.py
-└── pyproject.toml
-```
-
-Run `asbs setup ` to scaffold a complete project if needed.
-
-#### Invalid main.py Structure
-
-**Error:**
-```
-⚠ Could not auto-register (src/main.py not found or invalid)
-```
-
-**Solution:**
-Verify `src/main.py` contains:
-- Import statements at the top
-- `AppBuilder(config)` instantiation
-- `.build()` call
-
-Example valid structure:
-```python
-from blueprint.agents import AppBuilder, Config
-
-config = Config(...)
-
-app = (
- AppBuilder(config)
- # Components added here
- .build()
-)
-```
-
-### Manual Registration
-
-If auto-registration fails, the CLI displays instructions. Follow this pattern for each component type:
-
-#### Handler
-```python
-# In src/main.py
-
-from src.handlers.order_placed_handler import OrderPlacedHandler
-
-app = (
- AppBuilder(config)
- .with_handler(OrderPlacedHandler())
- .build()
-)
-```
-
-#### Service
-```python
-# In src/main.py
-
-from src.services.invoice_processor_service import InvoiceProcessorService
-
-app = (
- AppBuilder(config)
- .with_service(InvoiceProcessorService())
- .build()
-)
-```
-
-#### API
-```python
-# In src/main.py
-
-from src.models.order_management_models import OrderManagementRequest, OrderManagementResponse
-from src.api.order_management_api import OrderManagementApi
-
-app = (
- AppBuilder(config)
- .with_rest_api(OrderManagementApi())
- .build()
-)
-```
-
-#### Agent
-```python
-# In src/main.py
-
-from src.agents.document_analyzer_agent import build_document_analyzer_agent
-
-document_analyzer_agent: AgentRuntime = build_document_analyzer_agent(config)
-
-app = (
- AppBuilder(config)
- .with_agent(document_analyzer_agent)
- .build()
-)
-```
-
-#### Scheduler
-```python
-# In src/main.py
-
-from src.schedulers.cleanup_scheduler import CleanupScheduler
-
-app = (
- AppBuilder(config)
- .with_scheduler(CleanupScheduler())
- .build()
-)
-```
-
-### Registration Order Matters
-
-Register dependencies **before** dependents in the AppBuilder chain:
-
-1. Services first (contain business logic)
-2. Handlers and APIs next (use services)
-3. Agents last (may use multiple services)
-4. Schedulers last (use services)
-
-```python
-app = (
- AppBuilder(config)
- # 1. Services
- .with_service(OrderService())
- .with_service(PaymentService())
- # 2. Handlers and APIs
- .with_handler(OrderPlacedHandler())
- .with_rest_api(OrderApi())
- # 3. Agents
- .with_agent(analyzer_agent)
- # 4. Schedulers
- .with_scheduler(CleanupScheduler())
- .build()
-)
-```
-
----
-
-## asbs claude
-
-Generate or update Claude Code context files for AI integration. The CLI creates framework and project-specific CLAUDE.md files automatically.
-
-```bash
-asbs claude [create|update]
-```
-
-### Subcommands
-
-| Subcommand | Description |
-|------------|----------------------------------------------------------|
-| `create` | Generate new Claude Code context files |
-| `update` | Update existing Claude Code context files |
-
-### CLAUDE.md Placement
-
-The CLI creates and manages files in a consistent structure:
-
-| Path | Purpose | Updated By |
-|------|---------|-----------|
-| `src/CLAUDE.md` | Framework reference for Blueprint patterns | `asbs claude` |
-| `.claude/agents/` | CLI-generated agent documentation | `asbs create agent` |
-| `.claude/skills/` | CLI-generated skill definitions | `asbs` commands |
-| `CLAUDE.md` (optional) | Project-specific context (root) | User (manual) |
-
-### Framework CLAUDE.md
-
-Running `asbs claude create` generates:
-
-1. **`src/CLAUDE.md`** - Framework documentation containing:
- - Component base classes and imports
- - Critical rules (registry, lifecycle, wiring)
- - Component patterns with examples
- - Registry lookup patterns
- - Configuration structure
- - CLI command reference
-
-2. **`.claude/` directory** - Generated context for Claude Code:
- - Agent documentation in `.claude/agents/`
- - Skill definitions in `.claude/skills/`
- - Automatically updated when components are created
-
-### Example
-
-```bash
-# Generate initial Claude Code context files
-asbs claude create
-
-# Update after adding new components
-asbs claude update
-```
-
-The generated files include information about:
-
-- Project structure and component locations
-- Registered handlers, services, APIs, and agents
-- Configuration settings and environment variables
-- Testing patterns and commands
-- Build and deployment instructions
-
-### Project-Specific CLAUDE.md
-
-You can optionally create a `CLAUDE.md` file in your project root for project-specific context:
-
-```markdown
-# My Service - Blueprint Agents Project
-
-## Overview
-Brief description of this service's purpose and architecture.
-
-## Key Components
-- **OrderService**: Validates and processes orders
-- **OrderHandler**: Responds to order.placed events
-- **OrderApi**: REST endpoints for order management
-
-## Deployment
-Information specific to how this service is deployed.
-
-## Team Guidelines
-Any team-specific development guidelines or patterns.
-```
-
-This user-created file is not updated by `asbs` commands.
diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md
deleted file mode 100644
index 622d3851..00000000
--- a/docs/guides/deployment.md
+++ /dev/null
@@ -1,429 +0,0 @@
-# Deployment Guide
-
-This guide covers packaging, deploying, and operating Blueprint Agents applications in production environments using Docker, Kubernetes, and Helm.
-
----
-
-## Docker
-
-### Dockerfile
-
-Blueprint Agents projects ship with a multi-stage Dockerfile. The following template provides a production-ready build:
-
-```dockerfile
-# Stage 1: Base image
-FROM python:3.13-slim AS base
-
-ENV PYTHONDONTWRITEBYTECODE=1
-ENV PYTHONUNBUFFERED=1
-
-WORKDIR /app
-
-# Stage 2: Builder
-FROM base AS builder
-
-RUN pip install --no-cache-dir uv
-
-COPY pyproject.toml ./
-RUN uv pip install --system --no-cache -r pyproject.toml
-
-COPY src/ ./src/
-
-# Stage 3: Production
-FROM base AS production
-
-COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages
-COPY --from=builder /usr/local/bin /usr/local/bin
-COPY --from=builder /app /app
-
-COPY settings.toml ./
-COPY prompts/ ./prompts/
-
-EXPOSE 8000
-
-HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
- CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/live')"]
-
-CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
-```
-
-### Building and Running
-
-```bash
-# Build the image
-docker build -t my-ai-service:latest .
-
-# Run the container
-docker run -d \
- --name my-ai-service \
- -p 8000:8000 \
- -e DYNACONF_LLM__API_KEY="sk-..." \
- my-ai-service:latest
-```
-
-### Environment Variable Overrides
-
-Blueprint Agents uses Dynaconf for configuration. Any setting in `settings.toml` can be overridden at runtime using environment variables prefixed with `DYNACONF_`:
-
-```bash
-docker run -d \
- -p 8000:8000 \
- -e DYNACONF_APP__PORT=9000 \
- -e DYNACONF_LLM__PROVIDER="openai" \
- -e DYNACONF_LLM__MODEL="gpt-4" \
- -e DYNACONF_LLM__API_KEY="sk-..." \
- -e DYNACONF_CACHE__TTL=3600 \
- my-ai-service:latest
-```
-
-Nested settings use double underscores as separators. For example, `DYNACONF_LLM__API_KEY` maps to `settings.toml` entry:
-
-```toml
-[llm]
-api_key = "sk-..."
-```
-
----
-
-## Kubernetes with Helm
-
-### Helm Chart Structure
-
-```
-helm/
- Chart.yaml
- values.yaml
- templates/
- deployment.yaml
- service.yaml
- configmap.yaml
- hpa.yaml
-```
-
-### values.yaml
-
-```yaml
-replicaCount: 2
-
-image:
- repository: myregistry.azurecr.io/my-ai-service
- tag: "latest"
- pullPolicy: IfNotPresent
-
-service:
- type: ClusterIP
- port: 80
- targetPort: 8000
-
-dapr:
- enabled: true
- appId: "my-ai-service"
- appPort: 8000
- logLevel: "info"
-
-app:
- port: 8000
- logLevel: "info"
-
-resources:
- requests:
- cpu: 250m
- memory: 512Mi
- limits:
- cpu: "1"
- memory: 1Gi
-
-probes:
- liveness:
- path: /health/live
- initialDelaySeconds: 15
- periodSeconds: 20
- timeoutSeconds: 5
- failureThreshold: 3
- readiness:
- path: /health/ready
- initialDelaySeconds: 10
- periodSeconds: 10
- timeoutSeconds: 5
- failureThreshold: 3
-
-autoscaling:
- enabled: false
- minReplicas: 2
- maxReplicas: 10
- targetCPUUtilizationPercentage: 70
-```
-
-### Deployment Template
-
-```yaml
-# templates/deployment.yaml
-apiVersion: apps/v1
-kind: Deployment
-metadata:
- name: {{ .Release.Name }}
- labels:
- app: {{ .Release.Name }}
-spec:
- replicas: {{ .Values.replicaCount }}
- selector:
- matchLabels:
- app: {{ .Release.Name }}
- template:
- metadata:
- labels:
- app: {{ .Release.Name }}
- annotations:
- {{- if .Values.dapr.enabled }}
- dapr.io/enabled: "true"
- dapr.io/app-id: {{ .Values.dapr.appId | quote }}
- dapr.io/app-port: {{ .Values.dapr.appPort | quote }}
- dapr.io/log-level: {{ .Values.dapr.logLevel | quote }}
- {{- end }}
- spec:
- containers:
- - name: {{ .Release.Name }}
- image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
- imagePullPolicy: {{ .Values.image.pullPolicy }}
- ports:
- - containerPort: {{ .Values.app.port }}
- envFrom:
- - configMapRef:
- name: {{ .Release.Name }}-config
- - secretRef:
- name: {{ .Release.Name }}-secrets
- optional: true
- livenessProbe:
- httpGet:
- path: {{ .Values.probes.liveness.path }}
- port: {{ .Values.app.port }}
- initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }}
- periodSeconds: {{ .Values.probes.liveness.periodSeconds }}
- timeoutSeconds: {{ .Values.probes.liveness.timeoutSeconds }}
- failureThreshold: {{ .Values.probes.liveness.failureThreshold }}
- readinessProbe:
- httpGet:
- path: {{ .Values.probes.readiness.path }}
- port: {{ .Values.app.port }}
- initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }}
- periodSeconds: {{ .Values.probes.readiness.periodSeconds }}
- timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }}
- failureThreshold: {{ .Values.probes.readiness.failureThreshold }}
- resources:
- {{- toYaml .Values.resources | nindent 12 }}
-```
-
-### Service Template
-
-```yaml
-# templates/service.yaml
-apiVersion: v1
-kind: Service
-metadata:
- name: {{ .Release.Name }}
-spec:
- type: {{ .Values.service.type }}
- ports:
- - port: {{ .Values.service.port }}
- targetPort: {{ .Values.service.targetPort }}
- protocol: TCP
- selector:
- app: {{ .Release.Name }}
-```
-
-### ConfigMap Template
-
-```yaml
-# templates/configmap.yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: {{ .Release.Name }}-config
-data:
- DYNACONF_APP__PORT: {{ .Values.app.port | quote }}
- DYNACONF_APP__LOG_LEVEL: {{ .Values.app.logLevel | quote }}
-```
-
-### Deploying with Helm
-
-```bash
-# Install the chart
-helm install my-ai-service ./helm \
- --namespace ai-services \
- --create-namespace
-
-# Install with custom values
-helm install my-ai-service ./helm \
- --namespace ai-services \
- --set image.tag="v1.2.3" \
- --set replicaCount=3
-
-# Upgrade an existing release
-helm upgrade my-ai-service ./helm \
- --namespace ai-services \
- --set image.tag="v1.3.0"
-
-# Uninstall
-helm uninstall my-ai-service --namespace ai-services
-```
-
----
-
-## Health Probes
-
-Blueprint Agents provides three built-in health endpoints:
-
-### /health/live
-
-Returns a simple liveness check indicating the application process is running.
-
-```json
-{
- "status": "alive"
-}
-```
-
-Use this for the Kubernetes liveness probe. If this endpoint fails, the container should be restarted.
-
-### /health/ready
-
-Returns a readiness check indicating the application and its dependencies are ready to serve traffic.
-
-```json
-{
- "status": "ready"
-}
-```
-
-Use this for the Kubernetes readiness probe. If this endpoint fails, the pod is removed from the service load balancer until it recovers.
-
-### /health/detailed
-
-Returns component-level health status for debugging and monitoring.
-
-```json
-{
- "status": "healthy",
- "components": {
- "cache": {"status": "healthy", "latency_ms": 2},
- "llm_provider": {"status": "healthy", "latency_ms": 150},
- "event_bus": {"status": "healthy", "latency_ms": 5}
- }
-}
-```
-
-### Kubernetes Probe Configuration
-
-```yaml
-livenessProbe:
- httpGet:
- path: /health/live
- port: 8000
- initialDelaySeconds: 15
- periodSeconds: 20
- timeoutSeconds: 5
- failureThreshold: 3
-
-readinessProbe:
- httpGet:
- path: /health/ready
- port: 8000
- initialDelaySeconds: 10
- periodSeconds: 10
- timeoutSeconds: 5
- failureThreshold: 3
-```
-
----
-
-## Environment Configuration
-
-### Settings via ConfigMap
-
-Non-sensitive configuration values belong in a Kubernetes ConfigMap:
-
-```yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: my-ai-service-config
-data:
- DYNACONF_APP__PORT: "8000"
- DYNACONF_APP__LOG_LEVEL: "info"
- DYNACONF_CACHE__TTL: "3600"
- DYNACONF_LLM__PROVIDER: "openai"
- DYNACONF_LLM__MODEL: "gpt-4"
-```
-
-### Secrets via Kubernetes Secrets
-
-Sensitive values such as API keys and credentials belong in Kubernetes Secrets:
-
-```yaml
-apiVersion: v1
-kind: Secret
-metadata:
- name: my-ai-service-secrets
-type: Opaque
-stringData:
- DYNACONF_LLM__API_KEY: "sk-..."
- DYNACONF_DATABASE__PASSWORD: "secret-password"
-```
-
-### Dynaconf Override Hierarchy
-
-Dynaconf resolves configuration in the following order (later sources override earlier ones):
-
-1. `settings.toml` -- base configuration baked into the image
-2. `secrets.toml` -- local secrets (not used in production)
-3. Environment variables -- ConfigMap and Secret values injected into the pod
-
-This means environment variables always take precedence over file-based configuration.
-
----
-
-## Scaling Considerations
-
-### Horizontal Pod Autoscaling
-
-Enable automatic scaling based on CPU utilization:
-
-```yaml
-# templates/hpa.yaml
-{{- if .Values.autoscaling.enabled }}
-apiVersion: autoscaling/v2
-kind: HorizontalPodAutoscaler
-metadata:
- name: {{ .Release.Name }}
-spec:
- scaleTargetRef:
- apiVersion: apps/v1
- kind: Deployment
- name: {{ .Release.Name }}
- minReplicas: {{ .Values.autoscaling.minReplicas }}
- maxReplicas: {{ .Values.autoscaling.maxReplicas }}
- metrics:
- - type: Resource
- resource:
- name: cpu
- target:
- type: Utilization
- averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
-{{- end }}
-```
-
-### Cache Considerations
-
-When running multiple replicas, be aware of cache behavior:
-
-- **File-based cache**: Uses file-based locking to prevent corruption. If replicas share a volume, locking ensures consistency. If each replica has its own volume, caches are independent and may diverge.
-- **Recommendation**: For multi-replica deployments, prefer an external cache (Redis, Memcached) over file-based caching to ensure consistency across all replicas.
-
-### Stateless Design
-
-Handlers and services should be designed as stateless components:
-
-- Do not store request-specific state in instance variables.
-- Use the cache service for data that must persist across requests.
-- Use the event bus for inter-service communication rather than in-memory shared state.
-- Any initialization that must happen once should be performed in `on_startup()` and should be idempotent.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
deleted file mode 100644
index 71e8f13e..00000000
--- a/docs/guides/troubleshooting.md
+++ /dev/null
@@ -1,568 +0,0 @@
-# Troubleshooting Guide
-
-This guide covers common issues encountered when developing and deploying Blueprint Agents applications, along with their causes and solutions.
-
----
-
-## Installation Issues
-
-### Wrong Python Version
-
-**Symptom:** Installation fails with an error referencing unsupported syntax or incompatible package versions.
-
-```
-ERROR: Package 'avs-blueprint-agents' requires a different Python: 3.10.x not in '>=3.13'
-```
-
-**Cause:** Blueprint Agents requires Python 3.13 or later.
-
-**Solution:** Install the correct Python version and verify it is active:
-
-```bash
-python --version
-# Must be 3.13 or later
-
-# If using pyenv
-pyenv install 3.13.0
-pyenv local 3.13.0
-```
-
-### pip vs uv Installation
-
-**Symptom:** Dependencies fail to resolve or installation is unexpectedly slow.
-
-**Cause:** The standard `pip` resolver may struggle with complex dependency trees.
-
-**Solution:** Use `uv` for faster and more reliable installs:
-
-```bash
-pip install uv
-uv pip install avs-blueprint-agents
-```
-
-### TestPyPI Configuration
-
-**Symptom:** Package not found when installing a pre-release version.
-
-```
-ERROR: Could not find a version that satisfies the requirement avs-blueprint-agents==0.6.0a3
-```
-
-**Cause:** Pre-release versions may be hosted on TestPyPI rather than the main PyPI index.
-
-**Solution:** Configure pip to check TestPyPI as an additional index:
-
-```bash
-pip install avs-blueprint-agents==0.6.0a3 \
- --index-url https://test.pypi.org/simple/ \
- --extra-index-url https://pypi.org/simple/
-```
-
----
-
-## Configuration Errors
-
-### ConfigError on Startup
-
-**Symptom:** Application crashes immediately with a `ConfigError` or `ValidationError`.
-
-```
-blueprint.agents.exceptions.ConfigError: Missing required configuration: 'app.name'
-```
-
-**Cause:** Required settings are missing from `settings.toml` or have not been provided via environment variables.
-
-**Solution:** Verify that `settings.toml` contains all required keys:
-
-```toml
-[app]
-name = "my-ai-service"
-port = 8000
-
-[llm]
-provider = "openai"
-model = "gpt-4"
-```
-
-Check which settings are required by running validation:
-
-```bash
-asbs validate
-```
-
-### Missing Required Settings
-
-**Symptom:** A specific component fails to initialize because a setting it depends on is absent.
-
-**Cause:** The component expects a configuration key that was not provided.
-
-**Solution:** Check the component's documentation or source code for required settings. Use Dynaconf environment variable overrides if you cannot modify `settings.toml`:
-
-```bash
-export DYNACONF_LLM__API_KEY="sk-..."
-export DYNACONF_LLM__PROVIDER="openai"
-```
-
-### Invalid Port Configuration
-
-**Symptom:** Server fails to bind on startup.
-
-```
-[ERROR] Could not bind to port 80: Permission denied
-```
-
-**Cause:** The configured port is privileged (below 1024) or already in use.
-
-**Solution:** Use a non-privileged port in `settings.toml`:
-
-```toml
-[app]
-port = 8000
-```
-
-Or check for port conflicts:
-
-```bash
-lsof -i :8000
-```
-
----
-
-## Event Bus Connectivity
-
-### Dapr Sidecar Not Running
-
-**Symptom:** Application logs show errors when attempting to publish or subscribe to events.
-
-```
-ConnectionRefusedError: Cannot connect to Dapr sidecar at localhost:3500
-```
-
-**Cause:** The Dapr sidecar process is not running alongside the application.
-
-**Solution:**
-
-For local development, start the application via the Dapr CLI:
-
-```bash
-dapr run --app-id my-ai-service --app-port 8000 -- python -m uvicorn src.main:app
-```
-
-In Kubernetes, verify the Dapr annotations are present on the pod:
-
-```yaml
-annotations:
- dapr.io/enabled: "true"
- dapr.io/app-id: "my-ai-service"
- dapr.io/app-port: "8000"
-```
-
-### NATS Connection Refused
-
-**Symptom:** Event bus fails to connect to the NATS server.
-
-```
-nats.errors.ConnectionClosedError: connection refused
-```
-
-**Cause:** The NATS server is not reachable at the configured address.
-
-**Solution:** Verify the NATS server is running and accessible:
-
-```bash
-# Check if NATS is running locally
-nats-server --addr 0.0.0.0 --port 4222
-
-# Test connectivity
-nats sub test.subject
-```
-
-In Kubernetes, verify the NATS service is deployed and the Dapr component configuration points to the correct address.
-
-### Topic Mapping Mismatches
-
-**Symptom:** Events are published but handlers never receive them.
-
-**Cause:** The topic name in the handler's `event_type` does not match the topic used by the publisher.
-
-**Solution:** Verify that the event types match exactly between publisher and subscriber:
-
-```python
-# Publisher
-await event_bus.publish(topic="order.created", data=order_data)
-
-# Handler -- event_type must match exactly
-class OrderHandler(EventHandlerBase):
- event_type = "order.created" # Must match the publish topic
-```
-
-Check the Dapr subscription configuration to ensure topic mappings are correct.
-
----
-
-## LLM Provider Issues
-
-### Missing API Key
-
-**Symptom:** Agent calls fail with an authentication error.
-
-```
-AuthenticationError: No API key provided. Set DYNACONF_LLM__API_KEY or add it to secrets.toml.
-```
-
-**Cause:** The LLM provider API key is not configured.
-
-**Solution:** Set the API key in `secrets.toml` (for local development) or via an environment variable (for production):
-
-```toml
-# secrets.toml (local only -- do not commit)
-[llm]
-api_key = "sk-..."
-```
-
-```bash
-# Environment variable
-export DYNACONF_LLM__API_KEY="sk-..."
-```
-
-### Invalid Model Name
-
-**Symptom:** Agent initialization fails with a model-not-found error.
-
-```
-InvalidRequestError: The model 'gpt-5-turbo' does not exist
-```
-
-**Cause:** The configured model name is not recognized by the LLM provider.
-
-**Solution:** Verify the model name against the provider's documentation:
-
-```toml
-[llm]
-provider = "openai"
-model = "gpt-4" # Use a valid model identifier
-```
-
-### Timeout Errors
-
-**Symptom:** LLM calls fail intermittently with timeout errors.
-
-```
-TimeoutError: Request timed out after 30.0 seconds
-```
-
-**Cause:** The LLM provider is taking longer than the configured timeout to respond. This is common with complex prompts or during high provider load.
-
-**Solution:** Increase the timeout in configuration:
-
-```toml
-[llm]
-timeout = 60 # seconds
-```
-
-Alternatively, consider breaking complex prompts into smaller steps or implementing retry logic in your service.
-
-### Provider Not Supported
-
-**Symptom:** Application raises an error about an unsupported LLM provider.
-
-```
-ValueError: LLM provider 'anthropic_legacy' is not supported
-```
-
-**Cause:** The provider name in configuration does not match any registered provider.
-
-**Solution:** Use a supported provider name:
-
-```toml
-[llm]
-provider = "openai" # OpenAI API
-# provider = "azure" # Azure OpenAI
-# provider = "anthropic" # Anthropic Claude
-```
-
----
-
-## Component Registration Errors
-
-### Duplicate Component Names
-
-**Symptom:** Application fails to start with a duplicate registration error.
-
-```
-RegistrationError: Component 'order_handler' is already registered
-```
-
-**Cause:** Two components share the same `name` attribute.
-
-**Solution:** Ensure every component has a unique `name`:
-
-```python
-class OrderCreatedHandler(EventHandlerBase):
- name = "order_created_handler" # Must be unique
-
-class OrderUpdatedHandler(EventHandlerBase):
- name = "order_updated_handler" # Must be unique
-```
-
-Run validation to detect duplicates:
-
-```bash
-asbs validate
-```
-
-### Missing Dependencies in on_startup
-
-**Symptom:** A service raises a `KeyError` or `None` reference when trying to access another service during startup.
-
-```
-KeyError: 'pricing_engine'
-```
-
-**Cause:** The service is trying to access a dependency from the registry before that dependency has been registered and started.
-
-**Solution:** Access dependencies from the registry only within `on_startup()` or during request handling, not in `__init__()`. The framework calls `on_startup()` after all components are registered:
-
-```python
-class OrderService(ServiceBase):
- name = "order_service"
-
- async def on_startup(self) -> None:
- # Safe -- all components are registered by this point
- self.pricing = self.registry.get_service("pricing_engine")
-```
-
-### Accessing Registry in __init__
-
-**Symptom:** `AttributeError: 'NoneType' object has no attribute 'get_service'` during component construction.
-
-**Cause:** The registry is not available during `__init__()`. It is injected after construction.
-
-**Solution:** Move all registry access to `on_startup()`:
-
-```python
-class MyService(ServiceBase):
- name = "my_service"
-
- def __init__(self):
- # Do NOT access self.registry here -- it is not set yet
- self._client = None
-
- async def on_startup(self) -> None:
- # Registry is available here
- cache = self.registry.get_service("cache")
- self._client = await self._create_client()
-```
-
----
-
-## Health Check Failures
-
-### Client Health Checker Failing
-
-**Symptom:** The `/health/ready` endpoint returns unhealthy status for a specific client or external dependency.
-
-```json
-{
- "status": "unhealthy",
- "components": {
- "llm_provider": {"status": "unhealthy", "error": "Connection refused"}
- }
-}
-```
-
-**Cause:** The external service that the health checker is testing is unreachable.
-
-**Solution:** Verify the external service is running and accessible from the application. Check network policies and firewall rules in Kubernetes. Review the health checker configuration:
-
-```python
-# Verify the health check endpoint is correct
-health_checker = ClientHealthChecker(
- name="llm_provider",
- url="https://api.openai.com/v1/models",
- timeout=5
-)
-```
-
-### Custom Health Checkers
-
-**Symptom:** You need to add a health check for a custom dependency.
-
-**Solution:** Implement a custom health checker and register it with the application:
-
-```python
-from blueprint.agents.health import HealthCheckerBase
-
-
-class DatabaseHealthChecker(HealthCheckerBase):
- name = "database"
-
- async def check(self) -> dict:
- try:
- await self.db.ping()
- return {"status": "healthy"}
- except Exception as e:
- return {"status": "unhealthy", "error": str(e)}
-```
-
----
-
-## Cache Issues
-
-### Permission Errors on Cache Directory
-
-**Symptom:** Cache operations fail with permission errors.
-
-```
-PermissionError: [Errno 13] Permission denied: '/app/.cache/data.db'
-```
-
-**Cause:** The application process does not have write permissions to the cache directory.
-
-**Solution:** In Docker, ensure the cache directory is writable:
-
-```dockerfile
-RUN mkdir -p /app/.cache && chmod 777 /app/.cache
-```
-
-In Kubernetes, use an `emptyDir` volume:
-
-```yaml
-volumes:
- - name: cache-volume
- emptyDir: {}
-volumeMounts:
- - name: cache-volume
- mountPath: /app/.cache
-```
-
-### Disk Full
-
-**Symptom:** Cache writes fail with a disk space error.
-
-```
-OSError: [Errno 28] No space left on device
-```
-
-**Cause:** The cache has grown beyond the available disk space.
-
-**Solution:** Configure a cache size limit in `settings.toml`:
-
-```toml
-[cache]
-max_size_mb = 500
-ttl = 3600 # Entries expire after 1 hour
-```
-
-In Kubernetes, set a size limit on the `emptyDir` volume:
-
-```yaml
-volumes:
- - name: cache-volume
- emptyDir:
- sizeLimit: 1Gi
-```
-
-### Stale Cache
-
-**Symptom:** The application returns outdated data despite changes in the source.
-
-**Cause:** Cached entries have not expired and are being served instead of fresh data.
-
-**Solution:** Reduce the TTL or clear the cache manually:
-
-```toml
-[cache]
-ttl = 300 # 5 minutes
-```
-
-To clear the cache programmatically:
-
-```python
-cache = self.registry.get_service("cache")
-await cache.clear()
-```
-
----
-
-## Testing Issues
-
-### Async Test Setup
-
-**Symptom:** Async tests fail with `RuntimeWarning: coroutine was never awaited` or `PytestUnraisableExceptionWarning`.
-
-**Cause:** pytest is not configured to handle async test functions.
-
-**Solution:** Install `pytest-asyncio` and set the mode to `auto` in `pyproject.toml`:
-
-```bash
-pip install pytest-asyncio
-```
-
-```toml
-[tool.pytest.ini_options]
-asyncio_mode = "auto"
-```
-
-With `asyncio_mode = "auto"`, all async test functions are detected automatically. You do not need the `@pytest.mark.asyncio` decorator.
-
-### Mock Registry Patterns
-
-**Symptom:** Tests fail because the component cannot access services from the registry.
-
-**Cause:** The registry was not mocked or injected into the component under test.
-
-**Solution:** Create a mock registry fixture and assign it to the component:
-
-```python
-import pytest
-from unittest.mock import MagicMock, AsyncMock
-
-
-@pytest.fixture
-def mock_registry():
- registry = MagicMock()
- mock_cache = AsyncMock()
- mock_cache.get = AsyncMock(return_value=None)
- mock_cache.set = AsyncMock()
- registry.get_service = MagicMock(side_effect=lambda name: {
- "cache": mock_cache,
- }.get(name))
- return registry
-
-
-@pytest.fixture
-def my_service(mock_registry):
- from src.services.my_service import MyService
- svc = MyService()
- svc.registry = mock_registry
- return svc
-```
-
-### Missing pytest-asyncio
-
-**Symptom:** Tests are collected but skipped or produce warnings about missing async support.
-
-```
-PytestUnhandledCoroutineWarning: async def functions are not natively supported
-```
-
-**Cause:** The `pytest-asyncio` package is not installed.
-
-**Solution:**
-
-```bash
-pip install pytest-asyncio
-```
-
-Verify it is listed in your test dependencies in `pyproject.toml`:
-
-```toml
-[project.optional-dependencies]
-test = [
- "pytest>=7.0",
- "pytest-asyncio>=0.21",
- "pytest-mock>=3.10",
- "httpx>=0.24",
-]
-```
diff --git a/docs/superpowers/plans/2026-04-01-component-naming-refactor.md b/docs/plans/2026-04-01-component-naming-refactor.md
similarity index 99%
rename from docs/superpowers/plans/2026-04-01-component-naming-refactor.md
rename to docs/plans/2026-04-01-component-naming-refactor.md
index 97c425dd..dadd4c3f 100644
--- a/docs/superpowers/plans/2026-04-01-component-naming-refactor.md
+++ b/docs/plans/2026-04-01-component-naming-refactor.md
@@ -620,4 +620,4 @@ git commit -m "fix: address issues from integration testing"
---
-Plan complete. Ready for subagent-driven execution.
\ No newline at end of file
+Plan complete. Ready for subagent-driven execution.
diff --git a/docs/superpowers/plans/2026-07-06-sessions-agent-registration.md b/docs/plans/2026-07-06-sessions-agent-registration.md
similarity index 99%
rename from docs/superpowers/plans/2026-07-06-sessions-agent-registration.md
rename to docs/plans/2026-07-06-sessions-agent-registration.md
index bdce2225..487cbaf1 100644
--- a/docs/superpowers/plans/2026-07-06-sessions-agent-registration.md
+++ b/docs/plans/2026-07-06-sessions-agent-registration.md
@@ -8,7 +8,7 @@
**Tech Stack:** Python 3.12+, httpx / httpx-sse, pydantic v2, pytest (async), OpenTelemetry. Line length 140. Quality gate: `black`, `ruff`, `mypy`.
-**Spec:** `docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md`. Closes #45 and #44.
+**Spec:** `docs/specs/2026-07-06-sessions-agent-registration-design.md`. Closes #45 and #44.
**Branch:** work on `feature/sessions-agent-registration` (already created). **All commits end with the repo's standard trailer** (`Co-Authored-By: Claude Opus 4.8 (1M context) …` + `Claude-Session: …`) — append it to every commit message; it is omitted from the command examples below only for brevity.
diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md
new file mode 100644
index 00000000..20f142b1
--- /dev/null
+++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md
@@ -0,0 +1,361 @@
+# Change Log -- Multi-Agent Grouping
+
+| | |
+|---|---|
+| **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` |
+| **Implementation plan** | `docs/plans/2026-08-28-multi-agent-grouping.md` |
+| **Follow-up plans** | `docs/plans/2026-09-28-grouped-http-surface.md`, `docs/plans/2026-10-14-named-connections.md` |
+| **Branch** | `feature/multi-agent-namespaces` |
+
+The record of this branch: what each phase decided and what came out of it. It doubles as the
+pull-request description. **The step-by-step history -- every change, its code walkthrough and its
+measurements -- is in `git log` on this branch**; this file was condensed on 2026-10-15 (it had
+grown past 600 KB). User-facing changes and every breaking change are in `CHANGELOG.md` under
+`[Unreleased]`, which is the list to read before upgrading.
+
+---
+
+## What this feature does
+
+One agent used to mean one process, one port, one broker connection and one image, so a platform
+of 100 agents paid the ~154 MB Python baseline 100 times. **Which agents share a process is now a
+deployment parameter, not an architectural commitment.** Components carry an ambient
+**namespace** (`""` by default, so nothing existing changes); a namespace owns its handlers, agent
+runtimes, REST routes, AI client, thread pool, caches and broker connection, while the port and
+the health endpoint stay shared. A group of one gives process isolation, a group of twenty the
+shared-interpreter memory profile, and moving an agent between groups changes neither its
+broker-side consumer identity nor its telemetry identity.
+
+---
+
+## Decisions and outcomes, by phase
+
+**Spec and contracts.** Spec and phased plan extracted into the repo's conventions (`4233933`).
+Acknowledgement contract: a normal return acks, an exception does not, `NO_HANDLER_FOUND` acks
+(`b6ab1c9`). Selection and fan-out rules (spec sec. 7.7) with acceptance criteria (`13e4d28`,
+`b94f60c`).
+
+**P0 -- transport lifecycle.** Managed whole-map `subscribe()`, background retry, resubscription on
+reconnect, readiness gated on `subscriptions_ready` (`77af507`); in-flight handlers drain before
+the connection closes (`585e58c`); an undecodable payload is told apart from a failed dispatch
+(`3843abf`). Dapr declared topics actually subscribe (#81, `fac528b`).
+
+**P1 -- queue groups.** Core NATS subscriptions join a queue group derived from the agent, so a
+second replica no longer processes every message again (`05083c8`).
+
+**P2 -- acknowledgement.** Both transports render one decision table (ack / nak / term); Dapr's
+`NO_HANDLER_FOUND` answers `SUCCESS`, a critical error drops (`ce17f87`). Unmatched events are
+counted (`blueprint.events.unhandled`).
+
+**P3 -- consumers.** `ack_wait`, `max_ack_pending`, `max_deliver` configurable and broker-enforced;
+JetStream durables carry a deliver group; given-up messages are dead-lettered to
+`.dead-letter` (`8ce9600`). Three stream/durable naming defects fixed on the way.
+
+**P4 -- deduplication.** Opt-in (`idempotency_enabled` + required `idempotency_ttl`), keyed on event
+id and source, released on a failed dispatch; the scaffold and `asbs validate` make the author
+decide; duplicates are counted apart (`d127843`).
+
+**P5 -- scheduling.** `scheduler_mode` is **required** (breaking): `"event"` takes the tick as an
+event (the queue group picks one replica), `"in_process"` claims each tick in the cache
+(`CacheService.claim`, atomic on both backends) so one replica runs it. Second-timer defect (#43)
+and two scaffold defects fixed; publishing no longer requires consuming
+(`event_publishing_enabled`) (`662f7b5`).
+
+**P6 -- one transport per namespace.** Clients belong to a namespace, register under a qualified
+name and derive queue group and durable from it; connections are named
+`namespace.group.pod` (never used broker-side, C1); one alphabet and one gate for namespace names
+(`be5e489`). `/status/env` stopped returning credentials (#91).
+
+**Config rework.** Logging leaves `Config`; one loaded tree with one view per namespace (C5); the
+loader is unreachable from agent code; the env-var prefix is the project's; `/status/env` answers
+per agent.
+
+**Phases 0-7.** The namespace is ambient (`run_app`, one declaration applied alone or per agent);
+the registry resolves namespace-then-root without a fallback across agents; caches are looked up
+by name and namespace-scoped; one thread pool per agent, lazily; dispatch per agent with
+`get_handled_event_types()` as a selection hint; transport endpoints subscribe per agent; `build()`
+wires a transport per agent; an agent's HTTP surface lives under `/api/`; grouped Dapr is
+routed and fanned out in-process; a handler can name its runtime, and an ambiguous name fails at
+startup.
+
+**Phase 8 / 8b -- the group runs.** `AppBuilder` only records and `build()` is the only thing that
+builds; `AgentBuilder` records too and builds against its own agent's configuration; `AgentGroup`
+turns named declarations into one application; four declaration surfaces became one; a cache is
+private to its agent; health checks carry their agent; an agent's own settings file is its scope;
+`AGENTS.md` written and its design rules guarded by `test_design_rules.py`.
+
+**Phase 9 -- identity and failure survive grouping.** Per-agent telemetry resource and meter, a
+degraded agent drives `blueprint.namespace.up = 0` and an attributed ERROR, consumption pauses
+(not closes), a latched agent recovers by retry, blocked-loop watchdog.
+
+**Phase 10 -- setup and migration.** A scaffolded project is a group of one in every environment;
+`asbs validate` reports what a project has not decided; migration and deployment guides rewritten
+against what ships; scaffolded settings/secrets are the ones the framework reads.
+
+**Isolation.** The four routes by which an agent could reach a neighbour's data are closed: no root
+fallback into another agent, a view names only its own agent or the root, one declaration never
+hands two agents the same object, dotted keys stay inside their agent.
+
+**Review findings and hardening.** Publishing is declared (`nats_publish_mode`,
+`nats_publish_subjects`); `nats_url` no longer defaults to localhost outside development; NATS
+credentials supported and URL credentials redacted; handlers see `nats_subject`; a failed result
+publish fails the delivery (#1); the declared transport mode is enforced (#4); dedup claims
+atomically (#6); structured output and deps types reach the agent (#2); one `AgentBuilder` serves
+several agents (#10); REST payloads no longer logged (#12, #13); the sessions replay guard is
+bounded (#14); a standalone agent's v0.8.1 output restored; a Dapr sidecar mock for demos.
+
+**Grouped HTTP surface** (`2026-09-28-grouped-http-surface.md`). Reserved path segments for
+framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a developer
+`path_prefix`; standalone paths and tags never change.
+
+**Concurrency and named connections** (`2026-10-14-named-connections.md`, D1-D11).
+- Deliveries run concurrently (`nats_max_concurrent_runs` per agent and connection,
+ `nats_extra_runs_per_process` as a process pool), long runs send `in_progress` heartbeats
+ (`nats_heartbeat_enabled`), a run can be bounded (`nats_handler_timeout`, cancel + nak).
+- A `ConnectionSource` (`nats_connection_source`) supplies named connections: bindings with a
+ subject prefix onto the deployment's consumers, `validate` before a run, `run_scope` around it,
+ `claims` keep claimed subjects off the default connection (`nats_unclaimed_subjects`), runtime
+ changes through `watch(notify)`, readiness per connection (`nats_connections_readiness`).
+- A closed connection reconnects and resubscribes; reconnects are unlimited by default.
+- `HandlerResult.skipped(reason)` (D11): responsible but nothing to do -- chain stops, acked, INFO,
+ `blueprint.events.skipped`, `ProcessingStatus.SKIPPED`. An event no handler takes keeps its
+ WARNING (spec sec. 7.2 amended to match).
+- `nats_delivery_attempt` / `nats_max_deliver` in the handler context for JetStream deliveries.
+- Step 6: docs, scaffold, skills and examples agree with the code (inventory:
+ `docs/plans/2026-10-15-named-connections-step6-inventory.md`); `asbs validate` checks the NATS
+ keys; `examples/site_readings` shows two named connections end to end.
+
+**PR #96 review fixes** (`2026-10-16-pr96-review-fixes.md`).
+- Step 1, dedup bracket (B1, M11): a delivery keeps its dedup marker only when it is acknowledged.
+ The chain releases on any `BaseException` from dispatch (a handler timeout or shutdown is a
+ `CancelledError`); `EventProcessingService.process_event` releases in a `finally` unless the result
+ was settled and no cancellation is pending (a handler that swallowed it). Only the delivery that
+ won the claim releases (`CLAIMED_CONTEXT_KEY`), so a duplicate never drops the first delivery's
+ marker. Measured on JetStream (`nats_handler_timeout = 0.5`, disk cache): timeout, swallowed
+ cancellation and a scalar return each lost the event before (redelivery skipped and acked), and
+ run to completion on redelivery now; a real duplicate is still skipped.
+- Step 2, leaks in logs and responses (B2, S8, S4, N3): `describe_validation_errors` (`models/errors.py`)
+ renders a validation failure as `loc: type` only, used by the Dapr and NATS unparseable-payload lines
+ and the inner Dapr event's errors (no longer logged where raised, raised `from None`); a Dapr reason
+ is a `HandlerError`'s or the exception's type name; `_Link` hides `url` and `connect_options` from
+ `repr`; the default and named connection lines go through `_describe_error`. Measured with a
+ placeholder secret (JetStream, Dapr endpoint with the sidecar mock): in the logs and the answer
+ before, in neither now. A handler's own exception text is still logged as it is, by design.
+- Step 1a, connection isolation (T1): the dedup key adds `nats_connection` for a delivery from a named
+ connection (the default connection keeps `(source, id)`, no migration); handler-author docs say that
+ per-data-source state is keyed by that context key. Broker test on the accounts broker: the same
+ `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B
+ was skipped.
+- Final run with containers (2026-10-19): unit 3781 tests, 0 failed, 1 skipped; integration (JetStream,
+ accounts broker, Redis in WSL) 66 of 67 -- the one failure is the pre-existing
+ `test_the_broker_counts_it_as_a_redelivery`, which fails on the committed HEAD too. Two findings on the way,
+ both fixed: N14, M4's refusal check raced because nats-py 2.15 writes PING ahead of a pending SUB --
+ `_bind` now makes two round trips (8 of 8 runs green; before 3 of 9 failed); and step 20 published the
+ stand-in name 'ungrouped' of a group nothing named, so telemetry would have carried
+ `deployment.group = ungrouped` -- `group_config.DEFAULT_GROUP_NAME` is not published. The group image,
+ scaffolded fresh (`asbs setup --group`, two agents, `asbs validate --group` valid) and built from the
+ working tree, turned healthy under `BLUEPRINT_AGENTS` ('') and under a one-group file ('finance').
+- Step 21, docs and PR hygiene (W7, W8/D19, W9, D20): the isolation tests' xfail paragraph in the past tense;
+ `[0.9.0] - 2026-09-14` folded into `[Unreleased]`, one section per heading; `pyproject.toml` back to `0.8.2`
+ with no licence fields, `LICENSE` and its CHANGELOG entry removed (D20: no approval yet); a "Rolling back
+ to 0.8" section (durables, cache keys, grouped REST paths, metric labels). PR description drafted, not
+ posted.
+- Step 20, smaller items (S19, S23/D16, W2, W3/D7): `deployment.publish_deployment_group` from
+ `AgentGroup.resolve`, read first by `deployment_group()`; the in-process tick slot is the trigger's latest
+ fire time at or before now (`_arm_trigger`, `_tick_slot`); `diskcache-rs>=0.4.10`; the disk claim documented
+ as per-process (docstring, `handler_chain`, deployment guide, configuration keys); W3 documented on
+ `Component.registry` and in the grouping guide. Live (WSL): the group image with a one-group file and no
+ `BLUEPRINT_GROUP` exported `deployment.group = finance` for 'agent-group', 'orders' and 'billing' (control:
+ absent, supervisor lines said ''). Cross-process claim, 4 processes x 300 rounds on one
+ directory: several winners in 297 rounds through `DiskCacheService.claim` and through raw `Cache.add`, no
+ error; 0.4.9 refused the second process ('Database already open'). Found N13, open as D22.
+- Step 19, standalone compatibility (S10, S20, S21, N1): `HealthCheckEntry.builtin` and an application check
+ replacing a built-in one with a WARNING; `Registry.reorder` puts declared handlers in declaration order (the
+ refusal is gone); `SessionsJobHandler.get_handled_event_types` declares nothing when `can_handle_event` is
+ overridden; `event_loop_debug` off unless set, read with `parse_bool`; recovery tasks gathered with
+ `return_exceptions=True`, `actuator.on_shutdown` guarded; CHANGELOG "What the code sees change" for deferred
+ construction. Live (standalone app, Core NATS in WSL, `with_handler(First)` then `with_handler(Second())`,
+ `with_health_checker("cache", ...)`): both handlers ran First then Second, `/health/ready` showed the own
+ check under 'cache' with the WARNING, debug mode off and the watchdog started. Control: build refused the
+ handler order, then the 'cache' name; with both fixed away, debug mode was on.
+- Step 18, NATS leftovers (S1, W4, W5, N10): `_ensure_consumer` raises `JetStreamBindingError` for an existing
+ durable whose filter is not the topic (no rename); the run slot and in-flight count are given back when the
+ run cannot be started; `_durable_for` docstring corrected (dotted topics get a name 0.8 did not use); the
+ consumer INFO line renders an unset `ack_wait` as `server default`. Live (JetStream 2.10 in WSL): a consumer
+ 'orders-created-durable' filtering 'created' was refused for root topic 'orders-created', and a message on
+ 'created' did not reach its handler; the INFO line was logged. Control: bound, the 'created' message reached
+ the 'orders-created' handler, the INFO line was lost to `TypeError: must be real number, not NoneType`.
+ Found N12 (readiness UP while the agent is paused by its own failing subscription), left open as D21.
+- Step 17, telemetry (S22, W1, D17): `_SharedSpanProcessor` and `_SharedMetricExporter` count their
+ providers and are closed by the last; providers built with `shutdown_on_exit=False`;
+ `providers.shutdown_providers()` (agents first, root last) from `TelemetryManager.on_shutdown` at the
+ end of the lifespan and once from atexit; in a group an agent keeps `service.name` although
+ `OTEL_SERVICE_NAME` is set, with one WARNING. Live (group 'orders' + 'billing', OTLP collector with a
+ file exporter, OTEL_SERVICE_NAME set, a span and a counter in each handler's on_startup and
+ on_shutdown): 4 of 4 metric points and 4 spans under 'orders'/'billing'. Control: everything under
+ 'platform-wide', 2 of 4 metric points, four 'Exporter already shutdown' warnings.
+- Step 16, Dapr hardening (S5, S9, N5, D6): a deep copy of the CloudEvent per agent when a delivery fans
+ out to more than one; a startup WARNING for a shared topic with an agent's `idempotency_enabled` off;
+ `EventHandlingBase._metric_topic` hook, Dapr labels an undeclared topic ``; an ACK combined
+ with a TERM answers SUCCESS without a reason; `DaprDeliveryRoute` wraps only `/events/{topic}`. Live (a
+ group served by uvicorn, Dapr sidecar mock, agents 'orders' and 'billing' on 'orders.created'):
+ 'billing' read `{"order": 1}` after 'orders' changed it, the answer was `{"status": "SUCCESS"}`, 5
+ random topics gave one `` series per agent, the WARNING named both agents. Control: no
+ WARNING, reason attached, 'billing' saw the change, one series per random topic.
+- Step 15, dedup without a heartbeat and Redis calls (S6, S7, D4): `HandlerChain._claim`/`release` and the
+ scheduler's `_claim_tick_slot` run the cache call in `asyncio.to_thread`; a startup WARNING for dedup with
+ the NATS heartbeat off and for dedup under Dapr; `cache.redis_socket_timeout` (opt-in); redis-py floor
+ raised to 8.0 (its 5 s default timeout; 7.x had none). Live (Redis 7 in WSL, container paused, timeout 2 s):
+ longest event-loop gap 0.06 s and the claim failed open after 2.01 s; control: the loop stood for 2.02 s.
+- Step 14, scaffold and CLI (M10, S14, N6-N9, D10): `DYNACONF_APP_ENVIRONMENT` in both Dockerfiles
+ (production, development in the dev stage), a Python health check in `group_Dockerfile`, `asbs setup`
+ validates the name before writing, the `settings.txt` comment no longer carries the substituted token,
+ `asbs create service` imports what it names, `AgentRuntime` only where agents are used, the scheduler
+ template no longer claims a generated CronJob, and every `asbs dev` message says that without `--name`
+ the agent is served alone at the root. Live (WSL): a scaffolded two-agent group image built from the
+ working tree turned healthy in 10 s and loaded `production`; control with the old template: `curl: not
+ found`, never healthy, `development`. In the same image: `BLUEPRINT_CRITICAL_AGENTS=ordrs` exits 1
+ naming the typo (step 7), and a `.secrets.toml` mounted for `orders` reaches `orders` only (step 8).
+- Step 13, `/status/env` masker (M12): URL userinfo fails closed (an `@` left after `://`, an
+ unparseable port), secret query parameters and `Name=value;` segments are masked, a section under a
+ secret key is masked whole, `pass`/`dsn`/`conn`/`sig`/`signature` count as whole words. Live (a built
+ app under uvicorn, `GET /status/env`): 200 and no placeholder in the body; control: 500 with
+ `${PORT}`, and without it seven placeholders returned.
+- Step 12, Redis cache isolation (M6): the default store's `clear`, `list_namespaces` and `list_values`
+ take only keys of its own form (`::`); a clear without `key_prefix` warns;
+ no key-layout change. Live (Redis 7 in WSL, stores from `CacheBackendFactory` for root, `orders`,
+ `billing`): after a root clear both agents' keys and a foreign key remain, with prefix and without;
+ control: all agent keys gone, and without a prefix the whole database. The Redis integration tests
+ (`BLUEPRINT_TEST_REDIS_URL`) ran for the first time on this branch: 3 passed.
+- Step 11, scheduler robustness (S24-S27, D14, D15): `_started` is set only after the timer or the event
+ wiring stands; one tick-age gauge per meter reports every scheduler of it (weak registry); `validate_crontab`
+ runs in both modes, refuses day `7` and, in event mode, any numeric weekday; opt-in `scheduler_timezone`;
+ `asbs validate` and `--group` use the runtime's mode and transport checks and count environment
+ overrides. Live (real APScheduler timer, every-minute crontab, UTC, two schedulers): both ticked at the
+ next minute and the gauge reported both; control: one gauge point.
+- Step 10, grouped scheduler (M8, M9): the tick handler is built under `namespace_scope(self.namespace)`;
+ tick subject, trigger route and handler name use `base_name`; docs agree. Live (Core NATS, a group
+ with agent `orders`, scheduler `nightly`, event mode): subscribed `orders.scheduler.nightly`, handler
+ in `orders`, one tick from that subject and none from the doubled one, `POST
+ /api/orders/scheduler/nightly/trigger` 200 and ticks. Control: subscribed the doubled subject, handler
+ at the root, the documented route 404.
+- Step 9, registry and sharing guards (S15, S16, S17, W6, D11): the qualified hit in `_lookup` must
+ belong to the asking namespace; `clear`, `clear_components`, `shutdown_executors` are refused on a view,
+ `add_component`/`update_component_name` only for the view's own components, `get_or_create_executor`
+ only for its own namespace or the root; `is_shareable` looks into a bound method's `__self__` and a
+ closure's cells, and a shared declaration's factory target is checked too. W6 documented as allowed.
+- Step 8, agent settings merge (M5, S11, S12, S13, D9): an agent's `.secrets.toml` is merged before its
+ settings (`AgentGroup.secrets`, `merge_agent_settings(..., secret=True)` logs no value); fragments are
+ layered for `current_env` and inactive environment sections are dropped; `cache`, `event_publishing`,
+ `runtimes`, `runtime` are reserved namespaces and a root scalar is never replaced; a view refuses a bare
+ key naming an agent's section (`Config.declare_agent`). Repro of S13 first (ENV_FOR_DYNACONF=production:
+ root `prod`, fragment `frag-dev`); unit tests fail on the old code; live with the group image (step 14).
+- Step 7, group config validation (M7, N2, D8): unknown critical names (also against a
+ `BLUEPRINT_AGENTS`-replaced list), scalar `agents`/`critical_agents` and duplicate group names raise
+ `GroupConfigError`; `AgentGroup.from_config` refuses a group left with no agent. Unit tests fail on the
+ old code; the live check runs with the group image (step 14).
+- Step 6, named bindings (M3, M4, S2, S3): a binding superseded before it bound is retired at once and
+ hands over the binding still delivering, and a removal retires that one too; `_bind` flushes and fails
+ on a refusal naming its deliver subject (compared lowercased -- nats-py lowercases the -ERR line, found
+ live); a reconnect restores readiness only for `bound` bindings; binding mode answers flow control and
+ drops heartbeats; `ConnectionSpec.tls` is not compared. Accounts broker: change-change and change-remove
+ close the original link (control: open after 15 s), a refused deliver subject reads `retrying` with a
+ permission violation (control: `bound`), an operator consumer with heartbeat and flow control delivers
+ 20 of 20 once with no termination (control: status messages termed). Integration suite 64 passed,
+ 3 skipped (Redis).
+- Step 5, resume retry and C4 for sessions (M2, S18): a failed `resume_consumption` drops the partial
+ subscriptions, stays paused and retries in a backoff task (cancelled by a pause and by close), a
+ WARNING per attempt; `SessionsBus` gains `pause_consumption`/`resume_consumption` (stream closed,
+ a job reaching it left pending) and the supervisor pauses it with the IO clients. Live (JetStream,
+ health interval 2 s, a switchable check): the agent paused, its stream replaced by one blocking its
+ subjects, then healthy -- attempts 1-3 failed (1, 2, 4 s apart), resumed 7 s after the blocker was
+ removed, 5 of 5 events run. Control: one failed resume, still paused 36 s later. Sessions: unit
+ tests only, no sessions service to run against.
+- Step 4, JetStream reconnect (M1, N4, N11): `_on_reconnected` re-checks stream and consumers
+ (`_ensure_broker_state`) instead of subscribing again; the message handler naks a JetStream delivery
+ while paused; the first `nats.connect()` is bounded (`_first_connect_attempts`) and the configured
+ count is set on the connection afterwards; a connect while paused requests a health refresh. Live
+ (NATS 2.10, `/connz?subs=1`): broker restart -- 2 subscriptions before and after (control: 4), each of
+ 20 events run once; restart then pause -- 0 of 10 events run (control: 10); broker without storage
+ replaced -- stream and consumers recreated, 20 of 20 run once; no broker at startup -- startup
+ returns in 5.6 s and the agent consumes after the broker comes up (control: no return within 120 s).
+ Integration suite: 60 passed, 3 skipped (Redis not started).
+- Step 3, internal naming (B3): the first consumer's product name, subject prefix and module names are
+ replaced by generic ones (`acme.agent..`, "the first consumer") in the named-connections
+ plan, the accounts broker config, its connection source and three unit tests. Tree only; the
+ published history keeps them (D1). The named-connection broker tests pass with the new subjects.
+- Step 3, history (D1 revised 2026-10-21): the names are gone from the history as well -- the first
+ consumer's names on this branch, and two other projects' names that came in from `main` (the
+ job-scoped session-key spec and the release changelog). `git filter-repo` replaced them in file
+ contents and eight commit messages of `main`, `develop` and this branch from 2026-08-24 on, so each
+ of those commits has a new SHA and the release tags `v0.7.0` to `v0.9.0a17` moved with them. Author,
+ dates and the files each commit touches are unchanged. The plans' references to rewritten commits
+ name the new SHAs; older versions of those files keep the old ones. A review for project names before
+ every commit (a `CLAUDE.md` rule and a Claude Code hook) goes to `develop` in a pull request of its own.
+- Guards from `develop` (#108, merged into this branch): the commit review hook, the push guard against
+ the replaced history and the CI job "No replaced history". Tried live here, the push guard let an
+ old-history branch through whenever the command named the repository in double quotes
+ (`cd "C:/..." && git push`, `git -C "..." push`) or as `cd ` followed by a line break: the
+ extracted path kept the JSON-escaped quote or the `\n`, did not resolve, and an unresolved path is
+ let through. A quoted `-C` path with a space was not even recognised as a push. Fixed in
+ `.claude/hooks/replaced-history-guard.sh` (a quoted path is taken whole, then unquoted; a line break
+ ends a bare one), with regression tests in `tests/unit/hooks/` that now run in CI. Control, 18 ways to
+ name the repository: the old hook refused 5, the fixed one 18; live with `--dry-run`, the three shapes
+ that got through are refused and a clean branch still goes through.
+- Re-review of 2026-10-21, before the merge into `develop`: `CHANGELOG.md`'s Breaking items run 18-21
+ in order again (19 had landed after 21), and the standalone upgrade notes name `nats_nak_delay`,
+ which changes redelivery timing for a standalone agent too.
+
+**Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an
+accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs,
+heartbeat, run timeout, reconnect with resubscription, named connections without permission
+violations, skipped results, delivery attempts.
+
+---
+
+## Compatibility
+
+Every breaking change, with its migration, is listed in `CHANGELOG.md` under
+`[Unreleased]` -> *Breaking*. The two that most often bite:
+
+- **`scheduler_mode` is required** for a project with a scheduler; startup fails naming both values.
+ A deliberate departure from spec sec. 7.5 (defaulting would either keep a timer per replica, #73,
+ or stop ticking a service without a broker).
+- **A scoped `Config`'s telemetry `service.name` is the agent's name** unless
+ `.otel_service_name` is set.
+
+`tests/unit/agents/test_frozen_compatibility.py` holds what existing projects do; it is never edited
+to accommodate an API change.
+
+---
+
+## Open points
+
+Still open (the closed ones, and their history, are in `git log`):
+
+- **Pre-existing integration failure:** `test_acknowledgement_lifecycle.py::TestARetryableFailureComesBack::test_the_broker_counts_it_as_a_redelivery`
+ fails on the unchanged code too: the retryable failure is nak'd at once, so all `max_deliver`
+ attempts are spent before the test reads `num_redelivered`. The test's premise needs revisiting.
+- **Broker-test gap -- overlapping subjects in one queue group:** a wildcard plus a literal it covers
+ on one client is expected to be merged by the server into one delivery; not yet verified against
+ a real broker (referenced from `NATSClient`'s docstring).
+- **`test_three_replicas_run_one_tick` was flaky once** (2026-09-24); likely the disk cache's
+ non-atomic takeover of an expired claim. Not investigated.
+- **Spec amendments owed:** C4 (a degraded transport is paused, not closed), C2 (the metric reader
+ cannot be shared across providers), the root's role under `readiness_policy`, phase 7's ambiguity
+ is a WARNING rather than an error. `readiness_policy = "any"` has no acceptance criterion.
+- **The tick subject `.scheduler.` is provisional** (subject taxonomy unratified,
+ spec sec. 13).
+- **Dedup and tick claims are unbounded on disk** (logical expiry only); the dedup TTL is delegated
+ to the deployment (guidance: `nats_ack_wait * nats_max_deliver`).
+- **The dead-letter subject has no consumer;** draining it is an operational task.
+- **`get_stats()["size"]` double-counts** the disk backend's TTL entries.
+- **Spec sec. 13's shape questions** (20 or 100 agents; whether the 4 GB host budget is real).
+- **Group-file diagnostics:** the "no agents resolved" message omits the sole-group route, and a
+ `BLUEPRINT_GROUP_CONFIG` pointing at a directory is reported as nothing mounted.
+
+Closed since they were listed, for readers following older references: the four isolation routes
+(see `tests/unit/agents/test_agent_isolation.py`), the broker integration tests
+(`docs/plans/2026-09-11-broker-integration-tests.md`, #80), the latch that never released, the
+scaffold's settings and secrets files, the Windows console crash, the examples' migration, and the
+missing `LICENSE`.
diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md
new file mode 100644
index 00000000..c90415f2
--- /dev/null
+++ b/docs/plans/2026-08-28-multi-agent-grouping.md
@@ -0,0 +1,1413 @@
+# Plan -- Multi-Agent Grouping
+
+| | |
+|---|---|
+| **Status** | **Complete.** P0-P6, phases 0-10 landed on `feature/multi-agent-namespaces`. No PR opened yet; the changelog is its description. |
+| **Amendment** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10. Phase 8b below is its work breakdown; phases 0 and 3 are superseded by it. Step 9 was added on 2026-09-10 and is not in that proposal's original breakdown. |
+| **Deferred out** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature and **must not** be touched during 8b. |
+| **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` |
+| **What landed, and why** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` -- read before resuming |
+
+This is the phased work breakdown. The spec is normative: it carries the MUST/SHOULD requirements,
+the API surface, the config reference and the acceptance criteria, and where the two documents
+disagree the spec wins.
+
+**Issues:** resolves #75; unblocks #32, #35, #20; #73 is P5 below. Related: #33, #34, #36, #43, #74.
+
+**Deployment model:** the namespace model below is implemented in full, but *which* agents share a
+process is not hardcoded — it is selected at runtime from a group configuration
+(`BLUEPRINT_GROUP` env var), and Kubernetes runs one Deployment per group. Group size 1 gives
+per-agent process isolation; group size 20 gives the shared-process memory profile. Nothing in
+Phases 0-7 changes because of this; Phases 8-9 add the loader and the deployment-facing
+constraints.
+
+The spec (sec. 3) defines seven invariants (C1-C7) that this plan must satisfy. They are
+referenced by number in the phases below. C1-C6 keep regrouping invisible from outside the process; C7 (no
+silent failure at agent granularity) keeps the isolation cost grouping *does* incur attributable,
+and is therefore what makes the group-size dial usable in response to a real failure.
+
+## Goals
+
+- One app, one port, one health endpoint, one NATS/Dapr connection — shared infrastructure
+ is never duplicated.
+- Components gain an optional **namespace** (`""` by default). Empty namespace = today's
+ single-agent world. Zero migration required for existing projects.
+- **Opt-in multi-agent capability per agent.** A developer who wants their agent to
+ participate in a multi-agent system makes exactly two changes: `main.py` and `Dockerfile`.
+ Developers who do not opt in keep their current code and deployment unchanged.
+- **Multiple named `CacheService` instances** can be registered independently, looked up
+ by name from any namespace, and added at runtime after startup.
+- Every phase is independently shippable and backwards compatible.
+- **Per-namespace I/O isolation.** Each namespace gets its own `ThreadPoolExecutor`
+ (for blocking `DiskCacheService`/SQLite calls via `run_in_executor`) and its own
+ `AIClientBase` instance (separate async HTTP connection pool), so one agent's I/O
+ load cannot stall another's.
+- **Grouping is a deployment parameter, not an architectural commitment.** Regrouping an agent
+ must never change its broker-side consumer identity (C1) or its telemetry identity (C2).
+ If a change makes regrouping observable to the broker or to a dashboard, it is wrong.
+
+---
+
+## Prerequisites (blocking defects in the current code)
+
+These are independent of the namespace work and would need fixing under any option. **They block
+scaling any group past one replica** and must land before the multi-agent phases ship.
+
+**P0 — Transport lifecycle: managed subscription, retry, reconnect, readiness.** Lands as part
+of this work, ahead of everything else in this list, because the rest of it sits on top:
+
+- `ClientBase.subscribe(topic_callbacks)` replaces `subscribe(topic, callback)` — one call
+ carrying the whole `{topic: callback}` map, non-blocking, backed by a background retry task.
+ P6's per-namespace clients need exactly this shape.
+- `subscriptions_ready` plus health-check gating. C4 and C7 read it, and Phase 9 drives
+ `blueprint_namespace_up` from it.
+- `disconnected_cb` / `reconnected_cb`, re-subscribing JetStream durables on reconnect. P2's
+ correctness depends on this path: the server redelivers everything unacked after a reconnect.
+- Config keys `event_client_max_retries` (default `-1`, indefinite) and `event_client_retry_delay`
+ (default `5.0`).
+
+Three gaps to close while landing it, none of which the original PR addressed:
+
+- ~~**No shutdown drain.**~~ **Done.** `close()` now drains subscriptions, waits for in-flight
+ handlers, and only then closes the connection, bounded by `event_client_drain_timeout`
+ (default 30 s). The order matters: an acknowledgement travels over the delivering connection, so
+ closing first stranded it and made duplicates certain on every deploy.
+- **Partly done: the `except Exception` swallow in `message_handler`.** The boundary now
+ separates an undecodable payload from a failed dispatch, logs each once with the topic and
+ event id, and keeps the two failures distinguishable for the dispositions P2 assigns them
+ (term vs nak). It still *catches* both, because a broker callback must not raise into the
+ library and because nothing yet decides what to do with a failure. Remaining, and listed
+ under P2: stop `_process_event` in `io/api/eventing/nats.py` swallowing the classified
+ handler errors, and stop `_process_cloud_event` logging *and* re-raising them, so the
+ transport boundary becomes the single place that both sees and handles failure.
+- ~~**`DaprEventing` registers a callback map that Dapr delivery does not use.**~~ **Done**, and it
+ turned out to hide a live bug (issue #81): the discovery endpoint the sidecar fetches took a
+ required `topic` query parameter, so `GET /dapr/subscribe` answered 422 and no handler
+ declaration ever reached Dapr. The endpoint now renders `get_subscribed_topics()` as the
+ sidecar's subscription document, so one declaration drives both transports. The callback map is
+ kept deliberately — it is what starts the client's sidecar-reachability retry and feeds
+ `subscriptions_ready`, and removing it would silently disable readiness gating.
+
+**P1 — Core NATS subscriptions have no queue group.** `clients/io/nats_client.py:250` calls
+`client.subscribe(topic, cb=...)` with no `queue=`. JetStream is off by default
+(`nats_use_jetstream`, `nats_client.py:102`), so the default path today is: *every replica
+processes every message*. Setting `replicas: 2` silently doubles every side effect and every
+inference bill. Fix: `queue=` — derived from the namespace, never from the group or
+container (C1).
+
+**P2 — JetStream messages are never acknowledged.** `clients/io/nats_client.py:242-247`
+subscribes with `manual_ack=True`, and there is no `msg.ack()` call anywhere in the codebase.
+Every message redelivers after `ack_wait` until `max_deliver`. This is already a defect at one
+replica — each event is processed repeatedly — and at N replicas it presents as a scaling
+problem but is not one.
+
+The contract is normative in spec sec. 7.2: **a normal return acks, a raised exception does not.**
+`ProcessingStatus` has exactly two values, `PROCESSED` and `NO_HANDLER_FOUND`, so no failure can
+reach the transport as a returned value. That is why the transport edge never inspects
+`ProcessingResult` — it would learn nothing — and why an event that matches no handler's
+conditions acks like any other completed dispatch instead of being redelivered until
+`max_deliver`.
+
+What blocks this today is not the missing `msg.ack()` call but two layers that discard the
+classification before it can reach one:
+
+| Layer | Behaviour |
+|---|---|
+| `_process_cloud_event` (`io/api/eventing/event_handling_base.py`) | logs and **re-raises** — correct, keep |
+| `_process_event` (`io/api/eventing/nats.py`) | catches `RetryableHandlerError`, `InvalidEventError`, `CriticalHandlerError`, logs, returns `None` |
+| `message_handler` (`clients/io/nats_client.py`) | catches `Exception`, logs, returns |
+
+Work items:
+
+- Remove the `except` block from `_process_event` so classified exceptions reach the transport.
+- In `message_handler`, ack on normal return and map exception type to `nak()` / `term()` per the
+ spec table. Distinguish *before* dispatch from *during* dispatch: a payload that fails JSON or
+ CloudEvent parsing terms, because it will not parse on redelivery either.
+- Leave the callback type `Callable[[CloudEvent[Any]], Awaitable[None]]` unchanged. The
+ classification travels as an exception, so no signature widens and P0's nine callback-type
+ declarations stay untouched. Widen it only if P4's dedup or C7's in-flight gauge later needs the
+ result object at the transport edge — and then once, deliberately, not twice.
+- Bring Dapr into line (spec sec. 7.2): `NO_HANDLER_FOUND` → `SUCCESS` (`dapr.py:75`),
+ `CriticalHandlerError` → `DROP` (`dapr.py:102`), and the same in
+ `event_handling_base.handle_event`, whose returned dict *is* Dapr's acknowledgement.
+- Add the unhandled-event counter and the first-occurrence WARNING per (namespace, topic), so
+ acking an unmatched event does not hide a topic nobody handles.
+- Configure `max_deliver` and a dead-letter destination (with P3), since nak on an unexpected
+ exception otherwise redelivers forever.
+
+~~**P3 — Consumer tuning is not configurable.**~~ **Done.** `ack_wait`, `max_ack_pending`,
+`max_deliver` and a dead-letter subject are configurable and are set on an explicitly constructed
+`ConsumerConfig`, which the client creates through `add_consumer` and binds with `subscribe_bind`.
+The two items deferred into P3 landed with it:
+
+- **`max_deliver` and a dead-letter destination** (from P2). The nak on the last delivery the
+ broker permits is now rendered as a dead letter plus a term, so a message the framework gives up
+ on keeps its payload instead of expiring silently out of the consumer.
+- **A deliver group on the JetStream durable** (from P1). `nats-py` rejects a queue subscription
+ whose durable name differs from the queue name, so the queue group could not reach `js.subscribe`;
+ it is now `deliver_group` on the consumer config, bound with `subscribe_bind`, and JetStream is no
+ longer single-subscriber.
+
+Three defects had to be fixed to get there, none of them visible from the P3 description:
+
+- The stream was created per topic as `f"{topic}.>"`, which does not cover `topic` itself, so an
+ explicitly created consumer filtering that subject could not be bound at all. Provisioning now
+ happens once per connect with the union of every subscribed subject plus the dead-letter subject.
+- Every `add_stream` call after the first hit "stream name already in use" and was logged as a
+ warning, so with more than one topic only the first was ever captured by the stream.
+- The derived durable name `f"{topic}-durable"` is illegal for any dotted subject -- NATS allows no
+ `.`, `*`, `>` or whitespace in a consumer name -- which is every idiomatic NATS subject.
+
+**P4 — Idempotency, flagged not enforced.** Competing consumers make at-least-once permanent, and
+ack loss makes duplicate delivery *certain* rather than possible: a handler that finishes 60s of
+inference and then cannot ack has already committed its side effects, and the broker redelivers
+after `ack_wait`. But whether dedup is *correct* depends on the product built on the blueprint —
+some operations are naturally idempotent, others need business-level reconciliation the framework
+cannot see. So: provide an opt-in dedup mechanism (CloudEvent `id`, namespace cache, TTL, in the
+handler chain before dispatch), default **off**, and surface the requirement explicitly to the
+author — scaffolded handler comment, generated README, `asbs validate` notice. The author must
+make a decision, not inherit one silently.
+
+**P5 — Cron becomes an event source (#73).** `SchedulerBase.on_startup` creates an
+`AsyncIOScheduler` per process with no leader election, so every cron tick fires once per replica.
+Grouping widens this: one pod with 20 agents runs 20 schedulers, and two replicas duplicate all
+20 agents' crons at once.
+
+The fix is not leader election in production — it is removing the in-process timer:
+
+```toml
+scheduler_mode = "event" # default: schedule lives outside; the tick arrives as an event
+ "in_process" # apscheduler + leader lease, for plain Docker and local dev
+```
+
+**`"event"`** — a Kubernetes `CronJob` publishes a NATS message; the agent handles it through the
+event path it already has. A ~10 MB `nats-cli` container, not a pod re-paying the 154 MB baseline
+(#32). The queue group already guarantees exactly one replica picks it up, so nothing is elected;
+idempotency dedup, telemetry attribution and namespace routing all apply for free. One execution
+model instead of two.
+
+The developer still **declares** the schedule in the agent; the build **generates** the `CronJob`
+from that declaration, the same way manifests are generated from `deployment-groups.yaml`. Without
+generation, code can expect a tick nobody scheduled.
+
+**`"in_process"`** — the existing timer plus a NATS KV or cache-backed lease. Needed for
+un-orchestrated Docker and for local dev, where a `CronJob` is not available. Cheap to keep: event
+mode is "do not start the timer", since the handler path already exists.
+
+Neither mode is exactly-once. `CronJob` is at-least-once (controller restart, missed
+`startingDeadlineSeconds`) and a lease can briefly have two holders if it expires mid-tick, so P4
+applies either way. Set `concurrencyPolicy: Forbid` to prevent overlap, and watch that `CronJob`
+`timeZone` and apscheduler timezone handling agree across modes.
+
+Note #43 — schedulers started twice *within* one process by two `build()` passes — is a distinct
+defect; both touch scheduler startup and should be fixed together.
+
+**P6 — Transport topology: one connection per namespace. Done.** Ownership, naming and
+resolution are in place; Phases 5 and 6 are what actually *create* a second client, and they now
+have somewhere to create it. Landed as part of this: clients take a `namespace`, register under a
+namespace-qualified name so two can coexist, name their connection
+`f"{namespace}.{group}.{pod}"`, and derive queue group and durable from the namespace alone.
+`EventPublishingService` takes a namespace and resolves its own namespace's client, falling back
+to the root one. Not a defect, but it belongs here
+because it changes `NATSClient` ownership. Per-namespace clients confine ack loss and
+slow-consumer disconnects to one agent, and give named connections in `/connz` —
+`nats.connect()` is called today with no `name=` at all (`nats_client.py:93`). No config knob: a
+socket plus buffers against ~65 MB for a separate process (#32). For a single-agent app it is a
+no-op — one namespace, one connection. `EventPublishingService` becomes per-namespace too, or
+outbound traffic stays unattributable. The connection name contains the pod and **must never**
+feed C1 naming.
+
+Two scoping points, both easy to get wrong:
+
+- **NATS only.** Under Dapr the app holds no broker connection — `DaprClient` is an `httpx` client
+ against the sidecar (`dapr_client.py:89`), and the sidecar owns and multiplexes one broker
+ connection per pod. Connections track pods there, and the ack-loss and slow-consumer arguments
+ move into the sidecar. A per-namespace `DaprClient` is still useful for health attribution and
+ C4, but it does not confine either failure.
+- **Not a durability mechanism.** JetStream pending state is the server's, keyed by consumer and
+ stream sequence; an ack is a publish to the per-delivery reply subject, not an entry in a
+ framework-side registry. A shared connection therefore has no in-flight state to lose when the
+ process dies. The topology decides how many namespaces *repeat* work after a connection drop —
+ nothing more. Durability is settled by P1/P2, not here.
+
+---
+
+## Namespace model
+
+```
+Root Registry (namespace="")
+├── nats_client ← shared IO transport (one connection)
+├── event_publishing_service ← shared
+├── actuator_api ← one health endpoint
+│
+├── Named caches (flat, namespace-independent)
+│ ├── "default" ← backwards-compat alias for registry.cache_service
+│ └── "orders" ← any name, accessible from every namespace
+│
+├── Namespace "invoice"
+│ ├── invoice_agent (AgentRuntime)
+│ ├── invoice_handler (EventHandlerBase)
+│ ├── invoice_api (RestApiBase) → routes at /api/invoice/...
+│ ├── invoice_ai_client (AIClientBase) ← isolated connection pool
+│ └── _executor (ThreadPoolExecutor) ← blocking I/O isolation
+│
+└── Namespace "order"
+ ├── order_agent (AgentRuntime)
+ ├── order_handler (EventHandlerBase)
+ ├── order_api (RestApiBase) → routes at /api/order/...
+ ├── order_ai_client (AIClientBase) ← isolated connection pool
+ └── _executor (ThreadPoolExecutor) ← blocking I/O isolation
+```
+
+**Component resolution rule** for `get_component(Type, namespace="invoice")`:
+1. Search `"invoice"` namespace — if exactly one match, return it.
+2. Fall back to root `""` — if exactly one match, return it.
+3. Raise only if ambiguous within the same level.
+
+**Cache resolution** is by name only — no namespace dimension.
+`registry.get_cache("orders")` works identically from any namespace.
+
+---
+
+## Migration path for an existing agent
+
+**No change (stays standalone):** developer does nothing — existing `main.py` and
+Dockerfile work as-is forever.
+
+**Opt in to multi-agent:** three file changes. Earlier drafts of this plan said two and
+forgot `agents.toml`, which is required even for a group of one.
+
+`main.py` before:
+```python
+app = (
+ AppBuilder(config)
+ .with_service(OrderService)
+ .with_handler(OrderValidationHandler)
+ .with_handler(OrderEnrichmentHandler)
+ .with_rest_api(OrderApi)
+ .with_cache()
+ .build()
+)
+```
+Dockerfile before: `CMD uvicorn src.main:app --host 0.0.0.0 --port 8000`
+
+`main.py` after — **the same builder**, minus its `config` argument and minus the `.build()`:
+```python
+agent = (
+ AppBuilder()
+ .with_service(OrderService)
+ .with_handler(OrderValidationHandler)
+ .with_handler(OrderEnrichmentHandler)
+ .with_rest_api(OrderApi)
+ .with_cache()
+)
+
+def create_app(): # only if this agent is still to be served on its own
+ return agent.build()
+```
+Dockerfile after: `CMD python -m blueprint.agents.entrypoint`
+
+`agents.toml` (third change): `[agents.order]` / `module = "agents.order.main:agent"`.
+
+Note what did *not* change: `with_cache()` stays exactly where it was, and so does every other
+`with_*` call. That is the point of the single builder surface — migration removes two things and
+adds nothing, because the declaration and the application builder are the same class (spec
+sec. 4.2).
+
+One declaration, three deployment shapes:
+
+| Shape | Command |
+|---|---|
+| Standalone, unmigrated | `uvicorn src.main:app` |
+| Standalone, migrated | `uvicorn src.main:create_app --factory --reload` |
+| Grouped (including a group of one) | `python -m blueprint.agents.entrypoint` |
+
+An earlier draft of this plan used a dual-branch `main.py` —
+`if __name__ == "__main__": AppBuilder(...)...run_app()` / `else: registration = ...`. That is
+**rejected**: it makes the developer write the component list twice and keep both copies in sync,
+and it exposes the existence of two worlds. `create_app` above is not that: it repeats no
+component, and it is optional.
+
+**The consequence to state plainly.** A migrated agent run in a group uses its group name, so its
+queue group and its JetStream durable change — standalone runs at the root and takes its identity
+from `app_name`. Moving from standalone into a group is therefore a consumer migration on the
+first grouped deploy, not a rename (C1, phase 5's migration note). Regrouping *afterwards* changes
+nothing, which is the property the whole feature is built for.
+
+Because the module is imported into a shared runtime, it **must** contain only the declaration —
+no client construction at import time, no module-level mutable state, no `logging.basicConfig()`.
+CI check: import each agent module, assert the registry is still empty and the root logger has no
+handlers.
+
+A hand-written group `main.py`, for a project that wants one rather than the module entry
+point (no uvicorn, just a FastAPI app):
+```python
+from blueprint.agents import AgentGroup, Config
+from order_agent.src.main import agent as order_agent
+from invoice_agent.src.main import agent as invoice_agent
+
+config = Config(settings_files=["settings.toml"])
+
+app = (
+ AgentGroup(config)
+ .add("order", order_agent)
+ .add("invoice", invoice_agent)
+ .build()
+)
+```
+`AgentGroup` is a different class from `AppBuilder` on purpose: an `AppBuilder` never absorbs
+another builder and never learns it can be collected, so the group's refusals live in the class
+that imposes them (spec sec. 4.1). No cache is declared here — each agent declares its own, and
+gets only what it declared (spec sec. 8).
+
+---
+
+## API route namespacing
+
+`RestApiBase` subclasses require no changes. `_build_rest_endpoints` reads
+`rest_api._namespace` and adjusts prefix and tags at router-inclusion time.
+
+| Mode | Declared tag | Route | OpenAPI tag |
+|---|---|---|---|
+| Standalone (`namespace=""`) | `"Orders"` | `/api/orders/{id}` | `Orders` |
+| Multi-agent (`namespace="order"`) | `"Orders"` | `/api/order/orders/{id}` | `order.Orders` |
+
+---
+
+## Component sharing rules
+
+| Component | Sharing | Notes |
+|---|---|---|
+| `NATSClient` / `DaprClient` | **Per-namespace** | One named connection per agent (P6). Confines ack loss and slow-consumer kicks; single-agent apps unchanged |
+| `EventPublishingService` | **Per-namespace** | Must publish on its own namespace's client, or outbound traffic is unattributable |
+| `EventProcessingService` | Shared (root) | Namespace passed per-call |
+| `ActuatorApi` | Shared (root) | One health endpoint |
+| `CacheService` | **Per-namespace, declared only** | An agent gets exactly the caches it passed to `with_cache`, and no others: names qualified per namespace, no root fallback, no shared-cache opt-in. A flat store lets two independently developed agents both call `get_cache("sessions")` and silently share it once grouped. Sync ops via `run_in_executor` + namespace executor |
+| `AIClientBase` | Per-namespace strongly recommended | Shared async HTTP pool causes one agent's LLM calls to starve another's |
+| `ThreadPoolExecutor` | Per-namespace | Provisioned during wiring, lazily on first `Component.executor` access; prevents blocking DiskCache/SQLite from stalling event loop of other namespaces |
+| `EventHandlerBase` | Per-namespace | Core routing unit |
+| `AgentRuntime` | Per-namespace | Each agent in its own namespace |
+| `RestApiBase` | Per-namespace | Routes prefixed `/api/{namespace}/` |
+| `ServiceBase` (user) | Per-namespace | Typical; can be root if truly stateless and shared |
+| `SchedulerBase` | Per-namespace | Typical |
+| `SessionsApiClient` | Shared (root) | One sessions backend |
+
+---
+
+## Phase 0 — `run_app` utility + `AgentRegistration` (no breaking changes)
+
+> **Superseded in part by phase 8b.** `run_app` stands. `AgentRegistration` does not: phase 8b
+> deletes it, because an `AppBuilder` that records instead of constructing serves the same purpose
+> without a second class. The namespace-injection mechanism described below is unchanged — only its
+> owner moves, from `AgentRegistration._apply` to `AgentGroup`. Read this phase for the ContextVar
+> reasoning, not for the API.
+
+**Files:** `utils/utils.py`, `app_builder.py`, `__init__.py`
+
+`run_app(app: FastAPI, config: Config) -> None` in `utils/utils.py`:
+- Imports uvicorn and starts the server with dev/prod settings derived from config.
+- `app_environment = "development"` → `reload=False` (reload requires a string reference,
+ not an object; developers who need reload use the uvicorn CLI directly), workers=1,
+ log level debug.
+- `app_environment` anything else → workers from `app_workers` config (default 1),
+ log level from `log_level` config (default `"info"`).
+- Config keys read: `app_host` (default `"0.0.0.0"`), `app_port` (default `8000`),
+ `app_environment`, `log_level`, `app_workers`.
+
+`AgentRegistration` class in `app_builder.py`:
+- Fluent collector — same `with_handler`, `with_service`, `with_agent`, `with_rest_api`,
+ `with_scheduler` signatures as `AppBuilder` (and `NamespaceBuilder`), but stores
+ component classes instead of instantiating them.
+- No `with_cache()` — caches are global and registered on the orchestrating `AppBuilder`.
+- Internal `_apply(namespace_builder: NamespaceBuilder) -> None` iterates stored entries
+ and calls the corresponding `with_*` on the provided builder. Called by
+ `AppBuilder.with_namespace(..., registration=reg)`.
+- **Namespace injection:** at the start of `_apply`, set a module-level
+ `ContextVar[str]` (defined in `component.py`) to `namespace_builder._namespace`; reset
+ it in a `finally` block after all `with_*` calls complete. `Component.__init__` reads
+ the ContextVar to determine its namespace — zero changes required to user-defined
+ constructors. In the standalone case the ContextVar default (`""`) is never overridden.
+
+Export both `run_app` and `AgentRegistration` from `blueprint.agents.__init__`.
+
+---
+
+## Phase 1 — Registry namespace + named cache support
+
+**File:** `component/registry.py`
+
+**Namespace storage:**
+- Change `_components: dict[str, Any]` to `dict[str, dict[str, Any]]`
+ (namespace → name → component). Root namespace key is `""`.
+- Add `namespace: str = ""` param to `add_component`, `update_component_name`,
+ `get_component`, `get_components_by_type`, `get_component_names_by_type`, `has_component`.
+- `get_component` implements two-level fallback: own namespace → root `""` → raise.
+- All typed convenience getters (`get_event_handler`, `get_agents`, `get_services`,
+ `get_schedulers`, `get_rest_apis`, `get_clients`) accept optional `namespace=""`.
+- `add_component` raises on name collision only within the same namespace.
+- `get_known_namespaces() -> list[str]` returns all registered namespace keys
+ (used by `NatsEventing` and `build()` to iterate all namespaces).
+
+**Named cache storage (replaces the single `_cache_service`):**
+- Replace `_cache_service: CacheService | None` with `_caches: dict[str, CacheService]`.
+- `add_cache(name: str, service: CacheService) -> None` — upsert; no "already registered"
+ guard, so caches can be added at any time after startup.
+- `get_cache(name: str = "default") -> CacheService` — raises `ValueError` if not found.
+- `get_or_create_cache(name: str, factory: Callable[[], CacheService]) -> CacheService` —
+ atomic get-or-create protected by an `asyncio.Lock` for safe concurrent first-access.
+- `has_cache(name: str = "default") -> bool`.
+- `get_all_caches() -> dict[str, CacheService]` — returns a shallow copy of `_caches`.
+ Used by `ActuatorApi` (health checks) and `CacheManagementApi` (management endpoints)
+ instead of accessing `_caches` directly.
+- `cache_service` property kept as alias for `get_cache("default")` — backwards compat.
+- `cache_service` setter kept as alias for `add_cache("default", value)` — backwards compat.
+
+**Executor registry:**
+- Add `_executors: dict[str, ThreadPoolExecutor]` (namespace → executor).
+- `add_executor(namespace: str, executor: ThreadPoolExecutor) -> None`.
+- `get_executor(namespace: str = "") -> ThreadPoolExecutor` — falls back to root `""` if
+ the namespace has no executor; raises `ValueError` if root is also missing.
+- The root executor is provisioned in `AppBuilder.build()`, not while a declaration is being
+ collected, so standalone apps always have one.
+
+**Backwards compatibility:** All callers omitting `namespace` use `""` and see today's flat
+registry. Existing `registry.cache_service` access is unaffected.
+
+---
+
+## Phase 2 — Component namespace awareness
+
+**File:** `component/component.py`
+
+- Add a module-level `_current_namespace: ContextVar[str] = ContextVar("_current_namespace", default="")`.
+- `Component.__init__` reads `_current_namespace.get()` and stores it as `self._namespace`.
+- Pass `self._namespace` to `registry.add_component(name, self, namespace=self._namespace)`.
+- Add `executor` property: returns `registry.get_executor(self._namespace)`, falling back
+ to a root-level executor if none is registered for that namespace (root namespace always
+ has a default executor created in `build()`). Used by `CacheService` subclasses to
+ offload sync DiskCache/SQLite calls via `asyncio.get_event_loop().run_in_executor`.
+- `Component.shared_registry` remains a single class-level singleton.
+
+**Backwards compatibility:** Default `namespace=""` — existing subclasses unchanged.
+
+---
+
+## Phase 3 — NamespaceBuilder and AppBuilder extension
+
+> **Superseded by phase 8b**, except for `with_cache`'s signature rule and the lazy-executor
+> decision, both of which stand. `NamespaceBuilder`, `with_namespace` and the `namespace=` keyword
+> are deleted there: they existed only because `with_handler` constructed its component
+> immediately, and deferred wiring removes that reason. The C5 scoped-config wiring described below
+> still happens, but at `AgentGroup` wiring time rather than in `with_namespace`.
+
+**File:** `app_builder.py`
+
+- Add `NamespaceBuilder` class (same file):
+ - Holds reference to parent `AppBuilder` and its `namespace` string.
+ - Exposes `with_handler`, `with_agent`, `with_service`, `with_scheduler`,
+ `with_rest_api` — each delegates to parent with `namespace=self._namespace`.
+ - No `with_cache` — caches are always registered at root level.
+ - `end() -> AppBuilder` for explicit block-close style.
+ - All `with_*` methods return `self` for chaining.
+- `AppBuilder.with_namespace(name: str, *, registration: AgentRegistration | None = None, config: Config | None = None) -> AppBuilder`:
+ - Creates a `NamespaceBuilder` for `name`.
+ - **C5 — namespace-scoped config.** `Config` already supports `agent_scope`
+ (`config/config.py`), which tries `.` before falling back to `` at root.
+ When `config` is omitted, `with_namespace` builds one with `agent_scope=name` from the root
+ config's settings files. Prompts, model selection and usage limits become per-agent while
+ infrastructure keys stay shared. Components in the namespace receive this scoped `Config`.
+ - Provisions a `ThreadPoolExecutor(max_workers=config.get("executor_workers", os.cpu_count() + 4))`
+ for the namespace and registers it in the registry under that namespace key.
+ - If `registration` is provided, calls `registration._apply(ns_builder)` and returns
+ `self` — no `.end()` needed. This is the primary multi-agent API.
+ - If omitted, returns the `NamespaceBuilder` for indent-and-`.end()` style.
+ - Executors are shut down gracefully (`.shutdown(wait=True)`) in the lifespan shutdown
+ sequence, after all components have stopped.
+- Add `namespace: str = ""` to all existing `AppBuilder.with_*` methods (except
+ `with_cache`) for direct tagged calls. **Keyword-only** — `process_event` and friends already
+ have positional tails.
+- `AppBuilder.with_cache(enabled=True, enable_locking=True, *, name="default")` creates a
+ `CacheService` via `CacheBackendFactory` with `cache_dir = {base_dir}/{name}` (when
+ `name != "default"`, else the configured `cache_dir`) and calls `registry.add_cache(name, service)`.
+
+ **`name` must be keyword-only and must follow the two existing positional parameters.** The
+ current signature is `with_cache(enabled: bool = True, enable_locking: bool = True)`
+ (`app_builder.py:117`). Making `name` first would turn an existing `with_cache(False)` — which
+ *disables* caching — into a cache named `False`: caching silently switched on, no `TypeError`,
+ no warning. This is the only signature-level break in the whole plan; get it right here.
+- Executors are created **lazily on first `Component.executor` access**, not eagerly in `build()`.
+ Eager creation would add ~`cpu_count + 4` idle threads to every existing single-agent app and
+ works against #36's thread-count budget.
+
+**Backwards compatibility:** `with_cache()`, `with_cache(False)` and `with_cache(True, False)` all
+behave exactly as today. All existing `with_*` calls default to `namespace=""`.
+
+---
+
+## Phase 4 — Namespace-scoped HandlerChain and EventProcessingService
+
+**Files:** `handler/handler_chain.py`,
+`services/eventing/event_processing_service.py`
+
+`HandlerChain`:
+- Constructor accepts `namespace: str = ""`.
+- `process()` fetches `registry.get_event_handler(namespace=self._namespace)`.
+
+`EventProcessingService`:
+- Add `namespace: str = ""` param to `process_event` and `process_rest_request`.
+- Lazy-create one `HandlerChain` per namespace in a `dict[str, HandlerChain]`.
+- Wire previously unused `runtime_name`: after chain picks winner, resolve agent via
+ `get_runtime_name()` (Phase 7) within the namespace.
+
+**Dispatch index (spec sec. 7.7).** `handler_chain.py:52-55` sorts every registered handler and
+calls `can_handle` on each until one returns non-`None`. Build a `dict[event_type, list[handler]]`
+once at startup from declared event types, priority-sorted, and evaluate only the candidates for
+an event's type plus the wildcard bucket. The chain-of-responsibility fallthrough is preserved:
+a candidate whose `handle` returns `None` still passes to the next.
+
+**Handlers that declare nothing MUST stay in the wildcard bucket** and be evaluated for every
+event, which is today's behaviour. Nothing in the framework or in any scaffolded project declares
+event types today — `get_subscribed_topics()` is overridden nowhere and the generated
+`handler.txt` selects purely in `can_handle_event` — so an index that treats declarations as
+authoritative silences every existing handler, and P2's ack contract then discards the events
+instead of letting them pile up. `SessionsJobHandler` is the model case for opting in: its
+`can_handle_event` is `event.type == f"sessions.job.created.{self.JOB_TYPE}"`, so the framework can
+derive its declaration from `JOB_TYPE` without the author writing one.
+
+**Backwards compatibility:** Omitting `namespace` defaults to `""` — today's behaviour. The index
+changes selection for no handler that has not opted in.
+
+---
+
+## Phase 5 — NATS per-namespace topic routing
+
+**Files:** `io/api/eventing/nats.py`,
+`io/api/eventing/cloud_event_processor_mixin.py`,
+`io/api/eventing/event_handling_base.py`
+
+`NatsEventing.on_startup()`:
+- Iterate `registry.get_known_namespaces()`, collect `(namespace, topic)` pairs from each
+ handler's `get_subscribed_topics()`.
+- **Deduplicate within a namespace only.** Two agents subscribing to the same topic is
+ legitimate and expected — both want the event. A cross-namespace "first declaration wins" rule
+ silently disables one agent's subscription, and the author cannot observe it locally. Each
+ `(namespace, topic)` pair gets its own subscription and its own consumer.
+- Each `_subscribe_to_topic(topic, namespace)` closure passes `namespace=` to
+ `_process_cloud_event`.
+
+**Broker-side filter derivation (spec sec. 7.7).** Give each namespace's JetStream consumer a
+`filter_subjects` set, so a broad subject stops fanning every message out to every namespace. The
+set is the union of that namespace's declared `get_subscribed_topics()` and the configured
+`nats_subscriptions` — that is, exactly what is subscribed today, expressed one layer down.
+**Never infer a narrower filter from handler code**: an agent on `orders.>` whose handler selects
+by payload must keep receiving all of it.
+
+Collapse the derived set to the agent's domain prefix rather than tracking the exact handler list.
+A durable's filter set is broker state, so a filter that follows handler churn turns adding one
+handler into a consumer reconfiguration — and possibly a redelivery storm on deploy.
+
+`CloudEventProcessorMixin._dispatch_cloud_event`:
+- Accept `namespace: str = ""`, forward to `EventProcessingService.process_event`.
+
+`NATSClient` consumer identity (**C1 — invariant, cover with a test**):
+- JetStream durable: `f"{namespace}-{topic}-durable"` when namespace non-empty; config default
+ otherwise.
+- Core NATS queue group: `queue=namespace` (see P1).
+- Both derive from the **agent/namespace name only** — never from the group name, container
+ name, pod name or any deployment identifier. This is what makes replicas of a group compete
+ correctly *and* makes moving an agent between groups invisible to the broker. A durable name
+ that picks up the group name produces a fresh consumer on regrouping: replay from the start of
+ the stream, or a silent gap, depending on the delivery policy.
+
+**Migration note (spec sec. 7.7) — this rename is a consumer migration.** Today the durable is
+`nats_durable_name` from config, or `f"{topic}-durable"`. On the first deploy of this phase every
+pre-existing consumer becomes a new consumer, which resumes according to its delivery policy:
+replay from the start of the stream, or a gap covering whatever arrived in between. The release
+notes **must** state which, and the same applies to any later change of a filter set. Do not ship
+this phase and a filter-set change in the same release — if something replays, you want to know
+which change caused it.
+
+One `NATSClient` **per namespace** (P6), named `f"{namespace}.{group}.{pod}"`. The connection name
+contains the pod, so it must never feed durable or queue naming.
+
+**Backwards compatibility:** No declared namespaces → single root namespace → one connection →
+same as today.
+
+---
+
+## Phase 6 — AppBuilder.build() multi-namespace awareness + API route namespacing
+
+**File:** `app_builder.py`
+
+- `_eventing_component` → `list[DaprEventing | NatsEventing]` (one element initially).
+- `build()` scans all known namespaces when deciding whether to create an event bus client.
+- Lifespan manager and `_build_rest_endpoints` iterate the list.
+- **API route namespacing** in `_build_rest_endpoints`: when `rest_api._namespace` is
+ non-empty, rewrite `route.tags` to `[f"{ns}.{tag}" for tag in route.tags]` and include
+ the router with `prefix=f"/api/{ns}"`. Empty namespace → unchanged behaviour.
+- `CacheManagementApi`: one router, endpoints accept optional `?name=` query param
+ (defaults to `"default"` for backwards compat).
+- `ActuatorApi` cache health: iterates all entries in `registry._caches` at startup time.
+
+---
+
+## Phase 7 — Handler → Agent binding (get_runtime_name)
+
+**Files:** `handler/event_handler_base.py`,
+`services/eventing/event_processing_service.py`
+
+`EventHandlerBase`:
+- Add `get_runtime_name(event, context) -> str | None`, default returns `None`.
+
+`EventProcessingService.process_event`:
+- Call `winner.get_runtime_name(event, context)` after chain selects a handler.
+- Non-`None` → `registry.get_agent(name, namespace=namespace)`.
+- `None` + exactly one agent in namespace → use it (today's implicit behaviour).
+- `None` + multiple agents + no name declared → raise a descriptive error.
+
+---
+
+## Phase 8 — Group configuration + entry point
+
+**Files:** new `group_config.py` (`GroupConfig`), new `entrypoint.py` (runnable as
+`python -m blueprint.agents.entrypoint`), `app_builder.py` (`with_group`, `from_group`),
+`utils/utils.py`
+
+Turns the group configuration into a running app. Everything here is additive; standalone
+`main.py` deployments are untouched.
+
+**Not a separate "orchestrator" component.** The split is resolution versus wiring: the
+looping-over-agents half is builder work, and what stays outside it is the I/O — env reads, file
+reads, `sys.exit`, and knowledge of the agent repo's file layout. Wiring must remain a pure
+function of its call sequence so tests can construct exact compositions without controlling env or
+filesystem — the same layering mistake as putting retry logic in `EventHandlingBase` (see the
+event-client resilience decision record).
+
+Phase 8b moves that half from `AppBuilder` onto `AgentGroup`, which is **not** an orchestrator
+either: it is the wiring half, in a class of its own so that an `AppBuilder` never learns it can be
+collected and the group's refusals sit with the thing imposing them (spec sec. 4.1). Same layering,
+one fewer job per class.
+
+Avoid the name "orchestrator": it names the App-of-Apps supervisor process that this design
+rejected, and reusing it invites confusion with a component that deliberately does not exist.
+
+`deployment-groups.yaml` — single source of truth, read by the entry point at runtime, by the
+CI gate, and by Kubernetes manifest generation (Argo CD `ApplicationSet` list generator over
+`groups`, or Helm values), so the container and the cluster cannot drift:
+
+```yaml
+groups:
+ - name: finance
+ agents: [invoice, order, dunning]
+ resources: {cpu: "2", memory: "2Gi"}
+ replicas: 2
+ - name: contract-analysis # alone: CPU-heavy, isolated blast radius
+ agents: [contract-analysis]
+ replicas: 3
+```
+
+Agent discovery — explicit map (`agents.toml`), no convention scanning. **This one is baked into
+the image**; it changes only when an agent is added or removed, which is a rebuild anyway:
+
+```toml
+[agents.invoice]
+module = "agents.invoice.main:registration"
+```
+
+**Configuration delivery — both mechanisms, and they compose.** The group configuration is never
+baked into the image.
+
+1. **YAML file at a configurable path.** `BLUEPRINT_GROUP_CONFIG` (default
+ `./deployment-groups.yaml`) plus `BLUEPRINT_GROUP` to pick the group. The path is
+ configuration, not a constant, so one image serves a ConfigMap mount in Kubernetes, a bind
+ mount in `docker run`, and the repo file in local dev. Falling back to the repo file is what
+ makes `python -m blueprint.agents.entrypoint` work with no cluster and no mount.
+ `BLUEPRINT_GROUP` may be omitted when the file declares exactly one group. What gets mounted
+ is the **resolved slice** for one group, not the full multi-group document.
+2. **Environment variables injected directly.** `BLUEPRINT_AGENTS=invoice,order,dunning` and
+ `BLUEPRINT_CRITICAL_AGENTS=invoice` (feeds `readiness_policy = "critical"`, C3). No file, no
+ mount. Because these live in the pod template, changing them changes the template hash and
+ Kubernetes rolls automatically — a property the mounted file does not have.
+
+**Precedence: env vars override the file, key by key** (12-factor). The file supplies the
+baseline; a single Deployment can override one field without editing or duplicating it. Log the
+resolution at startup: which source each value came from, and the final agent list.
+
+Both are read **before** `Config` is constructed — group resolution decides which agents get a
+`Config` at all, so it is a plain env read plus a small YAML parse, deliberately not routed
+through Dynaconf. Hence the explicit `BLUEPRINT_` prefix rather than Dynaconf's `DYNACONF_`
+override mechanism.
+
+Entry point, in full:
+
+```python
+def main() -> None:
+ config = Config(settings_files=["settings.toml"])
+ group = GroupConfig.resolve(config) # env + file, validated; the only I/O
+ app = AgentGroup(config).with_group(group).build()
+ run_app(app, config)
+```
+
+`AgentGroup.from_group(config)` collapses lines 2-3 for callers who want one call; `with_group`
+takes an in-memory `GroupConfig` and reads neither environment nor filesystem, so tests construct
+one literally. (As shipped this reads `AppBuilder(config).with_group(group)`; phase 8b moves the
+two group methods onto `AgentGroup` and nothing else about this phase changes.)
+
+Flow:
+1. `GroupConfig.resolve`: read the YAML at `BLUEPRINT_GROUP_CONFIG` if present, apply env-var
+ overrides key by key, log the effective source of each value.
+2. Validate every agent named in the group against the in-image `agents.toml` map. Fail fast,
+ naming the group and the missing agent — this seam turns a config typo into a crash-loop with
+ a readable message instead of a silently short-staffed pod.
+3. Resolve each name via `importlib.import_module` + `getattr`, **lazily and per group** — only
+ the modules this group needs are imported, so cold start stays proportional to group size.
+4. `with_group` records one declaration per agent (`add(name, builder)`); `build()` constructs
+ every component inside its own namespace scope; `run_app`.
+
+**Resolution must complete before the first `Component.__init__`,** because namespace injection
+happens through the ContextVar read during construction. No incremental resolution, no namespace
+added once wiring has started.
+
+**Startup failure policy.** There is no partial build — one process, one `build()` — so the
+`critical` flag is evaluated *before* a namespace is wired, not after an exception:
+
+| Failure | `critical: true` (default) | `critical: false` |
+|---|---|---|
+| Agent missing from `agents.toml` | exit non-zero | log ERROR, skip |
+| Module import raises | exit non-zero | log ERROR, skip |
+| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue |
+
+Exit before the port is bound, so Kubernetes crash-loops with a readable message. Default
+`critical: true`: a partially loaded group whose missing agent's queue has no consumer is worse
+than no pod at all. The same flag drives `readiness_policy = "critical"` — one concept, both
+startup and runtime.
+
+**Startup log** must include the group name, the agent list, the source of each resolved config
+value, and per namespace the queue group and durable names. That last item makes C1 verifiable by
+diffing startup logs across a regrouping.
+
+**Settings fragment merge.** Each agent ships an unscoped `settings.toml` in its own directory
+(`model_name = "..."`, not `[default.order] model_name`). The build merges each fragment under its
+own scope so C5 resolves it, without the author knowing scopes exist. Collisions between a
+fragment and a root key are reported at build time.
+
+One image for the whole platform; the group is injected at container start, not baked at build
+time. Build-time dependency trimming is an opt-in optimisation for sharply diverging dependency
+sets or hard tenant boundaries only — it does not change this format.
+
+**Deployment note (agent repo, not this repo):** when mounting a file, give the ConfigMap a
+content-hashed name (`finance-group-a1b2c3`) — kustomize's `configMapGenerator` default, or a
+Helm `checksum/config` annotation. A plain ConfigMap edit leaves the pod template unchanged, so
+nothing restarts and the running process keeps the group it resolved at startup. One
+ConfigMap per group, not one shared: a shared one rolls all twenty agents whenever any group
+changes.
+
+---
+
+## Phase 8b — Builder unification (before 9, because 9 depends on it)
+
+**Amendment:** `docs/plans/2026-09-10-builder-unification.md` carries the reasoning, the decisions
+D1-D7 and the refusal table. This section is the work breakdown only; where the two differ, that
+document is the argument and the spec is normative.
+
+**Files:** `app_builder.py`, new `agent_group.py`, `agent/agent_builder.py`, `group_config.py`,
+`entrypoint.py`, `component/registry.py`, `config/config.py`, `services/infrastructure/`
+(cache scoping), `io/api/actuators/` (per-agent `/cache/*`, health-checker keys)
+
+**Not numbered 11.** Phase 10 is documentation and must stay last, and this must precede phase 9:
+D4 makes a health checker's owning agent available *as data*, which is exactly what phase 9's
+`readiness_policy = "critical"` needs in order to attribute a failing checker to an agent.
+
+**Why now rather than never.** Adding one `with_*` method today means editing four places
+(`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `AgentRegistration.apply`'s `appliers`
+dict), and three of those fail *silently* — the capability is simply absent from that surface. The
+duplication is not stylistic: `AppBuilder.with_handler(H)` constructs `H` immediately, and a
+component constructed before a namespace exists belongs to the root for ever, so a second class had
+to exist to defer construction. Deferred wiring removes the reason they diverged, and the other
+three classes then have no purpose. Four sites become one.
+
+**Steps, each its own commit, reported before the next begins:**
+
+1. **`AppBuilder` records.** A `Declaration` value object; the five `with_*` store instead of
+ constructing; `build(config=None)` wires at the root. `configure_logging()` moves from
+ `__init__` into `build()` — with nothing constructed before `build()`, that is where logging
+ configuration belongs. A builder is single-use and says so, rather than surfacing
+ `Component.configure`'s "already set" error. Order semantics preserved: `build()` raises on an
+ instance recorded after a class at equal priority (spec sec. 4.2).
+2. **`AgentBuilder` records too.** `config` optional in `__init__`, accepted by `build(config)`.
+ This fixes a live defect, not just a shape: `AgentBuilder.__init__` requires a `Config` and
+ `Component._shared_config` has no public read path, so the factory form phase 8 documents
+ (`lambda: AgentBuilder(config, ...).build()`) **cannot be written** in a declaration-only
+ `main.py`. Wiring calls `agent.build(config.for_namespace(ns))`, which also removes a second
+ latent bug: a lambda closes over whichever config was in scope where it was written, which in a
+ group is the wrong one.
+3. **`AgentGroup`** in its own module: named builders in, one `FastAPI` out. Every refusal from
+ the spec's sec. 4.2 table, each naming the agent and the fix. `with_group` and `from_group`
+ move here from `AppBuilder`; `entrypoint.build_group_app` calls it.
+4. **Delete** `AgentRegistration`, `NamespaceBuilder`, `AppBuilder.with_namespace`, the
+ `namespace=` keyword on the five `with_*`, `AgentRegistration.apply` and the `appliers` dict.
+5. **Caches per agent (D3):** qualify names by namespace, `get_cache` resolves within the
+ declaring agent and raises otherwise, `/cache/*` becomes per-agent. Deletes
+ `GroupConfig.cache_names` and `AgentScopedCache` — separate stores make the isolation
+ structural, so the prefixing lens has nothing left to prevent. Knock-on: an agent with
+ `idempotency_enabled` must declare `with_cache()`, which its existing error message already
+ says.
+6. **Health-checker attribution (D4):** `(namespace, name)` recorded as data, the qualified key
+ its rendering. Root keeps the bare name, so an existing readiness payload does not change.
+7. **Settings fragments (D5):** group settings are defaults only; each agent's own `settings.toml`
+ merges under that agent's scope; a process-scope key in an agent fragment raises. This closes
+ the fragment-merge open point that has been outstanding since config-rework step 3a.
+8. **Docstrings and gates:** group behaviour stated on each `with_*` (the decision was RTFM, not
+ authoring-time validation); a test asserting the declaration surface and `AgentGroup`'s replay
+ agree, so the recorder cannot drift from the API it replays; the frozen compatibility suite
+ extended to pin the standalone shape (spec sec. 10.2).
+9. **The rules, and the documents that carry them.** Last, because a rule can only be written
+ once the thing it describes exists. Three parts, each its own commit -- see the section below.
+
+**Done when** an existing standalone `main.py` runs unchanged, the same file with two lines removed
+runs in a group, adding a hypothetical `with_widget` requires exactly one edit, and every principle
+this overhaul established is written down in one place with a test behind the ones a test can hold.
+
+---
+
+## Phase 8b step 9 -- the rules, and the documents that carry them
+
+**Decided 2026-09-10 with the user, after an audit of every markdown reference in the repo.** The
+problem this solves is not documentation for its own sake: this overhaul establishes principles --
+collect then wire, ambient namespaces, validate never repair -- that a later feature can violate
+without anyone noticing, because they are currently recorded only in a 4600-line changelog nobody
+will read end to end.
+
+### Where they go, and why it is `AGENTS.md`
+
+`CLAUDE.md:5` says *"See `AGENTS.md` for architecture, component patterns, and testing conventions
+shared across all AI assistants."* **`AGENTS.md` has never existed.**
+`git log --all --diff-filter=A -- AGENTS.md` returns nothing: it was not written and later deleted,
+it was cited into existence. `docs/plans/2026-06-10-sessions-job-handler.md:122` goes further and
+quotes what it "states" about versioning.
+
+So writing it adds no node to the graph -- it turns a pointer that resolves nowhere into one that
+resolves. The alternatives were a new `docs/concepts/design-rules.md` (a fresh file in a tree that
+already has orphans, leaving the `AGENTS.md` pointer dead beside a new live one) and folding the
+rules into `docs/concepts/architecture.md` (descriptive prose for users; binding rules read badly
+mixed into it). Both were rejected for the same reason: they add, and this repository's
+documentation problem is that it already has more homes than content.
+
+### Part 1 -- `AGENTS.md`
+
+One document, grouped by what a rule governs. Each rule states the rule, the reason, and **the
+failure it prevents** -- a rule without its failure is advice, and advice gets argued away. Draft
+list; wording is settled when the step runs.
+
+**Construction and assembly**
+
+- **Collect, then wire.** A declaration API records; nothing is constructed, registered or
+ connected until `build()`. *Failure:* a component constructed during accumulation exists before
+ any namespace does and belongs to the root for ever -- which is what forced a second builder
+ class to exist for three phases.
+- **One declaration surface.** Adding a capability is one edit. A second class whose only job is
+ to defer construction is the smell this phase removed, not a pattern to copy.
+- **A builder is single-use, and says so**, rather than surfacing someone else's "already set".
+- **Group policy belongs to the collector.** Standalone stays permissive; the group refuses what
+ it cannot honour, at assembly, naming the agent and the fix. *Failure:* restrictions scattered
+ into the builder punish the single-agent case for the group's constraints.
+
+**Namespaces and isolation**
+
+- **A component never learns it is in a group.** The namespace is ambient, read by
+ `Component.__init__`; it is never a constructor parameter of a project's component, and never
+ enumerable from anything a component can reach (C6). *Failure:* an agent that can read its
+ neighbours can be written to depend on them, and regrouping then breaks it.
+- **Isolation is structural where it can be, audited where it cannot.** Separate stores beat a
+ prefix; where walling off would break a supported use, log and name the reader instead.
+- **A lookup never falls back across agents.** *Failure:* two agents that both asked for
+ `sessions` silently share one store, and only in production.
+- **An omitted namespace on the root registry means every namespace, not the root.** Framework
+ code that dispatches per agent names its namespace explicitly, even where it looks redundant.
+
+**Names and values that leave the process**
+
+- **A name that crosses the process boundary is validated, never repaired.** Queue groups,
+ durables, subjects, cache names, environment prefixes. *Failure:* silent rewriting breaks an
+ external dependency with nothing in the logs to debug.
+- **A check answerable at the call stays at the call.** *Failure:* an error reported several
+ `with_*` calls later names the wrong line.
+
+**Declarations and defaults**
+
+- **An empty declaration means everything, not nothing.** *Failure:* treating an empty set as
+ authoritative silences the application, and an unhandled event acknowledges -- so the deliveries
+ vanish rather than piling up where somebody would see them.
+- **A key whose absence changes behaviour is required, not defaulted**, and `must_exist=True`
+ beside a `default=` is a lie Dynaconf never enforces.
+
+**Configuration and logging**
+
+- **Configuration is injected before any component exists**, and is read through the component's
+ own scoped view. There is no public read path to the unscoped loader.
+- **Logging is configured by the application**, never by library code, a constructor, or import
+ time.
+
+**How the work is done**
+
+- **No unused code in the framework.** Git history is where removed work belongs; a plausible
+ unused abstraction misleads the next session into building on it.
+- **Probe against real objects.** Every real defect this feature surfaced was found by testing
+ against a real registry rather than a mock; a mock registry hides resolution bugs by
+ construction.
+- **The spec wins on precedence, not on correctness.** Challenge a requirement's premise, and
+ argue any departure in the changelog rather than quietly complying or quietly diverging.
+
+### Part 2 -- the guard tests
+
+Prose alone has already failed once here: `AGENTS.md` was cited for months without existing. So
+every rule that is mechanically checkable gets a test in
+`tests/unit/agents/test_design_rules.py`, whose failure message names the rule it enforces.
+
+| Guard | What it asserts |
+|---|---|
+| declaration surface | every `AppBuilder.with_*` records and constructs nothing -- called reflectively, registry asserted untouched |
+| replay agreement | the declaration surface and `AgentGroup`'s replay agree (step 8's test, moved here and generalised) |
+| no unscoped config | no attribute on `Component` or its metaclass returns the loader; `for_namespace` on a view raises |
+| no cross-agent fallback | `get_cache` raises on an unknown name; `get_known_namespaces` does not exist |
+| validated names | each namespace-bearing entry point refuses an illegal input rather than rewriting it |
+| logging ownership | no `basicConfig`, handler or formatter attachment in `src/` outside `LoggingManager` |
+| no diagnostics via print | `print(` absent from `src/` except the entry point's deliberate stderr line |
+| **references resolve** | every markdown link and document reference in the repo points at a file that exists -- the check that would have caught `AGENTS.md` |
+
+The last one is what makes the rest durable, and it is why this part is not optional.
+
+### Part 3 -- clean up the puddle
+
+The same audit found real duplication, and the instruction was that `AGENTS.md` alone is not
+enough: everything else has to be coherent too.
+
+- **`docs/superpowers/`** -- `plans/` and `specs/` mirroring `docs/plans` and `docs/specs`:
+ 3 files, 2079 lines, and **nothing in the repo links to any of them.** A second, abandoned home
+ for the same two document types. Fold into `docs/plans` / `docs/specs` or delete; git history
+ keeps them either way.
+- **Four cache documents, 968 lines** -- `docs/concepts/caching.md` (347),
+ `docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181),
+ `docs/guides/caching-getting-started.md` (208). `docs/README.md` links one of the four.
+ Consolidate, and link whatever survives.
+- **The false quotation** at `docs/plans/2026-06-10-sessions-job-handler.md:122`, which attributes
+ a versioning statement to a document that has never existed. Verify the claim against reality,
+ or remove it.
+- **`docs/development-workflow.md`**, cited by this plan's own file summary and never written:
+ write it, or drop the reference.
+
+Phase 10's documentation work is unaffected: it writes the multi-agent setup guide, which is
+content, not coherence.
+
+---
+
+## Phase 9 — Deployment-facing constraints (telemetry, probes)
+
+**Files:** `io/telemetry/telemetry.py`, `io/api/actuators/actuator_api.py`,
+`io/api/actuators/health.py`
+
+**C2 — per-namespace telemetry identity.** `telemetry.py:39-41` currently builds one `Resource`
+with one `service.name` for the whole process. Setting it to the group name would break every
+dashboard, alert and SLO on the day of a regrouping. Instead: one `TracerProvider` and
+`MeterProvider` per namespace, each with
+`Resource({"service.name": , "deployment.group": , "service.instance.id": })`,
+all sharing a single exporter and `BatchSpanProcessor`. Dashboards key on agent and stay blind
+to grouping.
+
+**Empty-namespace path is mandatory.** Implemented naively, a single-agent app would get
+`service.name = ""` and its dashboards would go dark on upgrade. Namespace `""` must keep
+producing exactly one provider using `otel_service_name` from config, as today.
+
+**C3 — liveness is never namespace-dependent.** If one degraded namespace fails the pod's
+liveness probe, Kubernetes restarts every agent in the group, reintroducing the blast radius the
+grouping was paid for.
+- Liveness: process and event loop only.
+- Readiness: `readiness_policy` config — `"all"` (default; any degraded namespace → not ready),
+ `"critical"` (only namespaces flagged `critical` in the group config gate readiness), `"any"`
+ (ready while at least one namespace is up).
+- Per-namespace degradation surfaces as a `blueprint_namespace_up{agent="..."}` gauge plus an
+ ERROR-level event. Alerting decides who is woken; the probe decides only where traffic goes.
+- `readiness_policy = "critical"` needs to know which agent a failing health checker belongs to.
+ Phase 8b step 6 records that as `(namespace, name)` data, so read it from there rather than
+ splitting the qualified key on a separator — a name containing the separator would silently
+ attribute a failure to the wrong agent, which is a C7 violation dressed as a string bug.
+- The actuator's two configuration-error branches (`actuator_api.py:95`, `:149`) are **dead**:
+ `Config.validate()` raises during `__init__`, so no live `Config` ever carries validation
+ errors. Out of scope here — it belongs to
+ `docs/plans/2026-09-10-config-validation-unification.md`, which decides whether the fix is to
+ delete them or to make readiness able to report a bad configuration at all.
+
+**C4 — a degraded namespace stops consuming.** Readiness gates HTTP only; a not-ready pod still
+holds its NATS subscriptions and still consumes events, so for an event-driven agent readiness
+alone is cosmetic. With per-namespace transports (P6) this is closing that namespace's client
+rather than selective unsubscription, and `ClientHealthChecker` already yields the per-agent
+health entries that `readiness_policy = "critical"` needs.
+
+**C6 — agent code cannot observe its grouping.** No supported API exposes the group name, its
+membership, or the number of namespaces in the process. This is what makes regrouping incapable
+of breaking agent code. `deployment.group` is set by the framework on telemetry resources and is
+not readable through a public API.
+
+**C7 — failure is never silent at namespace granularity.** Every path that stops a namespace
+serving emits an ERROR-level event carrying that namespace's telemetry identity, independently of
+any pod-level symptom. This is what makes the residual isolation cost of grouping manageable rather
+than merely accepted: the three failure classes that take a whole group down — memory limit
+breached, native crash, blocked event loop — raise no catchable exception, so careful error
+handling lowers how often a group dies without changing which failures kill it. Attribution is the
+only lever left, so it is normative. Work items:
+
+- Extend the C3 gauge and ERROR event to *every* removal-from-service path, not only the ones
+ readiness reads.
+- Audit every framework `ensure_future` / `create_task` for a done-callback that logs exceptions
+ with the namespace attached (`nats_client.py:77` is the pattern; a bare `ensure_future` is a
+ violation).
+- Drive `blueprint_namespace_up = 0` from per-namespace `subscriptions_ready`, so a namespace that
+ silently stops consuming is visible while the process stays healthy.
+- Tag in-flight handler spans with the namespace and emit a periodic per-namespace in-flight gauge,
+ so a process-terminating failure can be attributed post-mortem. Without this an OOM kill is
+ indistinguishable across a group's agents.
+
+Grouping removes the pod restart that used to serve as the alert, so the alert must be emitted
+deliberately.
+
+**Dev-mode detection.** Three mistakes are harmless alone and fatal in a group, and none can be
+hidden by API design — so they must be caught mechanically rather than documented:
+
+| Mistake | Detection |
+|---|---|
+| Blocking the event loop | dev mode sets `loop.set_debug(True)` with a slow-callback threshold; production keeps a higher-threshold watchdog naming the executing namespace (C7) |
+| Module-level side effects | CI: import each agent module, assert registry empty and root logger has no handlers |
+| Non-idempotent handlers | explicit flag at scaffold time and in `asbs validate` (P4) |
+
+---
+
+## Phase 10 — Migration and setup documentation (last, deliberately)
+
+**Files:** `docs/guides/multi-agent-setup.md` (new), `docs/guides/deployment.md` (rewrite),
+`agent_generator` CLI (`asbs setup`, `asbs create agent`, `asbs validate`)
+
+**Last on purpose.** Everything a migration guide would describe -- the single builder surface, the
+group configuration, the entry point, the single image -- is built in phases 0, 2, 8 and 8b. A guide
+written before them documents an API that does not exist, which is worse than no guide: a reader
+cannot tell which half is aspiration. So this phase adds no framework behaviour; it makes what the
+earlier phases built usable by someone who has only ever written a single-agent service.
+
+**What already holds, and is what makes migration safe to document at all.** P6 fixed the
+guarantee rather than asserting it: an existing project keeps every registry key, every queue
+group and every durable name, because the root namespace keeps them, and that is enforced by tests
+rather than by prose. The guide states this as the reason a migration is a no-op on the broker, and
+it is a claim the reader can check.
+
+**`docs/guides/multi-agent-setup.md`:**
+
+1. Scaffolding a fresh multi-agent repository -- what `asbs setup` produces and why one image
+ serves every group.
+2. Migrating an existing single-agent project -- the three file changes from *Migration path for
+ an existing agent* above (`main.py`, `Dockerfile`, `agents.toml`), and nothing else.
+3. What stays byte-identical and why: registry names, queue group, durable, telemetry
+ `service.name` (C1, C2) -- **for an agent left standalone**. This is the section that decides
+ whether anyone trusts the migration, so it must be equally explicit about the other half: an
+ agent moved *into a group* takes its identity from its agent name rather than `app_name`, so its
+ queue group, durable and route prefix change once, on the first grouped deploy. Regrouping after
+ that changes nothing. Say which of the two the reader is doing before showing either.
+4. The one decision to get right **before** migrating: the agent name becomes the queue group and
+ part of the durable name, so renaming it afterwards is a consumer migration (sec. 7.7), and it
+ must satisfy the namespace alphabet (C1) -- `""` or `[a-z][a-z0-9_]*`, no `-`.
+5. Group configuration, the entry point, and what regrouping does and does not change (C6).
+
+**CLI, and one deliberate omission.** `asbs setup` scaffolds a group; `asbs create agent` wires a
+new agent into the registration; `asbs validate` reports what a single-agent project must state
+before it can be grouped (`scheduler_mode` per namespace, `app_port` at root only). There is
+**no `asbs migrate` command**: `main.py` is the developer's own declaration, and a tool that
+rewrites it either guesses at intent or fails on anything hand-edited. A checklist plus a
+`validate` that names what is missing is the honest shape, and it matches the rule that a
+generator must fail loudly rather than emit something plausible.
+
+**`docs/guides/deployment.md` must be rewritten here or removed.** It ships today, assumes one
+Deployment per agent, recommends `replicaCount: 2` plus an HPA as ordinary scaling, and says
+nothing about schedulers (#73) or duplicate consumption (P1). It is listed under *Planned, not yet
+written* as a Phase 8 obligation; if Phase 8 does not get to it, it lands here, because the setup
+guide will contradict it directly.
+
+**Done when** a developer holding a single-agent service can follow the guide to a grouped
+deployment without reading the spec, the plan, or this changelog -- and a reviewer can verify from
+the guide alone that nothing broker-side changed.
+
+**Steps, each its own commit, reported before the next begins.** The CLI comes before the guides:
+a guide written against a CLI that does not behave that way yet documents an API that does not
+exist, which is the same failure this phase was put last to avoid.
+
+1. **A scaffolded project is a group of one, in every environment.** `src/main.py` becomes a
+ declaration (`agent = AppBuilder()...`, classes rather than instances, an unbuilt
+ `AgentBuilder`), a generated `agents.toml` maps the agent name to it, the Dockerfile's command
+ becomes `python -m blueprint.agents.entrypoint` and bakes no group, and `asbs dev` serves the
+ group under the agents' real namespaces. `asbs create` follows the new shape, because it edits
+ the file the generator wrote. **Landed.**
+2. **`asbs validate` reports what a project must state before it can be grouped**, and closes the
+ scheduler gap from P5's open points: a project in `"event"` mode with nothing publishing its
+ tick is the remaining silent-failure case. **Landed.**
+3. **`docs/guides/multi-agent-setup.md`** -- the five sections listed above, plus the rest of
+ `docs/guides/cli-reference.md` read against the code. **Landed.**
+4. **`docs/guides/deployment.md`** -- rewritten here, because the setup guide contradicts it
+ directly. **Landed.**
+
+---
+
+## File change summary
+
+| File | Phase |
+|---|---|
+| `utils/utils.py` | 0 |
+| `app_builder.py` | 0 (`AgentRegistration`), 3 (`NamespaceBuilder` + executor provisioning), 6, 8b (records instead of constructing; `AgentRegistration`, `NamespaceBuilder`, `with_namespace` and the `namespace=` keyword deleted) |
+| `agent_group.py` (new) | 8b (collection, and every group refusal) |
+| `agent/agent_builder.py` | 8b (records; `config` optional in `__init__`, accepted by `build`) |
+| `services/infrastructure/cache_service.py`, `io/api/actuators/` | 8b (per-agent caches and `/cache/*`; health-checker keys qualified) |
+| `AGENTS.md` (new), `tests/unit/agents/test_design_rules.py` (new) | 8b step 9 (the rules this overhaul establishes, and the guards that hold them) |
+| `__init__.py` | 0 |
+| `component/registry.py` | 1 (namespace storage, named caches, executor registry) |
+| `component/component.py` | 2 (`namespace` param, `executor` property) |
+| `handler/handler_chain.py` | 4 (namespace scope + dispatch index, spec sec. 7.7) |
+| `services/eventing/event_processing_service.py` | 4, 7 |
+| `services/infrastructure/cache_service.py` | 2 (sync ops via `run_in_executor(self.executor, ...)`) |
+| `io/api/eventing/nats.py` | P2 (stop swallowing classified exceptions), 5 |
+| `io/api/eventing/cloud_event_processor_mixin.py` | 5 |
+| `io/api/eventing/event_handling_base.py` | P2 (ack parity in `handle_event`), 5 |
+| `clients/client_base.py` | P0 (`subscribe(topic_callbacks)` abstract) |
+| `clients/io/nats_client.py` | P0 (managed subscribe, retry, reconnect, drain), P1-P3 (queue group, ack/nak/term, consumer tuning, dead letters) -- **done**; 5 (durable naming) |
+| `clients/io/dapr_client.py` | P0 (same lifecycle, mirrored) |
+| `io/api/eventing/dapr.py` | P2 (ack parity: `NO_HANDLER_FOUND` → SUCCESS, `CriticalHandlerError` → DROP) |
+| `handler/event_handler_base.py` | 7 |
+| `handler/handler_chain.py` | P4 (CloudEvent-id dedup before dispatch) |
+| `io/api/scheduling/scheduler.py` | P5 (`scheduler_mode`; timer suppressed in event mode, lease in in-process mode) |
+| `group_config.py` (new), `entrypoint.py` (new) | 8 |
+| `io/telemetry/telemetry.py` | 9 (C2 — per-namespace providers + empty-namespace path) |
+| `io/api/actuators/actuator_api.py`, `io/api/actuators/health.py` | 9 (C3, C4, C7 — gauge and ERROR event on every removal-from-service path) |
+| `clients/io/nats_client.py`, `clients/io/dapr_client.py` | 9 (C7 — done-callbacks on detached tasks; `subscriptions_ready` drives the per-namespace gauge) |
+| `config/config.py` | 3 (C5 — `agent_scope` wiring), 8 (fragment merge), 8b (group defaults + per-agent fragments; process-scope keys raise) |
+| `services/eventing/event_publishing_service.py` | P6 (per-namespace client) |
+
+**Scaffolding tracks the framework, every step.** `blueprint/agent_generator` is part of this
+feature's surface, not a follow-up to it. Any change that adds a config key, alters what a
+generated `settings.toml` must contain, changes what `main.py` or the `Dockerfile` looks like, or
+changes the meaning of a key a generated project already writes, carries a matching
+`agent_generator` change in the same step — templates under `base_files/`, the CLI commands, and
+the generated `claude_docs/CLAUDE.md`. A generated project that no longer matches the framework it
+generates against is a defect, and it is invisible from the framework's own tests.
+
+Known outstanding item from P1: `app_name` now determines the NATS queue group, so it is broker
+consumer identity rather than a display name. The generator writes it (`settings_part_generator.py`)
+and documents it (`claude_docs/CLAUDE.md`), and neither says so; `nats_queue_group` appears in
+neither. The fallback literal `"generated-agent"` in `cli/commands/create.py` is also now a
+collision source between projects that hit it.
+
+**Scaffolding changes (`blueprint/agent_generator`)** -- none of this exists yet:
+
+| Piece | Change |
+|---|---|
+| `asbs create agent-module ` | new; today `asbs setup` scaffolds a whole project, one agent per repo |
+| `asbs dev ` | extend; today hardcodes `src/main.py` and `uvicorn src.main:app` (`cli/commands/dev.py`) |
+| `asbs validate` | extend with the group gates below |
+| `base_files/Dockerfile` | root image for the agent monorepo; `ENTRYPOINT python -m blueprint.agents.entrypoint` |
+| `base_files/src/main.txt` | reduce to the single `registration = ...` declaration |
+| `base_files/settings.txt` | unscoped per-agent fragment |
+
+`asbs dev` runs one agent as a group of one using its **real** namespace, so local routes are
+`/api/order/orders/{id}` — identical to production — and local consumer identity is the production
+queue group. A dev mode at `namespace=""` would give every developer URLs and integration tests
+that differ from production. Consequently `namespace=""` is reserved for pre-migration agents;
+every newly scaffolded agent has a real namespace in every environment.
+
+**Per-agent migration (opt-in only)** — three changes, and no branches in `main.py`:
+- `main.py`: drop the `config` argument from `AppBuilder(...)` and drop the trailing `.build()`,
+ leaving `agent = AppBuilder()...`; add `def create_app(): return agent.build()` only if the agent
+ is still to be served on its own.
+- `Dockerfile`: `CMD uvicorn src.main:app` → `CMD python -m blueprint.agents.entrypoint`.
+- `agents.toml`: add the agent's entry, pointing at `main:agent`.
+
+The dual-branch recipe an earlier draft of this line described is rejected — see *Migration path
+for an existing agent* above and spec sec. 11.
+
+## Testing expectations
+
+New test coverage required alongside the implementation:
+
+- **Registry:** namespace isolation (component in `"order"` not visible from `"invoice"`),
+ two-level fallback resolution, named cache CRUD, executor registry add/get/fallback.
+- **`AppBuilder` / `AgentGroup` (8b):** nothing is constructed or registered until `build()`;
+ `build()` wires at the root; `AgentGroup` wires each agent into the correct namespace and resets
+ the ContextVar after each (no namespace leak between agents); every refusal in spec sec. 4.2's
+ table raises and names the agent; a class, a factory and an instance all work standalone while
+ only the instance is refused in a group; an instance recorded after a class at equal priority
+ raises at `build()`; the declaration surface and `AgentGroup`'s replay agree, so the recorder
+ cannot drift from the API it replays.
+- **Per-agent caches (8b):** two agents both declaring `sessions` get separate stores; an agent
+ reading a cache it did not declare raises rather than falling back to root; `/cache/*` reports
+ only the calling agent's caches.
+- **Settings fragments (8b):** a key in an agent's own `settings.toml` resolves for that agent and
+ is invisible to every other; a group default is served to an agent that declares nothing; a
+ process-scope key in an agent fragment raises at startup.
+- **Handler chain:** namespace-scoped handler selection — handlers registered under
+ namespace A are not invoked when processing events for namespace B.
+- **NATS:** per-namespace subscription closures capture and forward the correct namespace
+ to `process_event`.
+- **Consumer identity (C1):** durable name and queue group are a function of the namespace
+ alone — assert they are byte-identical across two builds where the same agent sits in
+ different groups. This is the test that keeps regrouping cheap; without it C1 rots silently.
+- **Ack lifecycle (P2):** a handled message is acked exactly once; a retryable failure naks; a
+ poison message terms. Regression test that no message is redelivered after a successful handle.
+- **Ack contract (P2):** an event no handler matches is **acked**, not naked — the transport edge
+ behaves identically for `PROCESSED` and `NO_HANDLER_FOUND`, proving it does not read
+ `ProcessingResult`; a payload that fails CloudEvent parsing terms without dispatching; and the
+ Dapr response mapping is asserted against the same outcome table as the NATS dispositions.
+- **Transport lifecycle (P0):** shutdown acknowledges in-flight work before unsubscribing;
+ a reconnect re-establishes JetStream durables without double-acking; `subscriptions_ready` is
+ false until every topic in the map is subscribed.
+- **Idempotency (P4):** the same CloudEvent `id` delivered twice dispatches to the handler once.
+- **Scheduler (P5):** with three simulated replicas a cron job fires once in both modes;
+ `scheduler_mode = "event"` starts no timer and the generated `CronJob` matches the declared schedule.
+- **Telemetry (C2):** each namespace's spans carry `service.name = `, not the group name.
+- **Silent failure (C7):** every path that stops a namespace serving emits an ERROR event and
+ `blueprint_namespace_up{agent} = 0` under that namespace's identity; a namespace whose
+ subscriptions vanish while the process stays healthy is reported; failing a task in each
+ background path produces a logged exception carrying the namespace, never a swallowed one.
+- **Probes (C3):** a degraded namespace never fails liveness; readiness follows
+ `readiness_policy` under all three settings.
+- **Group config (Phase 8):** every declared group resolves, imports and `build()`s without
+ external I/O; an unknown agent name and a duplicate agent across groups both fail loudly.
+- **Config delivery (Phase 8):** file-only, env-only, and both-together all resolve to the same
+ agent list; env vars override the file key by key; a missing `BLUEPRINT_GROUP_CONFIG` path falls
+ back to the repo file; an agent named in the group but absent from `agents.toml` fails at
+ startup with the group and agent name in the message.
+- **Backwards compat:** all existing unit tests pass unchanged with default `namespace=""`. That
+ proves the API still compiles, not that behaviour is preserved — so add both of:
+ - a **frozen compat suite** exercising today's usage patterns, including `with_cache(False)` and
+ `with_cache(True, False)` positionally, never updated to the new API. If it needs editing, a
+ break shipped. **It must include a handler that declares no topics and no event types, and
+ assert it is still evaluated for every event** (spec sec. 7.7, rule 1). That single test is
+ what keeps the dispatch index from silently disabling every pre-existing handler.
+ - a **filter-derivation test** (spec sec. 7.7, rule 2): the derived `filter_subjects` for a
+ namespace is never narrower than its declared topics unioned with `nats_subscriptions`, and an
+ agent declaring `orders.>` still receives `orders.other.created`.
+ - a **generated-project smoke test**: `asbs setup`, then build and start the result unchanged
+ against the new framework version. Catches the Dockerfile and `main.py` paths unit tests miss.
+
+## CI gates
+
+Run against `deployment-groups.yaml` on every change, so a bad grouping fails in CI and not at
+deploy:
+
+- Every agent appears in **exactly one** group per environment. Two groups consuming the same
+ agent is duplicate processing, not a scaling strategy.
+- No duplicate namespace names; no conflicting topic declarations within a group.
+- Every declared group builds (import + `build()`, no external I/O).
+
+Subject-breadth gates (spec sec. 7.7), which constrain projects rather than the framework and so
+**ship as warnings first, errors a release later** — the frozen compat suite covers runtime API
+and would not catch a build that newly fails:
+
+- No handler may declare a bare `>` or a root-level single-token wildcard. A declared subject
+ carries at least domain and entity tokens.
+- Every declared subject is reachable from the publish-side `topic_mapping`, catching typos and
+ orphaned subscriptions at build time — the same error class the unhandled-event counter catches
+ at runtime.
+- Report fan-out per subject: how many namespaces select it. Above a threshold, require an
+ explicit waiver rather than silent acceptance.
+
+---
+
+## Out of scope for this plan
+
+- Multiple simultaneous transport types (e.g. NATS + Dapr in one app).
+- Cross-namespace agent calls (orchestrator → worker patterns).
+- Dynamic namespace registration *after* startup. The group is resolved at process start from
+ `BLUEPRINT_GROUP`; namespaces are not added or removed while the process runs.
+- Ordering guarantees. Competing consumers provide no per-topic ordering; order-dependent work
+ needs a partition key and one subject (and consumer) per partition.
+- Lazy agent instantiation and scale-to-zero — both evaluated and rejected (spec sec. 1,
+ *Non-goals*). Do not re-propose without new measurements.
+
+---
+
+## Planned, not yet written
+
+Decided in discussion but not yet reflected anywhere in the repo. Each is a deliverable, not an
+open question.
+
+**Documentation**
+- `docs/development-workflow.md` — the end-to-end walkthrough: scaffold an agent inside the
+ monorepo, develop it, run it with `asbs dev`, test it, then how it reaches a cluster (CI gates ->
+ one image -> group config -> generated manifests -> pod startup -> regrouping later). The
+ per-piece changes are captured in *Scaffolding changes* above; the narrative is not.
+- `docs/guides/deployment.md` **contradicts this plan and ships today.** It recommends
+ `replicaCount: 2` plus an HPA as normal scaling, documents the multi-replica cache caveat, and
+ says nothing about schedulers (#73) or duplicate event consumption (P1). It also assumes one
+ Deployment per agent. Must be rewritten alongside Phase 8, or it actively misleads.
+- A downstream repo generates `supervisord` config for multi-agent hosts. Under this decision that
+ generator becomes dead code; whoever owns it needs telling.
+
+**Issue hygiene** (nothing has been posted yet — analysis only)
+- Comment the decision on #75 (deployment model: neither Model A nor Model B) and #35 (prefork vs
+ multi-tenant host: multi-tenant host chosen, prefork dropped).
+- Open issues for P1 and P2 — the missing queue group and the never-sent acknowledgement. They are
+ live defects independent of this plan and should not be buried inside it.
+- #32's success metric needs restating: "per-agent RAM" is meaningless once the interpreter is
+ shared. The unit becomes *baseline per group + marginal per agent*, and its "as-is 160-250 MB per
+ agent" row describes the model being retired.
+- #43 (schedulers started twice within one process) should be fixed together with P5 — same code
+ path, and they compound: #43 unfixed plus two replicas gives four ticks.
+- #28 (resilient broker startup) looks delivered by the `event-client-resilience` work; check
+ whether it can be closed.
+- An earlier implementation of P0 exists on `feature/event_handler_retries`. Reconciling it with
+ what lands here is its author's call, and deliberately out of scope for this plan.
+
+**Test environment**
+- **Local NATS and Dapr, exercised as real integration tests.** Every prerequisite and phase here is
+ covered by unit tests against mocked transports, which cannot show queue-group distribution,
+ redelivery after `ack_wait`, durable survival across a reconnect, or a sidecar fetching the
+ subscription document. Once the feature is implemented, stand both brokers up locally (a compose
+ file plus a CI job) and cover what only a real broker exhibits:
+ - queue-group distribution: N replicas, each event handled once (P1);
+ - ack, nak and term, and that a handled message is not redelivered (P2);
+ - `ack_wait` expiry redelivering to another replica mid-handler (P3);
+ - JetStream durables surviving a reconnect, and the ack-retry-on-reconnect spike (P0, P2);
+ - `close()` acknowledging in-flight work before exit (P0);
+ - `filter_subjects` applied to a durable that already exists — in place, or delete-and-recreate,
+ which is the migration question spec sec. 7.7 raises;
+ - the Dapr sidecar fetching `GET /dapr/subscribe` and delivering to `POST /events/{topic}`,
+ including the SUCCESS/RETRY/DROP mapping.
+
+ Blocked on the unit/integration split in #80: `tests/integration/` is not run by CI at all today,
+ so integration tests added now would be invisible.
+
+**Engineering spikes**
+- **Ack-retry-on-reconnect.** Belongs in P0's `_on_reconnected`. Capture the acknowledgement reply subject and re-send after a
+ reconnect, narrowing the duplicate window from "certain on any connection blip" to "only if the
+ pod also dies". Two unknowns make this a prototype rather than a design commitment: a redelivery
+ may already be in flight when the retry lands, and the behaviour of acking a stale delivery
+ attempt depends on how the server keys pending state on stream sequence. **Validate against a
+ real broker before relying on it.**
+- **Consumer-count budget.** One hundred agents times a few subjects each is several hundred
+ JetStream consumers, each carrying ack-pending state. The connection ceiling was closed as a
+ non-issue; this is the analogous number for consumers and is currently an assumption. Measure
+ before committing to per-subject filters at 100 agents.
+- **Marginal RSS per namespace.** Build N namespaces, report the resident-size delta per namespace,
+ reusing #36's benchmark harness. #32 measures ~6 MB per forked child with shared libraries; a
+ namespace has no separate process at all and should come in materially below that. This is the
+ number that retires the lazy-agent idea for good, and it is currently an estimate.
+- ~~**Broker connection ceiling.**~~ Closed, not a spike. 100 agents at 2 replicas is ~200
+ connections against a self-operated broker whose default `max_connections` is orders of magnitude
+ higher, and no authentication is wired today (`nats.connect()` takes URL and reconnect parameters
+ only, `nats_client.py:93`). The number only needs checking where the cap is issued externally per
+ account — a managed broker, or an operator-mode account JWT carrying a `conn` limit. Keep as a
+ deployment note, not an engineering question.
+- **`CronJob` generation.** P5 requires the schedule to stay declared in agent code and the
+ `CronJob` to be generated from it. The generation path is unspecified.
+
+---
+
+## Open questions
+
+Owned by the spec, sec. 13 -- they constrain the design, not the work breakdown, and duplicating
+them here would let the two copies drift. The two that most affect this plan: whether the target is
+20 or 100 agents, and whether the 4 GB host budget is real. Both decide how many groups the
+grouping dial actually has.
diff --git a/docs/plans/2026-09-10-builder-unification.md b/docs/plans/2026-09-10-builder-unification.md
new file mode 100644
index 00000000..c311107e
--- /dev/null
+++ b/docs/plans/2026-09-10-builder-unification.md
@@ -0,0 +1,296 @@
+# Proposal -- One builder, collected into a group
+
+| | |
+|---|---|
+| **Status** | Proposal. Decided in discussion 2026-09-09/10; not implemented. |
+| **Amends** | `docs/specs/2026-08-28-multi-agent-grouping.md` sec. 4.1, 4.2, 8, 11; `docs/plans/2026-08-28-multi-agent-grouping.md` phases 0 (part 3), 3, 6, 8 |
+| **Does not touch** | Configuration validation -- see `2026-09-10-config-validation-unification.md` |
+
+## The problem this solves
+
+Adding one `with_*` method today means editing **four** places:
+
+| Place | If forgotten |
+|---|---|
+| `AppBuilder.with_*` | standalone cannot use it |
+| `AgentRegistration.with_*` | grouped agents cannot declare it |
+| `NamespaceBuilder.with_*` | the block form cannot use it |
+| `AgentRegistration.apply`'s `appliers` dict | `KeyError` at apply time |
+
+Three of those fail **silently** -- the capability simply is not there on that surface. Only the
+fourth is loud. Nothing tells the next developer that the four exist.
+
+The duplication is not an accident of style. `AppBuilder.with_handler(H)` **constructs `H`
+immediately**, and a component constructed before a namespace exists belongs to the root for
+ever -- so a second class had to exist to defer construction until a namespace was in force.
+`AgentRegistration` is that class, `NamespaceBuilder` is the block-form sugar over it, and the
+`appliers` dict is the bridge between them.
+
+**So the fix is not to share the methods -- it is to remove the reason they diverged.** If
+`AppBuilder` records instead of constructing, one class serves both roles and the other two have
+no purpose.
+
+## The shape
+
+### One builder, which records
+
+```python
+class AppBuilder:
+ def __init__(self, config: Config | None = None) -> None: ...
+ def with_handler(self, handler, *, name=None, **kwargs) -> Self: ... # records
+ def with_service(self, service, *, name=None, **kwargs) -> Self: ... # records
+ def with_agent(self, agent, *, name=None, **kwargs) -> Self: ... # records
+ def with_scheduler(self, scheduler, *, name=None, **kwargs) -> Self: ... # records
+ def with_rest_api(self, api, *, name=None, **kwargs) -> Self: ... # records
+ def with_cache(self, enabled=True, enable_locking=True, *, name="default") -> Self: ...
+ def with_health_checker(self, name: str, checker) -> Self: ...
+ def build(self, config: Config | None = None) -> FastAPI: ... # wires, at the root
+ @property
+ def declarations(self) -> tuple[Declaration, ...]: ... # read by the collector
+```
+
+Nothing is constructed until `build()`. `build()` wires everything at the **root namespace**:
+standalone knows nothing about namespaces, which is the decision below.
+
+### A collector, which is a different thing
+
+`AppBuilder` does not know it can be collected. Assembling a group is its own unit -- it takes
+named builders and one configuration, enforces the group's rules, and drives one process-level
+wiring pass:
+
+```python
+def assemble(agents: Mapping[str, AppBuilder], config: Config) -> FastAPI: ...
+```
+
+This is where `with_group` and `from_group` move to, and where every refusal below lives. The
+division is the one the plan already states for phase 8 -- resolution versus wiring, with the I/O
+outside the builder -- extended one step: **group policy is not the builder's business either.**
+
+### Deleted
+
+- `AgentRegistration` -- `AppBuilder` used without `build()` is the declaration.
+- `NamespaceBuilder` and `AppBuilder.with_namespace` -- the collector takes named builders instead.
+- The `namespace=` parameter on the five `with_*` -- it existed only for `NamespaceBuilder`.
+- `AgentRegistration.apply` and its `appliers` dict.
+
+Four duplication sites become **one**. Adding a `with_*` method is one edit, and the collector
+replays whatever was recorded without knowing what it is.
+
+## Decisions
+
+### D1 -- Standalone knows nothing about namespaces
+
+`build()` wires at the root. An agent's name exists only in a group context, so it has exactly
+one home: the group configuration. `main.py` never names its agent, which is what keeps
+*a developer never sees namespaces* true.
+
+**Consequence, already documented:** moving an agent from standalone into a group changes its
+queue group and its JetStream durable, so the first grouped deploy is a consumer migration. See
+the phase 5 migration note.
+
+### D2 -- Standalone is permissive; the group has rules
+
+Everything that works today keeps working standalone. The group refuses what it cannot honour,
+at assembly time, with a message naming the agent and the fix. No deprecation warnings: spec
+sec. 10 makes the standalone shape supported indefinitely, so warning about it every startup
+would be crying wolf, and `DeprecationWarning` is invisible by default anyway.
+
+The refusals follow from what a group *is* -- one process, one configuration, one port, every
+component constructed inside a namespace scope, and no agent deciding for another:
+
+| Recorded call | In a group | Capability lost? |
+|---|---|---|
+| the five `with_*` with a class + kwargs | allowed | -- |
+| the five `with_*` with a factory | allowed; called inside the namespace scope | -- |
+| the five `with_*` with an **instance** | **refused** -- its namespace and registry key were fixed at construction | No: the factory form recovers it |
+| `with_cache(...)` | allowed; name qualified per agent (D3) | -- |
+| `with_health_checker(...)` | allowed; key qualified per agent (D4) | No: a checker is not a `Component` |
+| `AppBuilder(config)` | **refused** -- one process, one settings tree and one port | No, once D5 lands |
+| `build()` already called | **refused** -- already wired at the root | No |
+
+The instance refusal reuses wording that already exists in `AppBuilder._register`; it moves from
+record time to assembly time.
+
+### D3 -- A cache is private to the agent that declared it
+
+An agent has access to **exactly** the caches it declared, and to nothing else. `get_cache(name)`
+resolves within the declaring agent and raises otherwise -- no fallback of any kind. Cache names
+are qualified by namespace, so two agents may both declare `sessions` and get separate stores.
+
+This implements what spec sec. 8 actually requires -- *"Cache names MUST therefore be
+namespace-scoped by default"* -- of which only the data-partition half was ever built.
+
+**Deleted by this decision:**
+
+- `GroupConfig.cache_names` -- there is no shared cache, so a group has none to declare.
+- `AgentScopedCache` -- the partition-prefixing lens exists only to stop two agents colliding
+ inside one shared store, which can no longer happen. Separate stores make the isolation
+ structural rather than dependent on a prefix being applied correctly.
+
+**Knock-ons:** an agent with `idempotency_enabled` must declare `with_cache()` (its existing
+error message already says so), and `/cache/*` becomes per-agent rather than process-wide.
+
+### D4 -- A health checker's key carries its agent
+
+Two agents calling `with_health_checker("db", ...)` currently collide in a dict and one
+disappears silently. The key is qualified by namespace; the root keeps the bare name, so a
+standalone application's `/health/ready` payload does not change.
+
+The attribution is stored **as data** -- `(namespace, name)` -- and the prefix is its rendering.
+Phase 9's `readiness_policy = "critical"` needs to know which agent a failing checker belongs to,
+and recovering that by splitting a string breaks the moment a name contains the separator.
+
+For the record, the current policy this inherits: every checker is polled on a timer and ANDed
+(`health_cache.py:139`), so one unhealthy checker returns 503 for the whole pod. In a group that
+means one agent's outage removes every agent from rotation. That is `readiness_policy = "all"`,
+which phase 9 makes selectable; nothing here changes it.
+
+### D5 -- A group's settings are the defaults; an agent's own file is only its own
+
+- The group's `settings.toml` supplies **defaults, and only defaults**.
+- Each agent ships its own `settings.toml`, merged **under that agent's scope** -- never at root.
+
+Therefore an agent may set any key for itself, and can **never** change what another agent or the
+process sees. There is no collision to detect, because the two never occupy the same slot.
+
+This closes the settings-fragment merge open point outstanding since config rework step 3a; both
+of its unanswered questions dissolve. The one hole to close deliberately: **process-scope keys in
+an agent's file must raise**, from an explicit list (`app_port`, `event_bus`, `envvar_prefix`,
+`nats_stream_name`, ...). Scoped, they would be silently inert -- read by nothing, reported by
+nothing.
+
+### D6 -- `AgentBuilder` records too, and is wired with the agent's own configuration view
+
+`AgentBuilder.__init__` requires a `Config` as its first argument, and `Component._shared_config`
+deliberately has **no public read path**. So in a declaration-only `main.py` there is no
+configuration in scope, and the documented factory form
+
+```python
+.with_agent(lambda: AgentBuilder(config, runtime_name="orders").build())
+```
+
+**cannot be written at all.** That is a live defect in what phase 8 shipped, not a consequence of
+this proposal.
+
+The fix is the same change as for `AppBuilder`: `config` optional in `__init__`, accepted by
+`build()`. An unbuilt `AgentBuilder` is then handed straight to `with_agent`, and the wiring calls
+`agent.build(config)` with **that namespace's configuration view**:
+
+```python
+agent = AgentBuilder(runtime_name="orders").with_model_from_config()
+app_builder.with_agent(agent) # recorded, not built
+```
+
+This deletes the lambda escape hatch for the common case and fixes a second latent bug with it: a
+lambda closes over whichever configuration was in scope where it was written, which in a group is
+the wrong one. Handing the scoped view in at wiring time makes the right one structural.
+
+`with_agent` accepts: a class, an unbuilt `AgentBuilder`, a factory, or -- standalone only -- a
+built `AgentRuntime`.
+
+### D7 -- Group rules are documented on the methods
+
+Each `with_*` docstring states what the group does with it. There is no authoring-time
+validation: every refusal necessarily lands at assembly, because `with_cache()` is called at
+import, long before anything knows whether this builder will be collected. `asbs validate` is
+where authoring-time gates would go if they are ever wanted.
+
+## Behavioural changes to state
+
+**Registration order.** An instance passed to `with_*` is constructed by the caller at its source
+line; a class is constructed during `build()`. So an instance recorded *after* a class registers
+*before* it, which can flip equal-priority handler tie-breaking -- resolved by registration order
+today, as `DispatchIndex.build` already documents. `build()` can detect exactly this case, since
+it knows both the recorded order and which entries were instances, and raise. Order therefore
+still means what it means; the violation surfaces at `build()`.
+
+**Nothing is in the registry until `build()`.** Code that looks a component up between `with_*`
+calls breaks. The framework's own convention already forbids it -- collaborators are resolved in
+`on_startup`, and components must not read configuration in `__init__` -- so the fix is the
+documented pattern.
+
+**`configure_logging()` moves into `build()`.** It runs in `__init__` today so that component
+construction is logged with the right format. With deferred wiring nothing is constructed until
+`build()`, so configuring logging there is strictly more correct.
+
+**A builder is single-use, and says so.** `build()` calls `Component.configure`, which refuses a
+second call -- today that surfaces as someone else's error. It gets its own message.
+
+## Why this is not a Builder anti-pattern
+
+It is the pattern. GoF Builder accumulates parts; `build()` produces the product. What exists
+today is the smell: `with_handler` constructs a component and registers it into a process-global
+registry *during accumulation*, which is exactly why a second class was needed.
+
+The four anti-patterns this design is checked against:
+
+1. **Side effects during accumulation** -- removed; recording only.
+2. **A silently single-use builder** -- made explicit (above).
+3. **Requiring the product's context in the constructor** -- `config` moves to `build()`;
+ remaining in `__init__` only as the compatibility concession.
+4. **Replay drift** -- a recorder can diverge from the API it replays. Mitigated by storing the
+ *method name* and resolving it with `getattr`, which fails loudly, plus a test asserting the
+ builder's declaration surface and the collector's replay agree.
+
+`AppBuilder` is deliberately **not** a composite builder: it never absorbs another builder, and
+does not know it can be collected. Collection is the collector's job, and so are the group's
+rules.
+
+## Migration
+
+Unchanged for an existing project -- spec sec. 10's MUST holds: `AppBuilder(config)...build()` and
+`uvicorn src.main:app` behave exactly as today.
+
+To become groupable, `main.py` drops one argument and splits the last call off:
+
+```python
+agent = AppBuilder().with_service(OrderService).with_handler(OrderHandler)
+
+def create_app(): # uvicorn src.main:create_app --factory --reload
+ return agent.build()
+```
+
+`uvicorn` resolves dotted attributes after the colon (`importer.py`), so
+`uvicorn src.main:agent.build --factory` also works -- and because it is an import string,
+`--reload` works, which `run_app` cannot offer today.
+
+Three shapes, one implementation:
+
+| Shape | Command |
+|---|---|
+| Standalone, today's | `uvicorn src.main:app` |
+| Standalone, migrated | `uvicorn src.main:create_app --factory` |
+| Grouped | `python -m blueprint.agents.entrypoint` |
+
+## Work breakdown
+
+1. `Declaration` value object; `AppBuilder` records; `build(config=None)` wires at the root.
+2. `AgentBuilder` records; `config` optional in `__init__`, accepted by `build()` (D6).
+3. The collector: named builders in, one `FastAPI` out; every refusal in D2; `with_group` and
+ `from_group` move here; the entry point calls it.
+4. Delete `AgentRegistration`, `NamespaceBuilder`, `with_namespace`, the `namespace=` parameter,
+ `apply` and the `appliers` dict.
+5. Caches per agent (D3): qualify names, delete `cache_names` and `AgentScopedCache`, per-agent
+ `/cache/*`.
+6. Health-checker attribution (D4).
+7. Settings fragments (D5), including the process-scope key refusal.
+8. Docstrings (D7); the surfaces-agree test; the frozen compatibility suite that pins the
+ standalone shape.
+9. **The rules, last.** `AGENTS.md` -- the file `CLAUDE.md` already cites and that has never
+ existed -- carrying every principle this overhaul establishes, each with its reason and the
+ failure it prevents; a guard test for each rule a test can hold, including one asserting that
+ every document reference in the repo resolves; and the documentation duplication the audit
+ found cleaned up. Last, because a rule can only describe something that exists. Breakdown in
+ the plan's *Phase 8b step 9* section.
+
+Each step is its own commit, reported before the next begins, per `CLAUDE.md`.
+
+## Explicitly out of scope
+
+- **Configuration validation and its unification** -- `2026-09-10-config-validation-unification.md`.
+- **`readiness_policy` and per-namespace degradation** -- phase 9.
+- **Generating `agents.toml` and the group file** -- parked with manifest generation.
+- **Whether the group's composition should live in `settings.toml` rather than its own YAML.**
+ Raised in discussion and worth doing: the spec's justification for a separate mechanism is that
+ resolution happens "before `Config` is constructed", and it does not -- the entry point builds
+ `Config` first and passes it in. Deferred so that this proposal changes one thing at a time.
diff --git a/docs/plans/2026-09-10-config-validation-unification.md b/docs/plans/2026-09-10-config-validation-unification.md
new file mode 100644
index 00000000..1fdf4c8b
--- /dev/null
+++ b/docs/plans/2026-09-10-config-validation-unification.md
@@ -0,0 +1,159 @@
+# Proposal -- One startup pass that says everything the configuration is missing
+
+| | |
+|---|---|
+| **Status** | Proposal. Raised in discussion 2026-09-10; not implemented, not scheduled. |
+| **Relation to the grouping work** | **None. Do not touch this during the builder rewrite.** Explicitly carved out of `2026-09-10-builder-unification.md`. |
+| **Intended to be** | Non-breaking: the set of keys that must exist does not change. |
+
+## Why this is separate
+
+The builder rewrite changes *where* configuration is handed in (`build(config)` instead of
+`__init__`) and *how* an agent's fragment is merged. It does not change what happens when a key is
+missing -- and it should not, because the two would then fail together and neither could be
+reviewed on its own. This document is the second half, kept apart on purpose.
+
+## What exists today
+
+There are **four** unrelated mechanisms deciding what happens when a setting is absent, and they
+disagree about whether that is an error, a default, or nothing at all.
+
+### 1. Three Dynaconf validators that cannot fail
+
+`config.py:161-168` declares `app_name`, `app_port` and `app_environment` with
+`must_exist=True` -- and with `default=`. Verified against the installed Dynaconf:
+
+```
+Validator("app_name", must_exist=True, default="agent_blueprint") -> 'agent_blueprint'
+Validator("app_name", must_exist=True) -> ValidationError
+```
+
+When a default is present it is injected and `must_exist` never fires. So of the three
+declarations, the only condition that can actually fail is `is_type_of=int` on `app_port`. An
+application with no `settings.toml` at all starts, and calls itself `agent_blueprint`.
+
+That is a defensible policy -- these three have sensible defaults. It is not defensible that the
+code says `must_exist=True`, because the next person to add a genuinely required key will copy the
+pattern and get a silent default.
+
+### 2. `Config.validate()`, whose two real checks run somewhere unreachable
+
+`validate()` (`config.py:836`) is called from `Config.__init__` (`config.py:187`) and **raises**
+`ConfigError`. Beyond the validators it checks two things by hand: `app_port` in range, and an
+API key when the provider is `vllm`.
+
+Because it raises during construction, a `Config` object that exists has always passed. Therefore
+`_validation_errors` is always empty on any live instance, and the two places that read it --
+`actuator_api.py:95` in readiness and `actuator_api.py:149` in liveness -- are **dead branches**.
+The readiness probe was written to report configuration failure as a 503 with the reasons in the
+payload; it cannot, because the process never reaches the point of serving. Worth deciding
+deliberately which of the two behaviours is wanted rather than leaving both in the tree.
+
+### 3. Typed getters that turn a missing key into a default, silently
+
+`get_ai_config`, `get_cache_config`, `get_observability_config`, `get_event_publishing_config`,
+`get_prompt_config`, `get_runtime_config`, `get_nats_subscription_config` each read keys with
+`self.get(key, )` and hand back a Pydantic model. A typo'd or absent key is
+indistinguishable from one deliberately left out: the model is fully populated either way.
+
+This is where a missing *required* setting hides longest, because the value only turns out to be
+wrong much later, in a component, as a connection failure or an empty result.
+
+### 4. Per-component checks, each at a different moment
+
+| Check | Where | When it fires |
+|---|---|---|
+| `model_name`, `provider`, provider supported | `agent_builder.py:108-114` | declaration time, in `main.py` |
+| `sessions_service` present, `base_url`, `agent_id`, `api_key` | `sessions_bus.py:88-107`, `api_client.py:50-58`, `key_provider.py:71-185` | first connect |
+| `idempotency_ttl` numeric | `handler_chain.py:563` | first event |
+| `scheduler_mode` in range | `scheduler.py:352` | startup |
+| any numeric NATS key | `nats_client.py:444-451` | on read |
+
+Each message is good in isolation -- most name the key and the accepted values. The problem is the
+aggregate: a deployment missing three keys is fixed in three deploy cycles, because each failure
+hides the next, and some of them wait for the first request.
+
+## What to build
+
+### One declaration point
+
+A component declares what it needs, next to the code that reads it:
+
+```python
+class SessionsBus(ApiBase):
+ required_config = (
+ Required("sessions_service.base_url"),
+ Required("sessions_service.agent_id"),
+ Required("sessions_service.api_key", secret=True),
+ Required("sessions_service.max_concurrent_jobs", default=10, is_type=int),
+ )
+```
+
+`secret=True` keeps the value out of the message: a validation error may say the key is missing,
+never what it holds.
+
+### One pass, reporting everything at once
+
+At the end of `build()`, after every component is registered and each one's namespace is known,
+one pass walks the declarations, resolves each key **through that component's own configuration
+view**, and collects failures. If there are any, it raises once:
+
+```
+Configuration is incomplete. 3 required settings are missing or invalid:
+
+ billing.sessions_service.agent_id missing required by SessionsBus (agent 'billing')
+ orders.idempotency_ttl not an int required by HandlerChain (agent 'orders'), got 'thirty'
+ cache.redis_host missing required by RedisCacheService (agent 'orders')
+```
+
+Three properties this needs to have:
+
+- **Every failure, not the first.** That is the whole point.
+- **The agent named.** In a group, "missing `sessions_service.agent_id`" does not say whose, and
+ D5 of the builder proposal makes each agent's fragment its own -- so the answer is per agent.
+- **Before the port is bound.** Same rule as the group resolution failure in `entrypoint.main`:
+ a pod that binds its port has told Kubernetes it is a healthy replica.
+
+### Keep the required set exactly as it is
+
+The migration risk here is entirely in scope creep. Declaring a key required that today has a
+silent default breaks a running deployment at its next restart, and it will not be obvious that a
+configuration-validation change did it. So the first implementation transcribes what the four
+mechanisms require **today** and nothing more:
+
+- The three root validators keep their defaults, declared as defaults rather than as
+ `must_exist=True`.
+- Every check in mechanism 4 keeps the same condition, moved to a declaration.
+- The typed getters' defaults stay defaults.
+
+Anything that *should* become required is a second, separate change with its own migration note.
+
+### Decide what the actuator reports
+
+Once the pass exists, the dead branches resolve one way or the other:
+
+- **Fail the process** (today's actual behaviour): drop `has_validation_errors`,
+ `get_validation_errors` and both actuator branches. Simplest, and matches
+ "a misconfigured pod must not serve".
+- **Fail readiness** (what the actuator was written for): keep the errors as data, serve
+ `/health/live` as UP and `/health/ready` as 503 with the reasons, and let an operator read them
+ from the probe rather than from pod logs.
+
+The second is more useful in a cluster and is what the code intends; the first is what the code
+does. Not decided here.
+
+## What this does not cover
+
+- `models/config.py`'s topic-mapping parser, which validates *shape* rather than presence and is
+ already loud and well-tested.
+- Making anything newly required (above).
+- `asbs validate`, which could run the same pass at authoring time once it exists -- worth doing,
+ but after.
+
+## Sequence, when it is picked up
+
+1. `Required` value object and the `required_config` class attribute; no behaviour change.
+2. The startup pass, reporting collected failures, wired into `build()`.
+3. Transcribe mechanisms 1, 2 and 4 into declarations; delete the hand-written checks as each is
+ covered by a declaration and a test.
+4. Decide the actuator question and remove whichever half loses.
diff --git a/docs/plans/2026-09-11-broker-integration-tests.md b/docs/plans/2026-09-11-broker-integration-tests.md
new file mode 100644
index 00000000..a7b72e38
--- /dev/null
+++ b/docs/plans/2026-09-11-broker-integration-tests.md
@@ -0,0 +1,441 @@
+# Broker integration tests
+
+| | |
+|---|---|
+| **Status** | Steps 0-3 verified against a real broker, plus chores 1-3. |
+| **Why** | Everything the multi-agent work claims about delivery was unit-tested against **mocked transports** and had never been watched against a real broker. Steps 0-3 and chores 1-3 now have been; the rest of *Chores* has not. |
+| **Scope** | NATS. Dapr needs a sidecar rather than a broker and is a chore below. |
+| **Depends on** | #80, the unit/integration split -- settled in step 0, because `tests/integration/` was not run by CI and sat at 29 failures. |
+| **Related** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md`, whose *Open points* names what only a real broker can settle. |
+
+This document is both the plan and its running record, the way the grouping plan and its changelog
+are. It is **not** a phase of that plan: the grouping feature is complete and pushed. This is the
+list of things that feature asserts and nobody has yet verified.
+
+## The constraint that shapes how this is written
+
+Docker is on this machine, but **only the developer can reach it**. The tests are written here and
+**run by the developer**, who pastes failures back. That makes every step smaller than it would
+otherwise be, and makes the harness's first job to fail loudly and readably when the broker is
+absent -- every round trip costs a message, so a test that fails obscurely costs two.
+
+The second constraint follows from it: **a broker test must skip, not fail, when the broker is not
+there.** An offline run of the whole suite stays green, and `-m integration` is how you ask for the
+tests that need something running. This is not a formality: writing it the obvious way produced a
+suite that *hung* offline rather than skipping, which is recorded in step 1 below.
+
+## Plan
+
+- **Step 0 -- the unit/integration split (#80).** Landed. See below.
+- **Step 1 -- the harness.** Landed and green against NATS. See below.
+- **Step 2 -- the path, end to end.** Landed and green. See below.
+- **Step 3 -- the acknowledgement lifecycle.** Landed and green. See below.
+
+## Chores
+
+Recorded rather than built, so they are not rediscovered. Each is something only a real broker or a
+real cluster can answer.
+
+### Broker behaviour still unwatched
+
+- ~~**Queue-group distribution across replicas.**~~ **Done.** Two application instances sharing one queue group:
+ one delivery per message, not two. This is the claim that makes `replicaCount > 1` safe, and it
+ is the one P1 rests on.
+- **A durable surviving reconnect.** Kill the connection mid-stream and assert nothing is
+ redelivered that was already acked, and everything unacked is.
+- ~~**The shutdown drain.**~~ **Done.** In-flight handlers finish and their acknowledgements arrive *before* the
+ connection closes -- the ordering P0 fixed, and the one that makes duplicates certain on every
+ deploy when it is wrong.
+- **Overlapping subjects in one queue group.** A wildcard and a literal it covers, both subscribed
+ by one agent, one message matching both. `nats-server` is expected to merge the subscriptions and
+ deliver once; if it does not, the agent sees the event twice and P2 acks both copies as ordinary
+ work, which changes what P2 has to handle.
+- **`filter_subjects` on a durable that already exists**, and what the server does with an
+ `add_consumer` whose configuration differs from the durable already there.
+- **Whether `msg.metadata.num_delivered` lines up with `max_deliver`** the way the dead-letter
+ trigger assumes.
+
+### Grouping, against a real broker
+
+- ~~**C1 by observation.**~~ **Done.** Two agents in one `AgentGroup` on one NATS: each sees only its own topics,
+ and the durable and queue-group names are byte-identical to the same agent deployed alone. The
+ unit tests assert the names; this would assert the consequence.
+- **The scheduler tick claim across real processes.** Three replicas in separate processes sharing
+ one `DiskCacheService` directory -- whether `diskcache-rs` file locking actually makes `add`
+ atomic across processes -- and Redis `SET NX` under real contention.
+- **A `CronJob` tick delivered to exactly one replica** through the queue group, and what a
+ `CronJob` restart or a missed `startingDeadlineSeconds` actually produces.
+
+### Infrastructure
+
+- **A CI job.** NATS as a GitHub Actions service container, running `-m integration`. Until it
+ exists these tests are local-only, which is a smaller version of the problem #80 describes.
+- **Dapr.** Needs the sidecar, not just a broker: the discovery document actually fetched, and
+ deliveries arriving at `/events/{topic}`. Roughly doubles the harness, and is why it is not in
+ the plan above.
+- **Redis under contention**, for the dedup `exists`-then-`set` window and the tick claim.
+
+### Found on the way, not fixed
+
+- **`examples/webhook_relay` cannot start against a real NATS.** It sets `event_bus = "nats"` and
+ `app_name = "Webhook Relay"`; `app_name` is the root namespace's queue group since P1, and
+ `validate_subject_segment` rejects whitespace -- so `_resolve_queue_group` raises at subscribe
+ time. Confirmed by calling the validator directly. Four other examples carry a spaced `app_name`
+ and are latent rather than broken, because they use Dapr or no bus at all. The examples are
+ deliberately untouched by this work; this is exactly the kind of thing step 2's harness would
+ catch if it were pointed at them.
+
+---
+
+## Changelog
+
+### Chores 1-3 -- grouping observed, replicas, and the shutdown drain
+
+Three of the *Chores* below, done as tests rather than left as notes.
+
+#### C1 by observation (`test_grouped_agents.py`)
+
+Two agents in one process on one broker and one stream. The unit tests assert the *names* the
+framework derives; these assert the consequence:
+
+- an event on one agent's topic reaches that agent and not its neighbour, with both subscribed at
+ the same time -- and in both directions at once, so the test cannot pass by one agent being idle;
+- the queue group is the **agent's name**, not the group's: `AgentGroup("integration", ...)` is the
+ deployment, and nothing broker-side carries it, or moving an agent to another group would move
+ its queue group with it;
+- two agents subscribing to **the same subject** get a durable each, and both receive the event.
+ Sharing a durable would make them one consumer splitting the messages, so each agent would see
+ half its own events -- the failure P1 and P6 exist to prevent;
+- the same agent, hosted alone and hosted beside a neighbour, presents byte-identical names. If
+ they differed, regrouping would strand an agent's backlog on a consumer nothing binds to any
+ more: a migration rather than a deployment change.
+
+#### Replicas and the shutdown drain (`test_delivery_once.py`)
+
+The second replica is a raw nats-py subscription bound to **the names the framework derived** --
+its deliver subject, its queue group -- rather than a second interpreter. That is the sharper
+test: a real replica is identical to the first, so what makes distribution work is that both bind
+the *same* names. Six messages, two binders, six deliveries in total rather than twelve.
+
+The drain is three tests, because "it works" is three claims: an in-flight handler **finishes**
+when shutdown begins; its acknowledgement **reaches the broker before the connection closes**
+(`num_ack_pending == 0`, read after the lifespan has ended); and a second process started on the
+same durable is **not** given the message again. Any one of them false makes a rolling deploy
+produce duplicates.
+
+#### A false alarm, found by the harness itself
+
+Every run logged:
+
+```
+ERROR JetStream stream '...' does not carry subject(s) [...] and could not be updated
+ (subject "it....>" overlaps with "it....orders.created");
+ consumers filtering those subjects will fail to bind
+```
+
+and the consumers bound perfectly well. `_provision_stream` computed the subjects to add with a
+**set difference**, so a stream an operator provisioned as `orders.>` looked as though it were
+missing every literal underneath it. The client asked the server to add them, the server refused
+the overlap, and the client then predicted a failure that does not happen -- on every connect, to
+any deployment whose stream uses a wildcard.
+
+New `subject_is_covered_by` in `io_client_base.py` does the NATS match instead (`*` is one token,
+`>` is one or more and only last), and `missing` is computed with it. Nine parametrised cases pin
+the matcher, including the two easy ones to get wrong: `orders` is **not** covered by `orders.>`,
+and `orders.created.eu` is not covered by `orders.*`.
+
+#### One fixture bug, worth recording because it looked like a framework hang
+
+`nats_app` and `nats_group` reset the process-global registry so a test can start a second
+process. Put *inside* the lifespan, that cleared the components while shutdown was still running
+-- and a shutdown draining an in-flight handler then never returned. It read as the framework
+hanging; a standalone probe showed the real drain completing in 1.5s. The reset is now in a
+`finally` around the whole `async with`.
+
+### Step 3 -- the acknowledgement lifecycle
+
+`tests/integration/test_acknowledgement_lifecycle.py`. Spec sec. 7.2 fixes one outcome table for
+every transport; the unit tests assert the framework *decides* the right disposition, and these
+assert the broker then *does* it. Five groups, one per row of the table:
+
+- a `RetryableHandlerError` naks and the same event id reaches the handler again after
+ `nats_ack_wait`, with `num_redelivered` confirming it from the broker's side;
+- `CriticalHandlerError` and `InvalidEventError` term -- delivered once, and still once after the
+ ack-wait window has passed, which is the only way to tell a term from a slow nak;
+- an event **no handler matches is acknowledged**, not naked. Finding no work in an event is a
+ normal outcome, and naking it would put a message nobody wants back on the queue for ever;
+- a payload that is not a CloudEvent is termed **without being dispatched**, and dead-lettered
+ with its bytes unchanged -- there is no event id for the header, because nothing parsed;
+- `nats_max_deliver` exhaustion stops the handler being called and dead-letters with
+ `deliveries-exhausted` rather than `terminal-failure`, because a broken handler and a rejected
+ event are different operational problems.
+
+`nats_ack_wait` is 2s in `integration_config`, which is what makes the redelivery assertions
+affordable; the two "it did *not* come back" tests each wait two windows.
+
+**Green on the first run against a broker**, having been written entirely from the client's
+source with no broker available. All five rows of the disposition table hold as specified.
+
+### Step 2 -- the path, end to end
+
+`tests/integration/test_event_path.py`. Four claims, each read off the **server** rather than off
+the framework's account of itself: the handler receives what was published; its `HandlerResult`
+reaches the subject `event_publishing.topic_mapping` names, as a new CloudEvent with its own id
+and `app_name` as its source; the inbound message is acknowledged, with `num_ack_pending == 0` and
+the ack floor advanced; and **it is not redelivered once `nats_ack_wait` has passed**.
+
+That last one is the test a mock cannot write. An unacknowledged JetStream message comes back
+after `ack_wait` -- 2 seconds here -- so waiting the window out and finding the handler called once
+is the acknowledgement working. `num_ack_pending == 0` alone would pass against a consumer that
+had acked and then been redelivered for some other reason, so both are asserted.
+
+The test watches the outbound subject over **Core NATS**, not with a JetStream consumer of its
+own: a durable would be broker-side state to tear down, and would bind to the same stream the
+application's consumer is on.
+
+#### The framework's stream did not cover the subjects it publishes to -- now fixed
+
+The finding, and it is a live defect rather than a test-shaping detail. `_stream_subjects` returns
+the subscribed topics, their `.>` forms, and the dead-letter subject. **A subject a handler result
+is published *to* is not among them.** Probed against the broker, with the framework left to
+provision its own stream:
+
+```
+stream subjects: ['blueprint-it.dead-letter', 'itdfbb736c0a.in', 'itdfbb736c0a.in.>']
+outbound covered: False
+ERROR Failed to publish event to topic 'itdfbb736c0a.out': nats: timeout
+WARNING Failed to publish handler event: nats: timeout
+```
+
+Three consequences, in order of how long they would take to find:
+
+- **The publish stalls.** `js.publish` waits for a stream acknowledgement that no stream will
+ send, so every outbound event costs the JetStream publish timeout before it gives up.
+- **The event is not persisted.** A Core NATS subscriber *does* see it -- a JetStream publish
+ still puts the message on the subject -- so a live listener looks fine while a downstream
+ JetStream consumer receives nothing, which is the worst version of this to debug.
+- **The failure is a WARNING.** `EventPublishingService.publish_handler_event` catches every
+ exception and logs; the handler has already returned, so its inbound message is acked and the
+ result is simply gone.
+
+Was stated as `test_the_outbound_subject_is_covered_too`, `xfail(strict=True)`. **Closed**: the
+client now declares its publishable subjects and the stream carries them -- see the grouping
+changelog's *Publishing is its own decision, and its subjects are declared*. The marker is gone
+and the test is an ordinary one. The rest of step 2 still requests the `jetstream` fixture, which
+is what a deployment with an operator-provisioned stream looks like.
+
+#### The harness had a collision of its own
+
+Every test used one `app_name`, so every test's client derived the same queue group and therefore
+the same default dead-letter subject, `blueprint-it.dead-letter` -- which the client puts into the
+stream it provisions. Two tests' streams then claim one subject and the second is refused:
+
+```
+BadRequestError: code=400 err_code=10065 description='subjects overlap with an existing stream'
+```
+
+Found by leaving a stream behind when a probe crashed and starting the next one. `nats_queue_group`
+is now per test, so the dead-letter subject falls inside that test's own prefix. `nats_ack_wait`
+dropped from 5s to 2s at the same time, so a test that waits the redelivery window out costs three
+seconds rather than six.
+
+### Step 1 -- the harness
+
+Four files: `tests/integration/docker-compose.yml`, the fixtures in `conftest.py`, `helpers.py`,
+and `test_harness.py`, which tests the harness itself before anything is tested with it.
+
+**The services.** NATS with JetStream and Redis, both published on localhost because the tests run
+on the host:
+
+```yaml
+command: ["--jetstream", "--store_dir=/tmp/nats", "--http_port=8222"]
+```
+
+`--jetstream` is not optional: without it the server accepts the connection and refuses the stream,
+every subscription falls back to Core NATS, and steps 2 and 3 would be asserting redelivery and
+`max_deliver` against a transport that has neither. **No volumes, deliberately** -- JetStream state
+lives in the container and dies with it, so `down` then `up -d` is a clean broker. A durable
+remembers its filter subject and its delivery count, so a leftover one can make a redelivery test
+pass against last week's consumer.
+
+**Isolation per test.** `subject_prefix` is a fresh `it` per test and every subject goes
+under it; `jetstream_stream` yields `IT_` and **deletes the stream afterwards** -- which
+deletes its consumers with it. The fixture deliberately does *not* create the stream: the framework
+creates its own in `_ensure_stream`, and a test of that behaviour has to watch it happen.
+
+**The application fixture waits for the subscriptions.** `NATSClient.subscribe()` returns
+immediately and connects in a background retry task, so at the moment the lifespan returns the
+agent is typically not yet on its topics. A test that published there would be asserting on a
+race -- JetStream would hold the message and it would usually pass, Core NATS would drop it and it
+would usually fail, and neither outcome would be about the thing under test. So `nats_app` enters
+the lifespan directly (not through `TestClient`, which would run it on a second event loop in a
+background thread) and then blocks on `subscriptions_ready`.
+
+**The offline path had to be fixed before it worked at all, and this is the useful finding.** The
+obvious probe -- `nats.connect(...)`, catch, skip -- **hangs**. Two behaviours combine:
+`localhost` resolves to `::1` first on Windows, an unreachable IPv6 port drops the SYN rather than
+refusing it (`netstat` shows the connection sitting in `SYN_SENT`), so the attempt stalls for the
+whole `connect_timeout`; and nats-py then retries the initial connect **indefinitely**, because
+`max_reconnect_attempts` governs re-connection and not the first one. An offline `pytest
+tests/integration` sat there until it was killed. The probe is now a bare TCP `open_connection`
+under `asyncio.wait_for` -- no protocol handshake, no retry loop, a deadline the fixture owns --
+and the default URL is `nats://127.0.0.1:4222` rather than `localhost`. `nats_connection` also
+passes `allow_reconnect=False`, so a broker that disappears mid-run fails the test that noticed
+instead of parking it in the reconnect loop.
+
+Offline, the whole directory now skips in about a second, and every skip names the command:
+
+```
+SKIPPED [1] tests/integration/test_harness.py:59: No NATS server at nats://127.0.0.1:4222.
+ Start one with: docker compose -f tests/integration/docker-compose.yml up -d
+```
+
+**What `test_harness.py` asserts.** The broker (a Core NATS round trip, and that JetStream is
+enabled); the isolation (a stream is this test's own, and no `IT_` stream from an earlier test
+survived its teardown); and the application -- it connects and reaches `subscriptions_ready`, its
+client reports healthy, its queue group is the agent's identity, the framework creates the stream
+it was told to use and covers the subscribed subject, and an event published from outside the
+process reaches a handler inside it with no handler left in flight. That last one is step 2 minus
+the acknowledgement and the outbound result, and it is here so that a step-2 failure reads as being
+about those rather than about whether anything arrives at all.
+
+Also fixed in passing: `test_shared_redis_cache.py` pointed at a `docker run` command instead of
+the compose file, and its skip message carried a non-ASCII em-dash that rendered as a replacement
+character in the terminal.
+
+**Verified.** `nats:2.10-alpine` accepted the compose file, and all ten harness tests passed on
+the first run against it -- including the three that were most likely to be wrong, since they were
+written from the client's source rather than from a run: JetStream's reported subject list matching
+what the stream was created with, `_ensure_stream` creating the stream and covering the subscribed
+subject, and an event published from outside the process reaching a handler inside it. The whole
+directory runs in **29 seconds**.
+
+#### The one failure was a pre-existing test, and not about Redis
+
+`test_shared_redis_cache.py::test_two_processes_share_cache` failed the moment Redis was actually
+running -- it had skipped for its whole life, so its first real run was this one:
+
+```
+subprocess.TimeoutExpired: Command '[...python.exe, -c, "...RedisCacheService..."]'
+ timed out after 10 seconds
+```
+
+The subprocess spends its budget **importing the framework**, not talking to Redis: measured at
+**11.5s cold** for `from blueprint.agents.services.infrastructure.redis_cache_service import
+RedisCacheService`, which pydantic-ai dominates. Ten seconds was below the floor. Three fixes in
+`_run_reader`:
+
+- `IMPORT_BUDGET_SECONDS = 60`, named for what it actually pays for, with the measurement recorded
+ next to it.
+- `TimeoutExpired` becomes an `AssertionError` that says it is an import-speed problem. The failure
+ was a `subprocess.py` traceback pointing at nothing in this repository.
+- **A non-zero exit carrying stderr now fails with that stderr.** The child exits 1 for a genuine
+ cache miss, and every other error was being swallowed into the same `return None` -- so a broken
+ reader was indistinguishable from an empty cache, and reported as `read None, expected {...}`.
+
+It is the same lesson as the 29th failure in step 0: a test that has only ever skipped is a test
+whose first real run is a first draft.
+
+### Step 0 -- the unit/integration split, settled (#80)
+
+**The prerequisite, and the reason it is one.** `tests/integration/` was **not run by CI at all**
+(`ci.yml` and `publish.yml` both run `tests/unit`), so a broker test added there would have been
+invisible; and the directory sat at **29 failures**, so a new red line in it would have meant
+nothing. Neither is a thing to build on.
+
+The split was enforced three ways at once and agreed with itself in none of them: CI selected by
+**directory**, the `integration` marker was applied **by hand** to three tests out of roughly sixty,
+and everything else in `tests/integration/` was unmarked -- so `pytest -m "not integration"`
+deselected three tests and then failed 28. Two tests in there carried comments explaining that they
+were deliberately *not* marked because they were offline, which is a contributor documenting the
+confusion in place rather than fixing the category.
+
+**One rule now: a test in `tests/integration/` requires an external service.** New
+`tests/integration/conftest.py` applies the marker by location:
+
+```python
+def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:
+ for item in items:
+ if INTEGRATION_ROOT in Path(str(item.fspath)).parents:
+ item.add_marker(pytest.mark.integration)
+```
+
+Directory and marker can no longer drift apart, and nobody has to remember a decorator. The half
+that cannot be enforced -- that a test needing nothing does not belong there -- is stated in the
+module docstring and in `AGENTS.md`, and the two tests that were in the wrong place were **moved
+out rather than marked**.
+
+#### What moved, and what was deleted
+
+`tests/integration/examples/test_examples.py` asserted on seven example projects, **four of which
+were deleted from `examples/` over a year ago**. It imports only `pytest`, `pathlib` and `tomllib`:
+it never starts a process or opens a socket, so it is a repository-consistency check that had been
+filed as an integration test and therefore never run. Rewritten as
+`tests/unit/examples/test_example_structure.py`, where CI runs it.
+
+**The list is derived from the directory now, never hardcoded** -- that is the whole lesson of #80.
+The two directories that are not projects are listed with the reason, in the `KNOWN_GAPS` style this
+repository already uses, and a case asserts each listed one is *still* not a project so the
+allowlist cannot outlive its entries:
+
+- `shared_cache_demo` -- standalone demo scripts plus a README, illustrating the cache API. No
+ declaration and no settings, because it is not an application.
+- `customer_support_qa` -- a skeleton left by an earlier refactor: `src/api`, `src/handlers`,
+ `src/models` and `src/services`, but no `main.py`, no `settings.toml` and no `README.md`.
+
+Per project it checks what a reader needs before they can run it: a `main.py` (at the root or under
+`src/`, both shapes are in use), a `settings.toml` that parses and names the application, and a
+`README.md`. The five real projects pass.
+
+Two 1-line files were deleted rather than carried: `tests/integration/test_blueprint_integration.py`
+and `tests/integration/examples/test_example_startup.py`, both reading
+`# Tests removed -- to be recreated after architecture refactor`. The refactor happened.
+
+Two genuinely offline tests moved into `tests/unit/`, where their own comments said they belonged:
+
+- `test_sessions_startup_resilience.py` -> `tests/unit/agents/io/api/eventing/`. It binds and
+ releases a loopback port to guarantee ECONNREFUSED, which is offline by construction.
+- `test_scheduler_event_mode.py` -> `tests/unit/agents/io/api/scheduling/`.
+
+`test_shared_redis_cache.py` stays: it genuinely needs Redis, and skips cleanly without it.
+
+#### The 29th failure was a phase 9 regression nobody had recorded
+
+The changelog carried "the 28 pre-existing failures in `tests/integration/examples/`". There were
+**29**, and the extra one was not in `examples/`:
+`test_scheduler_event_mode.py::test_event_mode_tick_arrives_as_an_event` answered `RETRY` where it
+asserted `SUCCESS`.
+
+The chain: the test builds a Dapr application; the Dapr client's health check probes
+`localhost:3500` for a sidecar that is not there; the check fails; phase 9's namespace supervisor
+degrades the root agent and **pauses its transports** (C4); and the paused fan-out declines the
+tick. Every link is working as designed -- and the test's own docstring, "nothing here reaches the
+network", had quietly become false when phase 9 gave that health check a consequence.
+
+Worse than failing: it was **environment-dependent**. The result turned on whether anything happened
+to be listening on port 3500, so it would have passed for a developer with a sidecar running.
+
+Fixed in the test, with the framework's own switch rather than a patch:
+
+```toml
+health_check_dapr = false
+```
+
+The delivery path needs no sidecar; only the health check reaches for one. Turning that probe off
+is what makes the test offline again, and deterministic. A new rule in `AGENTS.md` states the
+general form: *a test that reaches for a service it does not need is not offline, it is lucky.*
+
+#### Result
+
+| | Before | After |
+|---|---|---|
+| `pytest tests/ -m "not integration"` | 28 failed, 990 passed | **passes**, 2924 collected |
+| `pytest tests/` | 29 failed | **passes** (3 Redis tests skip) |
+| `tests/integration/` contents | 6 files, 2 of them 1-line stubs, 1 asserting on deleted examples | 1 file, which needs Redis |
+
+`CLAUDE.md`'s test commands were corrected -- it documented
+`uv run pytest tests/ -m "not integration"` as "skip integration tests", which was not what that
+command did -- and `AGENTS.md` gained the two rules above.
+
+**Not done here, deliberately:** no CI job runs `-m integration`. That belongs with the harness
+that gives it something to run, and is listed under *Chores* below.
diff --git a/docs/plans/2026-09-28-grouped-http-surface.md b/docs/plans/2026-09-28-grouped-http-surface.md
new file mode 100644
index 00000000..a283e1ae
--- /dev/null
+++ b/docs/plans/2026-09-28-grouped-http-surface.md
@@ -0,0 +1,119 @@
+# Plan -- A Grouped Agent's HTTP Surface
+
+| | |
+|---|---|
+| **Amends** | `docs/specs/2026-08-28-multi-agent-grouping.md` -- sec. 11.2 (added in step 0) |
+| **Changelog** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` |
+| **Branch** | `feature/multi-agent-namespaces` |
+| **Decided** | 2026-09-28 |
+
+Worked in reviewable steps like the rest of the grouping feature: one step, then a report, then
+the next.
+
+---
+
+## Problem
+
+A grouped image's Swagger UI is unusable for the question every reader starts with -- *which
+agent do I want to look at?*
+
+- **Most operations sit under "default".** `AppBuilder._mount` rewrites the tags of a namespaced
+ component's routes, but only of routes that already carry one (`if isinstance(route, APIRoute)
+ and route.tags`). A developer's untagged route keeps `[]`, and FastAPI files it under "default",
+ mixed with every other agent's untagged routes.
+- **An agent's tagged groups are scattered.** Tags are rendered `.` (`orders.nats`,
+ `orders.cache`), and Swagger UI lists tags in the order it first meets them, so one agent's
+ groups interleave with another's and with "default".
+- **Paths have no consistent second level.** Cache routes already carry `cache/`, the scheduler
+ trigger carries the scheduler's name, NATS publish carries nothing (`/api//events/{topic}`),
+ and a developer's routes carry whatever they declare.
+
+## Decisions
+
+1. **One Swagger group per agent.** In a group, every operation of agent `orders` carries exactly
+ the tag `orders`, replacing whatever was declared -- the framework's tags and the developer's
+ alike. No grouped agent's operation is ever untagged.
+2. **The second level is the path, not the tag.** Swagger UI renders tags on one level only, so a
+ sub-grouping is expressed as `/api///...`. Within one agent's group Swagger lists
+ operations in registration order, which clusters them by segment without a sorter setting.
+3. **Framework segments are reserved.** `nats`, `cache` and `scheduler` belong to the framework
+ inside an agent's prefix:
+ - NATS publish: `/api//nats/events/{topic}`
+ - Scheduler trigger: `/api//scheduler//trigger`
+ - Cache: `/api//cache/*` (unchanged -- its routes already carry `cache/`)
+4. **Standalone apps are untouched.** Every rule above applies only to a component with a
+ namespace. A standalone agent (root namespace) keeps the tags the framework and the developer
+ declare today -- including "default" for untagged routes -- and every path it serves.
+ Root components of a grouped app (`root`, `actuators`, `dapr`) are process-wide and keep theirs.
+5. **A developer's own prefix is optional.** A developer may declare a path prefix on their API
+ class; it applies in both modes, so an agent's code is identical standalone and grouped. It is
+ not required: an existing agent joins a group without a code change. What *is* enforced, in a
+ group only, is that no developer route starts with a reserved segment.
+6. **Rejected: `x-tagGroups`.** A ReDoc vendor extension that Swagger UI ignores; once present,
+ ReDoc hides every tag not placed in a group. Revisit only as OpenAPI 3.2 `parent` tags, and
+ only once Swagger UI renders them.
+7. **Rejected: ` / ` sub-tags.** Superseded by decision 1 -- one group per agent, with
+ the path carrying the second level.
+
+The grouped paths change (`/events` -> `/nats/events`, `//trigger` ->
+`/scheduler//trigger`). Grouping shipped in 0.9.0, so this is a **breaking change for
+grouped 0.9 deployments** and is release-noted under *Breaking*. (An earlier draft of this plan
+said grouping had not been released; it had.)
+
+## Steps
+
+### Step 0 -- Spec amendment
+
+Add sec. 11.2 *An agent's HTTP surface* to the grouping spec, carrying decisions 1-5 as
+requirements, and a row to sec. 10's compatibility table. No code.
+
+### Step 1 -- Framework segments through `route_prefix`
+
+`RestApiBase` gains a class attribute naming a segment that applies only when the component
+belongs to an agent, folded into `route_prefix`:
+
+```python
+group_segment: str = "" # "nats" on NatsEventing, "scheduler" on SchedulerBase
+
+@property
+def route_prefix(self) -> str:
+ if not self.namespace:
+ return ""
+ return f"/api/{self.namespace}/{self.group_segment}" if self.group_segment else f"/api/{self.namespace}"
+```
+
+In `route_prefix` because two places must agree on it: the builder, which mounts the router, and
+`DaprEventing.subscribe`, which tells the sidecar where to post (`dapr.py:199`). `DaprEventing` is
+always root and so unaffected, but it must stay reading the same property.
+
+Tests: grouped NATS and scheduler paths; standalone paths unchanged; the frozen compatibility suite
+unchanged.
+
+### Step 2 -- One tag per agent
+
+`AppBuilder._mount`: for a namespaced component, every `APIRoute`'s tags become
+`[component.namespace]`, whether or not it had tags. Root components are left alone.
+
+Tests: an untagged grouped route is tagged with its agent; a tagged one loses its own tag; two
+agents never share a tag; root and standalone tags unchanged. The expectations in
+`test_route_namespacing.py` (`orders.orders`, `billing.orders`) change accordingly.
+
+### Step 3 -- Developer prefix and reserved segments
+
+- An optional class attribute on `RestApiBase` for a developer's own path prefix, applied in both
+ modes. The attribute's name and its interaction with `group_segment` are settled in this step.
+- `build()` fails with a message naming the component, the route and the segment when a grouped
+ agent's developer route starts with `nats`, `cache` or `scheduler`. Framework components are
+ exempt, since they are the owners.
+
+### Step 4 -- Documentation
+
+`guides/multi-agent-migration.md` and the `blueprint-migration` skill (tags and paths in a group;
+the reserved segments; the optional prefix), the `with_rest_api` / `with_scheduler` docstrings
+that describe the grouped paths and tags, `CHANGELOG.md`, and the feature changelog.
+
+## Out of scope
+
+Routes added directly to the `FastAPI` application in `main.py` (`@app.get`,
+`app.include_router`) never pass through `_mount` and can still land in "default". A check after
+`build()` could catch them; not planned unless asked for.
diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md
new file mode 100644
index 00000000..f2fb4d1d
--- /dev/null
+++ b/docs/plans/2026-10-14-named-connections.md
@@ -0,0 +1,367 @@
+# Plan -- Named NATS connections with concurrent runs
+
+**Status:** 2026-10-14, decisions D1-D10 taken with the owner (sec. 4); ready for step 1. Supersedes
+`docs/plans/2026-10-09-tenancy.md` (discarded: the framework does not take on tenancy).
+
+**Goal in one sentence:** an agent consumes from several *named connections* that the deployment
+supplies at runtime -- each with its own broker account and its own JetStream binding -- with
+concurrent runs per connection, and nothing of one connection's runs ever reaches another's.
+
+**What the framework does not know:** what a connection stands for. A deployment may map one
+connection to one tenant, one region or one customer; the framework sees a name, credentials, a
+binding and a validation hook. No tenant document, registry, tenant scope, tenant id or
+tenant-specific key enters the framework.
+
+**First consumer:** a multi-tenant agent application, which today does all of this beside the
+framework, in a connection pool and an ingress of its own. No deployment uses the framework's NATS path
+yet, so nothing has to be migrated.
+
+---
+
+## 1. Why
+
+- **The framework has one connection per agent.** One credential, one stream (`nats_stream_name`,
+ process scope, provisioned and widened by the client), durables, deliver subjects and deliver
+ groups derived by the client. A deployment whose streams and accounts are owned by someone else
+ -- one account and one stream per tenant, created by provisioning, consumers possibly created by
+ an operator -- cannot be served. The broker refuses the framework's stream over subjects that
+ already belong to another stream (`err_code=10065`).
+- **So the first consumer built its own transport**, and with it lost every delivery guarantee the
+ framework has (dispositions, dead letter, drain budget, telemetry) and had to re-implement the
+ rest (settlement, heartbeat, run limit, degraded pause).
+- **Concurrency.** Measured 2026-10-14: runs were strictly one at a time per subscription and
+ process in both implementations. `a20a2b7` fixed the framework's path
+ (`nats_max_concurrent_runs`, heartbeat); this plan carries it over to every connection.
+
+---
+
+## 2. Invariants
+
+- **N1 -- Isolation between (agent, connection).** A run started from a delivery on connection C for
+ agent A shares no mutable state with any run of another (agent, connection):
+ - each run starts in an **empty `contextvars.Context`** -- nothing is inherited from the
+ dispatcher, the subscription task or another run;
+ - each (agent, connection) has its own broker connection, subscription, run slots and in-flight
+ accounting; the only thing shared is the per-process run cap, a counter;
+ - a delivery is settled (ack / nak / term / in_progress) on the connection that delivered it;
+ - the handler learns its connection from the context key `nats_connection`, set by the framework
+ from the connection the message arrived on -- never from the payload.
+- **N2 -- Validation before dispatch.** A deployment-supplied hook sees (connection name, subject,
+ CloudEvent) before any handler runs. A rejection is terminated (`term`), logged, never processed,
+ never retried.
+- **N3 -- Bind, never provision, on a named connection.** The stream belongs to the binding. The
+ client never creates or widens it. Consumers are created or updated only when the binding says
+ so; otherwise the client binds to what exists and sends no `$JS.API` request at all.
+- **N4 -- Wire values come from the deployment, byte for byte.** Durable name, deliver subject,
+ deliver group and filter subjects of a named connection are taken from its binding, not derived.
+ Moving that application onto the framework is then a redeploy: every `consumer_info`
+ identical before and after.
+- **N5 -- Composition independence.** Behaviour does not depend on how many agents or connections a
+ process hosts. One slow connection does not slow another beyond the shared per-process cap.
+- **N6 -- Existing agents unchanged.** Without a connection source, an agent runs exactly as today
+ on its one configured connection.
+- **N7 -- The same delivery semantics everywhere.** Named connections use the existing delivery
+ path: run slots, `_run_delivery`, dispositions (spec sec. 7.2), heartbeat, drain, telemetry. There
+ is one implementation of settling a message.
+
+---
+
+## 3. Shape
+
+```
+ConnectionSource (deployment code, process-wide)
+ connections() -> {name: ConnectionSpec}; notifies on add / change / remove
+ binding(agent, subjects, spec) -> JetStreamBinding
+ validate(name, subject, event) -> None | reason
+ |
+ v
+NATSClient (one per agent, as today)
+ default connection -- from nats_url etc., as today (N6)
+ named connection "c1" -- own nats.Client, own subscription(s), own slots
+ named connection "c2" -- ...
+ |
+ v per delivery: validate -> run task in empty Context -> handler chain -> settle on "cX"
+```
+
+- **One `NATSClient` per agent stays.** The registry name, `NatsEventing`'s lookup, publishing and
+ the supervisor's pause/resume all assume it (`component.py:153`, `nats.py:69`,
+ `event_publishing_service.py:65`, `namespace_supervisor.py:222`). The client grows an internal
+ set of connections instead of the registry growing several clients.
+- **`ConnectionSpec`:** name, URL, credentials (secrets as `SecretStr`, never logged), connect
+ options. **`JetStreamBinding`:** the declared subjects it serves on this connection (D10), its
+ `subject_prefix` (filter subject = prefix + declared subject), stream, durable, deliver subject,
+ deliver group, `manage_consumer`, optional dead-letter subject (D6).
+- **Subjects:** an agent declares its subjects as today (`get_subscribed_topics()`,
+ `nats_subscriptions`), without any prefix. The source maps them to a connection's filter subjects
+ in `binding()` -- that is where a deployment adds a prefix such as `t..`. The framework never
+ rewrites a subject. Example: agent `risk` declares `risk.>`; for connection `A` the source returns
+ filter `t.A.risk.>`, durable `acme-agent-risk`, deliver subject
+ `acme.agent.A.risk`, deliver group `risk`.
+- **Context keys of a delivery on a named connection** (D10): `nats_topic` = the subscription *as
+ the agent declared it* (`risk.>`), so everything that matches on the declared topic keeps working
+ -- e.g. `SchedulerTickHandler` compares `nats_topic` with its own topic (`scheduler.py:195`);
+ `nats_subject` = the delivered subject with the binding's prefix stripped (`risk.created`), so
+ `can_handle_event` sees what the agent knows; `nats_connection` = `A`, an opaque name for logs.
+ The wire subject (`t.A.risk.created`) is not in the handler context.
+- **Without a source nothing changes (N6):** no `nats_connection_source`, no named connections; the
+ agent's subjects are subscribed on its one connection exactly as today, durables and stream
+ derived as today.
+- **Runtime changes:** a connection added, changed (credentials, binding) or removed is opened,
+ replaced or drained while the agent runs. Draining follows `close()`: stop deliveries, let runs
+ finish within the budget, settle, close. A consumer the framework did not create is never deleted.
+
+---
+
+## 4. Decisions
+
+All taken on 2026-10-14; each entry starts with the decision, followed by the analysis that led to it.
+
+- **D1 -- Connection granularity. Decided 2026-10-14: (a), one broker connection per (agent,
+ connection).** Step 1 separates a *link* (the `nats.Client`, connecting, callbacks) from a
+ *binding* (subscription, run slots, settlement), one link per binding for now, so a shared link
+ -- option (b) -- can be added later as its own step without reshaping the rest. Triggers for
+ building (b): pod memory gets tight, or the operator sets `max_connections` per account. What (b)
+ would add: a process-wide link pool with reference counting and shutdown ordering, fanning
+ connection events out to every agent on the link, readiness that tells "link down" from "agent
+ paused", an exception to C2's connection naming and to grouping spec sec. 6, and every acceptance
+ test in both modes. The analysis that led here:
+ One broker connection per (agent, connection) **(recommended)**:
+ confines a dropped connection (stranded acks) and a slow-consumer kick to one agent and one
+ connection, as the grouping spec does per agent (sec. 6). Cost: agents x connections connections
+ per pod (19 x 10 = 190). Alternative: one per named connection shared by the agents of a process
+ (what the first consumer's own pool does today) -- fewer connections, but one agent's flood or blip hits all.
+ *Measured 2026-10-14* (nats-py 2.15 in `python:3.13-slim-bookworm` containers, NATS 2.10 with TLS
+ (RSA 2048) and user/password, all in WSL): an idle connection costs ~313 KB in the client with TLS
+ (~89 KB without) and ~80 KB in the broker; no measurable idle CPU; 400 connections open in 2.1 s.
+ Broker restart under 3 pods x 400: all 1200 back within 0.7 s; 3 x 800: all 2400 within 1.6 s, broker
+ CPU ~3 cores for about a second, ~2 s client CPU per pod, none given up even with the framework's
+ `nats_max_reconnect_attempts = 5`. The cost of this option is memory: 300 connections ~ 95 MB per
+ pod. Not covered: real network latency, a clustered broker, per-account `max_connections` set by
+ the operator (agents x replicas per account under this option).
+- **D2 -- Registering the source. Decided 2026-10-14: (a), the process-scope config key.** The
+ builders are each agent's own declaration, and an agent must not know about the deployment's
+ connections; a builder call would put the source into agent code. The key goes into
+ `PROCESS_SCOPE_KEYS`; `asbs validate` checks that it imports. The analysis that led here:
+ A process-scope key naming a factory,
+ `nats_connection_source = "package.module:factory"` **(recommended)**: works in a group without
+ any agent code, like the group file. Alternative: a builder call -- needs a process-scope
+ registration a group does not have today.
+- **D3 -- Run scope hook. Decided 2026-10-14: (a), the source may supply `run_scope(name)`.**
+ Agents open no deployment scope themselves and cannot forget it. The analysis that led here:
+ The source may supply `run_scope(name)`, a context manager the framework
+ enters *inside* the run task, around the handler chain **(recommended)**. It is how a deployment
+ applies per-connection settings that live in ContextVars (today: per-tenant model override) without
+ agent code. Without it, every agent service has to open such scopes itself.
+- **D4 -- `HandlerResult` publishing for a run from a named connection. Decided 2026-10-14: (a),
+ refused for now.** A result without a topic mapping is skipped as today; an agent that has named
+ connections *and* a topic mapping fails startup, so no connection's result can reach the default
+ connection's subjects. Found: the first consumer's handlers return `HandlerResult`s but the
+ repository has no topic mapping, so nothing is published today. **Later, when needed -- option
+ (b):** publish on the delivering connection, the source mapping the target subject as it maps
+ bindings (e.g. `t.A.`); needs publish rights on the connection's account. The analysis
+ that led here: Today it goes out on the
+ agent's default connection. Options: keep that **(recommended for this step; documented as "leaves
+ the connection")**, publish on the delivering connection (needs publish rights on that account),
+ or refuse. Isolation-relevant: the event leaves the connection's account.
+- **D5 -- Readiness. Decided 2026-10-14:** new key `nats_connections_readiness = "never" | "any" |
+ "all"`, default `never`. `never`: named connections show in the readiness payload and metrics but
+ never make the agent not ready (= today's behaviour of the only user: tenant connections are
+ invisible to readiness); `any` (OR): ready while at least one named connection is up; `all` (AND):
+ ready only while every one is up. The **default connection keeps today's behaviour unchanged**
+ (`health_check`, `nats_client.py:1106`: not connected -> unhealthy). **Required regardless of the
+ mode:** a named connection's state feeds readiness only, never the supervisor's pause decision --
+ one agent health bit drives both today (`namespace_supervisor.py:131`), and a pause on one dead
+ connection would stop the agent on every connection. Acceptance in WSL: one account with a wrong
+ password, nothing paused, readiness as the mode says. The analysis that led here:
+ A named connection that is down degrades that (agent, connection) only and
+ shows in the readiness payload; the agent stays ready **(recommended)**, so one broken account
+ does not take every other connection's work off the pod. **Open:** whether an agent with named
+ connections but none of them up should report not ready.
+- **D6 -- Dead letters on a named connection. Decided 2026-10-14: (a).** Dead-lettered on the
+ delivering connection only when the binding carries a dead-letter subject; otherwise term + ERROR
+ log (event id, reason, delivery count) -- what the first consumer does today. Never via the
+ default connection: a connection's payload must not reach another account. The analysis that led
+ here: Use the binding's dead-letter subject if it has one;
+ none -> term + ERROR log, payload lost **(recommended)** -- a deployment's account may not be
+ allowed to publish.
+- **D7 -- Run limits. Decided 2026-10-14.** Event rates differ by orders of magnitude between agents
+ (once an hour to several times a minute), so a busy (agent, connection) may take many runs while
+ an idle one never waits:
+ - **One run per (agent, connection) is always allowed** and counts against no limit.
+ - **Every further run** needs both: the (agent, connection) is below `nats_max_concurrent_runs`
+ (K, the same for every connection of the agent, settable per agent), **and** a slot of the
+ process-wide pool `nats_extra_runs_per_process` is free.
+ - Both keys take an absolute number or a percentage of the current number of (agent, connection)
+ pairs in the process (`"33%"`), recomputed when connections are added or removed. The owner's
+ sizing: K up to about a third of the pairs.
+ - Defaults keep today's behaviour: K unset = one run at a time *per subscription* (what every
+ agent did before; corrected in step 1 -- `a20a2b7` had made it one per agent), pool unset
+ (unlimited). With K set, the subscriptions of a pair share its K runs.
+ - Order of acquisition is fixed (the pair's slot, then the pool), so there is no deadlock; waiters
+ are served first come, first served, so no pair starves.
+ - Consequence to measure: guaranteed first runs are uncapped, so in the worst case every pair
+ runs at once plus the whole pool. The step-3 stress scenario includes "every pair busy at once".
+ - Per-connection K from the binding (a large tenant gets more) is not built; it can be added later
+ without reshaping anything.
+ The analysis that led here: `nats_max_concurrent_runs` becomes per (agent, connection) -- it was per agent
+ in `a20a2b7`, which is unpushed and unused -- plus a new process-scope cap
+ `nats_max_concurrent_runs_per_process` across every agent and connection. Defaults: 1 and unset
+ (no cap) to keep N6; the deployment sets both.
+- **D8 -- Core NATS on named connections. Decided 2026-10-14: (a), JetStream only.** A binding
+ without stream and consumer fails that connection's start with a clear message. Core NATS on the
+ default connection is unchanged. **Later, when needed -- option (b):** Core NATS on a named
+ connection, subscribing the filter subjects in the queue group with no acknowledgement, heartbeat,
+ redelivery or dead letter; events published during a pause or restart are lost; every acceptance
+ test then runs in both modes. The analysis that led here: JetStream only **(recommended)**: a named connection
+ exists to bind an existing durable consumer.
+- **D9 -- Handler timeout. Decided 2026-10-14: in this plan.** `nats_handler_timeout` (seconds,
+ agent-scoped, every connection including the default one), **default unset = no limit**. At the
+ limit the run is cancelled and nak'd for immediate redelivery; a `TimeoutError` the handler raises
+ itself is an ordinary failure (the run's own timer is checked, not the exception type). The run's
+ slot is freed only when its task has actually ended -- a handler that swallows the cancellation
+ keeps holding its slot, logged, instead of running unseen beside its redelivery. The heartbeat
+ (`a20a2b7`) already exists and stops before the nak. The analysis that led here:
+ Part A's hard limit (`nats_handler_timeout`, cancel + nak) is in
+ the first consumer today and in the handler-time-bounds draft spec. Include it in this plan
+ **(recommended)** -- "everything works as it does now" requires it.
+
+- **D10 -- Which subjects go where. Decided 2026-10-14: (a), the source decides per connection.**
+ Agents know their events (`risk.>`), never how connections are built (prefixes, accounts,
+ streams): `can_handle_event` must be able to look at the event's subject *as the agent declared
+ it* and decide whether there is work. Hence the binding expresses its mapping as a plain
+ `subject_prefix` (a generic concept, not a tenant one): filter subject = prefix + declared subject,
+ and the framework strips the prefix again on delivery, so `nats_subject` is always the subject the
+ agent knows (`risk.created`) -- on the default connection exactly as today. The wire subject
+ (`t.A.risk.created`) reaches the validation hook and the framework's logs, not the handler
+ context. The analysis that led here: An agent may declare subjects that
+ belong to the named connections (tenant events) and subjects that do not (a scheduler tick, a
+ process-level event). Recommended: `binding()` returns, per connection, which of the declared
+ subjects it serves; a subject no connection serves stays on the default connection, as today.
+ The default connection then subscribes only what is left -- possibly nothing, which matters where
+ the process account may not subscribe at all (the first consumer).
+- **D11 -- "Responsible, but nothing to do" is a result, not a decline. Decided 2026-10-15: (B),
+ `HandlerResult.skipped(reason)`.** `can_handle_event` routes on the envelope only; whether a
+ particular event needs work is decided by the service the handler calls, and the handler reports
+ "no" as `HandlerResult.skipped(reason)`: the chain stops, the delivery is acknowledged, the reason
+ is logged at INFO and counted as `blueprint.events.skipped`, nothing is published. Rejected: (A) a
+ second hook (`is_relevant`) beside `can_handle_event` -- the relevance check usually needs the same
+ reads as the work, so it would split one service call into two. `None` keeps meaning "offer the
+ event to the next handler"; an event no handler is selected for is unchanged. Done in step 6.
+
+---
+
+## 5. Steps
+
+One step, one reviewable commit. Each step names its acceptance.
+
+1. **Refactor: connections inside `NATSClient`.** The client's connection state (nats client,
+ JetStream context, subscriptions, slots, in-flight, ack-wait map) moves into a `_Connection`
+ object; the client holds a default one. No behaviour change, with one addition decided
+ 2026-10-14: `nats_heartbeat_enabled` (bool, agent-scoped, default `true`) switches the heartbeat
+ of `a20a2b7` off per agent, as in handler-time-bounds sec. 4.1.
+ *Acceptance:* unit and integration suites unchanged; the 2026-10-14 probe (B1-B5, K1-K3) gives
+ the same results.
+2. **Binding mode.** A `_Connection` can bind with a `JetStreamBinding`: no stream provisioning,
+ consumer created only with `manage_consumer`, wire values verbatim (N3, N4).
+ *Acceptance:* broker test -- an operator-made consumer is bound with `consumer_info` identical
+ before and after; with `manage_consumer` the consumer equals what the first consumer's pool
+ creates for the same input.
+3. **Connection source, static.** `nats_connection_source` (D2), connections opened at startup,
+ validation hook (N2), empty Context per run, `nats_connection` context key, run scope hook (D3),
+ per-connection slots and per-process cap (D7), handler timeout (D9).
+ *Acceptance:* isolation test below; mismatch -> term; limits respected (measured overlap).
+4. **Connection source, dynamic. Done 2026-10-15 (4a `c8ec35a`, 4b).** Add, change, remove at runtime; drain on remove; never delete a
+ foreign consumer. Built on the rules of `docs/specs/2026-09-23-dynamic-subscriptions.md`, for whole
+ connections only (no selectors, no REST API), with building blocks that spec can reuse later:
+ - a change and a reconnect never interleave (one lock per agent, spec 7.2);
+ - a changed connection: open and bind the new link first, then drain and close the old (spec 7.4);
+ - a removed connection: drain, give running runs a grace period, then **revoke** what is left --
+ no ack, no nak, heartbeat stopped, not cancelled, `publish` refused (spec 7.5); the link closes
+ only after that, so no acknowledgement of a finished run is lost;
+ - a consumer the operator made is never deleted, and neither is a managed one on removal (a tenant
+ that drops out of the directory briefly must not lose messages; the first consumer's pool behaves so today);
+ - permission violations arrive through `error_cb`, not as the call's error: a JetStream request
+ that times out while one arrived is permanent, not retried as a slow broker (spec 7.9);
+ - a shutdown during a change cancels it, nothing is half applied (spec 7.10); readiness does not
+ change during a change (D7); nothing depends on group composition (D0).
+ **Also in this step (owner's review finding #10, decided 2026-10-14):** `nats_max_reconnect_attempts`
+ defaults to `-1` (unlimited) instead of 5 -- after about 10 s of outage the default connection
+ closed for good while readiness reported healthy -- and a client that did close reconnects **and
+ resubscribes** instead of only reconnecting in the health check. Core NATS's 128 MB client buffer
+ (also #10) is not part of this feature; a configurable limit is left for later.
+5. **Readiness and telemetry per connection** (D5): connection state in the readiness payload,
+ metrics labelled with the connection name. Take review finding #6 (the readiness probe waits on a
+ lock held during slow health checks) into account here. **Done 2026-10-15:** readiness entry
+ `.nats_client:connections` registered with `affects_consumption=False` (feeds the verdict,
+ never the supervisor), `nats_connections_readiness`, gauge `blueprint.nats.connection.bound`,
+ counter `blueprint.nats.connection.permission_violations`; `/health/ready` reads the cache without
+ the poll lock (#6); a paused agent whose default connection comes back re-evaluates at once.
+6. **Everything that describes the framework agrees with it -- no contradiction left anywhere.**
+ Not only the new feature: every statement about NATS delivery, consumers, concurrency, heartbeat,
+ run limits and connections is checked against the code after steps 1-5, and corrected or
+ removed. Covered:
+ - **Specs and plans:** `docs/specs/2026-08-28-multi-agent-grouping.md` (sec. 5.2 still lists
+ 300 s / 16 as defaults; sec. 6 and 7 against named connections),
+ `docs/specs/2026-09-24-handler-time-bounds.md` (sec. 4.5 assumes running handlers are bounded by
+ `nats_max_ack_pending`; what part A is now implemented), `docs/specs/2026-09-23-dynamic-subscriptions.md`
+ (overlap with step 4), the feature changelog, `CHANGELOG.md`, `README.md`, `AGENTS.md`.
+ ADRs (`docs/adr/`) are owned outside this repository: contradictions there are listed for their
+ owner, not edited.
+ - **Shipped docs:** `src/blueprint/agent_generator/docs/` -- concepts, guides (deployment, event
+ processing, scaling), reference (configuration keys, every new key with type, default and
+ scope), getting started.
+ - **Agent generator:** the templates in `base_files/` (e.g. `settings.txt`, the handler template
+ whose docstring and idempotency comment still put business logic in the handler), the
+ generator, `asbs validate` checks for the new keys (a source that cannot be imported, a binding
+ without a stream, limits below 1), `asbs docs` output.
+ - **Skills and assistant docs:** `claude_docs/CLAUDE.md`, `claude_docs/agents/`
+ (`blueprint-builder.md`, `blueprint-architect.md`), every skill under `claude_docs/skills/`
+ (`blueprint-events`, `blueprint-config`, `blueprint-deployment`, `blueprint-multi-agent`,
+ `blueprint-troubleshooting`, `blueprint-testing`, ...), and the assistant integrations -- the
+ `main.py` patterns they show are known to disagree with each other and with the template.
+ - **Examples:** every project under `examples/` builds and starts against the changed framework;
+ `order_event_pipeline` (or a new example) shows a connection source with two named connections.
+ *Acceptance:* a written inventory of every place checked, with what was changed or why nothing
+ was; the repository's reference and design-rule guards green; every example started once in WSL
+ against a real broker; a grep for removed or renamed keys and APIs over the whole repository
+ finds nothing outside the changelogs.
+
+Afterwards, outside this repository: the first consumer implements the source over its tenant
+documents and drops its own connection pool and the receiving half of its ingress.
+
+---
+
+## 6. Acceptance in WSL (every step from 3 on)
+
+Run against a broker with **real accounts** (a `nats-server` config with one account per
+connection, permissions as the operator grants them: subscribe to the deliver subject, publish acks,
+nothing else), not an open broker.
+
+- **Isolation:** 2 connections x 3 agents, `nats_max_concurrent_runs` > 1, bursts on every
+ (agent, connection). Every run records the connection it sees in its context, the value of a
+ ContextVar set by the run scope hook, and the subject of its delivery; the test fails on any
+ mismatch. A ContextVar set inside one run is never visible in another.
+- **Rejection:** a delivery whose payload disagrees with its connection (validation hook) is termed,
+ never reaches a handler, is not redelivered.
+- **Stress scenario** from the discarded plan (sec. 9): 15 events per lane -- 9 short, 3 longer than
+ twice `ack_wait`, 2 failing, 1 hanging -- `ack_wait` 3 s, limit 10 s. Nothing stuck, no live run
+ redelivered, hung runs cut at the limit, failing ones dead-lettered or termed after `max_deliver`.
+- **Limits:** measured maximum overlap per (agent, connection) and per process equals the configured
+ values; every pair always gets its first run, even with the pool exhausted.
+- **Every pair busy at once:** all (agent, connection) pairs receive a burst at the same moment;
+ measured event-loop lag, heartbeat punctuality (no live run redelivered) and run times against an
+ idle baseline.
+- **Later, after all three steps (framework, SDK, deployment):** a mock LLM that answers only after a
+ configurable number of minutes, to diagnose how a group with many tenants behaves under sustained
+ high load (loop lag, memory per run, limits, redeliveries) and to size K and the pool.
+- **Runtime change** (step 4): a connection added and removed while the others run; no delivery of
+ the others lost or duplicated.
+- **Control runs** against the code before the step, for every claim of the form "this fixes X".
+
+---
+
+## 7. Not in scope
+
+Tenant documents, a tenant registry, tenant ids, `current_tenant()`, per-tenant model settings,
+REST token verification, outbound backend credentials: all stay with the deployment. The framework
+offers the seams (source, binding, validation hook, run scope hook) and nothing that names a tenant.
diff --git a/docs/plans/2026-10-15-named-connections-step6-inventory.md b/docs/plans/2026-10-15-named-connections-step6-inventory.md
new file mode 100644
index 00000000..26085424
--- /dev/null
+++ b/docs/plans/2026-10-15-named-connections-step6-inventory.md
@@ -0,0 +1,77 @@
+# Named connections, step 6 -- inventory
+
+Acceptance record for step 6 of `2026-10-14-named-connections.md`: every place checked, what was
+changed or why nothing was, and what is still open. Checked against the code on
+`feature/multi-agent-namespaces` (2026-10-15). "Read" = compared with the code; "run" = executed.
+
+## Changed
+
+| Place | Finding | Change |
+|---|---|---|
+| `agent_generator/claude_docs/CLAUDE.md` | built `AgentRuntime` + `AppBuilder(config).build()` in "Wiring" (W1); handler example with two-step logic; no handler rules | template declaration with `create_app()`; rules 7-10 (routing on the envelope, one service call, relevance in the service, no LLM in handlers, no run state on `self`); `HandlerResult.skipped`; `context["runtime"]` (W9); `models/` split (W11) |
+| `claude_docs/agents/blueprint-builder.md` | scheduler without `super().on_startup()` (W4); built `AgentBuilder(config)...build(name=)` (W1) | fixed; handler pattern and rules 9 and 13 |
+| `claude_docs/agents/blueprint-architect.md` | no rule on service entry points or LLM placement | two rules added |
+| `claude_docs/skills/blueprint-events`, `add-component` | `None` described as "not mine, or nothing to publish"; handler/agent/scheduler guidance | return values incl. `skipped`; handler rules; scheduler `super()` |
+| `base_files/src/handlers/handler.txt` | "This is where the main business logic is implemented" (W7); idempotency comment asks for logic in the handler (W8) | docstrings and comment put the decision in the service |
+| `docs/components/event-handlers.md` | `HandlerResult` "does not stop subsequent handlers" (W2); tenant example in the context-key section; instance registration | chain semantics table; context keys per D10 incl. `nats_connection`; classes only; full example with DTO and `skipped` |
+| `docs/concepts/event-processing.md` | sync `can_handle_event(event)`, `priority = 1`, "any other value is available to the next handler" | rewritten against `_dispatch`; table per return value |
+| `docs/concepts/architecture.md` | `with_agent("name", Cls)`, `register_routes`, `execute()`, `priority = 10` (W3) | rewritten; startup order checked against `app_builder.py:1648-1684` (unchanged, correct) |
+| `docs/components/agents.md`, `rest-apis.md`, `schedulers.md`, `services.md`, `concepts/caching.md`, `concepts/configuration.md`, `getting-started.md` | `AppBuilder(config)...build()`, instances, `.with_config()`/`.with_api()`/`with_name()` (W1); wrong import paths in `agents.md` | declaration form; imports fixed |
+| `docs/reference/api.md` | `AppBuilder(config: Config)`, `AgentBuilder(config, ...)` required | optional config, `build(config=None)` for both |
+| `docs/reference/models.md`, `concepts/observability.md` | -- | `skip_reason`, `ProcessingStatus.SKIPPED`, `blueprint.events.skipped` |
+| `docs/reference/configuration-keys.md` | `nats_subscriptions`, `nats_publish_mode`, `nats_publish_subjects` read by the code, documented nowhere | rows added; every other `nats_*` key in the code is present (diffed) |
+| `docs/guides/deployment.md` | "never exercised against a real broker"; ack_wait rule ignored the heartbeat | banner states what `tests/integration` covers; skipped/timeout dispositions; heartbeat |
+| `docs/guides/testing.md` | `api.register_routes(app.router)` -- no such method | `app.include_router(api.router)` |
+| `docs/specs/2026-08-28-multi-agent-grouping.md` | sec. 5.2 defaults 300 / 16 / 5 the code does not apply; sec. 7.3 without the heartbeat | corrected; new keys listed; sec. 7.2 gains the skip |
+| `README.md` | -- (already the declaration) | feature line for concurrency / named connections; component table |
+| `examples/*/src/main.py` + READMEs | module-level `app = AppBuilder(config)...build()`, instances | declaration + `create_app()`; `uvicorn src.main:create_app --factory` |
+| `asbs validate` | no check of the new keys | `_nats_findings` (step-6 item "asbs validate checks for the new keys") |
+
+## Checked, unchanged
+
+- **W5**: already fixed by `9b4560c` (the second `CLAUDE.md` was removed).
+- `AGENTS.md`, `CLAUDE.md` (repository): no statement about delivery, handlers or `main.py` that
+ disagrees with the code.
+- `docs/guides/multi-agent-setup.md`, `multi-agent-migration.md`: already show the declaration;
+ the migration guide shows the old form deliberately as "before".
+- `claude_docs/skills/blueprint-config`, `-deployment`, `-multi-agent`, `-troubleshooting`,
+ `-testing`, `-cli`, `-migration`, `new-agent-service`: grepped for main.py patterns, chain
+ semantics and NATS delivery claims; nothing found that disagrees. Not read line by line.
+
+## Run
+
+- Unit suite: 3588 passed, 1 skipped (was 3553 before step 6).
+- `tests/integration/test_skipped_result.py` + `test_event_path.py` against `nats:2.10-alpine`
+ (throwaway container, port 14222): 8 passed. Control on the unchanged code: a `None` from the only
+ handler logs "No handler processed event" at WARNING.
+- `asbs setup` + `asbs create handler` + `asbs validate` on a scratch project: the scaffold carries
+ the new handler docstrings, validates clean, and `nats_max_concurrent_runs = 0` is reported.
+- Every example started once (`uvicorn src.main:create_app --factory`, Windows host, NATS in WSL
+ Docker): `/health/live` 200 for all five; `/health/ready` 200 for `inventory_api`,
+ `health_monitor` and `webhook_relay` (connected to the broker); 503 for `order_event_pipeline`
+ (no Dapr sidecar) and `document_summarizer` (no model key) -- both expected. Each example's own
+ tests and `tests/unit/examples`: green.
+- Grep for removed APIs (`with_config(`, `with_api(`, `with_prompt_file`, `register_routes(`,
+ `with_agent("name", Cls)`, `AgentBuilder(config` in docs): only plans and changelogs remain.
+
+## Done after the first pass (2026-10-15)
+
+- `webhook_relay` and `order_event_pipeline`: one handler per event type, one service call
+ (`f72c84a`, `1d40fdc`); `document_summarizer` without `assert` (`4cbc3c2`).
+- The named-connection example `examples/site_readings` (`30f14e7`), run live against a broker with
+ accounts.
+- Spec sec. 7.2 now matches the WARNING for an event no handler takes (`ad771f0`, own commit).
+- `nats_delivery_attempt` / `nats_max_deliver` in the handler context (`b7586e3`).
+
+## Open
+
+- **Model file names differ:** the template scaffolds `dto.py` / `domain_models.py` / `mapper.py`;
+ the examples use `schemas.py` (+ `domain.py` where there are handlers). `document_summarizer`,
+ `health_monitor` and `inventory_api` have no handlers and keep one `schemas.py`; their APIs pass
+ request DTOs to the service.
+- **Pre-existing integration failure:** `test_acknowledgement_lifecycle.py::TestARetryableFailureComesBack::test_the_broker_counts_it_as_a_redelivery`
+ fails on the unchanged code too (control run 2026-10-15).
+- **Not checked:** the untracked specs `2026-09-23-dynamic-subscriptions.md`,
+ `2026-09-24-handler-time-bounds.md` (sec. 4.5) and `2026-09-25-config-key-registry.md` (not in the
+ repository); ADRs (owned outside the repository); `asbs docs` output beyond the files above.
+- The examples were started on the Windows host against brokers in WSL Docker, not inside WSL.
diff --git a/docs/plans/2026-10-16-pr96-review-fixes.md b/docs/plans/2026-10-16-pr96-review-fixes.md
new file mode 100644
index 00000000..bb77fd6a
--- /dev/null
+++ b/docs/plans/2026-10-16-pr96-review-fixes.md
@@ -0,0 +1,370 @@
+# PR #96 review fixes -- verification and plan
+
+**Status:** steps 1-21 implemented 2026-10-19 and pushed 2026-10-20, each marked **Done** below with
+what ran live; final run with containers recorded in the feature changelog. Step 22 done 2026-10-20.
+Open: the way forward on D22 (N13), N18, and D23 (b) (a missing binding-mode stream or consumer);
+everything else in "Decisions" is settled.
+**Base:** `be15878` (head of `feature/multi-agent-namespaces`, unchanged since the reviews; `81f6bf2`
+before the history rewrite of 2026-10-21, see D1).
+**Sources:** pajoma's review (2026-10-15, CHANGES_REQUESTED, 3 blockers), Develebook's review
+(2026-10-16, 12 must-fix / 27 should-fix / 9 nits, inline), solicho's leftovers (2026-09-14/16).
+Earlier comments (version bump, retarget to `develop`, #97) are resolved.
+
+Every step below is one reviewable change under the multi-agent-grouping rules in `CLAUDE.md`:
+one step, report with the code walkthrough, record it in
+`docs/plans/2026-08-28-multi-agent-grouping-changelog.md`, then stop. NATS, Redis, Dapr and
+Dockerfile steps get a live run in WSL before they are reported as done.
+
+---
+
+## 1. Verification result
+
+Every finding was re-checked against `be15878`: by reading the code, and for most by a throwaway
+reproduction (fakes, fakeredis, InMemoryMetricReader, APScheduler/croniter, Docker in WSL).
+Verdicts: **C** confirmed, **P** partly, **R** refuted. "SA" = also affects standalone agents.
+
+### Blockers (pajoma)
+
+| # | Finding | Verdict | SA | Step |
+|---|---|---|---|---|
+| B1 | Dedup marker survives `CancelledError` (handler timeout, shutdown) -> redelivery ACK'd unrun | C (repro) | yes | 1 |
+| B2 | `dapr.py:46` logs `RequestValidationError` incl. payload values at ERROR | C (repro) | yes | 2 |
+| B3 | Internal product name / tenant subject prefix in 6 tracked files, 8 branch commits, public repo | C | -- | 3 |
+
+B3 detail: the name is absent from `develop`; it entered on this branch (plan `2026-10-14-named-connections.md`,
+`tests/integration/{nats-accounts.conf,connection_source.py}`, three unit tests under
+`tests/unit/agents/clients/io/`, and the feature changelog history). The branch is pushed, so the name is
+already public. References to sibling repositories (`docs/specs/2026-08-24-...`, `sessions_bus.py`,
+`key_provider.py`) predate the branch and are on `develop` too.
+
+### Must-fix (Develebook)
+
+| # | Finding | Verdict | SA | Step |
+|---|---|---|---|---|
+| M1 | JetStream reconnect re-subscribes although nats-py replays `_subs` -> orphaned duplicate subs | C (nats-py 2.15 read) | yes | 4 |
+| M2 | Failed `resume_consumption` never retried; health stays green | C | yes | 5 |
+| M3 | Superseded named binding keeps consuming after change-change / change-remove | C (code) | named conns | 6 |
+| M4 | Subscribe permission violation reads as "bound", never rebinds | C (nats-py read) | named conns | 6 |
+| M5 | Agent's own `.secrets.toml` never loaded in a group | C (repro) | no | 8 |
+| M6 | Clearing the root Redis cache deletes every agent's/named cache; `key_prefix=""` -> whole DB | C (fakeredis) | yes (named caches) | 12 |
+| M7 | `critical_agents` typo -> all non-critical; scalar YAML; zero-agent pod READY | C (repro) | no | 7 |
+| M8 | Grouped event-mode tick handler registered in root namespace (C1) | C (repro) | no | 10 |
+| M9 | Grouped tick subject / trigger route repeat the agent name; docs disagree | C (repro) | no | 10 |
+| M10 | `group_Dockerfile` HEALTHCHECK uses `curl`, absent in slim image | C (WSL) | no | 14 |
+| M11 | Dedup marker stays claimed when post-dispatch processing fails | C (repro) | yes | 1 |
+| M12 | `/status/env` masker leaks (`/?#` in password, query tokens, `AccountKey=`) and 500s on `${PORT}` | C (repro) | yes | 13 |
+
+### Should-fix and nits
+
+| # | Finding | Verdict | SA | Step |
+|---|---|---|---|---|
+| S1 | Durable clash root `orders-created` vs agent `orders`+`created`; drift only warns | C | yes | 18 |
+| S2 | Binding mode plain `subscribe` receives JetStream status/flow-control messages | C (mechanism) | named conns | 6 |
+| S3 | `ConnectionSpec.tls` in `__eq__` -> every notify rebinds every `tls://` link | C (repro) | named conns | 6 |
+| S4 | `_Link.connect_options` default repr leaks password/token/nkey | C (repro) | yes | 2 |
+| S5 | Dapr fan-out hands the same `CloudEvent` to every agent; no shared-topic warning | C | no | 16 |
+| S6 | Marker has no in-progress state: concurrent duplicate is ACK'd | C (repro) | yes | 15 |
+| S7 | Sync redis-py claim/delete on the event loop | P: redis-py 8.1 has 5 s timeouts, `>=5.0` pin allows None | yes | 15 |
+| S8 | Dapr returns `str(exc)` in response body (develop: fixed text) | C | yes | 2 |
+| S9 | Unbounded `topic` label cardinality via `/events/` | C (5000 points measured) | yes | 16 |
+| S10 | `SessionsJobHandler` auto-declares its type, narrowing widened `can_handle_event` | C | yes | 19 |
+| S11 | Bare key equal to another agent's namespace returns its section through a view | C (repro) | no | 8 |
+| S12 | Namespaces not reserved against shared sections / root scalars | C (weaker than claimed: fill-missing keeps a set root value) | no | 8 |
+| S13 | Fragments layered for first-pass `app_environment`, not the env Dynaconf loads | C (repro) | no | 8 |
+| S14 | `DYNACONF_ENVIRONMENT` in scaffold Dockerfiles selects nothing | C (repro; predates PR, matters since #89) | yes | 14 |
+| S15 | `_` separator ambiguity; qualified registry hit has no ownership check | C (code) | no | 9 |
+| S16 | Registry mutation methods unguarded on views | C (code) | no | 9 |
+| S17 | Bound methods / closures pass `is_shareable` | C (repro) | no | 9 |
+| S18 | C4 missing for `event_bus = "sessions"` | C | no (no C4 on develop) | 5 |
+| S19 | `deployment_group()` ignores the group resolved from the file | C | no | 20 |
+| S20 | Undocumented standalone breaks: built-in health check name, handler class+instance, deferred construction | C (vs develop) | yes | 19 |
+| S21 | `event_loop_debug` on by default in "development" (the default env) | C | yes | 19 |
+| S22 | One OTLP exporter (and one BatchSpanProcessor) shared, closed by first provider shutdown | C (repro) | no | 17 |
+| S23 | diskcache_rs exclusive lock vs "atomic across processes" docs | P: true for <=0.4.9 (redb), false for 0.4.10 (sqlite); pin `>=0.4.4` | yes | 20 |
+| S24 | Crontab dialect: APScheduler Mon=0 vs croniter Sun=0; `7` rejected; host timezone | C (APS 3.11.3; predates PR) | yes | 11 |
+| S25 | Scheduler `_started` set before success -> recovery reports success without timer | C (code) | partly | 11 |
+| S26 | Second scheduler's tick-age gauge dropped | C (InMemoryMetricReader) | yes | 11 |
+| S27 | `asbs validate` scheduler checks differ from runtime (a-e) | C (all five) | yes | 11 |
+| N1 | Shutdown aborted by a failed recovery task (more than a nit); `actuator.on_shutdown` unguarded | C; `_loop_watchdog.stop()` part **R** | yes | 19 |
+| N2 | Duplicate group names last-wins; scalar `agents` | C (repro) | no | 7 |
+| N3 | Raw `exc` in NATS WARNING/ERROR logs | P: defensive, no real nats-py text with password found | yes | 2 |
+| N4 | `pause_consumption` waits on `_change_lock`; `message_handler` has no paused gate | C | named conns | 4 |
+| N5 | Dapr TERM+ACK answers SUCCESS with a reason; `route_class` applies to the whole router | C (repro) | yes | 16 |
+| N6 | `asbs dev` without `--name` serves root, messages say otherwise | C | msgs only | 14 |
+| N7 | `asbs setup` validates the name after writing the project | C (repro) | yes | 14 |
+| N8 | `settings.txt` comment token `app_name` substituted | C | yes | 14 |
+| N9 | Scheduler template docstring wrong; `asbs create service` misses imports (older) | C | yes | 14 |
+| N10 | "Created JetStream consumer" INFO formats `ack_wait` with `%.1f`; unset `nats_ack_wait` is `None`, so the line is lost as a logging error | C (live, found in step 2) | yes | 18 |
+| N11 | Startup against an unreachable broker did not return within 6 s (only nats-py's own "encountered error" was logged) | observed live in step 2, not analysed; check against the `max_reconnect_attempts=-1` connect | yes | 4 |
+| N12 | An agent whose own subscription keeps failing reports ready: the failure degrades it, C4 pauses it, and a paused client reports healthy by design, so after one poll readiness is UP while `_retry_resume` keeps failing (backoff 5 s, 10 s, ...) and nothing is consumed | C (live, found in step 18; any persistent subscribe failure, not only S1) | **Fixed 2026-10-20** (22b, D21 decided with D23): liveness DOWN while the resume keeps failing; S1 itself is now final (22a) | 22 |
+| N13 | `DiskCacheService.claim` is not atomic across processes: diskcache-rs 0.4.10's `add` lets several processes on one directory win one key (297 of 300 rounds, 4 processes, no error); 0.4.9 refused a second process the directory | C (live, step 20) | docs corrected; fix open as D22 | -- |
+| N14 | M4's refusal check raced: nats-py 2.15 writes PING straight to the transport while the SUB still waits for the flusher, so the PONG could come back before the broker saw the SUB and the binding read as bound (`TestARefusedSubscriptionIsNotBound` failed 3 of 9 runs on the step-21 code, 1 of 2 on step 17, 0 of 2 on step 6) | C (live, final run) | **Fixed 2026-10-19**: two round trips in `_bind`; 8 of 8 runs green | -- |
+| N15 | `app_environment` inside `[default]` makes `Config.get("app_environment")` answer the configured value while Dynaconf loads the default section, so a development check can read the wrong environment (found by the docs agent with a probe; the docs now say the key selects only at top level or through `DYNACONF_APP_ENVIRONMENT`) | C (probe 2026-10-20: [development] loaded, `app_environment` read `production`) | **Fixed 2026-10-20** (22d): `Config.get("app_environment")` answers the loaded environment; a WARNING when the settings say otherwise | 22 |
+| N16 | `.otel_service_name` is resolved by `Config._resolve_service_name` but never reaches the resource: `TelemetryManager._configure_namespace` sets `service.name` to the namespace for every agent | C (code read by the docs agent) | **Fixed 2026-10-20** (22c): the agent's view resolves the name the resource carries | 22 |
+| N17 | `handler_chain._warn_without_a_heartbeat` compared `nats_heartbeat_enabled is False`, so `"false"` from an environment variable did not warn | C (unit test failed before) | **Fixed 2026-10-19**: read with `parse_bool` | -- |
+| N18 | The generated handler's `on_startup` read `.get("input_event_type", )` -- `None` when the key is missing -- and compared it to `""`, so a handler without its event type started anyway (found by the validator agent). Making the check fire stops every fresh scaffold: `asbs setup`'s own handler has no `input_event_type` and does not use it (`can_handle_event` is a stub) -- found live on a scaffold, `ValueError` at startup | C (live, with control) | open -- the fix was withdrawn on 2026-10-20 (owner decision); what the generated handler does with the event type is decided later. `test_a_fresh_project_starts_the_way_its_container_does` keeps a scaffold startable | -- |
+| N19 | The validator restates runtime rules that exist only as private methods: dedup policy and heartbeat/Dapr warnings (`HandlerChain`), the timezone check (`SchedulerBase`), the shared-topic grouping (`DaprEventing`), the `nats_url`/heartbeat/durable-count rules (`NatsClient`); pinned by tests, matched live word for word | C (code read) | **Fixed 2026-10-20** (22e): seven rules are public runtime functions the validator calls; two drifts found on the way -- the validator's heartbeat warning still compared `is False` (N17), and the runtime's Dapr shared-topic warning read `idempotency_enabled` raw, so `"false"` counted as on | 22 |
+| N20 | `test_design_rules.all_markdown()` walked the whole checkout with `rglob`, `.venv` included, and filtered afterwards -- about 0.6 s per test, 47 s for the module | C (measured) | **Fixed 2026-10-20**: directories pruned before they are entered; same 91 files, 14 s | -- |
+
+### pajoma warnings/suggestions and solicho leftovers
+
+| # | Finding | Verdict | Step |
+|---|---|---|---|
+| W1 | `OTEL_SERVICE_NAME` collapses grouped identity (C2) | C (repro) | 17 |
+| W2 | `in_process` claim slot from `datetime.now()` | P: correct, but practically harmless (misfire grace 1 s) | 20 |
+| W3 | Omitted `namespace` = all on root registry, own on a view | C, by design; risk only for user root components in groups | 20 |
+| W4 | Run slot can leak between acquire and `create_task` | P: theoretical | 18 |
+| W5 | `_durable_for` docstring says nothing is renamed (dotted topics are) | C | 18 |
+| W6 | Isolation guard keyed by `id(builder)` only | C; decided: document, sharing between agents is fine | 9 |
+| T1 | Dedup key not scoped to the named connection -> one tenant's event can suppress another's | C (code, found 2026-10-16) | 1a |
+| W7 | Stale xfail paragraph in `test_agent_isolation.py` | C | 21 |
+| W8 | Hand-set `version = "0.9.0"` and dated `[0.9.0]` CHANGELOG section vs `AGENTS.md` versioning rule | C | 21 |
+| W9 | PR description stale (#89, LICENSE, size), no `Closes`, no AI disclosure, #35 not linked, no rollback note | C | 21 |
+| W10 | CI runs only `tests/unit` | C | out of scope (CI, needs services) |
+| W11 | `NATSClient` 2,652 lines; transitional test-only members; PR size | C | out of scope (follow-up issue) |
+
+Overlap with the 2026-09-24 defect list: M1 was item 5 there, S7 item 9. Neither had been fixed.
+
+---
+
+## 2. Steps
+
+Must-fix and blockers first (steps 1-14), then hardening (15-20), then documentation and PR hygiene (21).
+
+1. **Dedup bracket** (B1, M11). `EventProcessingService.process_event` / `HandlerChain`: one
+ `try/except BaseException` from claim to settled result that releases the marker, replacing the
+ publish-only release. Tests: timeout + dedup, scalar return + dedup, cancel mid-handler.
+ **Done 2026-10-19** (not committed): also covers a handler that swallows the cancellation;
+ measured live on JetStream with a control run against the unchanged code.
+1a. **Connection isolation** (T1, user requirement 2026-10-16). The blueprint knows no tenants, only
+ named connections, but no framework-owned state may be shared across connections, because each one
+ stands for a different data source behind it. Checked: result publishing is refused on named
+ connections (`_refuse_result_publishing`), dead letters go out on the arrival link, each run has its
+ own task context. **Gap:** the dedup key is `(source, id)` only (`handler_chain.py:532`), so two
+ connections delivering the same producer's event id suppress each other. Fix: add the connection
+ name to the key when the delivery came from a named connection (the default connection keeps
+ today's key, no migration). Test: two connections, identical `(source, id)`, both handled. Docs: a
+ section for handler authors -- state that must stay per data source is keyed by the
+ `nats_connection` context key. M3 (a removed connection still consumed) is the same class, step 6.
+ **Done 2026-10-19** (not committed): unit tests with a control run, and a broker test on the accounts
+ broker (`test_dedup_keeps_the_connections_apart`) that fails without the change.
+2. **Leaks in logs and responses** (B2, S8, S4, N3). `dapr.py:46` logs `loc`/`type` only; the related
+ pre-existing ERROR logs in `event_processing_service.py:307/312`; Dapr reason = `exc.reason` or type
+ name; `_Link.connect_options` `repr=False`; NATS link logs via `_describe_error`.
+ **Done 2026-10-19** (not committed): also the NATS decode log (same leak as `dapr.py:46`, already on
+ `develop`) and `_Link.url` (`nats_url` may carry `user:pass@`); `resume_consumption`'s log is left
+ to step 5. Measured live with a control run; found N10 and N11 on the way.
+3. **Internal naming** (B3). Replace with generic names (`acme.agent..`) in the six files.
+ History: see decision D1.
+ **Done 2026-10-19** (not committed): also the consuming repository's internal module names in the
+ named-connections plan; `git grep` finds none of them; `test_named_connections.py` passes on the
+ accounts broker with the renamed subjects.
+4. **JetStream reconnect** (M1, N4; N11 checked here). **Done 2026-10-19** (not committed): N11 was a
+ hang -- nats-py retries the first connect itself when reconnects are unlimited; the first connect is
+ now bounded, and connecting while paused re-evaluates health at once. Measured live with a control
+ run (subscription counts from `/connz`, runs per event, paused runs, startup time). `_on_reconnected` stops re-subscribing under JetStream, re-checks
+ stream and consumers only; `message_handler` gets a `_consumption_paused` gate (NAK under JetStream).
+ Replace `test_reconnected_resubscribes_jetstream_topics` with a fake that replays `_subs`.
+ Live: broker restart in WSL, count subscriptions and deliveries per message.
+5. **Resume retry and C4 for sessions** (M2, S18). **Done 2026-10-19** (not committed): the sessions
+ bus closes its job stream while paused and leaves a job that reaches it pending; the supervisor
+ pauses it with the IO clients. Live: M2 on JetStream with a control run; the sessions part unit-only
+ (no sessions service available). Unsubscribe partial subscriptions on failure, then
+ per D2. `SessionsBus.pause_consumption/resume_consumption`, supervisor includes it. Test supervisor and
+ client together.
+6. **Named bindings** (M3, M4, S2, S3). Retire the `replaces` chain; `flush()` after subscribe and raise
+ on a matching permission error; `on_reconnected` sets ready only for bound links; drop/answer status
+ messages in binding mode; `tls` `compare=False`. Live: accounts broker from `tests/integration`.
+ **Done 2026-10-19** (not committed): four broker tests in `test_named_connections.py`, each failing on
+ the step-5 code; the live run also found that nats-py lowercases the -ERR line, so the refusal is
+ matched lowercased.
+7. **Group config validation** (M7, N2). Unknown critical names, non-list `agents`/`critical_agents`,
+ duplicate group names -> `GroupConfigError`; empty resolved group fails at startup; D8.
+ **Done 2026-10-19** (not committed): unit tests with a control run; the empty group is checked in
+ `AgentGroup.from_config` (with unknown critical names refused, `resolve` cannot produce one). Live:
+ with the group image in step 14.
+8. **Agent settings merge** (M5, S11, S12, S13). Merge `/.secrets.toml`; reserve shared-section
+ names and refuse to replace a root scalar; layer fragments for the environment Dynaconf actually
+ loaded and drop inactive sections; bare-key view refusal per D9.
+ **Done 2026-10-19** (not committed): the reserved names live in `namespace.py` (an import from the
+ config package would be a cycle) and a test keeps them equal to `SHARED_NESTED_PREFIXES`; the bare-key
+ refusal applies only where the root value is a section; `AgentGroup.assemble` declares every agent.
+ Live: with the group image in step 14.
+9. **Registry and sharing guards** (S15, S16, S17, W6). Ownership check on the qualified lookup branch;
+ `clear`/`clear_components`/`shutdown_executors` refused on views, ownership checks in
+ `update_component_name`/`get_or_create_executor`; bound methods/closures checked; W6 per D11.
+ **Done 2026-10-19** (not committed): also `add_component` on a view, and a shared declaration's
+ factory target; W6 documented in `_refuse_state_shared_between_agents` and the migration guide.
+ Unit tests fail on the old code; live with the group image (step 14).
+10. **Grouped scheduler** (M8, M9). Construct the tick handler under `namespace_scope(self.namespace)`;
+ topic and trigger route from `base_name`; fix `deployment.md`, `claude_docs/CLAUDE.md`,
+ `SKILL.md`, `configuration-keys.md`; literal-subject test. CHANGELOG line for alpha users of the
+ doubled subject. Live: NATS in WSL, publish the documented subject, see the tick.
+ **Done 2026-10-19** (not committed): also the tick handler's own name; the existing test that encoded
+ the doubled subject now asserts the base name. Live with a control run.
+11. **Scheduler robustness** (S24-S27). `_started` only after success; one tick-age gauge per meter with
+ a multi-scheduler callback; crontab dialect/timezone per D14/D15; validate shares the runtime's checks.
+ **Done 2026-10-19** (not committed): `validate_crontab(crontab, mode)` runs in both modes; S27 (a)-(e)
+ through `normalise_scheduler_mode` / `delivers_ticks`; a missing `event_bus` is a notice. Live: two
+ in-process schedulers with a real timer and an SDK reader, with a control run.
+12. **Redis cache isolation** (M6). Default store's `clear`/`list_namespaces` skip child-store keys
+ (no key-layout change); WARNING when the default store has `key_prefix=""` and is cleared.
+ Live: two agents on one Redis in WSL.
+ **Done 2026-10-19** (not committed): `_owns` (a 64-hex digest after exactly one namespace segment)
+ filters clear, list_namespaces and list_values; `BLUEPRINT_TEST_REDIS_URL` makes the Redis
+ integration tests runnable against a throwaway container. Live with a control run.
+13. **`/status/env` masker** (M12 + pajoma suggestion). Fail closed on `@` after `://`, query-string
+ and `Key=` segment masking, port inside `try`, secret-named dicts masked whole, `pass`/`dsn`/`conn` as
+ `_`-delimited markers.
+ **Done 2026-10-19** (not committed): also `sig`/`signature` as words (SAS tokens); a secret-named
+ list of sections is masked whole. Live over HTTP (uvicorn) with a control run.
+14. **Scaffold and CLI** (M10, S14, N6-N9). Python HEALTHCHECK in `group_Dockerfile`; environment
+ variable per D10; validate the name before generating; reword the `settings.txt` comment; correct
+ the `asbs dev` messages (behaviour unchanged); scheduler template docstring; service template imports.
+ Live: build the group image in WSL and watch it turn healthy.
+ **Done 2026-10-19** (not committed): the CLI service uses `BaseModel` (the generator derives the
+ parameter name from the type, so `dict[str, Any]` produced invalid code). Live: a scaffolded group
+ image (two agents) built in WSL from the working tree -- healthy after 10 s, environment
+ `production`; control (the old template): `curl: not found`, never healthy, `development`. The same
+ image ran the live checks of steps 7 and 8: a critical-name typo exits 1 with the message; an
+ agent's mounted `.secrets.toml` is merged into that agent only.
+15. **Dedup without a heartbeat, Redis calls** (S6, S7). Per D4: document the redelivery-while-running
+ limit, startup WARNING when dedup runs without a heartbeat; claim/delete via `asyncio.to_thread`; opt-in `redis_socket_timeout` (default unchanged).
+ **Done 2026-10-19** (not committed): S7 rechecked under the D16 rule -- redis-py 7.0.0 has no default
+ timeout, 8.0.0 has 5 s (read from the tagged sources), so the floor is now `redis>=8.0.0`. The
+ scheduler's tick claim moved off the loop too. Live on a paused Redis with a control run.
+16. **Dapr hardening** (S5, S9, N5). Deep copy per agent in fan-out; startup WARNING for a shared topic
+ with dedup off; `` topic label per D6; reason only when not ACK; `route_class` limited
+ to `/events/{topic}`.
+ **Done 2026-10-19** (not committed): the copy is made only when more than one agent receives the
+ delivery. Live: a uvicorn-served group against the Dapr sidecar mock, with a control run.
+17. **Telemetry** (S22, W1). Ref-counted exporter and span processor (keeps C2's "share one"); explicit
+ flush and shutdown in the lifespan, root last; `OTEL_SERVICE_NAME` per D17.
+ **Done 2026-10-19** (not committed): the providers are built without their own atexit hook;
+ `shutdown_providers()` runs from the lifespan (in a worker thread) and once from atexit as the
+ fallback. D17 applies to `OTEL_SERVICE_NAME` only: a `service.name` declared in
+ `OTEL_RESOURCE_ATTRIBUTES` still names every agent. Live against an OTLP collector with a control run.
+18. **NATS leftovers** (S1, W4, W5, N10). Refuse to bind on a `filter_subject` mismatch (no rename);
+ run-slot release on exception; `_durable_for` docstring; the consumer INFO line renders an unset
+ `ack_wait`.
+ **Done 2026-10-19** (not committed): the refusal is a `JetStreamBindingError` from
+ `_ensure_consumer` (a consumer listing exactly the topic in `filter_subjects` is bound);
+ `filter_subject` left the drift list. Live against JetStream with a control run; found N12.
+19. **Standalone compatibility** (S10, S20, S21, N1). User checker replaces a built-in one with a
+ WARNING; class and instance handlers register in declaration order; `SessionsJobHandler` declares only
+ when `can_handle_event` is not overridden; `event_loop_debug` off unless set (`parse_bool`);
+ shutdown via `gather(..., return_exceptions=True)`, guarded `actuator.on_shutdown`; CHANGELOG entry
+ for deferred construction.
+ **Done 2026-10-19** (not committed): `HealthCheckEntry.builtin`; `Registry.reorder` permutes the
+ declared handlers within the slots they hold (replacing `_check_declaration_order`);
+ `configure_loop_debug` lost its `development` parameter. Live (standalone app, Core NATS) with a
+ control run; the SessionsJobHandler and shutdown parts are unit-tested only.
+20. **Smaller items** (S19, S23, W2, W3). Publish the resolved group into the deployment identity;
+ diskcache per D16; floor the in-process slot to the scheduled time; W3 per D7.
+ **Done 2026-10-19** (not committed): `deployment.publish_deployment_group`, called by
+ `AgentGroup.resolve`; the tick slot is the trigger's latest fire time at or before now (a cursor
+ walked forward, misfires passed over). D16's live check failed: diskcache-rs 0.4.10 is not atomic
+ across processes (N13), so the docs drop the claim and D22 is open. Live in WSL with control runs.
+21. **Docs and PR hygiene** (W7, W8, W9, D20). xfail paragraph; CHANGELOG/version per D19; licence back
+ to develop's state per D20; rollback note
+ (cache keys, durables, REST paths, metric label); PR description draft (#89, LICENSE, size, `Closes`
+ lines, #35/#75 link, AI disclosure). The description is posted only after the user has read it.
+ **Done 2026-10-19** (not committed): xfail paragraph in the past tense (no test is marked any
+ more); `[0.9.0]` folded into `[Unreleased]` (one section per heading, the 0.9.0 introduction
+ first, no entry lost: 170 entries before, 169 + 4 rollback points after); `pyproject.toml` at
+ `0.8.2`, without `license`/`license-files`; `LICENSE` removed and its CHANGELOG entry with it;
+ "Rolling back to 0.8" in the CHANGELOG. Not touched: README's MIT badge and licence section
+ (develop has them too, linking a file develop does not have), and develop's MIT classifier,
+ which this branch had already dropped -- D20 lists the classifier as out. PR description and
+ the reply to the version-bump comment are drafts, not posted.
+22. **Startup and tenancy faults** (D23, D17, N12/D21, N15, N16, N19). After the review commits were
+ pushed (2026-10-20), one commit per part:
+ - **22a Deterministic faults fail early.** A `DeterministicTransportError` family -- JetStream
+ unavailable (exists), durable clash (S1), stream not creatable/updatable (the server answered),
+ JetStream permission refused, and the tenancy faults of a named connection (login refused,
+ deliver subject refused, binding-mode consumer filtering another subject) -- stops the retry
+ loop and goes to the fatal handler: CRITICAL with what failed, where and what to change;
+ liveness DOWN; the agent marked down; the root or a critical agent still ends the process as
+ before. At startup it fails the start whatever `critical_agents` says. Transient faults keep
+ retrying (D5). Deferred: a missing binding-mode stream/consumer.
+ - **22b Orphaned agents** (N12, D21 in principle): an agent that should consume and does not for
+ a non-transient reason makes the service unhealthy regardless of `readiness_policy`.
+ **Decided 2026-10-20 (owner):** a resume that keeps failing and a connection loop that gave up
+ take liveness DOWN until the agent consumes again; a latched agent (startup failure, a
+ non-critical agent's fatal transport fault) gates readiness under every policy, and startup
+ recovery keeps running. **Done 2026-10-20**; a resume that meets a fault no retry fixes is
+ reported fatal as well. Not run live: a resume that keeps failing while the agent's checks
+ pass (no broker-side setup produces it reliably); unit-tested, and the latch case runs through
+ a real lifespan.
+ **Done 2026-10-20** (22a, c, d, e; not committed): 22a as described -- not detectable, and so not
+ implemented, is a binding-mode consumer that filters another subject: with `manage_consumer` the
+ client rewrites it to the binding, without it the client sends no JetStream request (as for a
+ missing consumer, D23 (b)). Spec C1, C3 and 9.1 amended. 22c: the start fails on a `service.name`
+ only in `OTEL_RESOURCE_ATTRIBUTES` in a group; N16 by reading the agent's view. 22d: N15 fixed.
+ 22e: N19 fixed. Live in WSL (NATS, NATS accounts, Redis), each against the code before step 22
+ (`4c10274`) as control: durable clash -- before 8 attempts in 4 s, liveness 200, nothing CRITICAL;
+ now one, CRITICAL, liveness 503, SIGTERM for a critical agent; JetStream grant refused to the
+ agent's own connection -- before the agent started and stayed paused for good, liveness 200,
+ nothing logged (an orphaned agent, 22b); now the start fails with `JetStreamPermissionError`.
+ Found on the way: two agents of one process sharing a stream race to create it, and the loser's
+ "stream name already in use" (10058) was first classified as final -- it is a race, the stream is
+ re-read and widened (the full integration run had ended in pytest's own SIGTERM; a guard in the
+ integration conftest now fails such a test instead). Integration 70 of 71, the one pre-existing
+ failure. New integration tests: `test_final_faults.py` (clash, stream, grant) and the tenancy
+ faults in `test_named_connections.py` (refused login, refused deliver subject); D5's tests now
+ use an unreachable broker, a fault that may heal.
+ - **22c `service.name` in a group** (D17): only through `OTEL_RESOURCE_ATTRIBUTES`, without
+ `OTEL_SERVICE_NAME`, fails the start; N16 (`.otel_service_name` reaches the resource).
+ - **22d N15** checked and decided; **22e N19** -- the runtime rules the validator restates
+ become public and the validator calls them.
+
+23. **Findings of the first consumer's test report** (2026-10-20, 19 agents on 0.9.0a16 against a
+ local backend). B2 (regression of 22e/`1d877f2`): an unset `nats_url` outside development is a
+ validator notice, not an issue -- an image that validates while it is built has none yet. B3:
+ the health job runs late instead of being dropped (`misfire_grace_time=None`, `coalesce`). A
+ refresh at the end of startup, the report's other suggestion, was tried and withdrawn: it caught
+ the subscriptions still being made, the supervisor read that as a transition and paused the agent
+ mid-subscribe (integration tests timed out). Why each run started ~2.7 s late in their setup is
+ not explained. B4 also fixed the pre-existing `test_the_broker_counts_it_as_a_redelivery`. B4 (owner, 2026-10-20: a fixed default, not opt-in): `nats_nak_delay`,
+ default 1/5/15/30/60 s; a degraded agent's hand-back stays immediate. B1 (owner, 2026-10-20):
+ the publish route refuses a subject the agent's tenants own (403) and `operator_routes_enabled`
+ switches the publish and cache routes off; authentication stays the deployment's. Checked for
+ this agent's own tenants only -- another agent's tenant subjects are the process account's
+ permissions to deny.
+
+---
+
+## 3. Decisions
+
+### Settled by standing rules (no question needed)
+
+- S1: refuse to bind on mismatch, keep today's durable names (no consumer migration).
+- S7: socket timeouts as an opt-in key, default unchanged ("never change existing defaults").
+- S20: restore develop's behaviour for health check replacement and handler order ("existing agents keep working").
+- S21: `event_loop_debug` off unless set (develop had no debug mode).
+- N6: `asbs dev` behaviour unchanged, messages corrected.
+- M6: filter child keys rather than moving the default store (no cold cache).
+- M9: fixed as a bug; grouped alpha users get a CHANGELOG line.
+- D15 (timezone): host-local stays the default; opt-in `scheduler_timezone`.
+
+### Open, asked one at a time
+
+| ID | Question | Blocks step |
+|---|---|---|
+| D1 | B3: replace the names in the tree only, or also rewrite the published branch history? **Decided 2026-10-16: tree only, no history rewrite.** **Revised 2026-10-21: the history too** -- after further review feedback, internal project names were removed from the history of `main`, `develop` and this branch (every commit since 2026-08-24 has a new SHA), and the release tags moved with it. | 3 |
+| D2 | M2: after a failed resume, retry in a backoff task, or report unhealthy so the supervisor cycles? **Decided 2026-10-16: backoff task in the client (cancelled by pause/close), readiness unchanged, WARNING per failed attempt.** | 5 |
+| D4 | S6: in-progress TTL: opt-in key, derived from handler timeout / `ack_wait`, or document only? **Decided 2026-10-16: no in-progress state. The loss needs a redelivery while the first run is still going, which the heartbeat prevents. Document it, and log a startup WARNING when dedup runs without a heartbeat: NATS with `idempotency_enabled` and `nats_heartbeat_enabled = false`; Dapr with `idempotency_enabled` (Dapr has no heartbeat; the WARNING names the app-call timeout).** | 15 |
+| D6 | S9: undeclared topics as ``, a capped set, or drop the `topic` label? **Decided 2026-10-19: `` for every topic the agent did not declare; declared topics keep their name. With `dapr_declarative_subscriptions = true` everything counts as ``, the real name stays in the log line.** | 16 |
+| D7 | W3: change "omitted namespace" to mean root everywhere, warn only, or leave? **Decided 2026-10-19: leave the semantics, document them (grouping docs and the `Component.registry` docstring): a root component in a group sees every agent on collection lookups; `namespace=""` asks for the root only. Framework callers depend on "omitted = all" (`dapr.py:216/256`, `event_processing_service.py:66`, `cache.py:63`).** | 20 |
+| D8 | M7: `BLUEPRINT_AGENTS` overriding the file -- discard the file's `critical_agents` with a WARNING, or keep and reject unknown names? **Decided 2026-10-16: keep the file's list; a critical name outside the resolved group fails startup.** | 7 |
+| D9 | S11: a bare key naming another agent through a view -- `ValueError` or the default? **Decided 2026-10-16: `ValueError`, same rule as the dotted key.** | 8 |
+| D10 | S14: scaffold Dockerfiles -- `DYNACONF_APP_ENVIRONMENT="production"`, or remove the line? **Decided 2026-10-19: fixed as a bug. `DYNACONF_APP_ENVIRONMENT="production"` in the production stage of `Dockerfile` and `group_Dockerfile`, `"development"` in the dev stage, a comment that a custom `envvar_prefix` renames the variable, `deployment.md:51` corrected. The docs state plainly that `app_environment` defaults to `development` and a deployment must set `production` itself (what changes: no localhost broker fallback, logging, asyncio debug).** | 14 |
+| D11 | W6: refuse one mutable object handed to two separately declared agents, or document it? **Decided 2026-10-16: sharing between agents is allowed and documented. Sharing between tenants is not: see step 1a.** | 9 |
+| D14 | S24: fix the crontab dialect as a bug (moves firing days of `in_process` schedulers), or keep and warn? **Decided 2026-10-19: the blueprint's dialect is `0` = Monday ... `6` = Sunday (APScheduler's), so `in_process` firing days do not move. `7` is refused with a clear message in `in_process` and in `validate_crontab` (no croniter pass-through). In `event` mode a numeric day-of-week fails startup: the external CronJob counts `0` = Sunday, so a number is ambiguous; the error says so and asks for names (`mon-fri`, `sun`), which both read the same. Docs: `0` = Monday, examples with names (`0 9 * * mon`, `*/15 9-17 * * mon-fri`; today's `1-5` example means Tue-Sat), a note that an external cron counts differently. CHANGELOG line for event-mode schedulers with numeric weekdays.** | 11 |
+| D16 | S23: raise the pin to `diskcache-rs>=0.4.10`, or document disk as per-process only? **Decided 2026-10-19: raise the pin to `diskcache-rs>=0.4.10`. Live in WSL: two processes claim the same key, exactly one wins; "atomic across processes" stays in the docs only if that holds. Drop "a disk cache on a shared volume" for several replicas (`configuration-keys.md:144`, `deployment.md:386`): cross-pod dedup needs Redis, disk covers processes on one host. General rule (user, 2026-10-19): where a dependency's behaviour changed in a way that affects us, adapt to it and raise the minimum version -- S7 is re-checked under this rule in step 15 (which redis-py version brought the default socket timeouts).** | 20 |
+| D17 | W1: in a group, ignore `OTEL_SERVICE_NAME` for agents with a WARNING, refuse to start, or document? **Decided 2026-10-19: in a group every agent provider keeps `service.name` = agent name even when `OTEL_SERVICE_NAME` is set, so telemetry stays filterable per agent; the root provider still takes `OTEL_SERVICE_NAME`. One startup WARNING names the value and why it does not apply to the agents. `OTEL_RESOURCE_ATTRIBUTES` stays untouched. Docs: the exception to "declared keys are never replaced". Standalone unchanged.** | 17 |
+| D19 | W8: fold `[0.9.0]` into `[Unreleased]` and restore the `develop` version string, or keep as is? **Decided 2026-10-19: this PR follows its own `AGENTS.md` rule -- `[0.9.0] - 2026-09-14` (never released, only `v0.9.0a1..a15`) is folded into `[Unreleased]`, `pyproject.toml` goes back to develop's `0.8.2`; `publish.yml` sets the version from the tag anyway (L43/L66). Reply to SawwR's bump comment with the rule. Follow-up issue, not in this PR: derive the version from git tags with `setuptools-scm` so source installs report it too (drops the `sed` step); the stale `__version__ = "0.3.0"` fallback in `src/blueprint/__init__.py:8` goes with it.** | 21 |
+| D20 | Is the MIT licence choice approved by the responsible owner (pajoma F)? Not a code decision. **Decided 2026-10-19: no approval exists. The licence is deferred: this PR goes back to develop's licence state (`LICENSE` from `424d9dc` removed, `license`, `license-files` and the MIT classifier out of `pyproject.toml`). Open point for the `develop` -> `main` merge: licence approval by the responsible owner, then add it there. The PR description says so. Already published alphas (`v0.9.0a1..a15`) carry MIT and cannot be changed.** | 21 |
+| D21 | N12: a paused client whose own resume keeps failing reports healthy, so readiness is UP while the agent consumes nothing. Options: (a) while paused, report unhealthy once a resume attempt has failed, and let `_retry_resume` keep running through a re-pause (today a pause cancels it, which would then deadlock); (b) leave readiness as it is and add a `blueprint.nats.resume_failures` counter plus the failure in the readiness payload; (c) accept and document. **Decided 2026-10-20 with D23 -- see 22b.** Measured (step 18, root topic `orders-created` against a consumer filtering `created`, health interval 2 s): 200 at 0-2 s, 503 at 2.1 s (degraded, paused), 200 from 4.1 s on while paused, resume attempts failing at 5 s and 10 s backoff. | -- |
+| D22 | N13: make `DiskCacheService.claim` atomic across processes on one host -- an OS file lock (`fcntl.flock` / `msvcrt.locking`, or the `filelock` package) around the `add` -- or keep the disk cache per-process for claims and warn at startup when dedup or the in-process tick claim runs on a disk cache with `app_workers > 1`? **Decided 2026-10-19: document only, for now** -- the docs say per-process (claim docstring, deployment guide, configuration keys, CHANGELOG Known issues); how to proceed beyond that is to be clarified. | -- |
+| D23 | Startup and tenancy faults (owner, 2026-10-19). **Principle: a critical problem or collision found at startup fails the start; a fault caused by a wrong or problematic tenancy is logged CRITICAL and the process exits -- at startup and at runtime, when a `ConnectionSource` change hands it over -- because an operator must notice it.** Critical means deterministic (a retry cannot fix it): durable clash (S1), stream not creatable/updatable (subject overlap), missing JetStream permissions, tenant login refused, tenant deliver subject refused, binding-mode consumer missing or filtering another subject. Transient faults (broker unreachable, connection lost, timeouts) keep retrying; D5 stays for those. Open before implementing: (a) do an agent's own faults respect `critical_agents` (spec sec. 9.1) or always exit; (b) is a missing binding-mode stream fatal or still transient (provisioning); (c) D17 -- refuse `service.name` in `OTEL_RESOURCE_ATTRIBUTES` in a group, and what happens to `OTEL_SERVICE_NAME`. Partly supersedes D21 (N12). **Added (owner, 2026-10-19): a constellation that leaves orphaned agents -- agents that should exist but consume nothing for a non-transient reason (startup latch, final subscription fault, a resume that keeps failing) -- makes the service at least unhealthy, possibly exits.** So D21 is decided in principle: a paused client whose resume keeps failing reports unhealthy. Open: whether "unhealthy" is readiness DOWN or liveness DOWN, and whether it overrides `readiness_policy = "critical"` for a non-critical agent. **Settled (owner, 2026-10-19):** (1) such critical faults set **liveness** DOWN, and each is logged well enough for an operator to act on (what failed, which agent/connection, why it is not transient, what to change); (2) a transient fault stays under `readiness_policy`, an orphaned agent counts regardless of the policy; (3) D17: in a group, a `service.name` declared only through `OTEL_RESOURCE_ATTRIBUTES` (no `OTEL_SERVICE_NAME`), which would name every agent alike, **fails the start**; `OTEL_SERVICE_NAME` alone or together with it stays as implemented (agents keep their names, WARNING). Still open: (a) an agent's own faults vs `critical_agents`, (b) a missing binding-mode stream. **Clarified (owner, 2026-10-19): M agents x N tenants; N = 0 (the source hands over no tenant) is a valid state -- nothing to bind, nothing fails (as implemented: "consumes on 0 named connection(s)").** (b) concerns N >= 1: a tenant handed over whose binding names a stream (or, with `manage_consumer = false`, a consumer) that does not exist. **(b) deferred (owner, 2026-10-19):** whether a missing binding-mode stream -- or, with `manage_consumer = false`, a missing consumer -- is fatal at once or after a grace period depends on whether the tenancy source hands over a tenant only once its stream is provisioned; to be clarified with the tenancy owner. Until then it stays as implemented: retried, visible in readiness only (`.nats_client:connections` reads `retrying`); with `manage_consumer = false` a missing consumer is not detected at all (the client sends no JetStream request). **(a) settled (owner, 2026-10-19): fail early.** A deterministic fault (durable clash, stream not creatable/updatable, missing JetStream permissions) is fatal in every agent, whatever `critical_agents` says: logged CRITICAL, startup fails or liveness goes DOWN. `critical_agents` and `readiness_policy` keep deciding only for faults that may be transient (startup recovery, health). | 22 |
diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md
deleted file mode 100644
index 42737664..00000000
--- a/docs/reference/configuration-keys.md
+++ /dev/null
@@ -1,173 +0,0 @@
-# Configuration Keys Reference
-
-Complete reference for all `settings.toml` configuration keys in the Blueprint Agents framework.
-
-Settings are loaded from `settings.toml` (and optional environment-specific overrides). Environment variables can override any key using the prefix `BLUEPRINT_` with double-underscore separators (e.g., `BLUEPRINT_APP_PORT=9000`).
-
----
-
-## Application
-
-Top-level application settings.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `app_name` | `str` | `"agent_blueprint"` | Application name. Used in logging, health checks, and OpenTelemetry service identification. |
-| `app_port` | `int` | `8000` | HTTP port the application listens on. |
-| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`). |
-| `log_level` | `str` | `"INFO"` | Root log level. One of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. |
-| `log_format` | `str` | `"text"` | Log output format. `"text"` for human-readable, `"json"` for structured JSON logging. |
-
----
-
-## Event Bus
-
-Settings for the event bus transport layer.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `event_bus` | `str` | `""` | Event bus implementation. Set to `"dapr"` for Dapr pub/sub or `"nats"` for NATS. Empty string disables the event bus. |
-| `nats_url` | `str` | `"nats://localhost:4222"` | NATS server URL. Only used when `event_bus = "nats"`. |
-
----
-
-## Event Publishing
-
-Section: `[default.event_publishing]`
-
-Controls how outbound events are published to topics.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `default_pubsub_name` | `str` | `"pubsub"` | Default pub/sub component name (used with Dapr). |
-| `topic_mapping` | `dict` | `{}` | Maps event type strings to topic names. Events not in this mapping use the event type as the topic. |
-
----
-
-## AI / Model Runtime
-
-Section: `[default.runtimes.]`
-
-Each named runtime defines model provider settings. The `default` runtime is used when no name is specified.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `model_provider` | `str` | -- | Model provider. `"openai"` for OpenAI-compatible APIs, `"vllm"` for vLLM endpoints. |
-| `model_name` | `str` | -- | Model identifier (e.g., `"gpt-4o"`, `"meta-llama/Llama-3-70b"`). |
-| `model_api_key` | `str` | -- | API key for the model provider. Can also be set via environment variable. |
-| `model_base_url` | `str` | -- | Base URL for the model API. Required for `"vllm"` and custom OpenAI-compatible endpoints. |
-| `model_max_tokens` | `int` | -- | Maximum number of tokens in the model response. |
-| `model_temperature` | `float` | -- | Sampling temperature. Lower values produce more deterministic output. |
-| `concurrent_requests` | `int` | -- | Maximum number of concurrent requests to the model provider. |
-
----
-
-## Prompts
-
-Top-level settings for prompt file resolution.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `prompt_directory` | `str` | -- | Primary directory containing prompt template files. |
-| `prompt_search_paths` | `list[str]` | `[]` | Additional directories to search for prompt files, in order. |
-| `system_prompt_name` | `str` | `"system"` | Filename (without extension) of the system prompt template. |
-| `instruction_prompt_name` | `str` | `"instruction"` | Filename (without extension) of the instruction prompt template. |
-
----
-
-## Cache
-
-Section: `[default.cache]`
-
-Disk cache settings used when `with_cache()` is enabled on the `AppBuilder`.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `cache_dir` | `str` | `".cache/blueprint"` | Directory for cache storage. |
-| `size_limit` | `int` | `1000000000` | Maximum cache size in bytes (default ~1 GB). |
-| `eviction_policy` | `str` | `"least-recently-used"` | Cache eviction policy. |
-| `default_ttl` | `int` | `3600` | Default time-to-live for cache entries in seconds. |
-
----
-
-## Observability
-
-OpenTelemetry and tracing settings.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `otel_enabled` | `bool` | `false` | Enable OpenTelemetry tracing and metrics export. |
-| `otel_endpoint` | `str` | -- | OTLP collector endpoint URL (e.g., `"http://localhost:4317"`). |
-| `otel_service_name` | `str` | -- | Service name reported to the OTLP collector. Defaults to `app_name` if not set. |
-| `token_metrics_enabled` | `bool` | `true` | Record LLM token usage and response latency to OpenTelemetry. Only takes effect when `otel_enabled` is also `true`. |
-
----
-
-## Logging
-
-Additional logging behavior settings.
-
-| Key | Type | Default | Description |
-|-----|------|---------|-------------|
-| `suppress_noisy_loggers` | `bool` | `true` | Suppress verbose log output from third-party libraries (e.g., `httpx`, `httpcore`). |
-
----
-
-## Example settings.toml
-
-```toml
-# Application
-app_name = "my_agent_service"
-app_port = 8000
-app_environment = "development"
-log_level = "INFO"
-log_format = "text"
-
-# Event Bus
-event_bus = "nats"
-nats_url = "nats://localhost:4222"
-
-# Prompts
-prompt_directory = "prompts"
-prompt_search_paths = ["shared/prompts"]
-system_prompt_name = "system"
-instruction_prompt_name = "instruction"
-
-# Logging
-suppress_noisy_loggers = true
-
-# Observability
-otel_enabled = false
-otel_endpoint = "http://localhost:4317"
-otel_service_name = "my_agent_service"
-token_metrics_enabled = true
-
-[default.event_publishing]
-default_pubsub_name = "pubsub"
-
-[default.event_publishing.topic_mapping]
-"order.created.v1" = "orders"
-"order.completed.v1" = "orders"
-
-[default.runtimes.default]
-model_provider = "openai"
-model_name = "gpt-4o"
-model_api_key = "@format {this.OPENAI_API_KEY}"
-model_max_tokens = 4096
-model_temperature = 0.7
-concurrent_requests = 5
-
-[default.runtimes.fast]
-model_provider = "openai"
-model_name = "gpt-4o-mini"
-model_api_key = "@format {this.OPENAI_API_KEY}"
-model_max_tokens = 2048
-model_temperature = 0.3
-concurrent_requests = 10
-
-[default.cache]
-cache_dir = ".cache/blueprint"
-size_limit = 1000000000
-eviction_policy = "least-recently-used"
-default_ttl = 3600
-```
diff --git a/docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md b/docs/specs/2026-07-06-sessions-agent-registration-design.md
similarity index 100%
rename from docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md
rename to docs/specs/2026-07-06-sessions-agent-registration-design.md
diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md
new file mode 100644
index 00000000..fe6e57a9
--- /dev/null
+++ b/docs/specs/2026-08-28-multi-agent-grouping.md
@@ -0,0 +1,1310 @@
+# Spec -- Multi-Agent Grouping
+
+| | |
+|---|---|
+| **Implementation plan** | `docs/plans/2026-08-28-multi-agent-grouping.md` |
+| **Resolves** | #75 (deployment model decision), #73 (duplicate cron ticks) |
+| **Unblocks** | #32 (100 agents in 4 GB), #35 (shared interpreter), #20 (worker scaling) |
+| **Related** | #33 (lazy heavy imports), #34 / #74 (dependency slimming), #36 (concurrency bounds + benchmark), #43 (scheduler double-start), #6 (config service) |
+| **Amended by** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10, folded into sec. 2, 4, 5.3, 8, 9, 10 and 11 below. |
+| **Amended by** | `docs/plans/2026-09-28-grouped-http-surface.md` -- decided 2026-09-28, folded into sec. 10 and 11.2 below. |
+| **Amended by** | PR #96 review, 2026-10-19 -- brought in line with the implementation: C1 (root/agent durable clash), C2 (resolved group, per-provider metric readers, declared OTel keys), C4 (pause instead of close), sec. 2 and 11 (standalone agents at the root), 4.1 and 9 (`AgentGroup.resolve` / `from_config` / `assemble`), 4.2 (handler order restored, not refused), 5.1 (further group-file refusals), 5.3 (config refusals; process-scope keys dropped with a WARNING), 6 (resolved group; history), 7.1 and 7.2 (history; `SKIPPED`; ``; `max_deliver` optional), 7.4 (dedup key), 7.5 (no default mode; claim atomic on Redis only; slot from the fire time; crontab rules; `scheduler_timezone`), 9.1 (no agent left), 10 (instances refused by `build(config)`), 11.1 (`event_loop_debug`, watchdog), 12 (claim criteria scoped to Redis). Each change is marked in place. |
+| **Amended by** | PR #96 review step 22, 2026-10-20 -- owner decision D23 in `docs/plans/2026-10-16-pr96-review-fixes.md`: C1 (the root/agent clash is not retried), C3 (a transport fault no retry can fix takes liveness DOWN), 9.1 (such a fault fails the start whatever `critical` says). Each change is marked in place. |
+| **Deferred out of** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature. |
+
+Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense.
+
+---
+
+## 1. Scope
+
+Allow one Python process to host several independent agents, and make the grouping of agents
+into processes a deployment-time parameter rather than a code-time one.
+
+### In scope
+
+- A namespace dimension in the component registry, with per-namespace isolation of executors,
+ AI clients, event transports and configuration.
+- Group composition resolved at process start from a file and/or environment variables.
+- Event delivery that is correct under horizontal pod scaling.
+- Telemetry and health identities that are invariant under regrouping.
+- A development workflow in which an agent author never encounters namespaces or groups.
+
+### Non-goals
+
+- Multiple simultaneous transport types in one process (NATS *and* Dapr).
+- Cross-namespace agent calls.
+- Adding or removing namespaces after startup.
+- Ordering guarantees across replicas.
+- Lazy agent instantiation and scale-to-zero (evaluated and rejected; do not re-propose
+ without new measurements).
+- Prefork / copy-on-write process sharing. #35 lists "prefork" and "multi-tenant host" as
+ alternatives; this spec implements **multi-tenant host** and does not pursue prefork.
+
+---
+
+## 2. Terminology
+
+| Term | Meaning |
+|---|---|
+| **Agent** | A unit of business capability: handlers, services, prompts, optionally a REST API and scheduler. Authored as one directory. |
+| **Namespace** | The registry partition an agent's components live in. Equal to the agent name. `""` is the root namespace: where a standalone application runs -- a pre-migration single-agent app, or any agent served on its own (sec. 11). *(Amended 2026-10-19, PR #96 review: a scaffolded agent served standalone runs at the root too.)* |
+| **Group** | The set of agents loaded into one process, and therefore into one pod. |
+| **Declaration** | An `AppBuilder` whose `build()` has not been called -- component classes recorded without instantiation. |
+| **Root** | Namespace `""`, holding process-wide shared components. |
+
+---
+
+## 3. Invariants
+
+These are normative. C1-C6 exist because violating them makes regrouping observable outside the
+process, which would defeat the purpose of grouping. C7 exists for a different reason: it is what
+keeps the isolation cost that grouping *does* incur attributable, and therefore adjustable.
+
+### C1 -- Consumer identity derives from the agent
+
+Queue group names and JetStream durable names **MUST** be a pure function of the namespace.
+They **MUST NOT** incorporate the group name, container name, pod name, replica index, or any
+other deployment identifier.
+
+- Queue group: `namespace`, or `nats_queue_group` (default `app_name`) when the namespace is `""`.
+ It **MUST NOT** be the empty string.
+- JetStream durable: `f"{namespace}-{topic}-durable"`; when the namespace is `""`, the configured
+ `nats_durable_name` (one topic only), else `f"{topic}-durable"`. Only the topic is rewritten to
+ suit a consumer name; the namespace reaches it as declared. *(Amended 2026-10-19, PR #96
+ review: the root's bare form stated.)*
+- Namespace alphabet: a namespace **MUST** be `""` or match `[a-z][a-z0-9_]*`, and **MUST** be
+ validated where it enters the framework rather than by each consumer of it. It becomes a
+ registry key prefix, a queue group, part of a durable name and a telemetry `service.name`, and
+ a value each of those repairs differently is one agent under four names. Two exclusions do not
+ follow from any single consumer:
+ - `-` is the separator in the durable name above. With it allowed, namespace `orders-eu` on
+ topic `created` and namespace `orders` on topic `eu-created` produce one durable name, so two
+ agents would bind one JetStream consumer and consume each other's events.
+ The exclusion separates agents from each other, not the root from an agent: the root's bare
+ `f"{topic}-durable"` has no namespace segment, so root topic `orders-created` and agent
+ `orders` on topic `created` still derive one name (`orders-created-durable`). That clash
+ **MUST** fail rather than share a consumer: the client refuses to bind a durable whose filter
+ is another subject (`DurableConflictError`), naming the consumer and the fix. *(Amended
+ 2026-10-19, PR #96 review: the root/agent clash is not prevented by the alphabet, and is
+ refused at bind.)* It is not retried: it is a fault no retry can fix (C3, sec. 9.1).
+ *(Amended 2026-10-20, D23.)*
+ - `<` and `>` keep the sec. 6 connection-name placeholders unforgeable. `>` is a NATS wildcard
+ and illegal in a consumer name in any case.
+
+**A name that crosses the process boundary MUST be validated, never repaired.** This covers every
+name that becomes part of a subject, a queue group or a consumer: the namespace, `app_name` and
+`nats_queue_group` where they stand in for it, and a scheduler's name where it forms the tick
+subject. Silently rewriting one -- an `app_name` of `"My Service"` becoming `My_Service` in a
+subject -- leaves the party on the other side of the contract, typically a `CronJob` in another
+repository written by someone who has never read this framework, publishing to a subject nothing
+subscribes to. The tick simply never arrives, and no log on either side says why. The side that
+knows the name is unusable **MUST** fail its own startup instead, naming the key, the value and
+the subject that would have been derived.
+
+Two rewrites are permitted, and only these:
+
+- The **topic** portion of a durable name. Dots are idiomatic in subjects and illegal in consumer
+ names, so there is no alternative; it is bounded by the requirement that two topics resolving to
+ one durable name is an error, and the mapping is documented. Within one client the clash is
+ refused when the durables are resolved; between the root and an agent it is refused at bind
+ (above). *(Amended 2026-10-19, PR #96 review.)*
+- The **connection name** (sec. 6), which exists for attribution and which C1 forbids anything
+ from deriving from, so no external party can depend on its spelling.
+
+**The namespace MUST be validated in `Component.__init__`**, not in `Registry.add_component` and
+not per base class. Every component passes through that constructor, including the eight that
+opt out of registration, and it runs before the registry name is derived. A gate in the registry
+would miss unregistered components -- among them the eventing endpoints, which become
+namespace-owned in phase 2.
+- The NATS **connection name** (sec. 6) is deployment-specific and **MUST NOT** be used to derive
+ either of the above.
+
+### C2 -- Telemetry identity derives from the agent
+
+Each namespace **MUST** have its own `TracerProvider` and `MeterProvider` with
+`Resource({"service.name": , "deployment.group": , "service.instance.id": })`,
+subject to the declared keys below. `` is the group the process resolved --
+`BLUEPRINT_GROUP`, or the one group a group file declares -- and `deployment.group` is absent when
+no group was resolved; `service.instance.id` is absent when the pod cannot be determined.
+*(Amended 2026-10-19, PR #96 review: the group is the resolved one, not only the variable, and the
+resource carries no placeholders.)*
+
+All providers share one `BatchSpanProcessor` per exporter. Metric readers cannot be shared -- the
+SDK binds a reader to the provider that registered it -- so each provider has its own reader over
+the one shared metric exporter. The shared processor and exporter count the providers holding them
+and are shut down by the last one; shutdown runs the agents' providers first and the root's last,
+because the root's is the global provider. *(Amended 2026-10-19, PR #96 review: replaces "SHOULD
+share one exporter and one `BatchSpanProcessor`"; per-provider readers and reference-counted
+shutdown as implemented.)*
+
+When the namespace is `""`, the provider **MUST** use `otel_service_name` from config, reproducing
+current behaviour exactly (`io/telemetry/telemetry.py:39-41`).
+
+**Keys the deployment declares.** *(Amended 2026-10-19, PR #96 review; and 2026-10-20, decision
+D23 (c) in `docs/plans/2026-10-16-pr96-review-fixes.md`.)* A key set in `OTEL_RESOURCE_ATTRIBUTES` or
+by `OTEL_SERVICE_NAME` is used as declared and replaces the framework's value, on every provider.
+The one exception is `OTEL_SERVICE_NAME` in a group: every agent's provider keeps its own
+`service.name`, the root's provider takes the declared name, and one startup WARNING names the value
+and says it applies to the root only. A `service.name` given only in `OTEL_RESOURCE_ATTRIBUTES` --
+no `OTEL_SERVICE_NAME` -- **MUST** fail the start of a group, naming both ways out: taken as declared
+it would name every agent alike. Standalone it is used as declared.
+
+An agent's own `service.name` is its name, or `.otel_service_name` when the agent sets one for
+itself; the root's `otel_service_name` never applies to an agent. *(Amended 2026-10-20, N16: the
+agent's own setting was resolved and never used.)*
+
+### C3 -- Liveness is never namespace-dependent
+
+The liveness probe **MUST** reflect only process and event-loop health. A degraded namespace
+**MUST NOT** cause a liveness failure, because that restarts every agent in the group.
+
+**One exception: a transport fault no retry can fix.** The broker answered, and the answer is final
+-- a durable that filters another subject (C1), a stream the server refuses to create or widen, a
+grant the account lacks, a tenant's login or deliver subject refused. Such a fault **MUST** take
+liveness DOWN, in whichever agent it happens and whatever its `critical` flag, and **MUST** be logged
+CRITICAL with what failed, where, why it is final and what to change; `/health/live` answers 503
+naming each such agent and its reason. The agent consumes nothing until someone changes the broker
+or the deployment, so the pod is short a consumer for good, and a restart is how the orchestrator
+makes an operator look. Restarting the group's other agents is the accepted price. A fault that may
+heal -- the broker unreachable, a connection lost, a timeout, a stream not yet provisioned -- stays
+a degraded namespace under this invariant and `readiness_policy`. *(Amended 2026-10-20, owner
+decision D23: liveness was `UP` unconditionally.)*
+
+**An orphaned agent also takes liveness DOWN**: one that should consume and does not, for a reason
+that does not pass by itself -- its resume after a degradation keeps failing (the client is paused
+and so reports healthy), or its connection loop gave up (`event_client_max_retries`). Unlike the
+fault above it may still clear, so liveness comes back when the agent consumes again. *(Amended
+2026-10-20, N12 / D21, decided with D23.)*
+
+Readiness **MUST** follow `readiness_policy`:
+
+| Value | Behaviour |
+|---|---|
+| `"all"` | **Default.** Any degraded namespace makes the pod not ready. Reproduces current behaviour. |
+| `"critical"` | Only namespaces marked `critical` gate readiness. |
+| `"any"` | Ready while at least one namespace is up. |
+
+Whatever the policy, a namespace latched down (sec. 9.1, and a non-critical agent whose transport
+failed for good) **MUST** gate readiness: it consumes nothing for a reason that is not transient,
+and a policy that ignores it would report a pod short a consumer as ready. *(Amended 2026-10-20,
+N12 / D21: the policy decided for latched namespaces too.)*
+
+A degraded namespace **MUST** be reported as `blueprint_namespace_up{agent="..."} = 0` and an
+ERROR-level event regardless of policy. Alerting is driven by that signal, not by the probe. C7
+generalises this to every path that stops a namespace serving, not only the ones readiness reads.
+
+### C4 -- A degraded namespace stops consuming
+
+Readiness gates HTTP only; a not-ready pod still holds subscriptions. A namespace that becomes
+degraded **MUST** stop consuming its events so they redeliver to a healthy replica. With
+per-namespace transports (sec. 6) this is pausing that namespace's consumption, not closing its
+client: its NATS client drains its own subscriptions and keeps its connection open, its sessions
+job stream (`SessionsBus`) is paused likewise, and both resume when the namespace's health checks
+pass again. A JetStream delivery that still reaches a paused namespace is nak'd without running;
+under Dapr the event is not offered to the paused agent and is answered `RETRY`. *(Amended
+2026-10-19, PR #96 review: paused and resumed rather than closed -- a closed client reports
+unhealthy for ever, so the pause could never end, and publishing stays available.)*
+
+### C5 -- Configuration is namespace-scoped
+
+Each namespace **MUST** receive a `Config` with `agent_scope` set to its namespace name, so
+`.` resolves before the root ``. Infrastructure keys stay at root; prompts,
+model selection and usage limits become per-agent.
+
+### C6 -- Agent code cannot observe its grouping
+
+No API reachable from agent code **MUST** expose the group name, the group's membership, or the
+number of namespaces in the process. This is what makes regrouping incapable of breaking agent
+code. `deployment.group` on telemetry resources is set by the framework and is not readable
+through a supported API.
+
+### C7 -- Failure is never silent at namespace granularity
+
+Every path that removes a namespace from service **MUST** emit an ERROR-level event carrying that
+namespace's telemetry identity (C2), independently of any pod-level symptom. A failure observable
+only as a pod restart, a latency regression, or a metric that stopped arriving does not satisfy
+this invariant.
+
+C7 exists for a different reason than C1-C6. Those keep regrouping invisible from outside the
+process; C7 is what makes the residual isolation cost of grouping *manageable*. Three failure
+classes take a whole group down, and none of them raises a catchable exception:
+
+| Class | Why handler-level `try` / `except` cannot see it |
+|---|---|
+| Memory limit breached | The cgroup limit is per-pod; the kernel kills the process |
+| Native extension crash | The process dies without unwinding |
+| Event loop blocked | Not an error at all -- a latency and liveness symptom |
+
+Careful exception handling lowers how often a group dies; it cannot change which failures kill it.
+What remains available is attribution, so attribution is normative:
+
+- **In-process degradation.** `blueprint_namespace_up{agent="..."} = 0` plus an ERROR event for
+ every path that stops a namespace serving -- not only the paths that gate readiness (C3).
+- **Detached tasks.** Every task the framework creates via `ensure_future` / `create_task`
+ **MUST** carry a done-callback that logs exceptions with the namespace attached. The existing
+ `self._retry_task.add_done_callback(self._on_retry_done)` (`clients/io/nats_client.py:77`) is the
+ pattern; a bare `ensure_future` is a C7 violation.
+- **Silent consumer loss.** A namespace whose subscriptions are gone while the process stays
+ healthy **MUST** drive `blueprint_namespace_up = 0`. `subscriptions_ready`
+ (`clients/io/nats_client.py:60`) already carries this per client; per-namespace clients (sec. 6)
+ make it per-agent.
+- **Process-terminating failures.** These cannot report themselves, so the framework **MUST** emit
+ enough per-namespace context beforehand to attribute them post-mortem: the namespace on every
+ in-flight handler span, and a periodic per-namespace in-flight gauge. Without it an OOM kill is
+ indistinguishable across a group's agents, and the grouping dial cannot be turned in response.
+- **Blocked loop.** The dev-mode slow-callback threshold (sec. 11.1) **SHOULD** also run in
+ production at a higher threshold, logging the namespace of the executing handler. This is the one
+ group-wide failure class that is detectable from inside the process. *(Amended 2026-10-19, PR #96
+ review: met by the loop watchdog, on by default in every environment; it names the agents with
+ work in flight, since the blocking callback has returned by the time it runs. asyncio's debug
+ mode is opt-in, sec. 11.1.)*
+
+Grouping removes the pod restart that used to serve as the alert, so the alert **MUST** be emitted
+deliberately rather than inferred from a restart.
+
+---
+
+## 4. Public API
+
+### 4.1 New
+
+*(Amended 2026-10-19, PR #96 review: the names as implemented. `AgentGroup(config)` /
+`.add()` / `.with_group()` / `.from_group()` / `.build()` became a constructor over named
+declarations, `from_config`, `resolve` and `assemble`.)*
+
+```python
+class AgentGroup:
+ """The agents one process hosts, and the single application they become."""
+ def __init__(self, name: str, agents: Mapping[str, AppBuilder], *,
+ settings=None, secrets=None, roots=None, critical=None) -> None: ...
+
+ @classmethod
+ def resolve(cls, config: Config) -> "AgentGroup" # GroupConfig.resolve + from_config
+
+ @classmethod
+ def from_config(cls, group: GroupConfig) -> "AgentGroup" # import each module the group names
+
+ def assemble(self, config: Config) -> FastAPI # one root builder, one build()
+
+
+class GroupConfig:
+ """Resolved group composition. A value object; performs no I/O once constructed."""
+ name: str
+ agents: tuple[AgentSpec, ...] # name, module path, root, critical flag
+ image_root: Path
+ # No cache list: an agent may use only the caches it declared itself (sec. 8).
+
+ @classmethod
+ def resolve(cls, config: Config) -> "GroupConfig":
+ """Read file + env, validate against the agent map, or raise GroupConfigError."""
+
+
+def run_app(app: FastAPI, config: Config) -> None: ...
+```
+
+`GroupConfig.resolve` is the only member that reads the environment, the group file or the agent
+map. `AgentGroup.from_config` **MUST NOT** read the environment -- importing the agent modules a
+`GroupConfig` names is not a configuration read -- so tests can construct a `GroupConfig`
+literally. *(Amended 2026-10-19, PR #96 review: `from_config` replaces `with_group`; besides the
+imports it checks each agent's directory layout and whether `settings.toml` / `.secrets.toml`
+exist there, and `assemble` reads those files, sec. 5.3.)*
+
+**Collection is its own class, and `AppBuilder` MUST NOT know it can be collected.** An
+`AppBuilder` never absorbs another builder and exposes no group concept; `AgentGroup` constructs
+its own and replays what each agent recorded. This is what keeps one fluent surface honest: the
+group's restrictions belong to the thing imposing them, so `AppBuilder` stays permissive and every
+refusal in sec. 4.2 is raised by `AgentGroup` -- except the instance refusal, which
+`AppBuilder.build(config)` applies too (sec. 10). *(Amended 2026-10-19, PR #96 review.)*
+
+### 4.2 Changed
+
+```python
+class AppBuilder:
+ """One declaration surface. Records what it is told; wires nothing until build()."""
+ def __init__(self, config: Config | None = None) -> None: ...
+
+ # with_handler / with_service / with_agent / with_scheduler / with_rest_api:
+ # signatures unchanged. They record; nothing is constructed until build().
+
+ def with_cache(self, enabled: bool = True, enable_locking: bool = True,
+ *, name: str = "default") -> "AppBuilder"
+ def with_health_checker(self, name: str, checker) -> "AppBuilder"
+
+ def build(self, config: Config | None = None) -> FastAPI
+
+ @property
+ def declarations(self) -> tuple[Declaration, ...] # what AgentGroup replays
+```
+
+**Deferred wiring is normative.** A `with_*` call **MUST NOT** construct a component or enter
+anything into the registry; both happen only in `build()`. This is not a style preference:
+constructing a component reads the namespace from a `ContextVar` (sec. 4.3), so one built during a
+`with_*` call belongs to whichever namespace was in force at that line and can never be moved
+afterwards. Recording instead of constructing is what lets one class serve both the standalone and
+the grouped shape, and it is why no second collector type (`AgentRegistration`, `NamespaceBuilder`)
+needs to exist.
+
+`AppBuilder.build()` wires at the **root** namespace. There **MUST** be no `with_namespace` method
+and no `namespace` parameter on any `with_*` method: standalone has no namespace to name, and an
+agent's name lives only in the group configuration (sec. 11).
+
+**Configuration resolution:** `build(config)` or `AppBuilder(config)` -- giving both **MUST** be
+refused -- else the default settings files. *(Amended 2026-10-19, PR #96 review: `build()` raises
+when a configuration is given twice; there is no precedence between the two.)* `AgentGroup` **MUST** refuse a builder that carries its own
+configuration -- one process has one settings tree and one port -- and **MUST** wire each agent
+with that agent's own scoped view (C5).
+
+**What `AgentGroup` refuses, each because a group cannot honour it:**
+
+| Recorded call | In a group | Capability lost |
+|---|---|---|
+| a class plus kwargs | allowed | -- |
+| a factory or lambda | allowed; called inside the namespace scope | -- |
+| an already-constructed **instance** | **refused** -- its namespace and registry key were fixed before the group existed | none: the factory form recovers it |
+| `AppBuilder(config)` | **refused** -- one process, one settings tree, one port | none |
+| `with_cache(...)` | allowed; the name is qualified per agent (sec. 8) | -- |
+| `with_health_checker(...)` | allowed; the key is qualified per agent | none |
+| a builder whose `build()` already ran | **refused** -- already wired at the root | none |
+
+Every refusal **MUST** name the agent and the fix. Refusals land at assembly, not at authoring
+time: `with_cache()` runs at import, long before anything knows whether this builder will be
+collected.
+
+**Registration order keeps its meaning.** An instance is constructed by the caller at its own
+source line, a class during `build()`, so an instance recorded *after* a class would register
+*before* it -- which can flip equal-priority handler tie-breaking, resolved by registration order
+today. `build()` knows both the recorded order and which entries were instances, and **MUST**
+register the handlers in declaration order: after the replay it puts them back into the
+registry slots they already hold, in the order they were declared, so nothing else the registry
+holds moves. *(Amended 2026-10-19, PR #96 review: replaces "MUST raise on that combination rather
+than silently reordering" -- restoring the declared order keeps tie-breaking as written without
+refusing a valid declaration. The case arises only where instances are accepted -- `AppBuilder(config).build()`,
+or `build()` with no argument; `build(config)` and a group refuse instances.)*
+
+**`with_cache` is the one place where the obvious design breaks compatibility.** The current
+signature is `with_cache(enabled: bool = True, enable_locking: bool = True)`
+(`app_builder.py:117`). Making `name` the first parameter would turn an existing
+`with_cache(False)` -- meaning *disable caching* -- into a cache named `False`, silently enabling
+the cache with no `TypeError`. `name` therefore **MUST** be keyword-only and **MUST** follow the
+two existing positional parameters.
+
+### 4.3 Component
+
+`Component.__init__` **MUST NOT** gain a namespace parameter. The namespace is read from a
+module-level `ContextVar` set by `AgentGroup` around each agent's wiring, so no user subclass
+constructor signature changes and no positional argument shifts.
+
+`Component.executor` returns the namespace's `ThreadPoolExecutor`, falling back to root. The
+executor **MUST** be created lazily on first access; an app that never performs blocking work
+**MUST NOT** spawn one. (Eager creation in `build()` would add ~`cpu_count + 4` idle threads to
+every existing single-agent app, and works against #36's thread-count budget.)
+
+---
+
+## 5. Configuration
+
+### 5.1 Group resolution
+
+Read **before** `Config` is constructed -- group composition determines which agents get a
+`Config` at all -- so these are plain environment reads plus one YAML parse, deliberately not
+routed through Dynaconf. Hence the `BLUEPRINT_` prefix rather than Dynaconf's `DYNACONF_`.
+
+| Variable | Default | Meaning |
+|---|---|---|
+| `BLUEPRINT_GROUP_CONFIG` | `./deployment-groups.yaml` | Path to the group file. Absent file is not an error if env vars supply the group. |
+| `BLUEPRINT_GROUP` | -- | Group to load. **MAY** be omitted when the file declares exactly one group. |
+| `BLUEPRINT_AGENTS` | -- | Comma-separated agent names. Supplies the group without a file. |
+| `BLUEPRINT_CRITICAL_AGENTS` | -- | Comma-separated subset marked `critical`. |
+
+**Precedence: environment variables override the file, key by key.** The resolved value of every
+key, and its source, **MUST** be logged at startup.
+
+Resolution **MUST** fail with `GroupConfigError`, naming the file or variable and the fix, when:
+a group file declares one group name more than once; `agents` or `critical_agents` in the file
+is not a list (a scalar is refused, not split); a group names one agent twice; or the critical
+names (`critical_agents` / `BLUEPRINT_CRITICAL_AGENTS`) include an agent the group does not run
+-- once critical names are given, every agent they do not name is non-critical, so a misspelt
+name would make the whole group non-critical. *(Amended 2026-10-19, PR #96 review: refusals as
+implemented.)*
+
+Both mechanisms **MUST** be supported; neither is preferred. The file suits ConfigMap mounts and
+local development, env vars suit `docker run` and CI, and env values live in the pod template so
+changing them triggers a rolling update on their own.
+
+### 5.2 Runtime keys
+
+Defaults corrected 2026-10-15 to what ships: the NATS limits are unset unless configured, and
+the server's defaults apply (feature changelog, named connections step 6).
+
+| Key | Default | Meaning |
+|---|---|---|
+| `readiness_policy` | `"all"` | See C3. |
+| `executor_workers` | `os.cpu_count() + 4` | Per-namespace thread pool size. Bounded per #36. |
+| `nats_queue_group` | `app_name` | Queue group for the root namespace only. |
+| `nats_ack_wait` | unset -- the server's (NATS: 30 s) | Seconds. **MUST** exceed p99 handler duration unless the heartbeat is on (it is by default: a running delivery reports `in_progress` every third of `ack_wait`). See sec. 7.3. |
+| `nats_max_ack_pending` | unset -- the server's (NATS: 1000) | Per-consumer, shared across replicas. `-1` unlimited. Keep it near replicas x `nats_max_concurrent_runs`: what a pod receives beyond the runs it has started waits in the client's queue while its `ack_wait` runs. |
+| `nats_max_deliver` | unset -- the server's (NATS: unlimited) | Attempts before the message is dead-lettered. `-1` unlimited, and then nothing is ever dead-lettered. |
+| `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, `nats_heartbeat_enabled` | see the configuration reference | Concurrent runs per (agent, connection), the process pool beyond each pair's guaranteed run, a per-run time limit, the `in_progress` heartbeat. Added by `docs/plans/2026-10-14-named-connections.md`. |
+| `nats_connection_source`, `nats_connections_readiness`, `nats_unclaimed_subjects` | see the configuration reference | Named connections. Same plan. |
+| `nats_dead_letter_subject` | `.dead-letter` | Where a message the framework gives up on is republished. Derived from the agent's identity, as the queue group is (C1). `""` disables it and loses those payloads. **MUST NOT** be a wildcard or a subject the same namespace consumes. |
+| `idempotency_enabled` | `false` | Opt-in dedup. See sec. 7.4. |
+| `idempotency_ttl` | -- | Dedup window. |
+| `scheduler_mode` | -- (**required** with a scheduler) | `"event"` or `"in_process"`. Deliberately without a default; per namespace. See sec. 7.5. |
+| `event_publishing_enabled` | `false` | Opt into publishing without consuming. Requires `event_bus`. See sec. 7.5. |
+
+### 5.3 Settings authoring
+
+A group's own `settings.toml` supplies **defaults, and only defaults**. An agent author writes
+plain top-level keys in their own directory's `settings.toml` (`model_name = "..."`), not
+`[default.]`, and the build **MUST** merge that fragment **under that agent's scope** so C5
+resolves it, without the author knowing the scope exists.
+
+An agent may therefore set any key for itself, and **MUST NOT** be able to change what another
+agent or the process sees. A fragment and a root key never occupy the same slot, and a default
+restated in an agent's fragment is simply that agent's own value. Where a slot *could* be
+shared, the framework **MUST** refuse rather than merge or resolve, naming the agent and the key:
+*(Amended 2026-10-19, PR #96 review: replaces "there is consequently no collision to report" --
+these cases exist and are refused.)*
+
+- a root key named like the agent whose value is not a section -- merging the fragment would
+ replace that value for the whole process (`ConfigError`);
+- an agent named like a configuration section the process shares (`cache`, `event_publishing`,
+ `runtimes`, `runtime`) -- refused by namespace validation, since its fragment would be merged
+ into that shared section;
+- a bare key naming another agent, read through an agent's view -- at the root it is that agent's
+ whole section (`ValueError`), as is a dotted key outside the shared nested sections;
+- a fragment that scopes its keys under the agent's own name (`[default.]`), which would
+ nest as `..*` and be read by nothing (`ConfigError`).
+
+Process-scope keys in an agent fragment **MUST** be dropped at startup with a WARNING per key
+naming the agent, the key, the file and the value the process uses instead (a secrets file's
+values are not logged), from an explicit list: `PROCESS_SCOPE_KEYS` (`app_port`, `app_host`,
+`app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`,
+`suppress_noisy_loggers`, `health_check_interval_seconds`, `startup_retry_interval_seconds`,
+`readiness_policy`, `dot_placeholder`, `nats_stream_name`, `nats_connection_source`,
+`nats_extra_runs_per_process`) plus the deployment-identity keys (`blueprint_group`, `pod_name`,
+`hostname`). Scoped, such a key is read by nothing and reported by nothing -- C7's failure mode
+in configuration form -- and the WARNING is what lets its author discover that the value they set
+is inert. *(Amended 2026-10-19, PR #96 review: replaces "MUST raise" -- every example project
+declares `app_port` and `app_environment` in its settings file, so raising would bar any existing
+project from a group until edited; the list is longer than the four keys first named.)*
+
+What happens when a *required* key is absent is deliberately not specified here. It is
+`docs/plans/2026-09-10-config-validation-unification.md`, kept out of this feature so that the
+two cannot fail together.
+
+---
+
+## 6. Transport topology
+
+One `NATSClient` **per namespace**, not one per process.
+
+**This section applies to the direct-connection transport only.** Under Dapr the application holds
+no broker connection at all: `DaprClient` is an `httpx` client against the sidecar
+(`clients/io/dapr_client.py:89`), subscriptions are declarative (`GET /dapr/subscribe`, then the
+sidecar posts to `POST /events/{topic}`), and the sidecar owns and multiplexes the one broker
+connection per pod. Broker connections therefore track pods rather than agents on that path, and
+reasons 1 and 2 below move into the sidecar and out of this spec's reach. A per-namespace
+`DaprClient` **MAY** still be created for health attribution and for C4, but it **MUST NOT** be
+described as confining ack loss or slow-consumer disconnects, because it does not.
+
+Per-namespace clients deliberately trade back part of the shared-connection advantage credited
+to the namespace model. This is justified by three things, in order of weight:
+
+1. **Ack loss is confined.** A handler that completes 60 s of inference and then cannot ack
+ because the connection is down has already committed its side effects; the broker redelivers
+ after `ack_wait`. Duplicate processing is therefore *certain*, not merely possible. On a shared
+ connection one blip does this to every in-flight message across every agent in the group.
+2. **Slow-consumer disconnects are confined.** The broker kicks a connection whose pending buffer
+ overflows. Shared, one flooding agent takes down the group's transport and triggers a
+ re-subscribe storm across all namespaces (`clients/io/nats_client.py:265-280`).
+3. **Attribution.** When this spec was written, `nats.connect()` was called with no `name=`, so
+ every connection the framework opened was anonymous in `/connz`. Per-namespace named
+ connections make a pod's contents legible in connection-oriented tooling. *(Amended
+ 2026-10-19, PR #96 review: implemented; the defect is history.)*
+
+**Durability is not among the three, and the topology MUST NOT be justified by it.** JetStream
+pending state lives on the server, keyed by consumer and stream sequence; an ack is a message
+published to the per-delivery `$JS.ACK...` reply subject, not an entry in a framework-side
+registry. Nothing aggregates in-flight events on behalf of the namespaces sharing a process, so a
+shared connection has no such state to lose when the process dies -- `ack_wait` expires and the
+broker redelivers. What the topology decides is not whether work survives a failure, but **how many
+namespaces repeat work** when a connection drops. The durability question is settled by sec. 7.1
+and 7.2 (JetStream on, acks actually sent), not here.
+
+Cost accepted without a config knob: connection count scales with agent count. A connection is a
+socket plus buffers -- tens to low hundreds of KB -- against ~65 MB for the smallest possible
+separate process (#32). Protecting a few MB with a knob nobody should use is not worth the
+maintenance surface. 100 agents at 2 replicas is ~200 connections, which is not a practical
+constraint against a self-operated broker's default `max_connections`. The number **SHOULD** be
+checked before a large rollout only where the cap is issued externally per account -- a managed
+broker, or an operator-mode account whose JWT carries a `conn` limit set by someone else. Such
+authentication is wired: user and password, token, an nkey seed and a credentials file
+(`nats_creds_file`) reach `nats.connect()`. *(Amended 2026-10-19, PR #96 review: "no such
+authentication is currently wired" is history.)*
+
+A namespace that neither subscribes to anything nor publishes anything **MUST NOT** be given a
+client. A pure-scheduler agent on `scheduler_mode = "in_process"` that does not opt into publishing
+(sec. 7.5) is that case: a connection for it is a socket, a readiness dependency and a `/connz`
+entry for traffic that does not exist, and it would put a pod on a broker that the agent's own
+deployment may have no access to. The cost argument above justifies a connection *per namespace
+that uses one*; it does not justify one per namespace that does not.
+
+Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming.
+**Exception -- a standalone agent** (namespace `""` and no resolved group): the name **MUST** be
+the pod alone, and **MUST** be omitted when the pod cannot be determined. Neither a namespace nor a
+group exists for it, and `..` would imply a grouping that is not there; an
+omitted name is what a standalone agent sent before this feature. The root of a process whose
+group is named keeps the full form.
+The group is the one the process resolved: `BLUEPRINT_GROUP`, or the one group a group file
+declares when the variable is unset. *(Amended 2026-10-19, PR #96 review: the resolved group, not
+only the variable -- a group named by the file alone reached neither the connection name nor the
+telemetry resource.)*
+An absent segment **MUST** be filled with a placeholder rather than left empty -- `` for the
+root namespace, `` when no group was resolved, `` when the replica
+cannot be identified -- so all three positions always carry a value, a name never degenerates into
+`..pod-7`, and "no group" stays distinguishable from a group whose name happens to be empty.
+
+The placeholders **MUST** be unproducible by a real value rather than merely unlikely, because a
+placeholder that collides with a legitimate name reintroduces exactly the ambiguity it was
+introduced to remove. Two rules give that:
+
+- The namespace alphabet (C1, below) excludes `<` and `>`, so no legal namespace can spell one.
+- The group and the pod are supplied by the deployment and **MUST NOT** be rejected on this
+ ground -- failing a rollout over a display string is the wrong trade -- so they **MUST** be
+ sanitised for display instead: `<`, `>`, `.` and whitespace replaced. Replacing `.` is not
+ cosmetic; it keeps a group called `a.b` from turning a three-segment name into four and
+ misattributing the connection. Sanitising rather than validating is acceptable here only
+ because nothing derives from the connection name (C1), so a mangled segment loses no
+ information any consumer depends on.
+
+`EventPublishingService` **MUST** publish on its own namespace's client; otherwise outbound
+traffic is unattributable and reason 3 is defeated.
+
+Per-namespace clients also make C4 a per-client pause -- the client drains its own subscriptions
+and keeps its connection -- rather than selective unsubscription on a shared client, and give
+`ClientHealthChecker` per-agent health entries that feed `readiness_policy = "critical"` directly.
+*(Amended 2026-10-19, PR #96 review: a pause, not a close; see C4.)*
+
+---
+
+## 7. Event delivery
+
+### 7.1 Competing consumers
+
+With N replicas of a group, exactly one replica **MUST** process any given event. Core NATS
+subscriptions **MUST** pass a queue group; JetStream consumers **MUST** share a durable per C1.
+
+When this spec was written the code did neither: core subscriptions passed no `queue=`, so
+`replicas: 2` doubled every side effect and every inference bill -- a defect independent of
+grouping (see #20, #35). Core subscriptions now pass the queue group (C1) and JetStream consumers
+share their durable with a deliver group; JetStream stays off by default (`nats_use_jetstream`).
+*(Amended 2026-10-19, PR #96 review: the defect is history.)*
+
+### 7.2 Acknowledgement
+
+When this spec was written, JetStream subscriptions used `manual_ack=True` and **no `msg.ack()`
+call existed anywhere in the codebase**, so every JetStream message redelivered until
+`max_deliver` -- already a defect at one replica. Every JetStream delivery is now settled
+(`ack`, `nak` or `term`) per the table below. *(Amended 2026-10-19, PR #96 review: the defect is
+history.)*
+
+**Decision: ack after the handler completes.** The alternative (ack first) converts a connection
+blip from duplicate work into *lost* work, which is worse for expensive, side-effecting inference.
+Consequently at-least-once is permanent, and sec. 7.4 applies.
+
+**The contract is that a normal return acknowledges and a raised exception does not.**
+`ProcessingStatus` carries no failure value -- it is `PROCESSED`, `NO_HANDLER_FOUND` or `SKIPPED`
+-- so every failure already reaches the transport as an exception. *(Amended 2026-10-19, PR #96
+review: `SKIPPED` added, see below.)* The transport edge **MUST NOT** inspect
+`ProcessingResult` to decide acknowledgement: `ProcessingResult` is a reporting object and **MUST**
+remain independent of delivery control.
+
+| Outcome at the transport edge | NATS | Dapr response |
+|---|---|---|
+| Handler chain returned, any status | `ack()` | `SUCCESS` |
+| `RetryableHandlerError` | `nak()` | `RETRY` |
+| `InvalidEventError` | `term()` | `DROP` |
+| `CriticalHandlerError` | `term()` | `DROP` |
+| Any other exception raised during dispatch | `nak()`, bounded by `max_deliver` | `RETRY` |
+| Payload fails JSON or CloudEvent parsing, before dispatch | `term()` | `DROP` |
+
+**`NO_HANDLER_FOUND` MUST acknowledge.** An event that matches no handler's conditions has nothing
+to do, and redelivery cannot make a handler appear: a nak is a pointless loop until `max_deliver`,
+and under a queue group a loop that visits every replica in turn. When this spec was written the
+Dapr endpoint returned `RETRY` for this case; it now answers `SUCCESS`. *(Amended 2026-10-19,
+PR #96 review: the defect is history.)*
+
+**An unmatched event is acknowledged, and it is reported as a probable misconfiguration
+(changed 2026-10-15).** Deciding there is nothing to do is the handler's job: a handler that is
+responsible for the event and finds no work in it returns `HandlerResult.skipped(reason)` (below),
+which is an ordinary outcome, logged at INFO. An event that *no* handler takes therefore no longer
+stands for "the agent found nothing to do" -- it means the agent is subscribed to something none of
+its handlers routes, or a handler declines what it should claim. The framework **MUST** log it at
+WARNING ("No handler processed event", from the handler chain) and **MUST** still acknowledge it,
+since no redelivery makes a handler appear. It **MUST NOT** accumulate per-topic state about it --
+under Dapr the topic arrives from a URL path, so remembering each distinct value lets a caller grow
+the process's memory. (Before 2026-10-15 this paragraph required the opposite -- no WARNING --
+because "nothing to do" could only be said by declining; the chain logged a WARNING regardless.)
+
+It **MUST** be counted per namespace and topic, for one purpose: the *proportion* of received
+events a namespace declines is how a too-broad subscription shows up (sec. 7.7). A high count is a
+question about the subject filter, not about the handler. Under Dapr, a topic the agent did not
+declare is counted under the topic label `` (every topic is, with
+`dapr_declarative_subscriptions`), and the real topic stays in the log line; the same label
+applies to the duplicate and skipped counters. *(Amended 2026-10-19, PR #96 review: the label is
+what keeps a caller-chosen URL path from minting one time series per request.)*
+
+**A skip is the selected handler's own "nothing to do" (added 2026-10-15).** A handler that is
+responsible for an event -- `can_handle_event` routed it there -- and finds that this particular
+event needs nothing returns `HandlerResult.skipped(reason)`. The chain stops (no later handler is
+asked, unlike `None`), the run reports `ProcessingStatus.SKIPPED`, nothing is published, the reason
+is logged at INFO, and the transport acknowledges as for any return. It is counted apart from
+unmatched events, as `blueprint.events.skipped` per agent and topic: a skip is the agent's relevance
+rule at work, not a sign that the subscription is too broad. A REST caller gets `success = true`
+with the reason as message.
+
+**Both transports MUST map the same outcome to the same disposition.** Dapr's response dict *is*
+its acknowledgement, so the table above is normative for `dapr.py` and
+`event_handling_base.handle_event` exactly as it is for `nats_client.py`. When this spec was
+written they disagreed in two places: `NO_HANDLER_FOUND` as above, and `CriticalHandlerError`,
+which the Dapr endpoint retried -- a critical error is not made less critical by being delivered
+again. Both now map per the table. *(Amended 2026-10-19, PR #96 review: the defect is history.)*
+
+`max_deliver` **SHOULD** be configured, because nak on an unexpected exception otherwise
+redelivers indefinitely. `nats_max_deliver` is optional: unset, the server's default applies
+(NATS: unlimited) and nothing is ever dead-lettered; `-1` asks for unlimited explicitly and is
+warned about at startup. The dead-letter destination needs no configuration: it defaults to
+`.dead-letter` (sec. 5.2). *(Amended 2026-10-19, PR #96 review: replaces "MUST be
+configured" -- the framework sets no consumer limits a deployment did not configure, sec. 5.2.)*
+
+The nak on the last delivery `max_deliver` permits **MUST** be rendered as a dead letter followed
+by a term, not as a nak. The broker will not redeliver it, so a nak there differs from a term only
+in that the message leaves the consumer without a trace of why, and one `ack_wait` later than it
+had to. A dead letter **MUST** carry the original payload bytes unchanged -- a payload that failed
+to parse is the one most worth keeping -- with the reason, origin subject, delivery count and event
+id in headers rather than in the body.
+
+Implementations **SHOULD** capture the ack reply subject and retry the ack after a reconnect,
+which narrows the duplicate window from "certain on any blip" to "only if the pod also dies".
+Two caveats make this a prototype rather than a design commitment: a redelivery may already be in
+flight when the retry lands, and the behaviour of acking a stale delivery attempt depends on how
+the server keys pending state on stream sequence. **MUST** be validated against a real broker.
+
+### 7.3 Long handlers
+
+`ack_wait` **MUST** exceed p99 handler duration, or a slow handler is redelivered to another
+replica while the first is still working -- unless the delivery is heartbeated. Since the
+named-connections work (2026-10-14) a running JetStream delivery reports `in_progress()` every
+third of its consumer's `ack_wait` by default (`nats_heartbeat_enabled`), and `nats_handler_timeout`
+bounds a run. Heartbeats address slow handlers; they do **not** address connection loss, since
+they travel over the same connection, and they do not cover messages still waiting in the client's
+queue (bound those with `nats_max_ack_pending`).
+
+**A run knows its attempt (added 2026-10-15).** Every JetStream delivery, on the default and on
+named connections, puts `nats_delivery_attempt` (1-based, from `num_delivered`) and
+`nats_max_deliver` (the consumer's limit; `None` when unlimited or unknown) into the handler
+context, beside `nats_topic`, `nats_subject` and `nats_connection`. Equal values mark the last
+attempt, after which a failure is dead-lettered or dropped. Core NATS deliveries carry neither key.
+
+### 7.4 Idempotency
+
+At-least-once is unavoidable: rebalance, eviction, node drain and every rolling deploy produce
+redelivery, and ack loss guarantees it.
+
+This is a cost of *replication*, not of grouping. A single-agent process replicated twice faces the
+same competing consumers, the same redelivery and the same lost ordering, so the requirement lands
+identically on a pre-migration app that scales past one replica. It is specified here because
+grouping is where the requirement becomes visible, not because grouping creates it.
+
+Whether deduplication is *correct* depends on the product built on the blueprint -- some
+operations are naturally idempotent, others need business-level reconciliation the framework
+cannot see. The framework therefore **MUST NOT** silently enforce dedup, and **MUST**:
+
+- provide an opt-in dedup mechanism keyed on the CloudEvent `(source, id)` -- plus the connection
+ name for a delivery from a named connection (`nats_connection`) -- backed by the namespace's
+ cache with a TTL, applied in the handler chain before dispatch (`idempotency_enabled`). The
+ marker is claimed atomically before dispatch and kept only when the delivery is acknowledged
+ as a success; every other outcome releases it so the redelivery can run, and only the delivery
+ that won the claim releases it, never a duplicate. *(Amended 2026-10-19, PR #96 review: an `id`
+ is unique only within a source, and the same producer behind two connections emits the same
+ ids for different data; marker lifetime as implemented. Atomic across processes on Redis only,
+ sec. 7.5.)*
+- **flag the requirement explicitly to the agent author** -- a comment in the scaffolded handler,
+ a line in the generated README, and an `asbs validate` notice when a handler is registered with
+ `idempotency_enabled = false`. The author must make a decision, not inherit a default silently.
+
+### 7.5 Schedulers
+
+`SchedulerBase.on_startup` creates an `AsyncIOScheduler` per process with no leader election
+(#73), so every cron tick fires once per replica. Grouping widens the exposure: one pod hosting 20
+agents runs 20 schedulers, and two replicas duplicate all 20 agents' crons simultaneously.
+
+Two modes, selected by `scheduler_mode`:
+
+| Mode | Behaviour |
+|---|---|
+| `"event"` | No in-process timer. *(Amended 2026-10-19, PR #96 review: "Default" removed -- neither mode is the default, below.)* An external scheduler (Kubernetes `CronJob`) publishes an event; the agent handles it through its normal event path. |
+| `"in_process"` | `AsyncIOScheduler` in every replica, with each tick claimed in the shared cache so one replica runs it. For un-orchestrated Docker and local development. |
+
+`scheduler_mode` **MUST NOT** have a default: registering a scheduler without it **MUST** fail
+before the port is bound. Neither value is safe to inherit. `"in_process"` is the defect of #73 --
+one timer per replica, multiplied by every grouped agent in the pod -- and `"event"` needs a
+publisher and a transport that a service whose only job is periodic work may not have, so
+defaulting to it silences that service instead. Which value is correct depends on the deployment
+rather than the code: whether a broker is reachable, whether more than one replica runs, whether an
+orchestrator exists at all. The author therefore states it, exactly as sec. 7.4 requires for
+`idempotency_ttl`. `"event"` **MUST** additionally fail unless `event_bus` names a transport that
+carries topics, since a scheduler subscribed to nothing never ticks and reports no fault.
+
+`scheduler_mode` **MUST** resolve per namespace through C5, not once per process. A group may host
+a pure-scheduler agent that has to run `"in_process"` alongside an event-driven agent on `"event"`,
+and one process-wide value cannot express that -- which is exactly the deployment freedom grouping
+exists to provide.
+
+In `"event"` mode the framework **MUST NOT** start a timer, and the tick **MUST** be delivered as
+an ordinary namespaced event, so the queue group already guarantees single execution across
+replicas without electing anything. The publishing container **SHOULD** be a minimal NATS client
+image, not the agent image -- a `CronJob` running the agent re-pays the ~154 MB baseline (#32) for
+work that fires once a night.
+
+The schedule **MUST** remain declared in agent code, and the `CronJob` **MUST** be generated from
+that declaration -- the same generation path as manifests from `deployment-groups.yaml`. Hand-authored
+schedules let code expect a tick nobody scheduled.
+
+That generation path **MUST NOT** import a project's `src/main.py`. The declaration is reachable
+without it: configure from the project's settings and import the modules that define the
+schedulers. Generation **SHOULD** happen where the registrations are authored, and anything the
+generator cannot observe -- a registration-time rename, a scheduler needing constructor arguments
+-- **MUST** be reported rather than guessed at.
+
+Because manifests belong to a deployment group rather than to a single project once one image
+serves the platform (sec. 6, and the entrypoint model), the generator's input **SHOULD** be the
+group's agent map rather than one project's source tree.
+
+Independently of the manifest, the declared crontab **MUST** be validated in both modes, before
+the port is bound. `"event"` mode builds no `CronTrigger`, so nothing else parses the expression,
+and an invalid one otherwise presents as a scheduler that reports itself healthy and never ticks;
+`"in_process"` mode parses it only at startup and does not read it as an external cron would. It
+**MUST** be the five standard cron fields: an external scheduler reads those, and apscheduler's
+extensions -- a leading seconds field in particular -- are not portable to one.
+
+The day of the week is numbered as apscheduler numbers it, `0` = Monday to `6` = Sunday, which
+disagrees with a standard cron (`0` = Sunday) on every number. Day `7` **MUST** be refused in both
+modes (Sunday to cron, nothing to apscheduler). In `"event"` mode, where an external cron fires
+the tick, a day of the week given by number -- including `*/n`, which steps from day `0` -- **MUST**
+be refused: names (`mon-fri`, `sun`) read the same to both. *(Amended 2026-10-19, PR #96 review:
+replaces "validated in `"event"` mode" -- validation runs in both modes, and the weekday rules are
+added.)*
+
+**In-process coordination is a per-tick claim, not a leader lease.** An earlier form of this
+section called for a NATS KV or cache-backed leader lease. A slot claim satisfies the same
+requirement and is preferred, because it removes rather than answers the failover question: every
+replica's timer fires, each tries to store a marker keyed on `(scheduler, minute)` in the agent's
+own cache -- shared across that agent's replicas when the cache is Redis, and per sec. 8 invisible
+to every other agent, so two agents each running a scheduler of the same name cannot claim each
+other's slots -- and the replica that stores it runs the tick. *(Amended 2026-10-19, PR #96
+review: a disk cache is not shared across processes in a way the claim can rely on, below.)*
+Nothing is elected and nothing is held, so there
+is no renewal task to schedule (and therefore none to leak, C7), no lease left behind by a replica
+that dies holding one, and no takeover bound to specify -- the next slot is claimed from scratch by
+whoever is alive.
+
+The claim **MUST** use a set-if-absent primitive rather than a read followed by a write:
+`CacheService.claim`. Two replicas racing on an `exists`-then-`set` pair both pass the check and
+both tick, which is the failure this mechanism exists to prevent.
+
+`CacheService.claim` is atomic across processes only on the Redis backend. A disk cache's claim
+holds within one process: processes sharing one cache directory -- replicas on a shared volume,
+or `uvicorn --workers N` run by hand -- can each win the same key. Coordinating replicas therefore
+needs Redis. *(Amended 2026-10-19, PR #96 review: measured with diskcache-rs 0.4.10, several
+processes on one directory each won one key; how to proceed beyond documenting it is open, D22.)*
+
+The key **MUST** be derived from the scheduled slot rather than from the scheduler alone. Cron
+granularity is one minute, so replicas firing for the same scheduled time derive the same key and
+the next scheduled time derives a different one -- which is what keeps set-if-absent sufficient.
+The slot is the trigger's latest scheduled fire time at or before the current time, as a UTC
+minute, not the clock at run time: a run that starts late, or on a replica whose clock is a little
+ahead, still claims the slot it was scheduled for, and fire times that passed without a run are
+walked over rather than claimed late. Without a trigger, or before its first fire time, the clock
+decides. Clock skew therefore splits a slot only when it outlasts the marker (300 s); sec. 7.4
+covers that, as it covers every other repeat. *(Amended 2026-10-19, PR #96 review: replaces the
+clock-minute key, whose straddle of a minute boundary let two replicas both tick.)*
+
+With no cache registered there is nothing to claim with. The timer **MUST** still run -- the mode
+exists for local development, where requiring a cache would be gratuitous -- and startup **MUST**
+warn that ticks are uncoordinated, naming both remedies.
+
+Neither mode is exactly-once: `CronJob` is at-least-once (controller restart, missed
+`startingDeadlineSeconds`), and a claim fails open when the cache is unreachable, so every replica
+ticks. Sec. 7.4 therefore applies in both modes. `concurrencyPolicy: Forbid` **SHOULD** be set, and
+`CronJob` `timeZone` **MUST** be reconciled with apscheduler's timezone handling so the two modes
+do not diverge. The reconciliation point is the opt-in `scheduler_timezone` (an IANA name, per
+namespace): the `"in_process"` timer runs in it, and unset it keeps the host's local time as
+before. In `"event"` mode the external cron's own timezone decides and the key changes nothing,
+so the deployment sets `CronJob` `timeZone` to the same zone. *(Amended 2026-10-19, PR #96 review:
+how the reconciliation is done; CronJob generation is deferred, sec. 12.)*
+
+**Publishing and consuming are separate decisions.** A scheduler that emits a result event is a
+legitimate shape and **MUST NOT** require the agent to consume anything: an application that opts
+into publishing gets a transport client and no subscription, and its `event_bus` is what says a
+broker exists. Publishing **MUST** stay opt-in, because a project that wants only a timer may have
+no broker access at all, and a client created on its behalf becomes a readiness dependency on
+infrastructure it does not run.
+
+Note #43 -- schedulers being started twice *within* one process -- is a distinct defect with two
+causes, and both **MUST** be fixed: two `build()` passes driving the lifespan hooks twice, and
+`SchedulerBase` extending `RestApiBase` for its trigger route, which puts every scheduler in the
+REST-API lifespan loop *and* the scheduler loop within a single pass.
+
+### 7.6 Topic subscription scope
+
+Two agents subscribing to the same topic is legitimate and expected: both want the event. Topic
+deduplication **MUST** be scoped within a namespace. Each `(namespace, topic)` pair gets its own
+subscription and its own consumer. A cross-namespace "first declaration wins" rule would silently
+disable one agent's subscription, and the agent author could not observe it locally.
+
+### 7.7 Selection and fan-out
+
+Selection happens at two levels, and only one of them is enforced by the broker:
+
+| Level | Enforced by | Mechanism |
+|---|---|---|
+| Which subjects reach the process | broker | subscription subject, JetStream `filter_subjects` |
+| Which event a handler wants | in-process | `can_handle()` |
+
+NATS filters on **subject only** -- there is no content or header predicate -- so any selection
+finer than the subject is either encoded in the subject or paid for inside the process. Dapr can
+evaluate CEL rules over the CloudEvent, but in the sidecar, after the broker has already
+delivered.
+
+This matters at scale for a reason that is not CPU. With one consumer per `(namespace, topic)`
+pair (sec. 7.6), a broad subject makes the **broker** copy every message once per namespace, each
+copy carrying its own delivery, ack-pending state and redelivery timer. One hundred agents
+subscribed to `events.>` is a hundredfold fan-out before any handler code runs.
+
+**Selection that the framework is expected to push down to the broker MUST be declared
+statically.** `can_handle()` is imperative code and can never be pushed anywhere: it **MUST**
+remain available as the final in-process selector, and **MUST NOT** be the only selector
+available. Handlers **SHOULD** declare the subjects or event types they accept, and the framework
+**SHOULD** resolve declared event types to subjects through the same `topic_mapping` it uses when
+publishing, so publisher and consumer cannot drift.
+
+Two rules keep this non-breaking, and both are load-bearing, because **no handler in the framework
+or in any scaffolded project declares anything today**: `get_subscribed_topics()` is overridden
+only by the framework's own `SchedulerTickHandler`, the generated handler template selects purely
+inside `can_handle_event`, and
+`nats_subscriptions` appears in no generated settings file. Any design that treats declarations as
+authoritative therefore describes an empty set.
+
+1. **A handler that declares nothing MUST continue to be evaluated for every event its namespace
+ receives.** An in-process dispatch index **MAY** be keyed on declared event types as an
+ optimisation, but undeclared handlers **MUST** fall into a wildcard bucket that is always
+ evaluated. Without this every existing handler silently stops firing -- and because
+ `NO_HANDLER_FOUND` acknowledges (sec. 7.2), the events would be consumed and discarded rather
+ than accumulating visibly. This is the most destructive failure mode available in this design.
+2. **A broker-side filter MUST NOT be narrower than the union of the explicitly declared subjects
+ and the configured `nats_subscriptions` list.** Filters **MUST** derive from explicit
+ declarations only; the framework **MUST NOT** infer a narrower filter by reading handler code or
+ handler type checks. An agent subscribed to `orders.>` whose handler selects part of that space
+ on payload content has to keep receiving all of it.
+
+**Consumer reconfiguration is a migration, not a config change.** A durable's name and its filter
+set are broker-side state. Depending on server version, changing the filter set is applied in place
+or forces delete-and-recreate, and a recreated consumer resumes according to its delivery policy --
+replaying from the start of the stream, or skipping whatever arrived in between. Any release that
+changes a durable's name or filter set **MUST** state the migration explicitly, including whether
+replay or a gap is expected. This binds the durable renaming that C1 requires
+(`{namespace}-{topic}-durable`, replacing today's `nats_durable_name` default) exactly as it binds
+filter derivation: on first deploy, every pre-existing consumer becomes a new consumer.
+
+**Fan-out MUST be observable.** The framework **MUST** expose, per subject, how many namespaces
+select it. Together with the unhandled-event counter of sec. 7.2 this covers both directions of a
+subscription that is shaped wrongly: a subject delivered to namespaces that find no work in it, and
+a subject copied to far more namespaces than need it. Neither counter reports a fault on its own --
+they are read as ratios against the volume a namespace receives.
+
+Build-time gates on subject breadth belong to the implementation plan rather than here, because
+they constrain projects rather than the framework. They **SHOULD** ship as warnings before they
+become errors: the frozen compat suite and the generated-project smoke test cover runtime API and
+would not catch a newly failing build.
+
+---
+
+## 8. Caches
+
+Caches are looked up by name with no namespace dimension, which makes them a cross-agent
+collision surface: two independently developed agents both calling `get_cache("sessions")` share
+one cache the moment they are grouped, invisibly and only in production.
+
+An agent **MUST** have access to exactly the caches it declared with `with_cache`, and to no
+others. Cache names **MUST** be qualified by namespace, so two agents may both declare `sessions`
+and receive separate stores; `get_cache(name)` **MUST** resolve within the declaring agent and
+raise otherwise, with no root fallback and no shared-cache opt-in. Agents share no cache by
+design, and separate stores make that isolation structural rather than dependent on a key prefix
+being applied correctly at every call site.
+
+Two things follow. A group declares no caches of its own, so `GroupConfig` carries no cache list
+(sec. 4.1). And `/cache/*` is per agent: one process-wide cache endpoint would report one agent's
+keys to another, which is the collision this section exists to close.
+
+`registry.cache_service` (getter and setter) **MUST** be retained as an alias for the `"default"`
+cache in the root namespace.
+
+---
+
+## 9. Startup
+
+1. `GroupConfig.resolve(config)` -- file, then env overrides; log provenance.
+2. Validate every agent name against the in-image agent map. Fail with the group and the missing
+ agent named.
+3. Import each agent module lazily; read the declaration the agent map names
+ (`module = "pkg.mod:attribute"`).
+4. `AgentGroup.from_config(group)` -- one unbuilt declaration per agent. Steps 1-4 together are
+ `AgentGroup.resolve(config)`.
+5. `assemble(config)`, then `run_app(app, config)`. Every component is constructed here, inside
+ its own namespace scope; steps 1-4 construct nothing.
+
+*(Amended 2026-10-19, PR #96 review: `with_group` / `build()` are `from_config` / `assemble()`, sec.
+4.1; the declaration's attribute name comes from the agent map.)*
+
+Resolution **MUST** complete before the first `Component.__init__`, because namespace injection
+happens through a `ContextVar` read during construction. No incremental resolution.
+
+### 9.1 Failure policy
+
+There is no partial build: one process, one `build()`. The `critical` flag is therefore evaluated
+**before** a namespace is wired, not after an exception.
+
+| Failure | `critical: true` | `critical: false` |
+|---|---|---|
+| Agent missing from the agent map | exit non-zero | log ERROR, skip |
+| Module import raises | exit non-zero | log ERROR, skip |
+| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue; retry (below) |
+| No agent left after the skips above | exit non-zero | exit non-zero |
+| A transport fault no retry can fix (C3) | exit non-zero | exit non-zero |
+
+*(Amended 2026-10-19, PR #96 review: last row added -- a pod with no agent passes its probes while
+it consumes nothing, which is the failure criticality exists to prevent.)*
+
+*(Amended 2026-10-20, D23: last row added. `critical` decides only for failures that may heal,
+which is what the retry below is for; a fault no retry can fix would latch the agent down for good.
+Found after startup, such a fault is logged CRITICAL and takes liveness DOWN (C3); the root or a
+critical agent also ends the process, as for any fatal transport error.)*
+
+Exit **MUST** happen before the port is bound, so Kubernetes crash-loops with a readable message
+rather than reporting a healthy pod that is silently short-staffed.
+
+**A namespace marked down by a startup failure MUST be retried, and MUST NOT end the process.**
+Every `startup_retry_interval_seconds` (default 30, process scope) the framework calls `on_startup`
+again on that namespace's failed components, in their original start order, stopping at the first
+that raises again. When all of them have started, the mark is released and the namespace's health
+checks decide from then on. While it is marked, the readiness payload **MUST** report the namespace
+`DOWN` with the failure as its reason, whatever its health checks say, and the namespace gates
+readiness under every policy (C3) -- the mark exists because a
+component that failed to start may still pass its check. Terminating instead is not a recovery: a
+deterministic failure fails the same way after a restart, and the restart takes every healthy
+namespace in the process down with it. `on_startup` **MUST** therefore be safe to call again after
+it raised.
+
+The default for an unflagged agent is `critical: true`: a partially loaded group whose missing
+agent's queue has no consumer is a worse failure than no pod at all.
+
+### 9.2 Startup log
+
+**MUST** include: group name, agent list, the source of each resolved config value, and per
+namespace the queue group and durable names. The last item makes C1 verifiable by diffing startup
+logs across a regrouping.
+
+---
+
+## 10. Backwards compatibility
+
+An existing single-agent project **MUST** continue to work with no source change, no Dockerfile
+change, and `uvicorn src.main:app` as its entrypoint. Specifically:
+
+| Concern | Guarantee |
+|---|---|
+| `AppBuilder` fluent API | Unchanged. `AppBuilder(config)...build()` behaves as today, and no `namespace` parameter is added to anything. |
+| Passing a constructed instance to `with_*` | Unchanged for an application that builds itself (`AppBuilder(config)...build()`, or `build()` with no argument). Refused when the builder is collected into a group (sec. 4.2), and by `build(config)` -- which the scaffolded `create_app()` calls -- because a declaration built by a host has the shape a group hosts. *(Amended 2026-10-19, PR #96 review: was "refused only in a group".)* |
+| Component construction timing | Deferred to `build()`. Reading a component out of the registry between `with_*` calls was never supported -- collaborators resolve in `on_startup` -- and now breaks. |
+| `with_health_checker` keys | Bare name at the root, so an existing readiness payload is unchanged; qualified per agent in a group. |
+| OpenAPI tags and paths | Unchanged at the root: tags as the framework and the developer declare them, untagged routes under "default", every path as served today. Rewritten only per agent in a group (sec. 11.2). |
+| `with_cache(False)` / `with_cache(True, False)` | Unchanged (sec. 4.2). |
+| `Component` subclasses | No constructor change (sec. 4.3). |
+| `registry.cache_service` | Retained as alias. |
+| Liveness / readiness | `readiness_policy = "all"` reproduces today. |
+| Telemetry | Namespace `""` keeps `otel_service_name`. |
+| Threads | Executor lazy; no threads unless used. |
+| `Phase 7 get_runtime_name` | Purely additive -- `process_event` resolves no agent today; `runtime_name` is only logged (`event_processing_service.py:74`). |
+
+`Registry._components` changes from `dict[str, Any]` to two levels. It is underscore-private, but
+anything subclassing `Registry` or introspecting it breaks; this **MUST** be release-noted.
+
+### 10.1 The exception
+
+The transport fixes in sec. 7.1 and 7.2 change behaviour for already-deployed systems, without
+changing any signature:
+
+- Multi-replica deployments stop double-processing.
+- JetStream deployments stop redelivering every message forever.
+
+Both are bug fixes and neither is opt-out-able, since leaving them means the framework cannot be
+scaled. They **MUST** ship as their own release with explicit notes, not folded quietly into the
+grouping work.
+
+### 10.2 Enforcement
+
+- A **frozen compatibility suite** exercising today's usage patterns, including
+ `with_cache(False)` and `with_cache(True, False)` positionally. It is never updated to the new
+ API; if it needs editing, a break shipped.
+- A **generated-project smoke test**: `asbs setup`, then build and start the result unchanged
+ against the new framework version. Catches the Dockerfile and `main.py` paths unit tests miss.
+
+---
+
+## 11. Developer-facing surface
+
+An agent author's `main.py` is, in full:
+
+```python
+agent = (
+ AppBuilder()
+ .with_service(OrderService)
+ .with_handler(OrderValidationHandler)
+ .with_rest_api(OrderApi)
+)
+```
+
+No `Config`, no `run_app`, no `if __name__`, no namespace, no group -- and no `.build()`: the
+declaration is the file. A project that also wants to serve this agent alone adds one function and
+nothing else:
+
+```python
+def create_app(): # uvicorn src.main:create_app --factory --reload
+ return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=...))
+```
+
+The component list appears **once** either way. The dual-branch `main.py` of an earlier draft --
+the same components repeated under `if __name__ == "__main__"` and `else:` -- **MUST NOT** be
+used; two copies to keep in sync is itself a leak of the grouping model.
+
+`asbs dev` in an image directory (one with an `agents.toml`) hosts that image's agents under
+their **real** namespaces, as the deployment does. In an agent directory it serves the agent on
+its own, at the root namespace, as the agent's own Dockerfile and `create_app()` do; `asbs dev
+--name ` serves it as a group of one under that namespace instead, so local routes are
+`/api//...` and local consumer identity is the production queue group, identical to a
+grouped deployment.
+
+An agent therefore runs at its real namespace wherever a group hosts it, and at the root when it
+is served on its own. `namespace=""` is not reserved for pre-migration agents. *(Amended
+2026-10-19, PR #96 review: replaces "`asbs dev agents/` runs one agent as a group of one"
+and "every newly scaffolded agent MUST have a real namespace in every environment" -- an agent
+directory carries no name of its own, the name comes from whoever hosts it, and `--name`
+reproduces the grouped shape locally.)*
+
+### 11.1 What cannot be hidden
+
+Three mistakes are harmless in isolation and fatal in a group. They **MUST** be caught
+mechanically, because a rule that cannot be violated locally will not be followed:
+
+| Mistake | Detection |
+|---|---|
+| Blocking the event loop | `event_loop_debug = true` (read as a boolean, in any environment; off unless set) sets `loop.set_debug(True)` with a slow-callback threshold; otherwise a loop watchdog, on by default in every environment, reports a block above its threshold and names the agents with work in flight (C7) *(Amended 2026-10-19, PR #96 review: debug mode is no longer on by default in development -- its overhead is too high to be a default)* |
+| Module-level side effects (clients built at import, `basicConfig()`) | CI: import each agent module, assert the registry is empty and the root logger has no handlers |
+| Non-idempotent handlers | explicit flag at scaffold time and in `asbs validate` (sec. 7.4) |
+
+Two things an author still needs to know: their agent's name, and that handlers must not block.
+
+### 11.2 An agent's HTTP surface
+
+The first question a reader of a grouped image's Swagger UI asks is *which agent*, so an agent's
+operations **MUST** form one group, and nothing an agent serves may fall outside it. Swagger UI
+renders tags on one level only; the second level is therefore carried by the path, never by a
+sub-tag.
+
+Every requirement below applies to a component **with a namespace**. A root component -- every
+component of a standalone agent, and the process-wide `root`, `actuators` and Dapr endpoints of a
+grouped app -- keeps its declared tags and its paths (sec. 10).
+
+- **Tags.** Every operation of agent `` **MUST** carry exactly the tag ``, replacing any
+ tag the framework or the developer declared. An operation **MUST NOT** be untagged, which is what
+ would file it under Swagger UI's "default" group.
+- **Paths.** Every path of agent `` lives under `/api//` (sec. 11). Within it, the
+ segments `nats`, `cache` and `scheduler` are **reserved** for the framework:
+
+ | Endpoint | Grouped path | Standalone path (unchanged) |
+ |---|---|---|
+ | NATS publish | `/api//nats/events/{topic}` | `/events/{topic}` |
+ | Scheduler trigger | `/api//scheduler//trigger` | `/api//trigger` |
+ | Cache management | `/api//cache/...` | `/api/cache/...` |
+
+ The Dapr endpoints are not an agent's: one process-wide pair at the root, fixed by Dapr's
+ protocol (sec. 6).
+- **Developer paths.** A developer **MAY** declare a path prefix on their REST API class. It
+ applies standalone and grouped alike, so the agent's code does not depend on its grouping (C6);
+ it is not required, so an existing agent joins a group without a source change. `build()`
+ **MUST** refuse a grouped agent whose developer-declared route starts with a reserved segment,
+ naming the component, the route and the segment -- otherwise it would silently collide with the
+ framework's route of the same path.
+- **Not covered.** Routes added to the `FastAPI` application directly in `main.py` do not belong
+ to any agent and are not subject to these rules.
+
+---
+
+## 12. Acceptance criteria
+
+Status on `feature/multi-agent-namespaces`, 2026-09-14. A ticked box names what holds it. `[~]`
+means the behaviour is built and covered by unit tests against a mocked transport, while the
+criterion as written asks for something only a real broker shows -- those have tests waiting in
+`tests/integration/` and are tracked in `docs/plans/2026-09-11-broker-integration-tests.md`. An
+unticked box is not done, and says why.
+
+### Met
+
+- [x] Durable and queue names byte-identical across two builds where the same agent sits in
+ different groups (C1) -- `TestConsumerIdentityIgnoresTheDeployment`,
+ `tests/unit/agents/clients/io/test_nats_client.py`.
+- [x] Spans from namespace `invoice` carry `service.name = "invoice"`; a `namespace=""` app keeps
+ `otel_service_name` (C2).
+- [x] A degraded namespace: liveness `UP`, readiness per policy, `blueprint_namespace_up = 0`,
+ that namespace's consumers stopped (C3, C4).
+- [x] `.model_name` overrides root `model_name` for that namespace only (C5) --
+ `tests/unit/agents/config/test_namespace_views.py`: `orders` reads its own, `billing` falls
+ back to the root, and the two differ.
+- [x] No supported API exposes group membership to agent code (C6) --
+ `tests/unit/agents/test_agent_isolation.py` and `test_a_view_cannot_list_its_neighbours`.
+- [x] Every path that stops a namespace serving emits an ERROR event and
+ `blueprint_namespace_up{agent} = 0` carrying that namespace's identity; a namespace whose
+ subscriptions vanish while the process stays healthy is reported within one scrape interval
+ (C7).
+- [x] File-only, env-only and combined resolution produce identical groups; env overrides the file
+ key by key -- `tests/unit/agents/test_group_config.py`: `TestFromTheGroupFile`,
+ `TestFromTheEnvironmentAlone`, `TestPrecedence`.
+- [x] `CacheService.claim` is set-if-absent: of N concurrent callers on one key exactly one is
+ told it stored the value (sec. 7.5) -- `TestClaim` in both `test_disk_cache_service.py` and
+ `test_redis_cache_service.py`. Across processes this holds on Redis only; the disk
+ backend's claim holds within one process. *(Amended 2026-10-19, PR #96 review: scoped to
+ Redis.)*
+- [x] An `"in_process"` scheduler with no cache still ticks, and warns at startup that its ticks
+ are uncoordinated (sec. 7.5) -- `test_without_a_cache_every_replica_ticks` and
+ `test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick`.
+- [x] A registered scheduler with no `scheduler_mode` fails before the port is bound, and so does
+ `"event"` with no topic-carrying `event_bus` (sec. 7.5).
+- [x] Two namespaces in one group resolve different `scheduler_mode` values, and only the
+ `"in_process"` one starts a timer (sec. 7.5, C5).
+- [x] A pure-scheduler namespace that neither subscribes nor publishes is given no transport client
+ (sec. 6), and one that opts into publishing is given a client and no subscription (sec. 7.5)
+ -- `test_an_agent_that_neither_consumes_nor_publishes_gets_no_client` and
+ `test_a_publish_only_agent_gets_a_client_and_no_endpoint`.
+- [x] A scheduler's `on_startup` and `on_shutdown` each run exactly once per lifespan, asserted
+ against both lifespan loops a `SchedulerBase` appears in (#43) --
+ `test_repeated_startup_starts_no_second_timer`.
+- [x] An event that matches no handler is acknowledged, not redelivered: the transport edge
+ behaves identically for `PROCESSED` and `NO_HANDLER_FOUND` (sec. 7.2) --
+ `test_no_handler_found_still_acks`.
+- [x] The same outcome yields the same disposition on both transports -- `CriticalHandlerError`
+ drops on Dapr and terms on NATS, and a payload that fails to parse never naks (sec. 7.2) --
+ `test_critical_error_returns_drop`, `test_critical_error_terms`,
+ `test_invalid_event_error_terms`.
+- [x] A handler declaring no topics and no event types is still evaluated for every event its
+ namespace receives (sec. 7.7) --
+ `test_a_handler_that_declares_nothing_is_a_candidate_for_everything`.
+- [x] Frozen compat suite and generated-project smoke test both green (sec. 10.2) --
+ `tests/unit/agents/test_frozen_compatibility.py` and
+ `tests/unit/agent_generator/generator/test_generated_project.py`.
+- [x] Idempotency off by default, with the requirement surfaced at scaffold time and in
+ `asbs validate` -- `test_dedup_is_off_by_default`, plus the `DECIDE:` comment in the
+ scaffolded handler and the notice `asbs validate` prints.
+
+### Built, awaiting a real broker
+
+- [~] Two agents in one process; an event on a topic both subscribe to reaches both, once each.
+ Per-agent subscription and the Dapr in-process fan-out are unit-tested;
+ `tests/integration/test_grouped_agents.py` is the version that settles it.
+- [~] Two replicas of a two-agent group: each event processed exactly once per agent. Whether a
+ queue group merges overlapping subscriptions is the broker's behaviour, not ours.
+- [~] Cron fires once across three replicas in both `scheduler_mode` values (#73) -- in
+ `"in_process"` mode with a Redis cache. The claim is atomic on Redis by unit test; three
+ real replicas contending is not. On a disk cache the claim does not hold across processes
+ (sec. 7.5). *(Amended 2026-10-19, PR #96 review: scoped to Redis.)*
+
+### Not done
+
+- [ ] No framework-created task is detached without a done-callback that logs exceptions with the
+ namespace attached; asserted by a test that fails a task in each background path (C7).
+ Done-callbacks are on the NATS, Dapr and sessions paths and individually tested; the
+ *exhaustive* test the criterion asks for -- one that fails a task in every background path
+ -- does not exist, so nothing stops the next path being added without one.
+- [ ] The CI gate fails when an environment's group declaration omits an agent present in the
+ in-image agent map (sec. 13). `asbs validate` reports it locally; no CI gate enforces it.
+- [ ] `scheduler_mode = "event"` starts no timer, and the generated `CronJob` matches the schedule
+ declared in agent code. The first half holds (`test_event_mode_starts_no_timer`); manifest
+ generation was deliberately deferred and the renderer written for it was removed rather than
+ carried as dead code, so the second half has nothing to check yet.
+- [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed,
+ neither reported as a fault and neither keeping per-topic state (sec. 7.2, sec. 7.7).
+ `blueprint.events.unhandled` carries (agent, topic), on the agent's own meter; the namespaces-per-subject fan-out
+ gauge is not implemented.
+- [ ] Marginal RSS per additional idle namespace measured and published, reusing #36's
+ benchmark harness. #32 measures ~6 MB per forked child with shared libraries; a
+ namespace should be materially below that, and this number is what retires the
+ lazy-agent idea for good. No benchmark harness exists yet, so the number this feature
+ exists to produce has not been measured.
+
+### Superseded
+
+- A namespace's derived `filter_subjects` is never narrower than its declared topics unioned with
+ `nats_subscriptions`. The design moved: each agent owns its own durable filtering on its own
+ subjects, which is what makes a per-namespace `filter_subjects` set unnecessary
+ (`nats_client.py`). Recorded rather than deleted, because this spec is normative and a change
+ of approach belongs on it.
+
+
+---
+
+## 13. Open questions
+
+- **Is `deployment-groups.yaml` authored per environment, or one file with per-environment
+ overrides?** This is a trade-off rather than a gap: per-environment files are
+ readable without resolving inheritance and fit the difference actually being expressed
+ ("collapse every group into one" for dev is a different document, not a patch), while a single
+ overridden source avoids repeating the agent list and makes the *difference* the reviewable
+ artifact. Whichever is chosen, the duplication risk is *forgetting* an agent rather than the
+ duplication itself, and that is mechanically checkable -- the in-image agent map already
+ enumerates every agent, so the CI gate **SHOULD** require each environment's declaration to
+ account for all of them. Open: which shape, and how many environments actually differ.
+- What dedup TTL is defensible against the redelivery window? (Whether the dedup cache is
+ per-namespace or shared is **answered**: sec. 8 gives an agent only the caches it declared, so it
+ is necessarily per-namespace.)
+- **#32's metric needs restating.** "Per-agent RAM" stops being meaningful once the interpreter is
+ shared; the correct unit is *baseline per group + marginal per agent*. Its "as-is 160-250 MB per
+ agent" row describes the model being retired, and its acceptance criteria should be re-expressed
+ in the new unit before they are used to judge this work.
+- **Is the 4 GB host budget real?** #32 says "100 agents on a 4 GB host"; this spec assumes
+ Kubernetes with one Deployment per group. If 4 GB is a hard constraint, group count is capped at
+ roughly 10 at today's 154 MB baseline (rising to ~20 if #33 lands), which materially narrows the
+ isolation this design sells. #75 flagged the same ambiguity and it remains unanswered.
+- Earlier design context assumed "20+ agents"; #32 targets **100 agents in 4 GB**. Grouping
+ heuristics, connection totals and executor budgets all change materially at 100. Which figure
+ is the design target?
+- **Do the services running schedulers today have `event_bus` configured?** It decides how much
+ weight the `"in_process"` lease carries. If some have no broker at all they are permanently
+ `"in_process"`, and the lease stops being a development convenience and becomes the only thing
+ standing between them and duplicated ticks.
+- **Does the deployment path regenerate manifests from the build?** If it does, the generated
+ `CronJob` arrives with the upgrade and `"event"` costs an existing service nothing. If manifests
+ are hand-maintained, the generator emits a file someone has to notice and apply, which is where a
+ tick quietly stops.
+- **Who owns the subject taxonomy?** Pushing selection into the subject (sec. 7.7) only works if
+ publishers encode the discriminator, and the publishers are other services. `topic_mapping` lets
+ the framework enforce symmetry once a scheme exists, but it cannot invent the token order.
+ `..` is the usual shape. Open: who ratifies it, and how a subject is
+ added.
+- **What is the consumer-count budget?** One hundred agents times a few subjects each is several
+ hundred JetStream consumers, each with its own ack-pending state. The connection ceiling was
+ closed as a non-issue (sec. 6); consumer count is the analogous question and has not been asked.
+- **Do agents eventually become separate distributions?** Build-time dependency trimming would
+ require it, which is when the agent-to-module map should migrate to entry points. Not needed
+ while trimming stays opt-in.
diff --git a/examples/document_summarizer/README.md b/examples/document_summarizer/README.md
index 575bf8de..d7fa85df 100644
--- a/examples/document_summarizer/README.md
+++ b/examples/document_summarizer/README.md
@@ -33,7 +33,7 @@ model_api_key = "sk-your-actual-openai-api-key"
3. Run the service:
```bash
-uvicorn src.main:app --host 0.0.0.0 --port 8000
+uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000
```
## API Usage
diff --git a/examples/document_summarizer/settings.toml b/examples/document_summarizer/settings.toml
index a055ea15..e1065ef7 100644
--- a/examples/document_summarizer/settings.toml
+++ b/examples/document_summarizer/settings.toml
@@ -1,5 +1,5 @@
[default]
-app_name = "Document Summarizer"
+app_name = "document-summarizer"
app_port = 8000
app_environment = "development"
log_level = "INFO"
diff --git a/examples/document_summarizer/src/api/routes.py b/examples/document_summarizer/src/api/routes.py
index 40e3f781..20c735af 100644
--- a/examples/document_summarizer/src/api/routes.py
+++ b/examples/document_summarizer/src/api/routes.py
@@ -6,7 +6,8 @@
from blueprint.agents.io.api.rest_api_base import RestApiBase
-from src.models.schemas import DocumentRequest, SummarizeResponse
+from src.models.domain_models import Document
+from src.models.dto import DocumentRequest, SummarizeResponse
from src.services.summarizer_service import SummarizerService
logger = logging.getLogger(__name__)
@@ -15,13 +16,9 @@
class SummarizerApi(RestApiBase):
"""Exposes document summarization endpoints."""
- def __init__(self) -> None:
- super().__init__()
- self._service: SummarizerService | None = None
-
async def on_startup(self) -> None:
"""Resolve the summarizer service from the registry."""
- self._service = self.registry.get_service(SummarizerService) # type: ignore[assignment]
+ self._service: SummarizerService = self.registry.get_service(SummarizerService) # type: ignore[assignment]
logger.info("SummarizerApi started")
async def on_shutdown(self) -> None:
@@ -39,8 +36,8 @@ async def on_shutdown(self) -> None:
)
async def summarize_document(self, request: DocumentRequest) -> SummarizeResponse:
"""Accept a document and return a structured summary."""
- assert self._service is not None, "Service not initialised"
- return await self._service.summarize(request)
+ record = await self._service.summarize(Document(content=request.content, title=request.title))
+ return SummarizeResponse(document_id=record.document_id, summary=record.summary)
@RestApiBase.get(
"/summaries/{document_id}",
@@ -50,8 +47,7 @@ async def summarize_document(self, request: DocumentRequest) -> SummarizeRespons
)
async def get_summary(self, document_id: str) -> SummarizeResponse:
"""Return a previously generated summary by its document ID."""
- assert self._service is not None, "Service not initialised"
- result = await self._service.get_summary(document_id)
- if result is None:
+ record = await self._service.get_summary(document_id)
+ if record is None:
raise HTTPException(status_code=404, detail=f"Summary not found for document_id={document_id}")
- return result
+ return SummarizeResponse(document_id=record.document_id, summary=record.summary)
diff --git a/examples/document_summarizer/src/main.py b/examples/document_summarizer/src/main.py
index b42c4dad..de7c89e8 100644
--- a/examples/document_summarizer/src/main.py
+++ b/examples/document_summarizer/src/main.py
@@ -1,26 +1,23 @@
-"""Application entry point for the document summarizer service."""
+"""Declaration of the document summarizer agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own::
+
+ uvicorn src.main:create_app --factory
+"""
from pathlib import Path
from pydantic_ai import Tool
-from blueprint.agents import AppBuilder, AgentBuilder, Config
-from src.models.schemas import DocumentSummary
-from src.services.summarizer_service import SummarizerService
+from blueprint.agents import AgentBuilder, AppBuilder, Config
from src.api.routes import SummarizerApi
-from src.tools.text_tools import word_count, extract_metadata
-
-config = Config(
- settings_files=["settings.toml", "secrets.toml"],
- root_path=str(Path(__file__).parent.parent),
-)
+from src.models.domain_models import DocumentSummary
+from src.services.summarizer_service import SummarizerService
+from src.tools.text_tools import extract_metadata, word_count
-agent = (
- AgentBuilder(
- config,
- runtime_name="document_summarizer",
- package_root=Path(__file__).parent,
- )
+document_summarizer = (
+ AgentBuilder(runtime_name="document_summarizer", package_root=Path(__file__).parent)
.with_model_from_config()
.with_system_prompt("system")
.with_tools(
@@ -30,7 +27,17 @@
]
)
.with_result_type(DocumentSummary)
- .build()
)
-app = AppBuilder(config).with_agent(agent).with_service(SummarizerService).with_rest_api(SummarizerApi()).with_cache().build()
+agent = (
+ AppBuilder()
+ .with_service(SummarizerService)
+ .with_agent(document_summarizer, name="document_summarizer")
+ .with_rest_api(SummarizerApi)
+ .with_cache()
+)
+
+
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml", "secrets.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/examples/document_summarizer/src/models/schemas.py b/examples/document_summarizer/src/models/domain_models.py
similarity index 54%
rename from examples/document_summarizer/src/models/schemas.py
rename to examples/document_summarizer/src/models/domain_models.py
index 4d2cbb67..e831ecbe 100644
--- a/examples/document_summarizer/src/models/schemas.py
+++ b/examples/document_summarizer/src/models/domain_models.py
@@ -1,13 +1,13 @@
-"""Pydantic models for the document summarizer service."""
+"""Domain models: what SummarizerService works with. No request DTO reaches the service."""
from pydantic import BaseModel, Field
-class DocumentRequest(BaseModel):
- """Request payload for document summarization."""
+class Document(BaseModel):
+ """A document to summarize."""
- content: str = Field(..., description="The document text to summarize")
- title: str | None = Field(default=None, description="Optional document title")
+ content: str
+ title: str | None = None
class DocumentSummary(BaseModel):
@@ -27,8 +27,8 @@ class DocumentSummary(BaseModel):
)
-class SummarizeResponse(BaseModel):
- """Response wrapper for a document summarization request."""
+class SummaryRecord(BaseModel):
+ """A summary and the content-derived id it is stored under."""
- document_id: str = Field(..., description="Unique identifier derived from content hash")
- summary: DocumentSummary = Field(..., description="The structured document summary")
+ document_id: str
+ summary: DocumentSummary
diff --git a/examples/document_summarizer/src/models/dto.py b/examples/document_summarizer/src/models/dto.py
new file mode 100644
index 00000000..1898d067
--- /dev/null
+++ b/examples/document_summarizer/src/models/dto.py
@@ -0,0 +1,19 @@
+"""DTOs: the REST API's wire contract."""
+
+from pydantic import BaseModel, Field
+
+from .domain_models import DocumentSummary
+
+
+class DocumentRequest(BaseModel):
+ """Request payload for document summarization."""
+
+ content: str = Field(..., description="The document text to summarize")
+ title: str | None = Field(default=None, description="Optional document title")
+
+
+class SummarizeResponse(BaseModel):
+ """Response payload for a summary."""
+
+ document_id: str = Field(..., description="Unique identifier derived from content hash")
+ summary: DocumentSummary = Field(..., description="The structured document summary")
diff --git a/examples/document_summarizer/src/services/summarizer_service.py b/examples/document_summarizer/src/services/summarizer_service.py
index f3ae459b..633ffc9c 100644
--- a/examples/document_summarizer/src/services/summarizer_service.py
+++ b/examples/document_summarizer/src/services/summarizer_service.py
@@ -8,7 +8,7 @@
from blueprint.agents.agent.agent_runtime import AgentRuntime
from blueprint.agents.services.infrastructure.cache_service import CacheService
-from src.models.schemas import DocumentRequest, DocumentSummary, SummarizeResponse
+from src.models.domain_models import Document, DocumentSummary, SummaryRecord
logger = logging.getLogger(__name__)
@@ -37,34 +37,35 @@ async def on_shutdown(self) -> None:
# Public API
# ------------------------------------------------------------------
- async def summarize(self, request: DocumentRequest) -> SummarizeResponse:
+ async def summarize(self, document: Document) -> SummaryRecord:
"""Summarize a document, returning a cached result when available.
Args:
- request: The document to summarize.
+ document: The document to summarize.
Returns:
- A SummarizeResponse containing the document_id and structured summary.
+ The summary and the document_id it is stored under.
"""
- document_id = self._hash_content(request.content)
+ document_id = self._hash_content(document.content)
# Check cache
if self._cache is not None:
cached: dict[str, Any] | None = self._cache.get(document_id, namespace=CACHE_NAMESPACE)
if cached is not None:
logger.info("Cache hit for document_id=%s", document_id)
- return SummarizeResponse(
+ return SummaryRecord(
document_id=document_id,
summary=DocumentSummary(**cached),
)
# Build user prompt
- user_prompt = request.content
- if request.title:
- user_prompt = f"Title: {request.title}\n\n{request.content}"
+ user_prompt = document.content
+ if document.title:
+ user_prompt = f"Title: {document.title}\n\n{document.content}"
# Run the agent
- assert self._agent is not None, "Agent not initialised — was on_startup called?"
+ if self._agent is None:
+ raise RuntimeError("SummarizerService used before on_startup resolved its agent")
result = await self._agent.run(user_prompt)
summary: DocumentSummary = result.data # type: ignore[assignment]
@@ -77,16 +78,16 @@ async def summarize(self, request: DocumentRequest) -> SummarizeResponse:
)
logger.info("Cached summary for document_id=%s", document_id)
- return SummarizeResponse(document_id=document_id, summary=summary)
+ return SummaryRecord(document_id=document_id, summary=summary)
- async def get_summary(self, document_id: str) -> SummarizeResponse | None:
+ async def get_summary(self, document_id: str) -> SummaryRecord | None:
"""Retrieve a previously cached summary by document ID.
Args:
document_id: The hash-based identifier of the document.
Returns:
- The cached SummarizeResponse, or None if not found.
+ The cached summary record, or None if not found.
"""
if self._cache is None:
return None
@@ -95,7 +96,7 @@ async def get_summary(self, document_id: str) -> SummarizeResponse | None:
if cached is None:
return None
- return SummarizeResponse(
+ return SummaryRecord(
document_id=document_id,
summary=DocumentSummary(**cached),
)
diff --git a/examples/document_summarizer/tests/test_summarizer_service.py b/examples/document_summarizer/tests/test_summarizer_service.py
index 7c80328c..173a8ce4 100644
--- a/examples/document_summarizer/tests/test_summarizer_service.py
+++ b/examples/document_summarizer/tests/test_summarizer_service.py
@@ -6,7 +6,7 @@
import pytest
-from src.models.schemas import DocumentRequest, DocumentSummary, SummarizeResponse
+from src.models.domain_models import Document, DocumentSummary, SummaryRecord
from src.services.summarizer_service import SummarizerService, CACHE_NAMESPACE
@@ -21,8 +21,8 @@ def _make_summary() -> DocumentSummary:
)
-def _make_request(content: str = "Some document content for testing.", title: str | None = None) -> DocumentRequest:
- return DocumentRequest(content=content, title=title)
+def _make_request(content: str = "Some document content for testing.", title: str | None = None) -> Document:
+ return Document(content=content, title=title)
class TestSummarize:
@@ -42,7 +42,7 @@ async def test_returns_summary_from_agent(self) -> None:
request = _make_request()
response = await service.summarize(request)
- assert isinstance(response, SummarizeResponse)
+ assert isinstance(response, SummaryRecord)
assert response.summary == summary
assert len(response.document_id) == 16
service._agent.run.assert_awaited_once()
diff --git a/examples/health_monitor/README.md b/examples/health_monitor/README.md
index 338ea4c9..43e82ed4 100644
--- a/examples/health_monitor/README.md
+++ b/examples/health_monitor/README.md
@@ -28,7 +28,7 @@ asbs dev
Or directly with uvicorn:
```bash
-uvicorn src.main:app --reload
+uvicorn src.main:create_app --factory --reload
```
The API will be available at `http://localhost:8000`. Interactive docs at `http://localhost:8000/docs`.
diff --git a/examples/health_monitor/settings.toml b/examples/health_monitor/settings.toml
index 00036931..5de9cf5f 100644
--- a/examples/health_monitor/settings.toml
+++ b/examples/health_monitor/settings.toml
@@ -1,8 +1,11 @@
[default]
-app_name = "Health Monitor"
+app_name = "health-monitor"
app_port = 8000
app_environment = "development"
log_level = "INFO"
+# Required: two schedulers are registered and this service has no event_bus, so its
+# ticks have to come from an in-process timer. Single replica by design.
+scheduler_mode = "in_process"
[default.monitor]
check_timeout_seconds = 10
diff --git a/examples/health_monitor/src/api/routes.py b/examples/health_monitor/src/api/routes.py
index 7a9022d5..ee0fb0a5 100644
--- a/examples/health_monitor/src/api/routes.py
+++ b/examples/health_monitor/src/api/routes.py
@@ -8,7 +8,7 @@
from blueprint.agents.io.api.rest_api_base import RestApiBase
-from src.models.schemas import EndpointStatus, UptimeReport
+from src.models.domain_models import EndpointStatus, UptimeReport
from src.services.monitor_service import MonitorService
logger = logging.getLogger(__name__)
diff --git a/examples/health_monitor/src/main.py b/examples/health_monitor/src/main.py
index 289309c4..5985c5a5 100644
--- a/examples/health_monitor/src/main.py
+++ b/examples/health_monitor/src/main.py
@@ -1,4 +1,12 @@
-"""Application entry point for the Health Monitor."""
+"""Declaration of the Health Monitor agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own::
+
+ uvicorn src.main:create_app --factory
+"""
+
+from pathlib import Path
from blueprint.agents import AppBuilder, Config
@@ -7,14 +15,16 @@
from src.schedulers.report_scheduler import ReportScheduler
from src.services.monitor_service import MonitorService
-config = Config(settings_files=["settings.toml"])
-
-app = (
- AppBuilder(config)
+agent = (
+ AppBuilder()
.with_service(MonitorService)
- .with_rest_api(MonitorApi())
- .with_scheduler(HealthCheckScheduler())
- .with_scheduler(ReportScheduler())
+ .with_rest_api(MonitorApi)
+ .with_scheduler(HealthCheckScheduler)
+ .with_scheduler(ReportScheduler)
.with_cache()
- .build()
)
+
+
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/examples/health_monitor/src/models/schemas.py b/examples/health_monitor/src/models/domain_models.py
similarity index 100%
rename from examples/health_monitor/src/models/schemas.py
rename to examples/health_monitor/src/models/domain_models.py
diff --git a/examples/health_monitor/src/schedulers/health_check_scheduler.py b/examples/health_monitor/src/schedulers/health_check_scheduler.py
index c2b0502b..ea166440 100644
--- a/examples/health_monitor/src/schedulers/health_check_scheduler.py
+++ b/examples/health_monitor/src/schedulers/health_check_scheduler.py
@@ -35,9 +35,7 @@ async def tick(self) -> None:
return
logger.info("HealthCheckScheduler: running health checks")
- results = await self._monitor_service.check_all_endpoints()
- for result in results:
- await self._monitor_service.store_result(result)
+ results = await self._monitor_service.run_checks()
logger.info(
"HealthCheckScheduler: completed %d checks, %d healthy",
len(results),
diff --git a/examples/health_monitor/src/services/monitor_service.py b/examples/health_monitor/src/services/monitor_service.py
index f3de192d..1a31860e 100644
--- a/examples/health_monitor/src/services/monitor_service.py
+++ b/examples/health_monitor/src/services/monitor_service.py
@@ -11,7 +11,7 @@
from blueprint.agents.services.service_base import ServiceBase
from blueprint.agents.services.infrastructure.cache_service import CacheService
-from src.models.schemas import EndpointConfig, EndpointStatus, HealthResult, UptimeReport
+from src.models.domain_models import EndpointConfig, EndpointStatus, HealthResult, UptimeReport
logger = logging.getLogger(__name__)
@@ -99,6 +99,13 @@ async def check_all_endpoints(self) -> list[HealthResult]:
results.append(result)
return results
+ async def run_checks(self) -> list[HealthResult]:
+ """Check every endpoint and store each result: the one method the scheduler calls."""
+ results = await self.check_all_endpoints()
+ for result in results:
+ await self.store_result(result)
+ return results
+
async def store_result(self, result: HealthResult) -> None:
"""Persist a health-check result and update the endpoint status counters."""
if self._cache is None:
diff --git a/examples/health_monitor/tests/test_monitor_service.py b/examples/health_monitor/tests/test_monitor_service.py
index 88dde920..f7532196 100644
--- a/examples/health_monitor/tests/test_monitor_service.py
+++ b/examples/health_monitor/tests/test_monitor_service.py
@@ -7,7 +7,7 @@
import pytest
-from src.models.schemas import EndpointConfig, HealthResult
+from src.models.domain_models import EndpointConfig, HealthResult
from src.services.monitor_service import MonitorService
@@ -223,3 +223,15 @@ async def test_report_overall_unhealthy(self, service: MonitorService) -> None:
report = await service.generate_report()
assert report.overall_healthy is False
+
+
+class TestRunChecks:
+ @pytest.mark.asyncio
+ async def test_checks_every_endpoint_and_stores_each_result(self) -> None:
+ """The facade the scheduler calls: check, then store each result."""
+ service = MonitorService.__new__(MonitorService)
+ results = [object(), object()]
+ service.check_all_endpoints = AsyncMock(return_value=results) # type: ignore[method-assign]
+ service.store_result = AsyncMock() # type: ignore[method-assign]
+ assert await service.run_checks() == results
+ assert service.store_result.await_count == 2
diff --git a/examples/health_monitor/tests/test_schedulers.py b/examples/health_monitor/tests/test_schedulers.py
index bae3490a..54d63ac4 100644
--- a/examples/health_monitor/tests/test_schedulers.py
+++ b/examples/health_monitor/tests/test_schedulers.py
@@ -6,7 +6,7 @@
import pytest
-from src.models.schemas import HealthResult, UptimeReport
+from src.models.domain_models import HealthResult, UptimeReport
from src.schedulers.health_check_scheduler import HealthCheckScheduler
from src.schedulers.report_scheduler import ReportScheduler
@@ -34,6 +34,12 @@ def mock_monitor_service() -> AsyncMock:
]
)
svc.store_result = AsyncMock()
+ svc.run_checks = AsyncMock(
+ return_value=[
+ _make_health_result("httpbin"),
+ _make_health_result("jsonplaceholder"),
+ ]
+ )
svc.generate_report = AsyncMock(
return_value=UptimeReport(
generated_at="2026-01-01T00:00:00+00:00",
@@ -47,14 +53,14 @@ def mock_monitor_service() -> AsyncMock:
class TestHealthCheckScheduler:
@pytest.mark.asyncio
async def test_tick_calls_check_and_store(self, mock_monitor_service: AsyncMock) -> None:
- """tick() should call check_all_endpoints and store each result."""
+ """tick() makes one service call: the service checks and stores."""
scheduler = HealthCheckScheduler.__new__(HealthCheckScheduler)
scheduler._monitor_service = mock_monitor_service
await scheduler.tick()
- mock_monitor_service.check_all_endpoints.assert_awaited_once()
- assert mock_monitor_service.store_result.await_count == 2
+ mock_monitor_service.run_checks.assert_awaited_once()
+ mock_monitor_service.check_all_endpoints.assert_not_awaited()
@pytest.mark.asyncio
async def test_tick_skips_when_no_service(self) -> None:
diff --git a/examples/inventory_api/README.md b/examples/inventory_api/README.md
index edbea898..e684c6fe 100644
--- a/examples/inventory_api/README.md
+++ b/examples/inventory_api/README.md
@@ -27,7 +27,7 @@ asbs dev
Or directly with uvicorn:
```bash
-uvicorn src.main:app --reload
+uvicorn src.main:create_app --factory --reload
```
The API will be available at `http://localhost:8000`. Interactive docs at `http://localhost:8000/docs`.
diff --git a/examples/inventory_api/settings.toml b/examples/inventory_api/settings.toml
index c5fc6c35..148a3aec 100644
--- a/examples/inventory_api/settings.toml
+++ b/examples/inventory_api/settings.toml
@@ -1,5 +1,5 @@
[default]
-app_name = "Inventory API"
+app_name = "inventory-api"
app_port = 8000
app_environment = "development"
log_level = "INFO"
diff --git a/examples/inventory_api/src/api/routes.py b/examples/inventory_api/src/api/routes.py
index 0add4ab0..1084a641 100644
--- a/examples/inventory_api/src/api/routes.py
+++ b/examples/inventory_api/src/api/routes.py
@@ -5,27 +5,16 @@
import logging
from fastapi import HTTPException
-from pydantic import BaseModel
from blueprint.agents.io.api.rest_api_base import RestApiBase
-from src.models.schemas import (
- CreateProductRequest,
- Product,
- ProductSearchResult,
- UpdateProductRequest,
-)
+from src.models.domain_models import NewProduct, Product, ProductChanges
+from src.models.dto import CreateProductRequest, ProductSearchResult, StockAdjustment, UpdateProductRequest
from src.services.inventory_service import InventoryService
logger = logging.getLogger(__name__)
-class StockAdjustment(BaseModel):
- """Request body for stock adjustment."""
-
- quantity: int
-
-
class InventoryApi(RestApiBase):
"""Product inventory CRUD endpoints."""
@@ -66,7 +55,8 @@ async def list_products(self, category: str | None = None) -> list[Product]:
)
async def search_products(self, q: str) -> ProductSearchResult:
"""Search products by name or description."""
- return self.service.search_products(q)
+ matches = self.service.search_products(q)
+ return ProductSearchResult(products=matches, total=len(matches))
@RestApiBase.get(
"/products/{product_id}",
@@ -90,7 +80,7 @@ async def get_product(self, product_id: str) -> Product:
)
async def create_product(self, request: CreateProductRequest) -> Product:
"""Create a new product."""
- return self.service.create_product(request)
+ return self.service.create_product(NewProduct(**request.model_dump()))
@RestApiBase.put(
"/products/{product_id}",
@@ -100,7 +90,7 @@ async def create_product(self, request: CreateProductRequest) -> Product:
)
async def update_product(self, product_id: str, request: UpdateProductRequest) -> Product:
"""Update an existing product."""
- product = self.service.update_product(product_id, request)
+ product = self.service.update_product(product_id, ProductChanges(**request.model_dump(exclude_unset=True)))
if product is None:
raise HTTPException(status_code=404, detail=f"Product {product_id} not found")
return product
diff --git a/examples/inventory_api/src/main.py b/examples/inventory_api/src/main.py
index 4bceca34..cb8ead94 100644
--- a/examples/inventory_api/src/main.py
+++ b/examples/inventory_api/src/main.py
@@ -1,10 +1,21 @@
-"""Application entry point for the Inventory API."""
+"""Declaration of the Inventory API agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own::
+
+ uvicorn src.main:create_app --factory
+"""
+
+from pathlib import Path
from blueprint.agents import AppBuilder, Config
from src.api.routes import InventoryApi
from src.services.inventory_service import InventoryService
-config = Config(settings_files=["settings.toml"])
+agent = AppBuilder().with_service(InventoryService).with_rest_api(InventoryApi).with_cache()
+
-app = AppBuilder(config).with_service(InventoryService).with_rest_api(InventoryApi()).with_cache().build()
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/examples/inventory_api/src/models/schemas.py b/examples/inventory_api/src/models/domain_models.py
similarity index 59%
rename from examples/inventory_api/src/models/schemas.py
rename to examples/inventory_api/src/models/domain_models.py
index 0f0a2977..1d6a5036 100644
--- a/examples/inventory_api/src/models/schemas.py
+++ b/examples/inventory_api/src/models/domain_models.py
@@ -1,8 +1,8 @@
-"""Pydantic models for the Inventory API."""
+"""Domain models: what InventoryService works with. No request DTO reaches the service."""
from __future__ import annotations
-from datetime import datetime, UTC
+from datetime import UTC, datetime
from uuid import uuid4
from pydantic import BaseModel, Field
@@ -20,8 +20,8 @@ class Product(BaseModel):
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
-class CreateProductRequest(BaseModel):
- """Request body for creating a new product."""
+class NewProduct(BaseModel):
+ """A product to create: everything but the id and the timestamp, which the service assigns."""
name: str
description: str
@@ -30,18 +30,11 @@ class CreateProductRequest(BaseModel):
category: str
-class UpdateProductRequest(BaseModel):
- """Request body for updating an existing product. All fields are optional."""
+class ProductChanges(BaseModel):
+ """The fields to change on a product; only the fields that are set are applied."""
name: str | None = None
description: str | None = None
price: float | None = None
stock: int | None = None
category: str | None = None
-
-
-class ProductSearchResult(BaseModel):
- """Response for product search queries."""
-
- products: list[Product]
- total: int
diff --git a/examples/inventory_api/src/models/dto.py b/examples/inventory_api/src/models/dto.py
new file mode 100644
index 00000000..ca5c7eee
--- /dev/null
+++ b/examples/inventory_api/src/models/dto.py
@@ -0,0 +1,40 @@
+"""DTOs: the REST API's wire contract."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel
+
+from .domain_models import Product
+
+
+class CreateProductRequest(BaseModel):
+ """Request body for creating a new product."""
+
+ name: str
+ description: str
+ price: float
+ stock: int
+ category: str
+
+
+class UpdateProductRequest(BaseModel):
+ """Request body for updating an existing product. All fields are optional."""
+
+ name: str | None = None
+ description: str | None = None
+ price: float | None = None
+ stock: int | None = None
+ category: str | None = None
+
+
+class StockAdjustment(BaseModel):
+ """Request body for stock adjustment."""
+
+ quantity: int
+
+
+class ProductSearchResult(BaseModel):
+ """Response for product search queries."""
+
+ products: list[Product]
+ total: int
diff --git a/examples/inventory_api/src/services/inventory_service.py b/examples/inventory_api/src/services/inventory_service.py
index 73177117..2c287265 100644
--- a/examples/inventory_api/src/services/inventory_service.py
+++ b/examples/inventory_api/src/services/inventory_service.py
@@ -9,12 +9,7 @@
from blueprint.agents.services.service_base import ServiceBase
from blueprint.agents.services.infrastructure.cache_service import CacheService
-from src.models.schemas import (
- CreateProductRequest,
- Product,
- ProductSearchResult,
- UpdateProductRequest,
-)
+from src.models.domain_models import NewProduct, Product, ProductChanges
logger = logging.getLogger(__name__)
@@ -65,15 +60,15 @@ def get_product(self, product_id: str) -> Product | None:
)
return product
- def create_product(self, request: CreateProductRequest) -> Product:
+ def create_product(self, new: NewProduct) -> Product:
"""Create a new product with a generated UUID and timestamp."""
product = Product(
id=str(uuid4()),
- name=request.name,
- description=request.description,
- price=request.price,
- stock=request.stock,
- category=request.category,
+ name=new.name,
+ description=new.description,
+ price=new.price,
+ stock=new.stock,
+ category=new.category,
created_at=datetime.now(UTC),
)
self._products[product.id] = product
@@ -88,13 +83,13 @@ def create_product(self, request: CreateProductRequest) -> Product:
logger.info("Created product %s (%s)", product.id, product.name)
return product
- def update_product(self, product_id: str, request: UpdateProductRequest) -> Product | None:
+ def update_product(self, product_id: str, changes: ProductChanges) -> Product | None:
"""Update an existing product. Returns None if not found."""
product = self._products.get(product_id)
if product is None:
return None
- update_data = request.model_dump(exclude_unset=True)
+ update_data = changes.model_dump(exclude_unset=True)
updated = product.model_copy(update=update_data)
self._products[product_id] = updated
@@ -121,11 +116,10 @@ def delete_product(self, product_id: str) -> bool:
logger.info("Deleted product %s", product_id)
return True
- def search_products(self, query: str) -> ProductSearchResult:
+ def search_products(self, query: str) -> list[Product]:
"""Search products by name or description (case-insensitive)."""
q = query.lower()
- matches = [p for p in self._products.values() if q in p.name.lower() or q in p.description.lower()]
- return ProductSearchResult(products=matches, total=len(matches))
+ return [p for p in self._products.values() if q in p.name.lower() or q in p.description.lower()]
def update_stock(self, product_id: str, quantity: int) -> Product | None:
"""Adjust the stock level of a product by the given quantity.
diff --git a/examples/inventory_api/tests/test_inventory_service.py b/examples/inventory_api/tests/test_inventory_service.py
index 954412d2..67ac135e 100644
--- a/examples/inventory_api/tests/test_inventory_service.py
+++ b/examples/inventory_api/tests/test_inventory_service.py
@@ -7,7 +7,7 @@
import pytest
-from src.models.schemas import CreateProductRequest, UpdateProductRequest
+from src.models.domain_models import NewProduct, ProductChanges
from src.services.inventory_service import InventoryService
@@ -42,8 +42,8 @@ def service(mock_cache: MagicMock) -> InventoryService:
@pytest.fixture
-def sample_request() -> CreateProductRequest:
- return CreateProductRequest(
+def sample_request() -> NewProduct:
+ return NewProduct(
name="Widget",
description="A useful widget",
price=9.99,
@@ -53,7 +53,7 @@ def sample_request() -> CreateProductRequest:
class TestCreateProduct:
- def test_create_returns_product_with_id(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_create_returns_product_with_id(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
assert product.id is not None
assert product.name == "Widget"
@@ -62,13 +62,13 @@ def test_create_returns_product_with_id(self, service: InventoryService, sample_
assert product.category == "tools"
assert product.created_at is not None
- def test_create_stores_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_create_stores_product(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
assert service.get_product(product.id) is not None
class TestGetProduct:
- def test_get_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_get_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
fetched = service.get_product(product.id)
assert fetched is not None
@@ -79,9 +79,9 @@ def test_get_nonexistent_product(self, service: InventoryService) -> None:
class TestUpdateProduct:
- def test_update_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_update_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
- update = UpdateProductRequest(price=19.99, name="Super Widget")
+ update = ProductChanges(price=19.99, name="Super Widget")
updated = service.update_product(product.id, update)
assert updated is not None
assert updated.price == 19.99
@@ -89,12 +89,12 @@ def test_update_existing_product(self, service: InventoryService, sample_request
assert updated.description == "A useful widget" # unchanged
def test_update_nonexistent_product(self, service: InventoryService) -> None:
- update = UpdateProductRequest(price=5.0)
+ update = ProductChanges(price=5.0)
assert service.update_product("nonexistent-id", update) is None
class TestDeleteProduct:
- def test_delete_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_delete_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
assert service.delete_product(product.id) is True
assert service.get_product(product.id) is None
@@ -104,29 +104,29 @@ def test_delete_nonexistent_product(self, service: InventoryService) -> None:
class TestSearchProducts:
- def test_search_by_name(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_search_by_name(self, service: InventoryService, sample_request: NewProduct) -> None:
service.create_product(sample_request)
result = service.search_products("widget")
- assert result.total == 1
- assert result.products[0].name == "Widget"
+ assert len(result) == 1
+ assert result[0].name == "Widget"
- def test_search_by_description(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_search_by_description(self, service: InventoryService, sample_request: NewProduct) -> None:
service.create_product(sample_request)
result = service.search_products("useful")
- assert result.total == 1
+ assert len(result) == 1
- def test_search_no_match(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_search_no_match(self, service: InventoryService, sample_request: NewProduct) -> None:
service.create_product(sample_request)
result = service.search_products("nonexistent")
- assert result.total == 0
- assert result.products == []
+ assert len(result) == 0
+ assert result == []
class TestListProducts:
- def test_list_all(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_list_all(self, service: InventoryService, sample_request: NewProduct) -> None:
service.create_product(sample_request)
service.create_product(
- CreateProductRequest(
+ NewProduct(
name="Gadget",
description="A handy gadget",
price=14.99,
@@ -137,10 +137,10 @@ def test_list_all(self, service: InventoryService, sample_request: CreateProduct
products = service.list_products()
assert len(products) == 2
- def test_list_filtered_by_category(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_list_filtered_by_category(self, service: InventoryService, sample_request: NewProduct) -> None:
service.create_product(sample_request)
service.create_product(
- CreateProductRequest(
+ NewProduct(
name="Gadget",
description="A handy gadget",
price=14.99,
@@ -154,13 +154,13 @@ def test_list_filtered_by_category(self, service: InventoryService, sample_reque
class TestUpdateStock:
- def test_increase_stock(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_increase_stock(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
updated = service.update_stock(product.id, 25)
assert updated is not None
assert updated.stock == 125
- def test_decrease_stock(self, service: InventoryService, sample_request: CreateProductRequest) -> None:
+ def test_decrease_stock(self, service: InventoryService, sample_request: NewProduct) -> None:
product = service.create_product(sample_request)
updated = service.update_stock(product.id, -10)
assert updated is not None
diff --git a/examples/order_event_pipeline/README.md b/examples/order_event_pipeline/README.md
index 0cde1d59..eda4106e 100644
--- a/examples/order_event_pipeline/README.md
+++ b/examples/order_event_pipeline/README.md
@@ -1,28 +1,24 @@
# Order Event Pipeline
An e-commerce order processing pipeline built with the Blueprint Agents framework,
-demonstrating Dapr pub/sub event processing with a handler chain-of-responsibility pattern.
+demonstrating Dapr pub/sub event processing: one handler translates, one service decides.
## Overview
This example shows how to build an event-driven order processing system where:
1. An `order.created` CloudEvent arrives via Dapr pub/sub.
-2. The **OrderValidationHandler** (priority 10) validates the order payload. If
- validation fails it publishes an `order.rejected` event and short-circuits the
- chain. If the order is valid it passes control to the next handler.
-3. The **OrderEnrichmentHandler** (priority 20) enriches valid orders with tax
- calculations, shipping estimates, and timestamps, then publishes an
- `order.validated` event.
-4. A REST API exposes cached order statuses for querying.
+2. The **OrderHandler** routes it (envelope only), extracts the `OrderPayload` DTO, turns it into
+ an `Order` domain value and calls `OrderService.process_order()` **once**.
+3. `process_order()` decides: an invalid order is cached as `rejected` and comes back with its
+ errors; a valid one is enriched (tax, shipping estimate, timestamp) and cached as `validated`.
+4. The handler publishes the answer as `order.rejected` or `order.validated`.
+5. A REST API exposes cached order statuses for querying.
```
-order.created --> [ValidationHandler] --invalid--> order.rejected
- |
- valid
- |
- v
- [EnrichmentHandler] --> order.validated
+order.created --> [OrderHandler] --> OrderService.process_order()
+ |-- invalid --> order.rejected
+ '-- valid ----> enrich --> order.validated
```
## Project Structure
@@ -34,10 +30,10 @@ order_event_pipeline/
src/
main.py # Application entry point
models/
- schemas.py # Pydantic data models
+ dto.py # DTO: OrderPayload (event data)
+ domain_models.py # Domain: Order, ValidationError, OrderOutcome
handlers/
- order_validation_handler.py
- order_enrichment_handler.py
+ order_handler.py # order.created -> OrderService.process_order()
services/
order_service.py # Business logic (validation, enrichment)
api/
@@ -52,7 +48,7 @@ order_event_pipeline/
### With Dapr
```bash
-dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:app --host 0.0.0.0 --port 8000
+dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000
```
### Without Dapr (development mode)
@@ -60,10 +56,10 @@ dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:app --host
Set `event_bus = ""` in `settings.toml` to disable Dapr integration, then run:
```bash
-uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload
+uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload
```
-The handler chain still processes events submitted via the REST API, but no
+The handler still processes events submitted via the REST API, but no
pub/sub publishing occurs.
## Example CloudEvent Payload
diff --git a/examples/order_event_pipeline/settings.toml b/examples/order_event_pipeline/settings.toml
index 2660e883..e522c347 100644
--- a/examples/order_event_pipeline/settings.toml
+++ b/examples/order_event_pipeline/settings.toml
@@ -1,5 +1,5 @@
[default]
-app_name = "Order Event Pipeline"
+app_name = "order-event-pipeline"
app_port = 8000
app_environment = "development"
log_level = "INFO"
diff --git a/examples/order_event_pipeline/src/api/routes.py b/examples/order_event_pipeline/src/api/routes.py
index 565f634e..c258c7d4 100644
--- a/examples/order_event_pipeline/src/api/routes.py
+++ b/examples/order_event_pipeline/src/api/routes.py
@@ -15,12 +15,8 @@
class OrderApi(RestApiBase):
"""Exposes cached order data via REST endpoints."""
- def __init__(self) -> None:
- super().__init__()
- self._order_service: OrderService | None = None
-
async def on_startup(self) -> None:
- self._order_service = self.registry.get_service(OrderService) # type: ignore[assignment]
+ self._order_service: OrderService = self.registry.get_service(OrderService) # type: ignore[assignment]
logger.info("OrderApi started")
async def on_shutdown(self) -> None:
@@ -33,7 +29,6 @@ async def on_shutdown(self) -> None:
)
async def get_order(self, order_id: str) -> dict[str, Any]:
"""Return the cached status and data for a single order."""
- assert self._order_service is not None
result = self._order_service.get_cached_order(order_id)
if result is None:
raise HTTPException(status_code=404, detail=f"Order {order_id} not found")
diff --git a/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py b/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py
deleted file mode 100644
index 159ff66e..00000000
--- a/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""Handler that enriches validated orders (priority 20)."""
-
-import logging
-from typing import Any
-
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-from ..models.schemas import OrderPayload
-from ..services.order_service import OrderService
-
-logger = logging.getLogger(__name__)
-
-
-class OrderEnrichmentHandler(EventHandlerBase):
- """Enriches valid orders with tax, shipping estimate, and timestamps.
-
- Runs after ``OrderValidationHandler`` (priority 20 > 10). Only reached
- when validation passed (the validation handler returned ``None``).
- Publishes an ``order.validated`` event with the enriched data.
- """
-
- def __init__(self) -> None:
- super().__init__(priority=20)
- self._order_service: OrderService | None = None
-
- async def on_startup(self) -> None:
- self._order_service = self.registry.get_service(OrderService)
- logger.info("OrderEnrichmentHandler started")
-
- async def on_shutdown(self) -> None:
- pass
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "order.created"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult:
- assert self._order_service is not None
- payload = OrderPayload(**event.data)
-
- enriched = self._order_service.enrich_order(payload)
- logger.info("Order %s enriched successfully", payload.order_id)
-
- self._order_service.cache_order_status(
- payload.order_id,
- "validated",
- enriched,
- )
-
- return HandlerResult(
- event_type="order.validated",
- data=enriched,
- )
-
- def get_published_event_types(self) -> tuple[str, str]:
- return ("order.validated", "order.rejected")
diff --git a/examples/order_event_pipeline/src/handlers/order_handler.py b/examples/order_event_pipeline/src/handlers/order_handler.py
new file mode 100644
index 00000000..aa2abf0a
--- /dev/null
+++ b/examples/order_event_pipeline/src/handlers/order_handler.py
@@ -0,0 +1,43 @@
+"""The handler for ``order.created``: translate the event, call the service once, translate back."""
+
+import logging
+from typing import Any
+
+from blueprint.agents.handler.event_handler_base import EventHandlerBase
+from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
+
+from ..models.domain_models import Order
+from ..models.dto import OrderPayload
+from ..services.order_service import OrderService
+
+logger = logging.getLogger(__name__)
+
+ORDER_CREATED = "order.created"
+_EVENT_TYPE_BY_STATUS = {"validated": "order.validated", "rejected": "order.rejected"}
+
+
+class OrderHandler(EventHandlerBase):
+ """Processes order.created. Validation and enrichment are OrderService.process_order's decisions."""
+
+ def __init__(self) -> None:
+ super().__init__(priority=10)
+
+ async def on_startup(self) -> None:
+ self._order_service = self.registry.get_service(OrderService)
+
+ async def on_shutdown(self) -> None:
+ pass
+
+ def get_handled_event_types(self) -> list[str]:
+ return [ORDER_CREATED]
+
+ async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
+ return event.type == ORDER_CREATED
+
+ async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult:
+ payload = self.extract_payload(event, OrderPayload)
+ outcome = await self._order_service.process_order(Order.model_validate(payload.model_dump()))
+ return HandlerResult(event_type=_EVENT_TYPE_BY_STATUS[outcome.status], data=outcome.data)
+
+ def get_published_event_types(self) -> tuple[str, str]:
+ return ("order.validated", "order.rejected")
diff --git a/examples/order_event_pipeline/src/handlers/order_validation_handler.py b/examples/order_event_pipeline/src/handlers/order_validation_handler.py
deleted file mode 100644
index 28820a4c..00000000
--- a/examples/order_event_pipeline/src/handlers/order_validation_handler.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""Handler that validates incoming order events (priority 10)."""
-
-import logging
-from typing import Any
-
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-from ..models.schemas import OrderPayload
-from ..services.order_service import OrderService
-
-logger = logging.getLogger(__name__)
-
-
-class OrderValidationHandler(EventHandlerBase):
- """Validates order.created events.
-
- If the order is invalid, publishes an ``order.rejected`` event and
- short-circuits the handler chain. If valid, returns ``None`` so the
- next handler in the chain (enrichment) can process the order.
- """
-
- def __init__(self) -> None:
- super().__init__(priority=10)
- self._order_service: OrderService | None = None
-
- async def on_startup(self) -> None:
- self._order_service = self.registry.get_service(OrderService)
- logger.info("OrderValidationHandler started")
-
- async def on_shutdown(self) -> None:
- pass
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "order.created"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- assert self._order_service is not None
- payload = OrderPayload(**event.data)
-
- is_valid, errors = self._order_service.validate_order(payload)
-
- if not is_valid:
- error_dicts = [e.model_dump() for e in errors]
- logger.warning("Order %s rejected: %s", payload.order_id, error_dicts)
- self._order_service.cache_order_status(
- payload.order_id,
- "rejected",
- {"errors": error_dicts},
- )
- return HandlerResult(
- event_type="order.rejected",
- data={"order_id": payload.order_id, "errors": error_dicts},
- )
-
- logger.info("Order %s passed validation", payload.order_id)
- # Pass to the next handler in the chain
- return None
-
- def get_published_event_types(self) -> tuple[str, str]:
- return ("order.validated", "order.rejected")
diff --git a/examples/order_event_pipeline/src/main.py b/examples/order_event_pipeline/src/main.py
index c392f2fc..bcf76ab4 100644
--- a/examples/order_event_pipeline/src/main.py
+++ b/examples/order_event_pipeline/src/main.py
@@ -1,20 +1,22 @@
-"""Application entry point for the Order Event Pipeline."""
+"""Declaration of the Order Event Pipeline agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own::
+
+ uvicorn src.main:create_app --factory
+"""
+
+from pathlib import Path
from blueprint.agents import AppBuilder, Config
-from .handlers.order_validation_handler import OrderValidationHandler
-from .handlers.order_enrichment_handler import OrderEnrichmentHandler
-from .services.order_service import OrderService
from .api.routes import OrderApi
+from .handlers.order_handler import OrderHandler
+from .services.order_service import OrderService
+
+agent = AppBuilder().with_service(OrderService).with_handler(OrderHandler).with_rest_api(OrderApi).with_cache()
+
-config = Config(settings_files=["settings.toml"])
-
-app = (
- AppBuilder(config)
- .with_service(OrderService)
- .with_handler(OrderValidationHandler)
- .with_handler(OrderEnrichmentHandler)
- .with_rest_api(OrderApi)
- .with_cache()
- .build()
-)
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/examples/order_event_pipeline/src/models/domain_models.py b/examples/order_event_pipeline/src/models/domain_models.py
new file mode 100644
index 00000000..67a763eb
--- /dev/null
+++ b/examples/order_event_pipeline/src/models/domain_models.py
@@ -0,0 +1,38 @@
+"""Domain models: what OrderService works with. No CloudEvent and no DTO reaches the service."""
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class OrderLine(BaseModel):
+ """One line of an order."""
+
+ product_id: str
+ name: str
+ quantity: int
+ unit_price: float
+
+
+class Order(BaseModel):
+ """An order to process."""
+
+ order_id: str
+ customer_id: str
+ items: list[OrderLine]
+ shipping_address: str
+ total_amount: float
+
+
+class ValidationError(BaseModel):
+ """A single validation error (not an exception)."""
+
+ field: str
+ message: str
+
+
+class OrderOutcome(BaseModel):
+ """What OrderService decided: ``rejected`` with the errors, or ``validated`` with the enriched order."""
+
+ status: Literal["validated", "rejected"]
+ data: dict[str, Any] = Field(default_factory=dict)
diff --git a/examples/order_event_pipeline/src/models/schemas.py b/examples/order_event_pipeline/src/models/dto.py
similarity index 50%
rename from examples/order_event_pipeline/src/models/schemas.py
rename to examples/order_event_pipeline/src/models/dto.py
index 48e8bb84..b3f0ae72 100644
--- a/examples/order_event_pipeline/src/models/schemas.py
+++ b/examples/order_event_pipeline/src/models/dto.py
@@ -1,4 +1,4 @@
-"""Pydantic models for order event processing."""
+"""DTOs: the payload of an ``order.created`` event."""
from pydantic import BaseModel
@@ -20,19 +20,3 @@ class OrderPayload(BaseModel):
items: list[OrderItem]
shipping_address: str
total_amount: float
-
-
-class OrderResult(BaseModel):
- """Result of order processing."""
-
- order_id: str
- status: str # "validated" | "rejected"
- reason: str | None = None
- enriched_data: dict | None = None
-
-
-class ValidationError(BaseModel):
- """A single validation error (not an exception)."""
-
- field: str
- message: str
diff --git a/examples/order_event_pipeline/src/services/order_service.py b/examples/order_event_pipeline/src/services/order_service.py
index 62427cb9..a60ea55c 100644
--- a/examples/order_event_pipeline/src/services/order_service.py
+++ b/examples/order_event_pipeline/src/services/order_service.py
@@ -6,7 +6,7 @@
from blueprint.agents.services.service_base import ServiceBase
from blueprint.agents.services.infrastructure.cache_service import CacheService
-from ..models.schemas import OrderPayload, ValidationError
+from ..models.domain_models import Order, OrderOutcome, ValidationError
logger = logging.getLogger(__name__)
@@ -26,7 +26,24 @@ async def on_startup(self) -> None:
async def on_shutdown(self) -> None:
"""No-op shutdown."""
- def validate_order(self, payload: OrderPayload) -> tuple[bool, list[ValidationError]]:
+ async def process_order(self, order: Order) -> OrderOutcome:
+ """Validate, then enrich: the one method the handler calls for an order.created event.
+
+ An invalid order is cached as ``rejected`` and comes back with its errors; a valid one is
+ enriched, cached as ``validated`` and comes back with the enriched data.
+ """
+ is_valid, errors = self.validate_order(order)
+ if not is_valid:
+ error_dicts = [error.model_dump() for error in errors]
+ logger.warning("Order %s rejected: %s", order.order_id, error_dicts)
+ self.cache_order_status(order.order_id, "rejected", {"errors": error_dicts})
+ return OrderOutcome(status="rejected", data={"order_id": order.order_id, "errors": error_dicts})
+ enriched = self.enrich_order(order)
+ self.cache_order_status(order.order_id, "validated", enriched)
+ logger.info("Order %s validated and enriched", order.order_id)
+ return OrderOutcome(status="validated", data=enriched)
+
+ def validate_order(self, payload: Order) -> tuple[bool, list[ValidationError]]:
"""Validate an order payload.
Checks:
@@ -51,7 +68,7 @@ def validate_order(self, payload: OrderPayload) -> tuple[bool, list[ValidationEr
is_valid = len(errors) == 0
return is_valid, errors
- def enrich_order(self, payload: OrderPayload) -> dict:
+ def enrich_order(self, payload: Order) -> dict:
"""Enrich a validated order with computed fields.
Adds:
diff --git a/examples/order_event_pipeline/tests/test_handlers.py b/examples/order_event_pipeline/tests/test_handlers.py
index 158968b7..3f013e4a 100644
--- a/examples/order_event_pipeline/tests/test_handlers.py
+++ b/examples/order_event_pipeline/tests/test_handlers.py
@@ -1,23 +1,17 @@
-"""Unit tests for order event handlers."""
+"""Unit tests for OrderHandler: it translates, OrderService.process_order decides."""
-import pytest
+from unittest.mock import AsyncMock, MagicMock
-from unittest.mock import MagicMock
+import pytest
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
+from blueprint.agents.models.events import GenericCloudEvent
-from src.handlers.order_validation_handler import OrderValidationHandler
-from src.handlers.order_enrichment_handler import OrderEnrichmentHandler
-from src.models.schemas import ValidationError as VError
+from src.handlers.order_handler import OrderHandler
+from src.models.domain_models import Order, OrderOutcome
def _make_event(data: dict, event_type: str = "order.created") -> GenericCloudEvent:
- return GenericCloudEvent(
- id="evt-test-001",
- type=event_type,
- source="/tests",
- data=data,
- )
+ return GenericCloudEvent(id="evt-test-001", type=event_type, source="/tests", data=data)
VALID_ORDER_DATA = {
@@ -28,129 +22,49 @@ def _make_event(data: dict, event_type: str = "order.created") -> GenericCloudEv
"total_amount": 25.0,
}
-INVALID_ORDER_DATA = {
- "order_id": "order-101",
- "customer_id": "cust-2",
- "items": [],
- "shipping_address": "",
- "total_amount": -10.0,
-}
+@pytest.fixture
+def handler():
+ """An OrderHandler holding an OrderService double, as ``on_startup`` would leave it."""
+ h = object.__new__(OrderHandler)
+ h._priority = 10
+ h._order_service = MagicMock()
+ h._order_service.process_order = AsyncMock(return_value=OrderOutcome(status="validated", data={"order_id": "order-100"}))
+ return h
-# ---------------------------------------------------------------------------
-# OrderValidationHandler
-# ---------------------------------------------------------------------------
-
-
-class TestOrderValidationHandler:
- @pytest.fixture
- def handler(self):
- h = object.__new__(OrderValidationHandler)
- h._priority = 10
- h._name = "order_validation_handler"
-
- mock_service = MagicMock()
- mock_service.validate_order.return_value = (True, [])
- mock_service.cache_order_status = MagicMock()
- h._order_service = mock_service
- return h
-
- @pytest.mark.asyncio
- async def test_can_handle_order_created(self, handler):
- event = _make_event(VALID_ORDER_DATA)
- assert await handler.can_handle_event(event, {}) is True
-
- @pytest.mark.asyncio
- async def test_ignores_other_events(self, handler):
- event = _make_event(VALID_ORDER_DATA, event_type="order.shipped")
- assert await handler.can_handle_event(event, {}) is False
-
- @pytest.mark.asyncio
- async def test_valid_order_returns_none(self, handler):
- handler._order_service.validate_order.return_value = (True, [])
- event = _make_event(VALID_ORDER_DATA)
- result = await handler.handle_event(event, {})
- assert result is None
-
- @pytest.mark.asyncio
- async def test_invalid_order_returns_rejected(self, handler):
- errors = [
- VError(field="items", message="Order must contain at least one item"),
- VError(field="shipping_address", message="Shipping address is required"),
- ]
- handler._order_service.validate_order.return_value = (False, errors)
- event = _make_event(INVALID_ORDER_DATA)
- result = await handler.handle_event(event, {})
-
- assert isinstance(result, HandlerResult)
- assert result.event_type == "order.rejected"
- assert result.data["order_id"] == "order-101"
- assert len(result.data["errors"]) == 2
- @pytest.mark.asyncio
- async def test_rejection_caches_status(self, handler):
- errors = [VError(field="items", message="empty")]
- handler._order_service.validate_order.return_value = (False, errors)
- event = _make_event(INVALID_ORDER_DATA)
- await handler.handle_event(event, {})
- handler._order_service.cache_order_status.assert_called_once()
+class TestRouting:
+ async def test_declares_and_accepts_order_created(self, handler):
+ assert handler.get_handled_event_types() == ["order.created"]
+ assert await handler.can_handle_event(_make_event(VALID_ORDER_DATA), {}) is True
- def test_published_event_types(self, handler):
- assert handler.get_published_event_types() == (
- "order.validated",
- "order.rejected",
- )
-
-
-# ---------------------------------------------------------------------------
-# OrderEnrichmentHandler
-# ---------------------------------------------------------------------------
-
-
-class TestOrderEnrichmentHandler:
- @pytest.fixture
- def handler(self):
- h = object.__new__(OrderEnrichmentHandler)
- h._priority = 20
- h._name = "order_enrichment_handler"
-
- mock_service = MagicMock()
- mock_service.enrich_order.return_value = {
- "order_id": "order-100",
- "customer_id": "cust-1",
- "items": [{"product_id": "p1", "name": "Widget", "quantity": 1, "unit_price": 25.0}],
- "shipping_address": "456 Test Ave",
- "total_amount": 25.0,
- "tax_amount": 2.5,
- "grand_total": 27.5,
- "shipping_estimate": "3-5 business days",
- "processed_at": "2026-03-30T10:00:00+00:00",
- }
- mock_service.cache_order_status = MagicMock()
- h._order_service = mock_service
- return h
-
- @pytest.mark.asyncio
- async def test_can_handle_order_created(self, handler):
- event = _make_event(VALID_ORDER_DATA)
- assert await handler.can_handle_event(event, {}) is True
-
- @pytest.mark.asyncio
- async def test_returns_validated_result(self, handler):
- event = _make_event(VALID_ORDER_DATA)
- result = await handler.handle_event(event, {})
-
- assert isinstance(result, HandlerResult)
+ async def test_declines_other_events_without_calling_the_service(self, handler):
+ assert await handler.can_handle_event(_make_event({}, event_type="order.shipped"), {}) is False
+ handler._order_service.process_order.assert_not_awaited()
+
+
+class TestTranslation:
+ async def test_the_payload_reaches_the_service_as_a_domain_order(self, handler):
+ await handler.handle_event(_make_event(VALID_ORDER_DATA), {})
+ order = handler._order_service.process_order.await_args.args[0]
+ assert isinstance(order, Order)
+ assert order.order_id == "order-100"
+ assert order.items[0].product_id == "p1"
+
+ async def test_one_service_call_per_event(self, handler):
+ await handler.handle_event(_make_event(VALID_ORDER_DATA), {})
+ assert handler._order_service.process_order.await_count == 1
+ assert [c for c in handler._order_service.method_calls if not c[0].startswith("process_order")] == []
+
+ async def test_validated_is_published_as_order_validated(self, handler):
+ result = await handler.handle_event(_make_event(VALID_ORDER_DATA), {})
assert result.event_type == "order.validated"
- assert result.data["order_id"] == "order-100"
- assert result.data["tax_amount"] == 2.5
-
- @pytest.mark.asyncio
- async def test_caches_validated_status(self, handler):
- event = _make_event(VALID_ORDER_DATA)
- await handler.handle_event(event, {})
- handler._order_service.cache_order_status.assert_called_once_with(
- "order-100",
- "validated",
- handler._order_service.enrich_order.return_value,
- )
+ assert result.data == {"order_id": "order-100"}
+
+ async def test_rejected_is_published_as_order_rejected(self, handler):
+ handler._order_service.process_order.return_value = OrderOutcome(status="rejected", data={"order_id": "order-101", "errors": []})
+ result = await handler.handle_event(_make_event(VALID_ORDER_DATA), {})
+ assert result.event_type == "order.rejected"
+
+ def test_published_event_types(self, handler):
+ assert handler.get_published_event_types() == ("order.validated", "order.rejected")
diff --git a/examples/order_event_pipeline/tests/test_order_service.py b/examples/order_event_pipeline/tests/test_order_service.py
index 5768c9ad..1381ee06 100644
--- a/examples/order_event_pipeline/tests/test_order_service.py
+++ b/examples/order_event_pipeline/tests/test_order_service.py
@@ -2,7 +2,9 @@
import pytest
-from src.models.schemas import OrderItem, OrderPayload
+from unittest.mock import MagicMock
+
+from src.models.domain_models import Order, OrderLine
from src.services.order_service import OrderService
@@ -18,16 +20,16 @@ def service():
return svc
-def _make_payload(**overrides) -> OrderPayload:
+def _make_payload(**overrides) -> Order:
defaults = {
"order_id": "order-001",
"customer_id": "cust-001",
- "items": [OrderItem(product_id="p1", name="Widget", quantity=1, unit_price=10.0)],
+ "items": [OrderLine(product_id="p1", name="Widget", quantity=1, unit_price=10.0)],
"shipping_address": "123 Test St",
"total_amount": 10.0,
}
defaults.update(overrides)
- return OrderPayload(**defaults)
+ return Order(**defaults)
class TestValidateOrder:
@@ -80,13 +82,13 @@ def test_enrichment_adds_shipping_estimate(self, service: OrderService):
assert "shipping_estimate" in result
def test_small_order_fast_shipping(self, service: OrderService):
- items = [OrderItem(product_id="p1", name="Widget", quantity=2, unit_price=5.0)]
+ items = [OrderLine(product_id="p1", name="Widget", quantity=2, unit_price=5.0)]
payload = _make_payload(items=items, total_amount=10.0)
result = service.enrich_order(payload)
assert result["shipping_estimate"] == "3-5 business days"
def test_large_order_slow_shipping(self, service: OrderService):
- items = [OrderItem(product_id="p1", name="Widget", quantity=10, unit_price=5.0)]
+ items = [OrderLine(product_id="p1", name="Widget", quantity=10, unit_price=5.0)]
payload = _make_payload(items=items, total_amount=50.0)
result = service.enrich_order(payload)
assert result["shipping_estimate"] == "5-7 business days"
@@ -95,3 +97,21 @@ def test_enrichment_has_processed_at(self, service: OrderService):
payload = _make_payload()
result = service.enrich_order(payload)
assert "processed_at" in result
+
+
+class TestProcessOrder:
+ """The facade the handler calls: validate, then enrich, and cache the status either way."""
+
+ async def test_a_valid_order_is_validated_enriched_and_cached(self, service: OrderService):
+ service._cache = MagicMock()
+ outcome = await service.process_order(_make_payload())
+ assert outcome.status == "validated"
+ assert outcome.data["tax_amount"] == 1.0
+ assert service._cache.set.call_args.args[1]["status"] == "validated"
+
+ async def test_an_invalid_order_is_rejected_with_its_errors_and_cached(self, service: OrderService):
+ service._cache = MagicMock()
+ outcome = await service.process_order(_make_payload(items=[], total_amount=0))
+ assert outcome.status == "rejected"
+ assert {e["field"] for e in outcome.data["errors"]} == {"items", "total_amount"}
+ assert service._cache.set.call_args.args[1]["status"] == "rejected"
diff --git a/examples/site_readings/README.md b/examples/site_readings/README.md
new file mode 100644
index 00000000..f7d1e2d9
--- /dev/null
+++ b/examples/site_readings/README.md
@@ -0,0 +1,71 @@
+# Site Readings -- named connections
+
+One agent consumes the same subject (`readings.>`) from two sites, each with its own NATS account,
+over two **named connections** supplied by a **connection source**. The agent's code never learns
+that there are sites: the source decides which connections exist, how each one is consumed, which
+deliveries may run, and what each run sees.
+
+A reading above its site's threshold is stored as an alert; one within it is skipped
+(`HandlerResult.skipped`). `GET /api/alerts` lists the alerts.
+
+## What the source does
+
+`src/connections.py` (named by `nats_connection_source` in `settings.toml`):
+
+| Hook | Here |
+|---|---|
+| `claims(agent, subjects)` | Every declared subject under `readings.` belongs to the sites -- so none of them is ever consumed on the agent's default connection, even before a site exists. |
+| `connections()` | `site_a` and `site_b`, each logging in as its own account's agent user (`example_sites` in `settings.toml`; the password from `EXAMPLE_NATS_PASSWORD`). |
+| `binding(agent, subjects, connection)` | The site's durable consumer: subject prefix `site..` (wire subject `site.site_a.readings.recorded`, the handler sees `readings.recorded`), stream `READINGS_`, deliver subject `deliver..`. Bind-only: the consumer is the deployment's (`deploy/provision.py`). |
+| `validate(connection, subject, event)` | A delivery runs only if the wire subject and the event's `source` (`/sites/`) both name the connection's site; anything else is terminated before a handler sees it. |
+| `run_scope(connection)` | Opens the site's settings (`src/sites.py`) around the run, so the service applies that site's threshold. Each run starts in an empty context: a run sees its own site only. |
+
+The agent itself is the usual shape: `ReadingHandler` routes `reading.recorded`, extracts the
+`ReadingRecorded` DTO and calls `ReadingService.on_reading()` once; the service decides.
+
+## Running
+
+```bash
+export EXAMPLE_NATS_PASSWORD= # the broker and the agent read the same variable
+export DYNACONF_NATS_PASSWORD="$EXAMPLE_NATS_PASSWORD"
+docker compose -f deploy/docker-compose.yml up -d # broker with accounts PROC, SITE_A, SITE_B on :4224
+python deploy/provision.py # streams and consumers, as each site's admin
+uvicorn src.main:create_app --factory --port 8000
+python deploy/provision.py --publish # one reading below, one above each threshold
+curl localhost:8000/api/alerts # site_a 51.0 (threshold 50), site_b 81.0 (threshold 80)
+docker compose -f deploy/docker-compose.yml down
+```
+
+`/health/ready` stays 503 until both site connections are bound (`nats_connections_readiness = "all"`).
+The process account (`proc`) may neither publish nor subscribe: the agent's default connection is
+opened but carries no subject, which is what `claims` guarantees.
+
+## Project structure
+
+```
+site_readings/
+ settings.toml # nats_connection_source, the sites, readiness
+ src/
+ main.py # declaration + create_app()
+ connections.py # the ConnectionSource (deployment side)
+ sites.py # per-run site settings, set by run_scope
+ handlers/reading_handler.py
+ services/reading_service.py
+ models/dto.py # DTO: ReadingRecorded
+ models/domain_models.py # Reading, Alert
+ api/routes.py # GET /api/alerts
+ deploy/
+ nats-accounts.conf # the example broker: one account per site, passwords from the environment
+ docker-compose.yml
+ provision.py # what the deployment owns: streams and consumers
+ tests/
+```
+
+## Tests
+
+```bash
+pytest tests
+```
+
+The tests need no broker: they check the source's answers (connections, claims, bindings,
+validation, run scope isolation) and the handler/service split.
diff --git a/examples/site_readings/deploy/docker-compose.yml b/examples/site_readings/deploy/docker-compose.yml
new file mode 100644
index 00000000..e146e250
--- /dev/null
+++ b/examples/site_readings/deploy/docker-compose.yml
@@ -0,0 +1,17 @@
+# The example broker with one account per site. Local example only.
+#
+# export EXAMPLE_NATS_PASSWORD=
+# docker compose -f deploy/docker-compose.yml up -d
+# python deploy/provision.py # streams and consumers, as each site's admin
+services:
+ nats:
+ image: nats:2.10-alpine
+ container_name: site-readings-nats
+ command: ["-c", "/etc/nats/accounts.conf"]
+ environment:
+ EXAMPLE_NATS_PASSWORD: ${EXAMPLE_NATS_PASSWORD:?set EXAMPLE_NATS_PASSWORD}
+ volumes:
+ - ./nats-accounts.conf:/etc/nats/accounts.conf:ro
+ ports:
+ - "4224:4222"
+ - "8224:8222"
diff --git a/examples/site_readings/deploy/nats-accounts.conf b/examples/site_readings/deploy/nats-accounts.conf
new file mode 100644
index 00000000..5b0daf5f
--- /dev/null
+++ b/examples/site_readings/deploy/nats-accounts.conf
@@ -0,0 +1,38 @@
+# The example broker: one account per site, plus the process account. Stands for a deployment
+# where each site owns its account and the agent may only receive its deliveries and acknowledge.
+#
+# No password is written here: every user's password is $EXAMPLE_NATS_PASSWORD, read by the
+# server from its environment (see docker-compose.yml). Local example only.
+
+port: 4222
+http_port: 8222
+jetstream: { store_dir: "/tmp/nats-site-readings" }
+
+accounts: {
+ PROC: {
+ users: [
+ # The agent's default connection. It subscribes nothing (every subject is claimed by a site).
+ { user: proc, password: $EXAMPLE_NATS_PASSWORD, permissions: { publish: { deny: [">"] }, subscribe: { deny: [">"] } } }
+ ]
+ }
+ SITE_A: {
+ jetstream: enabled
+ users: [
+ { user: admin-site-a, password: $EXAMPLE_NATS_PASSWORD }
+ { user: agent-site-a, password: $EXAMPLE_NATS_PASSWORD, permissions: {
+ publish: { allow: ["$JS.ACK.>"] }
+ subscribe: { allow: ["deliver.site_a.>"] }
+ } }
+ ]
+ }
+ SITE_B: {
+ jetstream: enabled
+ users: [
+ { user: admin-site-b, password: $EXAMPLE_NATS_PASSWORD }
+ { user: agent-site-b, password: $EXAMPLE_NATS_PASSWORD, permissions: {
+ publish: { allow: ["$JS.ACK.>"] }
+ subscribe: { allow: ["deliver.site_b.>"] }
+ } }
+ ]
+ }
+}
diff --git a/examples/site_readings/deploy/provision.py b/examples/site_readings/deploy/provision.py
new file mode 100644
index 00000000..29defecf
--- /dev/null
+++ b/examples/site_readings/deploy/provision.py
@@ -0,0 +1,67 @@
+"""What the deployment owns, done once per site: the stream and the agent's consumer.
+
+The agent never creates either (its users may only receive and acknowledge). Run after the broker
+is up; reads EXAMPLE_NATS_PASSWORD and the same settings the source reads::
+
+ python deploy/provision.py [--publish]
+
+``--publish`` also sends one reading below and one above each site's threshold.
+"""
+
+import asyncio
+import json
+import os
+import sys
+import tomllib
+import uuid
+from pathlib import Path
+
+import nats
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+
+from src.connections import SiteSource, stream_name, subject_prefix # noqa: E402
+
+
+class _Settings:
+ """The two keys the source reads, from settings.toml, without starting the framework."""
+
+ def __init__(self) -> None:
+ self._values = tomllib.loads((ROOT / "settings.toml").read_text(encoding="utf-8"))["default"]
+
+ def get(self, key: str, default: object = None) -> object:
+ return self._values.get(key, default)
+
+
+async def provision(publish: bool) -> None:
+ settings = _Settings()
+ source = SiteSource(settings)
+ agent = str(settings.get("app_name"))
+ password = os.environ["EXAMPLE_NATS_PASSWORD"]
+ for site, spec in source.connections().items():
+ admin = await nats.connect(spec.url, user=f"admin-{site.replace('_', '-')}", password=password)
+ jsm = admin.jsm()
+ await jsm.add_stream(name=stream_name(site), subjects=[f"{subject_prefix(site)}>"])
+ binding = source.binding(agent, ("readings.>",), spec)
+ if binding is None:
+ raise SystemExit(f"{site}: the source binds nothing for readings.> -- check src/connections.py")
+ await jsm.add_consumer(binding.stream, config=binding.consumer_config())
+ print(f"{site}: stream {binding.stream}, consumer {binding.durable} -> {binding.deliver_subject}")
+ if publish:
+ threshold = float(settings.get("example_sites")[site]["alert_threshold"]) # type: ignore[index]
+ for value in (threshold - 1, threshold + 1):
+ event = {
+ "specversion": "1.0",
+ "id": str(uuid.uuid4()),
+ "type": "reading.recorded",
+ "source": f"/sites/{site}",
+ "data": {"sensor_id": f"{site}-s1", "value": value},
+ }
+ await admin.jetstream().publish(f"{subject_prefix(site)}readings.recorded", json.dumps(event).encode())
+ print(f"{site}: published {threshold - 1} and {threshold + 1}")
+ await admin.close()
+
+
+if __name__ == "__main__":
+ asyncio.run(provision("--publish" in sys.argv))
diff --git a/examples/site_readings/pyproject.toml b/examples/site_readings/pyproject.toml
new file mode 100644
index 00000000..e8f49fe0
--- /dev/null
+++ b/examples/site_readings/pyproject.toml
@@ -0,0 +1,18 @@
+[build-system]
+requires = ["setuptools>=80.0.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "site-readings"
+version = "0.1.0"
+requires-python = ">=3.13"
+dependencies = ["avs-blueprint-agents>=0.9.0a15"]
+
+[project.optional-dependencies]
+dev = ["pytest>=8.0.0", "pytest-asyncio>=1.0.0"]
+
+[tool.setuptools]
+packages = ["src", "src.api", "src.handlers", "src.services", "src.models"]
+
+[tool.setuptools.package-dir]
+"" = "."
diff --git a/examples/site_readings/settings.toml b/examples/site_readings/settings.toml
new file mode 100644
index 00000000..36ed17bc
--- /dev/null
+++ b/examples/site_readings/settings.toml
@@ -0,0 +1,31 @@
+[default]
+app_name = "site_readings"
+app_port = 8000
+app_environment = "development"
+log_level = "INFO"
+
+event_bus = "nats"
+# The agent's own (default) connection: the process account. Every subject this agent declares is
+# claimed by the source, so it subscribes nothing here.
+nats_url = "nats://localhost:4224"
+nats_user = "proc"
+# nats_password comes from the environment: DYNACONF_NATS_PASSWORD (same value as EXAMPLE_NATS_PASSWORD)
+
+# Named connections: one per site, supplied by src/connections.py.
+nats_connection_source = "src.connections:create_source"
+nats_connections_readiness = "all" # ready only while every site's connection is bound
+nats_max_concurrent_runs = 4 # per (agent, site) pair
+
+# Read by the source, not by the framework.
+example_broker_url = "nats://localhost:4224"
+
+[default.example_sites.site_a]
+user = "agent-site-a"
+alert_threshold = 50.0
+
+[default.example_sites.site_b]
+user = "agent-site-b"
+alert_threshold = 80.0
+
+[default.cache]
+cache_dir = ".cache/site_readings"
diff --git a/src/blueprint/agents/models/event_routing.py b/examples/site_readings/src/__init__.py
similarity index 100%
rename from src/blueprint/agents/models/event_routing.py
rename to examples/site_readings/src/__init__.py
diff --git a/examples/site_readings/src/api/__init__.py b/examples/site_readings/src/api/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/site_readings/src/api/routes.py b/examples/site_readings/src/api/routes.py
new file mode 100644
index 00000000..3102e6ed
--- /dev/null
+++ b/examples/site_readings/src/api/routes.py
@@ -0,0 +1,22 @@
+"""REST endpoint: the alerts the agent has raised, across all sites."""
+
+from typing import Any
+
+from blueprint.agents.io.api.rest_api_base import RestApiBase
+
+from ..services.reading_service import ReadingService
+
+
+class AlertApi(RestApiBase):
+ """Read-only view of the stored alerts."""
+
+ async def on_startup(self) -> None:
+ self._service = self.registry.get_service(ReadingService)
+
+ async def on_shutdown(self) -> None:
+ pass
+
+ @RestApiBase.get("/alerts", summary="List recent alerts", tags=["Alerts"])
+ async def list_alerts(self) -> dict[str, Any]:
+ alerts = self._service.recent_alerts()
+ return {"count": len(alerts), "alerts": alerts}
diff --git a/examples/site_readings/src/connections.py b/examples/site_readings/src/connections.py
new file mode 100644
index 00000000..813dd7b9
--- /dev/null
+++ b/examples/site_readings/src/connections.py
@@ -0,0 +1,109 @@
+"""The connection source: two named connections, one per site, each its own broker account.
+
+Named in ``settings.toml`` as ``nats_connection_source = "src.connections:create_source"``; the
+framework calls :func:`create_source` once per process with the process ``Config``. Everything the
+source needs comes from there and from the environment (the password, never from a file):
+
+- ``example_broker_url``: the broker every site's account lives on;
+- ``example_sites``: per site, the account user the agent logs in as and its alert threshold.
+
+The framework never learns what a site is. It opens the connections listed here, consumes each
+site's subjects through the binding below, asks :meth:`SiteSource.validate` before a delivery runs,
+and enters :meth:`SiteSource.run_scope` around every run.
+"""
+
+import os
+from collections.abc import Iterator, Mapping
+from contextlib import contextmanager
+from typing import Any
+
+from blueprint.agents.clients.io.nats_connections import ConnectionSpec, JetStreamBinding
+
+from .sites import SiteSettings, enter_site, leave_site
+
+PASSWORD_ENV = "EXAMPLE_NATS_PASSWORD"
+"""The environment variable holding the example broker's password (the same one ``deploy/`` uses)."""
+
+CLAIMED_ROOT = "readings."
+"""The subject scheme: every subject under ``readings.`` belongs to the sites, never to the default connection."""
+
+
+def subject_prefix(site: str) -> str:
+ """What a site's subjects carry on the wire: ``site..readings.recorded``."""
+ return f"site.{site}."
+
+
+def stream_name(site: str) -> str:
+ return f"READINGS_{site.upper()}"
+
+
+def deliver_subject(site: str, agent: str) -> str:
+ return f"deliver.{site}.{agent}"
+
+
+def durable_name(agent: str) -> str:
+ return f"{agent}-readings"
+
+
+class SiteSource:
+ """One named connection per configured site."""
+
+ def __init__(self, config: Any) -> None:
+ self._url = str(config.get("example_broker_url"))
+ self._sites: dict[str, dict[str, Any]] = dict(config.get("example_sites") or {})
+ self._password = os.environ.get(PASSWORD_ENV, "")
+ if not self._password:
+ raise ValueError(f"Set {PASSWORD_ENV}: the password of the example broker's site users.")
+
+ def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]:
+ """Every declared subject under ``readings.`` belongs to the sites -- whether a site exists yet or not."""
+ return tuple(subject for subject in subjects if subject.startswith(CLAIMED_ROOT))
+
+ def connections(self) -> Mapping[str, ConnectionSpec]:
+ return {
+ site: ConnectionSpec(name=site, url=self._url, user=str(spec["user"]), password=self._password)
+ for site, spec in self._sites.items()
+ }
+
+ def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding | None:
+ """The consumer ``deploy/provision.py`` creates for ``agent`` in this site's account."""
+ claimed = self.claims(agent, subjects)
+ if not claimed:
+ return None
+ return JetStreamBinding(
+ subjects=claimed,
+ stream=stream_name(connection.name),
+ durable=durable_name(agent),
+ deliver_subject=deliver_subject(connection.name, agent),
+ deliver_group=agent,
+ ack_wait=30.0,
+ subject_prefix=subject_prefix(connection.name),
+ max_deliver=5,
+ )
+
+ def validate(self, connection: str, subject: str, event: Any) -> str | None:
+ """A delivery runs only if the wire subject and the event's source both name this connection's site."""
+ if not subject.startswith(subject_prefix(connection)):
+ return f"subject {subject!r} is not under {subject_prefix(connection)!r}"
+ if event.source != f"/sites/{connection}":
+ return f"event source {event.source!r} is not /sites/{connection}"
+ return None
+
+ def run_scope(self, connection: str) -> Any:
+ """Open the site's settings around the run: the threshold the service applies."""
+ settings = SiteSettings(name=connection, alert_threshold=float(self._sites[connection]["alert_threshold"]))
+
+ @contextmanager
+ def scope() -> Iterator[None]:
+ token = enter_site(settings)
+ try:
+ yield
+ finally:
+ leave_site(token)
+
+ return scope()
+
+
+def create_source(config: Any) -> SiteSource:
+ """The factory ``nats_connection_source`` names."""
+ return SiteSource(config)
diff --git a/examples/site_readings/src/handlers/__init__.py b/examples/site_readings/src/handlers/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/site_readings/src/handlers/reading_handler.py b/examples/site_readings/src/handlers/reading_handler.py
new file mode 100644
index 00000000..e892cb60
--- /dev/null
+++ b/examples/site_readings/src/handlers/reading_handler.py
@@ -0,0 +1,42 @@
+"""The handler for ``reading.recorded``: translate the event, call the service once, translate back."""
+
+from typing import Any
+
+from blueprint.agents.handler.event_handler_base import EventHandlerBase
+from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
+
+from ..models.domain_models import Reading
+from ..models.dto import ReadingRecorded
+from ..services.reading_service import ReadingService
+
+READING_RECORDED = "reading.recorded"
+
+
+class ReadingHandler(EventHandlerBase):
+ """Knows the subject it consumes (``readings.>``), never the connection or the site it came from."""
+
+ def __init__(self) -> None:
+ super().__init__(priority=10)
+
+ async def on_startup(self) -> None:
+ self._service = self.registry.get_service(ReadingService)
+
+ async def on_shutdown(self) -> None:
+ pass
+
+ def get_subscribed_topics(self) -> list[str]:
+ return ["readings.>"]
+
+ def get_handled_event_types(self) -> list[str]:
+ return [READING_RECORDED]
+
+ async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
+ return event.type == READING_RECORDED
+
+ async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult:
+ payload = self.extract_payload(event, ReadingRecorded)
+ alert = await self._service.on_reading(Reading(sensor_id=payload.sensor_id, value=payload.value), event_id=event.id)
+ if alert is None:
+ return HandlerResult.skipped("reading within the site's threshold")
+ # No event_type: an agent on named connections does not publish results (named-connections plan, D4).
+ return HandlerResult(data=alert.model_dump())
diff --git a/examples/site_readings/src/main.py b/examples/site_readings/src/main.py
new file mode 100644
index 00000000..1f47e9d8
--- /dev/null
+++ b/examples/site_readings/src/main.py
@@ -0,0 +1,25 @@
+"""Declaration of the site readings agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own::
+
+ uvicorn src.main:create_app --factory
+
+Nothing here mentions the sites: the connections come from ``nats_connection_source`` in
+``settings.toml``, which the process reads, not the agent.
+"""
+
+from pathlib import Path
+
+from blueprint.agents import AppBuilder, Config
+
+from .api.routes import AlertApi
+from .handlers.reading_handler import ReadingHandler
+from .services.reading_service import ReadingService
+
+agent = AppBuilder().with_service(ReadingService).with_handler(ReadingHandler).with_rest_api(AlertApi).with_cache()
+
+
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/examples/site_readings/src/models/__init__.py b/examples/site_readings/src/models/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/site_readings/src/models/domain_models.py b/examples/site_readings/src/models/domain_models.py
new file mode 100644
index 00000000..08e74f80
--- /dev/null
+++ b/examples/site_readings/src/models/domain_models.py
@@ -0,0 +1,19 @@
+"""Domain models: what ReadingService works with."""
+
+from pydantic import BaseModel
+
+
+class Reading(BaseModel):
+ """One sensor reading."""
+
+ sensor_id: str
+ value: float
+
+
+class Alert(BaseModel):
+ """A reading above the threshold that applies to the run."""
+
+ sensor_id: str
+ value: float
+ threshold: float
+ site: str
diff --git a/examples/site_readings/src/models/dto.py b/examples/site_readings/src/models/dto.py
new file mode 100644
index 00000000..b60069c6
--- /dev/null
+++ b/examples/site_readings/src/models/dto.py
@@ -0,0 +1,10 @@
+"""DTO: the payload of a ``reading.recorded`` event."""
+
+from pydantic import BaseModel
+
+
+class ReadingRecorded(BaseModel):
+ """One sensor reading, as a site publishes it."""
+
+ sensor_id: str
+ value: float
diff --git a/examples/site_readings/src/services/__init__.py b/examples/site_readings/src/services/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/site_readings/src/services/reading_service.py b/examples/site_readings/src/services/reading_service.py
new file mode 100644
index 00000000..3432fae4
--- /dev/null
+++ b/examples/site_readings/src/services/reading_service.py
@@ -0,0 +1,43 @@
+"""Business logic: decide whether a reading is an alert, and keep the alerts for the API."""
+
+import logging
+from typing import Any
+
+from blueprint.agents.services.service_base import ServiceBase
+
+from ..models.domain_models import Alert, Reading
+from ..sites import current_site
+
+logger = logging.getLogger(__name__)
+
+ALERTS_NAMESPACE = "alerts"
+
+
+class ReadingService(ServiceBase):
+ """Applies the current site's threshold to each reading."""
+
+ async def on_startup(self) -> None:
+ self._cache = self.registry.cache_service
+
+ async def on_shutdown(self) -> None:
+ pass
+
+ async def on_reading(self, reading: Reading, event_id: str) -> Alert | None:
+ """The one method the handler calls. ``None``: the reading is within its site's threshold.
+
+ Safe to run twice for the same event: the alert is stored under the event id, so a
+ redelivery overwrites it rather than adding a second one.
+ """
+ site = current_site()
+ if reading.value <= site.alert_threshold:
+ return None
+ alert = Alert(sensor_id=reading.sensor_id, value=reading.value, threshold=site.alert_threshold, site=site.name)
+ self._cache.set(event_id, alert.model_dump(), namespace=ALERTS_NAMESPACE)
+ logger.info(
+ "Alert at site %s: sensor %s reads %s (threshold %s)", site.name, reading.sensor_id, reading.value, site.alert_threshold
+ )
+ return alert
+
+ def recent_alerts(self, limit: int = 50) -> list[dict[str, Any]]:
+ """The stored alerts, for the REST API."""
+ return list(self._cache.list_values(namespace=ALERTS_NAMESPACE, limit=limit))
diff --git a/examples/site_readings/src/sites.py b/examples/site_readings/src/sites.py
new file mode 100644
index 00000000..3940900b
--- /dev/null
+++ b/examples/site_readings/src/sites.py
@@ -0,0 +1,42 @@
+"""Per-run site settings, set by the connection source's ``run_scope`` and read by the service.
+
+This is the one place the agent's code meets the deployment: the source decides which site a run
+belongs to (from the connection it arrived on) and opens that site's settings around the run. Each
+run starts in an empty context, so a run can only ever see its own site's settings.
+"""
+
+from contextvars import ContextVar, Token
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class SiteSettings:
+ """What differs per site. Here: where an alert starts."""
+
+ name: str
+ alert_threshold: float
+
+
+_CURRENT: ContextVar[SiteSettings | None] = ContextVar("site_readings_current_site", default=None)
+
+
+def current_site() -> SiteSettings:
+ """The settings of the site the current run belongs to.
+
+ Raises:
+ LookupError: outside a run from a named connection -- a reading without a site has no threshold.
+ """
+ settings = _CURRENT.get()
+ if settings is None:
+ raise LookupError("No site in scope: readings are only processed in runs from a site's connection.")
+ return settings
+
+
+def enter_site(settings: SiteSettings) -> Token[SiteSettings | None]:
+ """Set the current site; returns the token for :func:`leave_site`. Used by the source only."""
+ return _CURRENT.set(settings)
+
+
+def leave_site(token: Token[SiteSettings | None]) -> None:
+ """Restore what was current before :func:`enter_site`."""
+ _CURRENT.reset(token)
diff --git a/examples/site_readings/tests/__init__.py b/examples/site_readings/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/site_readings/tests/test_connection_source.py b/examples/site_readings/tests/test_connection_source.py
new file mode 100644
index 00000000..26ea1823
--- /dev/null
+++ b/examples/site_readings/tests/test_connection_source.py
@@ -0,0 +1,96 @@
+"""The connection source: what the framework gets told about the two sites."""
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from blueprint.agents.clients.io.nats_connections import ConnectionSource
+
+from src.connections import PASSWORD_ENV, SiteSource, create_source
+from src.sites import current_site
+
+SETTINGS = {
+ "example_broker_url": "nats://localhost:4224",
+ "example_sites": {
+ "site_a": {"user": "agent-site-a", "alert_threshold": 50.0},
+ "site_b": {"user": "agent-site-b", "alert_threshold": 80.0},
+ },
+}
+
+
+class _Config:
+ def get(self, key, default=None):
+ return SETTINGS.get(key, default)
+
+
+@pytest.fixture
+def source(monkeypatch) -> SiteSource:
+ monkeypatch.setenv(PASSWORD_ENV, "placeholder-for-tests")
+ return create_source(_Config())
+
+
+def _event(source: str) -> SimpleNamespace:
+ return SimpleNamespace(source=source)
+
+
+class TestTheSource:
+ def test_it_is_a_connection_source(self, source):
+ assert isinstance(source, ConnectionSource)
+
+ def test_without_the_password_the_factory_refuses(self, monkeypatch):
+ monkeypatch.delenv(PASSWORD_ENV, raising=False)
+ with pytest.raises(ValueError, match=PASSWORD_ENV):
+ create_source(_Config())
+
+ def test_two_connections_one_per_site_each_with_its_own_user(self, source):
+ connections = source.connections()
+ assert sorted(connections) == ["site_a", "site_b"]
+ assert connections["site_a"].user == "agent-site-a"
+ assert connections["site_b"].user == "agent-site-b"
+ assert "placeholder" not in repr(connections["site_a"]), "a password must never appear in a repr"
+
+ def test_claims_every_readings_subject_and_nothing_else(self, source):
+ assert source.claims("site_readings", ("readings.>", "maintenance.tick")) == ("readings.>",)
+
+ def test_the_binding_prefixes_the_subject_per_site(self, source):
+ binding = source.binding("site_readings", ("readings.>",), source.connections()["site_b"])
+ assert binding.subject_prefix == "site.site_b."
+ assert binding.filter_subjects == ("site.site_b.readings.>",)
+ assert binding.deliver_subject == "deliver.site_b.site_readings"
+ assert binding.stream == "READINGS_SITE_B"
+ assert binding.local_subject("site.site_b.readings.recorded") == "readings.recorded"
+
+ def test_no_binding_for_an_agent_that_declares_no_readings(self, source):
+ assert source.binding("other", ("maintenance.tick",), source.connections()["site_a"]) is None
+
+
+class TestValidate:
+ def test_matching_subject_and_source_run(self, source):
+ assert source.validate("site_a", "site.site_a.readings.recorded", _event("/sites/site_a")) is None
+
+ def test_a_subject_of_another_site_is_refused(self, source):
+ assert "not under" in source.validate("site_a", "site.site_b.readings.recorded", _event("/sites/site_a"))
+
+ def test_an_event_claiming_another_site_is_refused(self, source):
+ assert "event source" in source.validate("site_a", "site.site_a.readings.recorded", _event("/sites/site_b"))
+
+
+class TestRunScope:
+ def test_the_run_sees_its_sites_settings_and_nothing_after(self, source):
+ with source.run_scope("site_b"):
+ assert current_site().name == "site_b"
+ assert current_site().alert_threshold == 80.0
+ with pytest.raises(LookupError):
+ current_site()
+
+ async def test_concurrent_runs_see_their_own_site(self, source):
+ seen: dict[str, str] = {}
+
+ async def run(site: str) -> None:
+ with source.run_scope(site):
+ await asyncio.sleep(0.01)
+ seen[site] = current_site().name
+
+ await asyncio.gather(asyncio.create_task(run("site_a")), asyncio.create_task(run("site_b")))
+ assert seen == {"site_a": "site_a", "site_b": "site_b"}
diff --git a/examples/site_readings/tests/test_reading_flow.py b/examples/site_readings/tests/test_reading_flow.py
new file mode 100644
index 00000000..5af1591d
--- /dev/null
+++ b/examples/site_readings/tests/test_reading_flow.py
@@ -0,0 +1,83 @@
+"""ReadingHandler translates; ReadingService decides against the run's site threshold."""
+
+from contextlib import contextmanager
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from blueprint.agents.models.events import GenericCloudEvent
+
+from src.handlers.reading_handler import ReadingHandler
+from src.models.domain_models import Alert, Reading
+from src.services.reading_service import ReadingService
+from src.sites import SiteSettings, enter_site, leave_site
+
+
+@contextmanager
+def site(name: str, threshold: float):
+ token = enter_site(SiteSettings(name=name, alert_threshold=threshold))
+ try:
+ yield
+ finally:
+ leave_site(token)
+
+
+def _event(value: float) -> GenericCloudEvent:
+ return GenericCloudEvent(id="evt-1", type="reading.recorded", source="/sites/site_a", data={"sensor_id": "s1", "value": value})
+
+
+@pytest.fixture
+def service() -> ReadingService:
+ svc = object.__new__(ReadingService)
+ svc._cache = MagicMock()
+ return svc
+
+
+class TestService:
+ async def test_within_the_threshold_is_no_alert(self, service):
+ with site("site_a", 50.0):
+ assert await service.on_reading(Reading(sensor_id="s1", value=50.0), event_id="e1") is None
+ service._cache.set.assert_not_called()
+
+ async def test_above_the_threshold_is_an_alert_stored_under_the_event_id(self, service):
+ with site("site_b", 80.0):
+ alert = await service.on_reading(Reading(sensor_id="s1", value=81.0), event_id="e2")
+ assert alert == Alert(sensor_id="s1", value=81.0, threshold=80.0, site="site_b")
+ assert service._cache.set.call_args.args[0] == "e2"
+
+ async def test_the_same_value_differs_by_site(self, service):
+ with site("site_a", 50.0):
+ assert await service.on_reading(Reading(sensor_id="s1", value=60.0), event_id="e3") is not None
+ with site("site_b", 80.0):
+ assert await service.on_reading(Reading(sensor_id="s1", value=60.0), event_id="e4") is None
+
+ async def test_outside_a_sites_run_there_is_no_threshold(self, service):
+ with pytest.raises(LookupError):
+ await service.on_reading(Reading(sensor_id="s1", value=1.0), event_id="e5")
+
+
+@pytest.fixture
+def handler() -> ReadingHandler:
+ h = object.__new__(ReadingHandler)
+ h._priority = 10
+ h._service = MagicMock()
+ h._service.on_reading = AsyncMock(return_value=None)
+ return h
+
+
+class TestHandler:
+ async def test_routes_on_the_type_and_declares_its_subject(self, handler):
+ assert handler.get_subscribed_topics() == ["readings.>"]
+ assert handler.get_handled_event_types() == ["reading.recorded"]
+ assert await handler.can_handle_event(_event(1.0), {}) is True
+
+ async def test_no_alert_is_a_skip(self, handler):
+ result = await handler.handle_event(_event(1.0), {})
+ assert result.is_skipped
+ handler._service.on_reading.assert_awaited_once_with(Reading(sensor_id="s1", value=1.0), event_id="evt-1")
+
+ async def test_an_alert_is_returned_unpublished(self, handler):
+ handler._service.on_reading.return_value = Alert(sensor_id="s1", value=99.0, threshold=50.0, site="site_a")
+ result = await handler.handle_event(_event(99.0), {})
+ assert result.event_type is None
+ assert result.data["site"] == "site_a"
diff --git a/examples/webhook_relay/README.md b/examples/webhook_relay/README.md
index 6d0f44e2..a6684abb 100644
--- a/examples/webhook_relay/README.md
+++ b/examples/webhook_relay/README.md
@@ -8,18 +8,18 @@ events over NATS.
## Architecture
-The processing pipeline is built as a **handler chain** with three stages:
+One handler, one service -- the shape every Blueprint agent follows:
-| Priority | Handler | Responsibility |
-|----------|----------------------|-----------------------------------------------------|
-| 5 | WebhookNormalizer | Parse raw payload, deduplicate, normalize structure |
-| 10 | ContentFilter | Drop bot events, test events, and other noise |
-| 15 | MetadataEnricher | Add priority scores, timestamps, publish final event |
+| Component | Responsibility |
+|---|---|
+| `WebhookHandler` | Routes `webhook.received` (envelope only), extracts the `WebhookPayload` DTO, turns it into an `IncomingWebhook` domain value and calls `WebhookService.relay()` **once**. Translates the answer into a result. |
+| `WebhookService.relay()` | Every decision: duplicate? (cache), normalise per source, content filter (GitHub bots, Stripe test events), enrich (priority score, timestamp), record for dedup and the recent list. |
-Lower priority numbers execute first. Each handler can:
+The handler's results:
-- Return `None` to pass the event to the next handler in the chain.
-- Return a `HandlerResult` to publish an event and stop processing.
+- `HandlerResult(event_type="webhook.processed", ...)` -- relayed and enriched.
+- `HandlerResult(event_type="webhook.filtered", ...)` -- dropped by a content rule, with the reason.
+- `HandlerResult.skipped(reason)` -- a duplicate: nothing to do, acknowledged, logged at INFO.
## Event Flow
@@ -27,17 +27,11 @@ Lower priority numbers execute first. Each handler can:
POST /api/webhooks
|
v
-[webhook.received] --> WebhookNormalizer (5)
- |
- v (stores normalized_event in context)
- ContentFilter (10)
- |
- v (filters bots / test events)
- MetadataEnricher (15)
- |
- v
- [webhook.processed] --> NATS topic: webhooks-processed
- [webhook.filtered] --> NATS topic: webhooks-filtered
+[webhook.received] --> WebhookHandler --> WebhookService.relay()
+ |
+ duplicate <--------------+--> filtered -> [webhook.filtered] -> webhooks-filtered
+ (skipped) |
+ +--> processed -> [webhook.processed] -> webhooks-processed
```
## NATS Configuration
@@ -69,17 +63,17 @@ nats_url = "nats://localhost:4222"
```bash
pip install -e .
- uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload
+ uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload
```
### Without NATS (handlers still execute, publishing is a no-op)
```bash
pip install -e .
-uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload
+uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload
```
-The handler chain processes events locally. Published events will log a warning
+The handler and service process events locally. Published events will log a warning
if NATS is unreachable but will not crash the service.
### Testing the endpoint
@@ -124,11 +118,10 @@ webhook_relay/
src/
main.py # AppBuilder wiring
models/
- schemas.py # Pydantic models
+ dto.py # DTO: WebhookPayload (REST body and event data)
+ domain_models.py # Domain: IncomingWebhook, NormalizedEvent, RelayOutcome
handlers/
- webhook_normalizer.py
- content_filter.py
- metadata_enricher.py
+ webhook_handler.py # webhook.received -> WebhookService.relay()
services/
webhook_service.py # Business logic and caching
api/
diff --git a/examples/webhook_relay/settings.toml b/examples/webhook_relay/settings.toml
index ef087372..42dfe157 100644
--- a/examples/webhook_relay/settings.toml
+++ b/examples/webhook_relay/settings.toml
@@ -1,5 +1,5 @@
[default]
-app_name = "Webhook Relay"
+app_name = "webhook-relay"
app_port = 8000
app_environment = "development"
log_level = "INFO"
diff --git a/examples/webhook_relay/src/api/routes.py b/examples/webhook_relay/src/api/routes.py
index d0b9514d..84eff0d8 100644
--- a/examples/webhook_relay/src/api/routes.py
+++ b/examples/webhook_relay/src/api/routes.py
@@ -15,7 +15,7 @@
EventProcessingService,
)
-from ..models.schemas import WebhookPayload
+from ..models.dto import WebhookPayload
from ..services.webhook_service import WebhookService
logger = logging.getLogger(__name__)
@@ -28,7 +28,9 @@ def __init__(self) -> None:
super().__init__()
async def on_startup(self) -> None:
- """No API-specific startup needed."""
+ """Resolve the services this API delegates to."""
+ self._events = self.registry.get_service(EventProcessingService)
+ self._webhooks = self.registry.get_service(WebhookService)
async def on_shutdown(self) -> None:
"""No API-specific shutdown needed."""
@@ -52,18 +54,16 @@ async def receive_webhook(self, payload: WebhookPayload, request: Request) -> JS
data=payload.model_dump(),
)
- event_processing: EventProcessingService = self.registry.get_service(
- EventProcessingService,
- )
-
- result_event = await event_processing.process_event(cloud_event)
+ processing = await self._events.process_event(cloud_event)
+ results = [result.data for result in processing.result if result.data is not None]
return JSONResponse(
status_code=202,
content={
- "status": "accepted",
+ "status": processing.status.value,
"webhook_id": webhook_id,
- "result": result_event.data if result_event else None,
+ "message": processing.message,
+ "result": results[0] if results else None,
},
)
@@ -74,8 +74,7 @@ async def receive_webhook(self, payload: WebhookPayload, request: Request) -> JS
)
async def list_recent(self) -> JSONResponse:
"""Return recently processed webhooks from the cache."""
- webhook_service: WebhookService = self.registry.get_service(WebhookService)
- recent = webhook_service.get_recent(limit=20)
+ recent = self._webhooks.get_recent(limit=20)
return JSONResponse(
status_code=200,
content={"count": len(recent), "webhooks": recent},
diff --git a/examples/webhook_relay/src/handlers/content_filter.py b/examples/webhook_relay/src/handlers/content_filter.py
deleted file mode 100644
index 3a7c54ef..00000000
--- a/examples/webhook_relay/src/handlers/content_filter.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""Handler that filters out unwanted webhook events (priority 10)."""
-
-from __future__ import annotations
-
-import logging
-from typing import Any
-
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-logger = logging.getLogger(__name__)
-
-
-class ContentFilter(EventHandlerBase):
- """Drop bot-generated and test events.
-
- Filtering rules:
- - GitHub: actor containing ``[bot]`` is discarded.
- - Stripe: event_category starting with ``test_`` is discarded.
-
- When an event is filtered a ``webhook.filtered`` result is returned so it
- can be published to the filtered-events topic. If the event passes, the
- handler returns ``None`` to continue the chain.
- """
-
- def __init__(self) -> None:
- super().__init__(priority=10)
-
- async def on_startup(self) -> None:
- """No handler-specific startup needed."""
-
- async def on_shutdown(self) -> None:
- """No handler-specific shutdown needed."""
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "webhook.received"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- normalized = context.get("normalized_event", event.data)
- webhook_id = context.get("webhook_id", event.id)
-
- actor = normalized.get("actor") or ""
- event_category = normalized.get("event_category", "")
- original_source = normalized.get("original_source", "")
-
- # GitHub bot filter
- if original_source == "github" and "[bot]" in actor:
- reason = f"Filtered GitHub bot event from {actor}"
- logger.info(reason)
- return HandlerResult(
- event_type="webhook.filtered",
- data={"reason": reason, "webhook_id": webhook_id},
- )
-
- # Stripe test-event filter
- if original_source == "stripe" and event_category.startswith("test_"):
- reason = f"Filtered Stripe test event: {event_category}"
- logger.info(reason)
- return HandlerResult(
- event_type="webhook.filtered",
- data={"reason": reason, "webhook_id": webhook_id},
- )
-
- # Event is allowed -- pass to next handler
- return None
-
- def get_published_event_types(self) -> tuple[str, str] | None:
- return ("webhook.filtered", "webhook.filtered.error")
diff --git a/examples/webhook_relay/src/handlers/metadata_enricher.py b/examples/webhook_relay/src/handlers/metadata_enricher.py
deleted file mode 100644
index c186fc3f..00000000
--- a/examples/webhook_relay/src/handlers/metadata_enricher.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Handler that enriches and publishes the final event (priority 15)."""
-
-from __future__ import annotations
-
-import logging
-from datetime import UTC, datetime
-from typing import Any
-
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-from ..services.webhook_service import WebhookService
-
-logger = logging.getLogger(__name__)
-
-# Simple priority scoring by event category keyword.
-_PRIORITY_KEYWORDS: dict[str, int] = {
- "security": 90,
- "payment": 80,
- "deploy": 70,
- "release": 60,
- "push": 50,
- "pull_request": 40,
- "issue": 30,
-}
-
-
-def _score_priority(event_category: str) -> int:
- """Return a numeric priority score (higher = more important)."""
- lower = event_category.lower()
- for keyword, score in _PRIORITY_KEYWORDS.items():
- if keyword in lower:
- return score
- return 10 # default low priority
-
-
-class MetadataEnricher(EventHandlerBase):
- """Add priority score and processed timestamp, then publish.
-
- This is the terminal handler in the chain. It always returns a
- ``HandlerResult`` with event_type ``webhook.processed``.
- """
-
- def __init__(self) -> None:
- super().__init__(priority=15)
-
- async def on_startup(self) -> None:
- """No handler-specific startup needed."""
-
- async def on_shutdown(self) -> None:
- """No handler-specific shutdown needed."""
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "webhook.received"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- webhook_service: WebhookService = self.registry.get_service(WebhookService) # type: ignore
- normalized = context.get("normalized_event", event.data)
- webhook_id = context.get("webhook_id", event.id)
-
- # Enrich
- enriched: dict[str, Any] = {**normalized}
- enriched["priority_score"] = _score_priority(normalized.get("event_category", ""))
- enriched["processed_at"] = datetime.now(UTC).isoformat()
- enriched["webhook_id"] = webhook_id
-
- # Mark as processed for dedup and store for the recent-list
- webhook_service.mark_processed(webhook_id)
- webhook_service.store_recent(webhook_id, enriched)
-
- logger.info("Enriched webhook %s (priority=%s)", webhook_id, enriched["priority_score"])
-
- return HandlerResult(
- event_type="webhook.processed",
- data=enriched,
- )
-
- def get_published_event_types(self) -> tuple[str, str] | None:
- return ("webhook.processed", "webhook.processed.error")
diff --git a/examples/webhook_relay/src/handlers/webhook_handler.py b/examples/webhook_relay/src/handlers/webhook_handler.py
new file mode 100644
index 00000000..ef664b01
--- /dev/null
+++ b/examples/webhook_relay/src/handlers/webhook_handler.py
@@ -0,0 +1,51 @@
+"""The handler for ``webhook.received``: translate the event, call the service once, translate back."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from blueprint.agents.handler.event_handler_base import EventHandlerBase
+from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
+
+from ..models.domain_models import IncomingWebhook
+from ..models.dto import WebhookPayload
+from ..services.webhook_service import WebhookService
+
+WEBHOOK_RECEIVED = "webhook.received"
+
+
+class WebhookHandler(EventHandlerBase):
+ """Relays incoming webhooks. All decisions -- duplicate, filtered, enriched -- are the service's."""
+
+ def __init__(self) -> None:
+ super().__init__(priority=10)
+
+ async def on_startup(self) -> None:
+ self._service = self.registry.get_service(WebhookService)
+
+ async def on_shutdown(self) -> None:
+ """No handler-specific shutdown needed."""
+
+ def get_handled_event_types(self) -> list[str]:
+ return [WEBHOOK_RECEIVED]
+
+ async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
+ return event.type == WEBHOOK_RECEIVED
+
+ async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult:
+ payload = self.extract_payload(event, WebhookPayload)
+ webhook = IncomingWebhook(
+ webhook_id=payload.webhook_id or event.id,
+ source=payload.source,
+ event_type=payload.event_type,
+ payload=payload.payload,
+ )
+ outcome = await self._service.relay(webhook)
+ if outcome.kind == "duplicate":
+ return HandlerResult.skipped(outcome.reason)
+ if outcome.kind == "filtered":
+ return HandlerResult(event_type="webhook.filtered", data=outcome.data)
+ return HandlerResult(event_type="webhook.processed", data=outcome.data)
+
+ def get_published_event_types(self) -> tuple[str, str] | None:
+ return ("webhook.processed", "webhook.filtered")
diff --git a/examples/webhook_relay/src/handlers/webhook_normalizer.py b/examples/webhook_relay/src/handlers/webhook_normalizer.py
deleted file mode 100644
index 37b5f6dd..00000000
--- a/examples/webhook_relay/src/handlers/webhook_normalizer.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""Handler that normalizes raw webhook payloads (priority 5 -- runs first)."""
-
-from __future__ import annotations
-
-import logging
-from typing import Any
-
-from blueprint.agents.handler.event_handler_base import EventHandlerBase
-from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-
-from ..models.schemas import WebhookPayload
-from ..services.webhook_service import WebhookService
-
-logger = logging.getLogger(__name__)
-
-
-class WebhookNormalizer(EventHandlerBase):
- """Parse the incoming webhook, deduplicate, and normalize.
-
- Stores the normalized event in ``context["normalized_event"]`` so
- downstream handlers can use it without re-parsing.
-
- Returns ``None`` to pass control to the next handler.
- """
-
- def __init__(self) -> None:
- super().__init__(priority=5)
-
- async def on_startup(self) -> None:
- """No handler-specific startup needed."""
-
- async def on_shutdown(self) -> None:
- """No handler-specific shutdown needed."""
-
- async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "webhook.received"
-
- async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- webhook_service: WebhookService = self.registry.get_service(WebhookService) # type: ignore
-
- # Parse incoming data into the domain model
- payload = WebhookPayload.model_validate(event.data)
-
- # Deduplicate
- webhook_id = payload.webhook_id or event.id
- if webhook_service.is_duplicate(webhook_id):
- logger.info("Duplicate webhook %s -- skipping", webhook_id)
- return None
-
- # Normalize
- normalized = webhook_service.normalize_payload(payload)
- context["normalized_event"] = normalized.model_dump()
- context["webhook_id"] = webhook_id
- logger.info(
- "Normalized webhook %s from %s (%s/%s)",
- webhook_id,
- normalized.original_source,
- normalized.event_category,
- normalized.event_action,
- )
-
- # Pass to next handler
- return None
diff --git a/examples/webhook_relay/src/main.py b/examples/webhook_relay/src/main.py
index 74981b54..a87958ba 100644
--- a/examples/webhook_relay/src/main.py
+++ b/examples/webhook_relay/src/main.py
@@ -1,4 +1,10 @@
-"""Application entry point -- wires all components via AppBuilder."""
+"""Declaration of the webhook relay agent.
+
+``agent`` records what the agent is made of; nothing is constructed until it is built.
+``create_app()`` builds it as an application of its own, with the settings next to ``src/``::
+
+ uvicorn src.main:create_app --factory
+"""
from __future__ import annotations
@@ -7,31 +13,22 @@
from blueprint.agents import AppBuilder, Config
from .api.routes import WebhookApi
-from .handlers.content_filter import ContentFilter
-from .handlers.metadata_enricher import MetadataEnricher
-from .handlers.webhook_normalizer import WebhookNormalizer
+from .handlers.webhook_handler import WebhookHandler
from .services.webhook_service import WebhookService
-# Load settings relative to this file so `uvicorn src.main:app` works from
-# the example directory.
-_HERE = Path(__file__).resolve().parent.parent
-
-config = Config(
- settings_files=["settings.toml"],
- root_path=str(_HERE),
-)
-
-app = (
- AppBuilder(config)
- # Handler chain -- priority determines execution order (low first)
- .with_handler(WebhookNormalizer) # priority 5 -- normalize
- .with_handler(ContentFilter) # priority 10 -- filter
- .with_handler(MetadataEnricher) # priority 15 -- enrich & publish
- # Business service
+agent = (
+ AppBuilder()
+ # Business service: deduplication, normalisation, filtering, enrichment
.with_service(WebhookService)
+ # One handler for webhook.received: translates, calls WebhookService.relay once
+ .with_handler(WebhookHandler)
# REST API
.with_rest_api(WebhookApi)
# Persistent cache for dedup and recent-event tracking
.with_cache()
- .build()
)
+
+
+def create_app():
+ """Build this agent as an application of its own."""
+ return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).resolve().parent.parent)))
diff --git a/examples/webhook_relay/src/models/domain_models.py b/examples/webhook_relay/src/models/domain_models.py
new file mode 100644
index 00000000..683a792f
--- /dev/null
+++ b/examples/webhook_relay/src/models/domain_models.py
@@ -0,0 +1,44 @@
+"""Domain models: what the service works with. No CloudEvent and no DTO reaches the service."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class IncomingWebhook(BaseModel):
+ """One webhook to relay, identified by ``webhook_id``."""
+
+ webhook_id: str
+ source: str
+ event_type: str
+ payload: dict[str, Any]
+
+
+class NormalizedEvent(BaseModel):
+ """Source-agnostic representation of a webhook event."""
+
+ original_source: str
+ event_category: str
+ event_action: str
+ actor: str | None = None
+ resource_id: str | None = None
+ resource_type: str | None = None
+ metadata: dict[str, Any] = Field(default_factory=dict)
+ received_at: str = Field(
+ default_factory=lambda: datetime.now(UTC).isoformat(),
+ )
+
+
+class RelayOutcome(BaseModel):
+ """What the service decided for one webhook.
+
+ ``duplicate``: already relayed, nothing to do. ``filtered``: dropped by a content rule, ``data``
+ says why. ``processed``: normalised and enriched, ``data`` is the event to publish.
+ """
+
+ kind: Literal["duplicate", "filtered", "processed"]
+ reason: str = ""
+ data: dict[str, Any] = Field(default_factory=dict)
diff --git a/examples/webhook_relay/src/models/dto.py b/examples/webhook_relay/src/models/dto.py
new file mode 100644
index 00000000..3a4e97a2
--- /dev/null
+++ b/examples/webhook_relay/src/models/dto.py
@@ -0,0 +1,17 @@
+"""DTOs: what arrives over HTTP and in the ``webhook.received`` event."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel
+
+
+class WebhookPayload(BaseModel):
+ """Incoming webhook payload from an external source (REST body and event data)."""
+
+ source: Literal["github", "stripe", "generic"] = "generic"
+ event_type: str
+ payload: dict[str, Any]
+ timestamp: str | None = None
+ webhook_id: str | None = None
diff --git a/examples/webhook_relay/src/models/schemas.py b/examples/webhook_relay/src/models/schemas.py
deleted file mode 100644
index b48f9163..00000000
--- a/examples/webhook_relay/src/models/schemas.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Pydantic models for the webhook relay pipeline."""
-
-from __future__ import annotations
-
-from datetime import UTC, datetime
-from typing import Any, Literal
-
-from pydantic import BaseModel, Field
-
-
-class WebhookPayload(BaseModel):
- """Incoming webhook payload from an external source."""
-
- source: Literal["github", "stripe", "generic"] = "generic"
- event_type: str
- payload: dict[str, Any]
- timestamp: str | None = None
- webhook_id: str | None = None
-
-
-class NormalizedEvent(BaseModel):
- """Source-agnostic representation of a webhook event."""
-
- original_source: str
- event_category: str
- event_action: str
- actor: str | None = None
- resource_id: str | None = None
- resource_type: str | None = None
- metadata: dict[str, Any] = Field(default_factory=dict)
- received_at: str = Field(
- default_factory=lambda: datetime.now(UTC).isoformat(),
- )
-
-
-class FilterDecision(BaseModel):
- """Result of the content-filtering stage."""
-
- allowed: bool
- reason: str
diff --git a/examples/webhook_relay/src/services/webhook_service.py b/examples/webhook_relay/src/services/webhook_service.py
index 615fd791..96fc7354 100644
--- a/examples/webhook_relay/src/services/webhook_service.py
+++ b/examples/webhook_relay/src/services/webhook_service.py
@@ -1,4 +1,4 @@
-"""Business logic for webhook normalisation and deduplication."""
+"""Business logic of the relay: deduplication, normalisation, content filtering and enrichment."""
from __future__ import annotations
@@ -9,13 +9,24 @@
from blueprint.agents.services.service_base import ServiceBase
from blueprint.agents.services.infrastructure.cache_service import CacheService
-from ..models.schemas import NormalizedEvent, WebhookPayload
+from ..models.domain_models import IncomingWebhook, NormalizedEvent, RelayOutcome
logger = logging.getLogger(__name__)
WEBHOOK_NAMESPACE = "webhooks"
RECENT_NAMESPACE = "webhooks_recent"
+# Simple priority scoring by event category keyword (higher = more important).
+_PRIORITY_KEYWORDS: dict[str, int] = {
+ "security": 90,
+ "payment": 80,
+ "deploy": 70,
+ "release": 60,
+ "push": 50,
+ "pull_request": 40,
+ "issue": 30,
+}
+
class WebhookService(ServiceBase):
"""Normalizes webhook payloads and tracks duplicates via the cache."""
@@ -35,11 +46,69 @@ async def on_startup(self) -> None:
async def on_shutdown(self) -> None:
"""Nothing to tear down."""
+ # ------------------------------------------------------------------
+ # Entry point
+ # ------------------------------------------------------------------
+
+ async def relay(self, webhook: IncomingWebhook) -> RelayOutcome:
+ """Decide what happens to one webhook: the one method the handler calls.
+
+ Duplicate -> nothing to do. A content rule matches -> filtered, with the reason. Otherwise
+ normalised, enriched, recorded for deduplication and the recent list, and returned for
+ publishing.
+ """
+ if self.is_duplicate(webhook.webhook_id):
+ return RelayOutcome(kind="duplicate", reason=f"webhook {webhook.webhook_id} already relayed")
+ normalized = self.normalize_payload(webhook)
+ reason = self.filter_reason(normalized)
+ if reason is not None:
+ logger.info("Webhook %s filtered: %s", webhook.webhook_id, reason)
+ return RelayOutcome(kind="filtered", reason=reason, data={"reason": reason, "webhook_id": webhook.webhook_id})
+ enriched = self.enrich(normalized, webhook.webhook_id)
+ self.mark_processed(webhook.webhook_id)
+ self.store_recent(webhook.webhook_id, enriched)
+ logger.info("Relayed webhook %s (priority=%s)", webhook.webhook_id, enriched["priority_score"])
+ return RelayOutcome(kind="processed", data=enriched)
+
+ # ------------------------------------------------------------------
+ # Filtering and enrichment
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def filter_reason(normalized: NormalizedEvent) -> str | None:
+ """Why this event is dropped, or ``None`` to relay it.
+
+ GitHub: an actor containing ``[bot]``. Stripe: an event category starting with ``test_``.
+ """
+ actor = normalized.actor or ""
+ if normalized.original_source == "github" and "[bot]" in actor:
+ return f"Filtered GitHub bot event from {actor}"
+ if normalized.original_source == "stripe" and normalized.event_category.startswith("test_"):
+ return f"Filtered Stripe test event: {normalized.event_category}"
+ return None
+
+ @staticmethod
+ def score_priority(event_category: str) -> int:
+ """Return a numeric priority score (higher = more important)."""
+ lower = event_category.lower()
+ for keyword, score in _PRIORITY_KEYWORDS.items():
+ if keyword in lower:
+ return score
+ return 10
+
+ def enrich(self, normalized: NormalizedEvent, webhook_id: str) -> dict[str, Any]:
+ """The event to publish: the normalised fields plus priority score, timestamp and id."""
+ enriched: dict[str, Any] = normalized.model_dump()
+ enriched["priority_score"] = self.score_priority(normalized.event_category)
+ enriched["processed_at"] = datetime.now(UTC).isoformat()
+ enriched["webhook_id"] = webhook_id
+ return enriched
+
# ------------------------------------------------------------------
# Normalisation
# ------------------------------------------------------------------
- def normalize_payload(self, payload: WebhookPayload) -> NormalizedEvent:
+ def normalize_payload(self, payload: IncomingWebhook) -> NormalizedEvent:
"""Convert a source-specific webhook into a NormalizedEvent."""
if payload.source == "github":
return self._normalize_github(payload)
@@ -48,7 +117,7 @@ def normalize_payload(self, payload: WebhookPayload) -> NormalizedEvent:
return self._normalize_generic(payload)
@staticmethod
- def _normalize_github(payload: WebhookPayload) -> NormalizedEvent:
+ def _normalize_github(payload: IncomingWebhook) -> NormalizedEvent:
data = payload.payload
action = data.get("action", payload.event_type)
sender = data.get("sender", {})
@@ -68,7 +137,7 @@ def _normalize_github(payload: WebhookPayload) -> NormalizedEvent:
)
@staticmethod
- def _normalize_stripe(payload: WebhookPayload) -> NormalizedEvent:
+ def _normalize_stripe(payload: IncomingWebhook) -> NormalizedEvent:
data = payload.payload
event_type_parts = data.get("type", payload.event_type).rsplit(".", 1)
category = event_type_parts[0] if len(event_type_parts) > 1 else payload.event_type
@@ -87,7 +156,7 @@ def _normalize_stripe(payload: WebhookPayload) -> NormalizedEvent:
)
@staticmethod
- def _normalize_generic(payload: WebhookPayload) -> NormalizedEvent:
+ def _normalize_generic(payload: IncomingWebhook) -> NormalizedEvent:
return NormalizedEvent(
original_source=payload.source,
event_category=payload.event_type,
diff --git a/examples/webhook_relay/tests/test_handlers.py b/examples/webhook_relay/tests/test_handlers.py
index e28425cd..12e77ea0 100644
--- a/examples/webhook_relay/tests/test_handlers.py
+++ b/examples/webhook_relay/tests/test_handlers.py
@@ -1,18 +1,17 @@
-"""Unit tests for the webhook relay handler chain."""
+"""Unit tests for WebhookHandler: it translates, the service decides."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
from blueprint.agents.models.events import GenericCloudEvent, HandlerResult
-from src.handlers.content_filter import ContentFilter
-from src.handlers.metadata_enricher import MetadataEnricher
-from src.handlers.webhook_normalizer import WebhookNormalizer
+from src.handlers.webhook_handler import WebhookHandler
+from src.models.domain_models import IncomingWebhook, RelayOutcome
from src.services.webhook_service import WebhookService
# ---------------------------------------------------------------------------
@@ -79,183 +78,53 @@ def _stripe_test_data() -> dict[str, Any]:
@pytest.fixture()
-def mock_registry():
- """Return a mock registry with a fake WebhookService."""
+async def handler_and_service():
+ """A WebhookHandler holding a WebhookService double, as ``on_startup`` would leave it."""
service = MagicMock(spec=WebhookService)
- service.is_duplicate.return_value = False
- service.normalize_payload.side_effect = lambda p: WebhookService._normalize_github(p)
- service.mark_processed = MagicMock()
- service.store_recent = MagicMock()
-
- registry = MagicMock()
- registry.get_service.return_value = service
- return registry
-
-
-# ---------------------------------------------------------------------------
-# WebhookNormalizer
-# ---------------------------------------------------------------------------
-
-
-class TestWebhookNormalizer:
- @pytest.mark.asyncio
- async def test_can_handle_correct_event_type(self):
- handler = WebhookNormalizer.__new__(WebhookNormalizer)
- handler._priority = 5
- event = _make_event(_github_push_data())
- assert await handler.can_handle_event(event, {}) is True
-
- @pytest.mark.asyncio
- async def test_ignores_other_event_types(self):
- handler = WebhookNormalizer.__new__(WebhookNormalizer)
- handler._priority = 5
- event = _make_event(_github_push_data(), event_type="order.placed")
- assert await handler.can_handle_event(event, {}) is False
-
- @pytest.mark.asyncio
- async def test_normalizes_and_passes(self, mock_registry):
- handler = WebhookNormalizer.__new__(WebhookNormalizer)
- handler._priority = 5
- handler._name = "webhook_normalizer"
- type(handler).registry = property(lambda self: mock_registry) # type: ignore
-
- event = _make_event(_github_push_data())
- context: dict[str, Any] = {}
- result = await handler.handle_event(event, context)
-
- assert result is None
- assert "normalized_event" in context
- assert context["normalized_event"]["original_source"] == "github"
-
- @pytest.mark.asyncio
- async def test_duplicate_skipped(self, mock_registry):
- mock_registry.get_service.return_value.is_duplicate.return_value = True
-
- handler = WebhookNormalizer.__new__(WebhookNormalizer)
- handler._priority = 5
- handler._name = "webhook_normalizer"
- type(handler).registry = property(lambda self: mock_registry) # type: ignore
-
- event = _make_event(_github_push_data())
- context: dict[str, Any] = {}
- result = await handler.handle_event(event, context)
-
- assert result is None
- assert "normalized_event" not in context
-
-
-# ---------------------------------------------------------------------------
-# ContentFilter
-# ---------------------------------------------------------------------------
-
-
-class TestContentFilter:
- @pytest.mark.asyncio
- async def test_allows_normal_event(self):
- handler = ContentFilter.__new__(ContentFilter)
- handler._priority = 10
-
- context = {
- "normalized_event": {
- "original_source": "github",
- "event_category": "push",
- "actor": "octocat",
- },
- "webhook_id": "wh-1",
- }
- event = _make_event(_github_push_data())
- result = await handler.handle_event(event, context)
- assert result is None
-
- @pytest.mark.asyncio
- async def test_filters_github_bot(self):
- handler = ContentFilter.__new__(ContentFilter)
- handler._priority = 10
-
- context = {
- "normalized_event": {
- "original_source": "github",
- "event_category": "push",
- "actor": "dependabot[bot]",
- },
- "webhook_id": "wh-2",
- }
- event = _make_event(_github_bot_data())
- result = await handler.handle_event(event, context)
-
- assert isinstance(result, HandlerResult)
- assert result.event_type == "webhook.filtered"
- assert "bot" in result.data["reason"].lower() # type: ignore
-
- @pytest.mark.asyncio
- async def test_filters_stripe_test(self):
- handler = ContentFilter.__new__(ContentFilter)
- handler._priority = 10
-
- context = {
- "normalized_event": {
- "original_source": "stripe",
- "event_category": "test_charge",
- "actor": None,
- },
- "webhook_id": "wh-3",
- }
- event = _make_event(_stripe_test_data())
- result = await handler.handle_event(event, context)
-
- assert isinstance(result, HandlerResult)
- assert result.event_type == "webhook.filtered"
- assert "test" in result.data["reason"].lower() # type: ignore
-
-
-# ---------------------------------------------------------------------------
-# MetadataEnricher
-# ---------------------------------------------------------------------------
-
-
-class TestMetadataEnricher:
- @pytest.mark.asyncio
- async def test_enriches_and_publishes(self, mock_registry):
- handler = MetadataEnricher.__new__(MetadataEnricher)
- handler._priority = 15
- handler._name = "metadata_enricher"
- type(handler).registry = property(lambda self: mock_registry) # type: ignore
-
- context = {
- "normalized_event": {
- "original_source": "github",
- "event_category": "push",
- "event_action": "completed",
- "actor": "octocat",
- },
- "webhook_id": "wh-4",
- }
- event = _make_event(_github_push_data())
- result = await handler.handle_event(event, context)
-
+ service.relay = AsyncMock(return_value=RelayOutcome(kind="processed", data={"webhook_id": "evt-test-001"}))
+ handler = WebhookHandler.__new__(WebhookHandler)
+ handler._priority = 10
+ handler._service = service
+ return handler, service
+
+
+class TestRouting:
+ async def test_declares_and_accepts_webhook_received(self, handler_and_service):
+ handler, _ = handler_and_service
+ assert handler.get_handled_event_types() == ["webhook.received"]
+ assert await handler.can_handle_event(_make_event(_github_push_data()), {}) is True
+
+ async def test_declines_other_types_without_calling_the_service(self, handler_and_service):
+ handler, service = handler_and_service
+ assert await handler.can_handle_event(_make_event({}, event_type="other.event"), {}) is False
+ service.relay.assert_not_awaited()
+
+
+class TestTranslation:
+ async def test_the_payload_reaches_the_service_as_a_domain_value(self, handler_and_service):
+ handler, service = handler_and_service
+ await handler.handle_event(_make_event(_github_push_data()), {})
+ webhook = service.relay.await_args.args[0]
+ assert isinstance(webhook, IncomingWebhook)
+ assert webhook.webhook_id == "evt-test-001" # no webhook_id in the payload -> the event id
+ assert webhook.source == "github"
+
+ async def test_processed_is_published_as_webhook_processed(self, handler_and_service):
+ handler, _ = handler_and_service
+ result = await handler.handle_event(_make_event(_stripe_payment_data()), {})
assert isinstance(result, HandlerResult)
assert result.event_type == "webhook.processed"
- assert result.data["priority_score"] == 50 # "push" keyword # type: ignore
- assert "processed_at" in result.data # type: ignore
- mock_registry.get_service.return_value.mark_processed.assert_called_once_with("wh-4")
-
- @pytest.mark.asyncio
- async def test_payment_gets_high_priority(self, mock_registry):
- handler = MetadataEnricher.__new__(MetadataEnricher)
- handler._priority = 15
- handler._name = "metadata_enricher"
- type(handler).registry = property(lambda self: mock_registry) # type: ignore
-
- context = {
- "normalized_event": {
- "original_source": "stripe",
- "event_category": "payment_intent",
- "event_action": "succeeded",
- },
- "webhook_id": "wh-5",
- }
- event = _make_event(_stripe_payment_data())
- result = await handler.handle_event(event, context)
- assert isinstance(result, HandlerResult)
- assert result.data["priority_score"] == 80 # "payment" keyword # type: ignore
+ async def test_filtered_is_published_as_webhook_filtered(self, handler_and_service):
+ handler, service = handler_and_service
+ service.relay.return_value = RelayOutcome(kind="filtered", reason="bot", data={"reason": "bot"})
+ result = await handler.handle_event(_make_event(_github_bot_data()), {})
+ assert result.event_type == "webhook.filtered"
+ assert result.data == {"reason": "bot"}
+
+ async def test_a_duplicate_is_skipped_with_the_services_reason(self, handler_and_service):
+ handler, service = handler_and_service
+ service.relay.return_value = RelayOutcome(kind="duplicate", reason="webhook evt-test-001 already relayed")
+ result = await handler.handle_event(_make_event(_stripe_test_data()), {})
+ assert result.is_skipped
+ assert result.skip_reason == "webhook evt-test-001 already relayed"
diff --git a/examples/webhook_relay/tests/test_webhook_service.py b/examples/webhook_relay/tests/test_webhook_service.py
index c499435b..192d9b8f 100644
--- a/examples/webhook_relay/tests/test_webhook_service.py
+++ b/examples/webhook_relay/tests/test_webhook_service.py
@@ -5,7 +5,7 @@
from unittest.mock import MagicMock
-from src.models.schemas import NormalizedEvent, WebhookPayload
+from src.models.domain_models import IncomingWebhook, NormalizedEvent
from src.services.webhook_service import WebhookService
# ---------------------------------------------------------------------------
@@ -35,7 +35,8 @@ def _make_service(*, with_cache: bool = False) -> WebhookService:
class TestNormalizePayload:
def test_github_push(self):
- payload = WebhookPayload(
+ payload = IncomingWebhook(
+ webhook_id="wh-test",
source="github",
event_type="push",
payload={
@@ -56,7 +57,8 @@ def test_github_push(self):
assert result.resource_type == "repository"
def test_stripe_payment_intent(self):
- payload = WebhookPayload(
+ payload = IncomingWebhook(
+ webhook_id="wh-test",
source="stripe",
event_type="payment_intent.succeeded",
payload={
@@ -75,7 +77,8 @@ def test_stripe_payment_intent(self):
assert result.resource_type == "payment_intent"
def test_generic_passthrough(self):
- payload = WebhookPayload(
+ payload = IncomingWebhook(
+ webhook_id="wh-test",
source="generic",
event_type="alert.fired",
payload={
@@ -97,7 +100,8 @@ def test_generic_passthrough(self):
assert result.metadata["severity"] == "critical"
def test_github_missing_optional_fields(self):
- payload = WebhookPayload(
+ payload = IncomingWebhook(
+ webhook_id="wh-test",
source="github",
event_type="ping",
payload={},
@@ -163,3 +167,52 @@ def test_store_recent_noop_without_cache(self):
def test_get_recent_empty_without_cache(self):
svc = _make_service(with_cache=False)
assert svc.get_recent() == []
+
+
+# ---------------------------------------------------------------------------
+# relay: the one entry point, and the decisions the handlers used to make
+# ---------------------------------------------------------------------------
+
+
+def _webhook(source: str, event_type: str, payload: dict) -> IncomingWebhook:
+ return IncomingWebhook(webhook_id="wh-r1", source=source, event_type=event_type, payload=payload)
+
+
+class TestRelay:
+ async def test_a_duplicate_needs_nothing(self):
+ svc = _make_service(with_cache=True)
+ svc._cache.exists.return_value = True # type: ignore
+ outcome = await svc.relay(_webhook("github", "push", {}))
+ assert outcome.kind == "duplicate"
+ assert "wh-r1" in outcome.reason
+ svc._cache.set.assert_not_called() # type: ignore
+
+ async def test_a_github_bot_is_filtered_and_not_recorded(self):
+ svc = _make_service(with_cache=True)
+ outcome = await svc.relay(_webhook("github", "push", {"sender": {"login": "dependabot[bot]"}}))
+ assert outcome.kind == "filtered"
+ assert outcome.data == {"reason": "Filtered GitHub bot event from dependabot[bot]", "webhook_id": "wh-r1"}
+ svc._cache.set.assert_not_called() # type: ignore
+
+ async def test_a_stripe_test_event_is_filtered(self):
+ svc = _make_service()
+ outcome = await svc.relay(_webhook("stripe", "test_charge.created", {"type": "test_charge.created"}))
+ assert outcome.kind == "filtered"
+ assert "test_charge" in outcome.reason
+
+ async def test_a_normal_event_is_enriched_recorded_and_returned(self):
+ svc = _make_service(with_cache=True)
+ outcome = await svc.relay(_webhook("stripe", "payment_intent.succeeded", {"type": "payment_intent.succeeded", "id": "pi_1"}))
+ assert outcome.kind == "processed"
+ assert outcome.data["priority_score"] == 80
+ assert outcome.data["webhook_id"] == "wh-r1"
+ assert "processed_at" in outcome.data
+ assert svc._cache.set.call_count == 2 # type: ignore # dedup marker + recent list
+
+
+class TestScoring:
+ def test_unknown_category_gets_the_default(self):
+ assert WebhookService.score_priority("something.else") == 10
+
+ def test_security_outranks_push(self):
+ assert WebhookService.score_priority("security_advisory") > WebhookService.score_priority("push")
diff --git a/pyproject.toml b/pyproject.toml
index b8a92b38..31c22207 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -17,7 +17,6 @@ requires-python = ">=3.13"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
- "License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.13",
"Typing :: Typed",
@@ -34,15 +33,15 @@ dependencies = [
"opentelemetry-api>=1.38.0",
"opentelemetry-sdk>=1.38.0",
"opentelemetry-instrumentation-fastapi>=0.59b0",
+ "opentelemetry-instrumentation-httpx>=0.59b0",
"opentelemetry-exporter-otlp>=1.38.0",
"dapr>=1.16.0",
"python-multipart>=0.0.20",
"apscheduler>=3.11.2",
- "diskcache-rs>=0.4.4",
- "nats-py>=2.13.1",
+ "diskcache-rs>=0.4.10",
+ "nats-py[nkeys]>=2.13.1",
"croniter>=6.0.0",
- "pytest",
- "pytest-asyncio"
+ "pyyaml>=6.0"
]
[project.optional-dependencies]
@@ -55,10 +54,10 @@ ci = [
"mypy>=1.18.2",
"httpx>=0.28.1",
"fakeredis>=2.26.0",
- "redis[hiredis]>=5.0.0",
+ "redis[hiredis]>=8.0.0",
"respx>=0.22.0",
]
-redis = ["redis[hiredis]>=5.0.0"]
+redis = ["redis[hiredis]>=8.0.0"]
dev = [
"avs-blueprint-agents[ci]",
"debugpy>=1.8.17",
@@ -108,7 +107,7 @@ packages = [
[tool.setuptools.package-data]
"blueprint.agents" = ["py.typed"]
-"blueprint.agent_generator" = ["base_files/**/*", "assistant_integrations/**/*", "claude_docs/**/*"]
+"blueprint.agent_generator" = ["base_files/**/*", "claude_docs/**/*", "docs/**/*"]
[tool.black]
line-length = 140
@@ -131,6 +130,15 @@ extend-exclude = '''
[tool.ruff]
target-version = "py313"
line-length = 140
+# The packaged documentation lives under src/ so it ships in the wheel, which puts it in reach of
+# "ruff format src". Ruff formats Python code blocks inside Markdown, and the examples in these
+# pages are wrapped on purpose -- a fluent AppBuilder chain is one call per line because that is
+# what makes the shape readable. Formatting them collapses each chain onto a single 140-column
+# line, which is worse prose and not what the reader is being shown.
+extend-exclude = [
+ "src/blueprint/agent_generator/docs",
+ "src/blueprint/agent_generator/claude_docs",
+]
lint.select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
@@ -171,6 +179,7 @@ module = [
"croniter",
"dapr.*",
"nats.*",
+ "yaml",
]
ignore_missing_imports = true
diff --git a/pytest.ini b/pytest.ini
index c3256b69..4bbb4ece 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -10,4 +10,4 @@ pythonpath =
examples/simple_event_processor
examples/complex_agent
markers =
- integration: requires external services (e.g. Redis) — skipped in offline CI
+ integration: requires external services (NATS, Redis) — skipped in offline CI
diff --git a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md b/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md
deleted file mode 100644
index 1da40eb3..00000000
--- a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# Claude Code Guidelines
-
-This file is read automatically by Claude Code at the start of every session.
-
-## Framework
-
-This project uses the **Blueprint Agents** framework. All application components extend
-base classes from the framework:
-
-| Class | Import | Purpose |
-|---|---|---|
-| `EventHandlerBase` | `blueprint.agents.handler` | CloudEvent processing (chain-of-responsibility) |
-| `ServiceBase` | `blueprint.agents.services` | Domain logic, state, orchestration |
-| `AgentRuntime` | via `AgentBuilder` from `blueprint.agents` | LLM agents (wraps pydantic-ai) |
-| `RestApiBase` | `blueprint.agents.io.api` | HTTP endpoints via FastAPI |
-| `SchedulerBase` | `blueprint.agents.io.api.scheduling` | Background cron tasks |
-
-## Key Architecture Rules
-
-- **Never access `self.registry` or `self.config` in `__init__`** — they are not linked until after construction. Always resolve dependencies in `on_startup()`.
-- **Register dependencies before dependents** — services before handlers/agents that use them.
-- **`main.py` is wiring only** — no business logic.
-- **Services contain ALL business logic** — handlers and APIs are thin delegation layers with one method per responsibility.
-- No global state, no module-level component instances.
-
-```python
-# Correct — resolve in on_startup()
-class MyHandler(EventHandlerBase):
- async def on_startup(self) -> None:
- self._service = self.registry.get_service(MyService)
-
- async def handle_event(self, event, context):
- payload = self.extract_payload(event, MyModel) # Typed extraction with validation
- return await self._service.process(payload)
-```
-
-## Code Style
-
-- Complete type hints on every method signature
-- All I/O must be `async` / `await` — never blocking I/O in async code
-- Every public method needs a docstring (one-liner is fine for simple methods)
-- Use `%s`-style args in log calls, not f-strings (deferred formatting)
-- Validate all external input with Pydantic at system boundaries
-- Never hardcode secrets — use environment variables via `secrets.toml`
-- **No `assert` statements in production code** — `assert` is only permitted in test files (`tests/`)
-- **All imports at the top of the file** — never inside methods, functions, or classes
-
-## Agent Prompts
-
-- **System prompt** (`system.prompt`): Static context — no dynamic inputs. Loaded by `AgentBuilder.with_system_prompt()`.
-- **Instruction prompt** (`instruction.prompt`): Contains `{placeholders}` for dynamic inputs.
-- Files go in `src/prompts/` as `.prompt` files
-
-**Always use `agent.get_prompt().format()` for user prompts with variable inputs:**
-
-```python
-prompt = self._agent.get_prompt("instruction").format(
- ticket_text=ticket_text,
- customer_tier=customer_tier,
-)
-result = await self._agent.run(user_prompt=prompt)
-```
-
-## Error Handling
-
-- Define domain-specific exceptions when callers need to catch them selectively
-- Always use context managers (`async with`) for files, HTTP clients, DB connections
-- Set explicit timeouts on all external calls
-- Never log passwords, tokens, or API keys
-
-## Testing
-
-- Test files: `test_.py` | Classes: `Test` | Methods: `test__`
-- Use `MagicMock(spec=...)` for sync deps, `AsyncMock()` for async deps
-- Shared fixtures in `conftest.py`
-- `asyncio_mode = auto` in `pytest.ini`
-
-## Project Structure
-
-```
-src/
-├── main.py # AppBuilder wiring only
-├── api/ # RestApiBase subclasses
-├── handlers/ # EventHandlerBase subclasses
-├── services/ # ServiceBase subclasses
-├── schedulers/ # SchedulerBase subclasses
-├── agents/ # AgentBuilder setup code
-├── models/ # Pydantic models
-└── prompts/ # .prompt files (system + instruction)
-```
-
-## Running the Service
-
-```bash
-pip install -e .
-uvicorn src.main:app --reload # development
-pytest tests/ # run tests
-asbs validate # validate project structure
-```
diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile
index df5fe8c1..a09c3979 100644
--- a/src/blueprint/agent_generator/base_files/Dockerfile
+++ b/src/blueprint/agent_generator/base_files/Dockerfile
@@ -11,7 +11,9 @@ WORKDIR /app
# Layer 1: Copy dependency manifests and install dependencies
# This layer caches if only code changes, not deps
-COPY pyproject.toml README.md ./
+# Only the manifest: the generated pyproject.toml declares no readme, and no README.md is
+# generated, so copying one failed a fresh `docker build` at this line.
+COPY pyproject.toml ./
RUN uv pip install --system --no-cache \
--upgrade pip setuptools wheel && \
@@ -29,9 +31,18 @@ FROM builder AS dev
RUN uv pip install --system --no-cache ".[dev]" ipython debugpy pytest
ENV PYTHONPATH="/app/src"
-ENV DYNACONF_ENVIRONMENT="development"
-
-CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
+# app_environment selects the settings section, and it defaults to development. The variable is
+# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own
+# envvar_prefix renames it to _APP_ENVIRONMENT.
+ENV DYNACONF_APP_ENVIRONMENT="development"
+
+# src/main.py declares an agent; it does not build one, so there is no `src.main:app` to
+# serve. create_app() builds the declaration with this directory's settings, and uvicorn
+# reloads it because a factory is an import string rather than a built object.
+#
+# Nothing group-related here either: this stage expects the project bind-mounted at /app and
+# serves the one agent it contains.
+CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "src.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--reload"]
# ============================================================================
# Production - Minimal runtime image
@@ -60,25 +71,52 @@ COPY --from=builder /usr/local/bin /usr/local/bin
COPY --chown=appuser:appuser src ./src
COPY --chown=appuser:appuser settings.toml ./
-# Note: secrets.toml is NOT copied into the image.
-# Mount it at runtime via Docker secrets or volume mount.
-# Example (Docker Swarm):
-# docker run --secret secrets_file_id \
-# -e DYNACONF_SETTINGS=/run/secrets/secrets_file_id \
-# pir-agent:latest
-# Example (Volume mount):
-# docker run -v ./secrets.toml:/app/secrets.toml:ro pir-agent:latest
-
+# No agent map, and no group. This image contains one agent and serves it directly through
+# its own create_app() factory -- a standalone agent defines nothing group-related, because
+# a group of one is a group, and an agent must not have to declare itself one to run alone.
+#
+# The same directory is hosted by a group image without changing a line: that image's
+# agents.toml names this module and builds the same declaration under the agent's namespace,
+# which is where the routes gain their /api/ prefix.
+
+# The disk cache backend writes here, and it cannot create this itself: WORKDIR made /app
+# root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time,
+# which is also the mount point to use under a read-only root filesystem -- see the
+# "Writable cache directory" section of docs/guides/deployment.md.
+RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache
+
+# Note: .secrets.toml is NOT copied into the image. Mount it at runtime, at that exact path --
+# the entry point loads ["settings.toml", ".secrets.toml"] relative to the working directory, so
+# a file mounted under any other name is loaded by nothing and reports nothing.
+# Example (volume mount):
+# docker run -v ./.secrets.toml:/app/.secrets.toml:ro
+# Example (Docker secret, which lands under /run/secrets):
+# docker run --secret source=agent_secrets,target=/app/.secrets.toml
+# An individual key can also be supplied as an environment variable instead, with no file at
+# all: -e DYNACONF_MODEL_API_KEY=...
+
+# app_environment selects the settings section, and it defaults to development. The variable is
+# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own
+# envvar_prefix renames it to _APP_ENVIRONMENT.
ENV PYTHONPATH="/app/src" \
- DYNACONF_ENVIRONMENT="production" \
+ DYNACONF_APP_ENVIRONMENT="production" \
PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
USER appuser
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
- CMD curl -f http://localhost:8000/health || exit 1
+ CMD curl -f http://localhost:8000/health/live || exit 1
EXPOSE 8000
-ENTRYPOINT ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]
+# This image contains one agent and serves it. There is no group to choose at container
+# start, no agent map to read and no BLUEPRINT_* variable to set:
+#
+# docker run -p 8000:8000
+#
+# Its components are built at the root namespace, so the routes are the ones the API
+# declares. Hosted in a group image instead, the same directory gains an /api/
+# prefix -- that identity change happens once, on the first grouped deploy, and is what
+# the migration guide covers. Nothing in this directory changes to make it.
+ENTRYPOINT ["python", "-m", "uvicorn", "src.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/src/blueprint/agent_generator/base_files/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile
new file mode 100644
index 00000000..02062942
--- /dev/null
+++ b/src/blueprint/agent_generator/base_files/group_Dockerfile
@@ -0,0 +1,84 @@
+# syntax=docker/dockerfile:1.7
+
+# ============================================================================
+# Group image - hosts several agents in one process
+# ============================================================================
+#
+# The two images run differently. An agent's own Dockerfile serves its one declaration directly
+# (uvicorn src.main:create_app --factory), at the root namespace, with no map and no group. This
+# one runs the group entry point, which reads agents.toml and hosts each agent the deployment
+# names under its own namespace (/api/). The agent directories are copied as they are,
+# beside the map that names them.
+#
+# Each agent directory is exactly what `asbs setup ` wrote -- its own settings.toml and
+# src/ -- and carries no agents.toml. That is what lets the same directory be built by its own
+# Dockerfile as a single-agent image without editing anything. Its .secrets.toml is NOT copied
+# (.dockerignore excludes every one): mount it at runtime beside the agent's src, at
+# /app//.secrets.toml, where is the agent's `root` in agents.toml -- for example
+# docker run -v ./agents/billing/.secrets.toml:/app/agents/billing/.secrets.toml:ro
+# or supply single keys as environment variables (DYNACONF___MODEL_API_KEY=...).
+
+FROM python:3.13-bookworm AS builder
+
+RUN pip install --no-cache-dir --upgrade pip uv
+
+WORKDIR /app
+
+COPY pyproject.toml ./
+RUN uv pip install --system --no-cache .
+
+# ============================================================================
+# Runtime
+# ============================================================================
+FROM python:3.13-slim-bookworm AS runtime
+
+RUN useradd --create-home --shell /bin/bash appuser
+
+WORKDIR /app
+
+COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages
+COPY --from=builder /usr/local/bin /usr/local/bin
+
+# The agents, each in the directory its entry in agents.toml points at with `root`. Copy the
+# directories this image actually contains; a blanket `COPY . .` would bake in whatever else
+# the repository holds, including other images' build context.
+COPY --chown=appuser:appuser agents ./agents
+
+# The image's own settings: the process-wide keys -- app_port, app_host, event_bus, log_level
+# and the rest. One process has one of each, so an agent that sets them in its own settings
+# file has them dropped before the merge, with a warning naming the value the process uses.
+COPY --chown=appuser:appuser settings.toml ./
+
+# The map: which agents this image contains, and where each one's files are. The group file
+# does NOT belong here -- which of these agents a process runs is a deployment decision, so it
+# arrives as a mount or as BLUEPRINT_AGENTS.
+COPY --chown=appuser:appuser agents.toml ./
+
+# The disk cache backend writes here and cannot create it itself: WORKDIR made /app
+# root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time.
+RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache
+
+# app_environment selects the settings section, and it defaults to development. The variable is
+# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own
+# envvar_prefix renames it to _APP_ENVIRONMENT.
+ENV DYNACONF_APP_ENVIRONMENT="production" \
+ PYTHONUNBUFFERED=1 \
+ PYTHONDONTWRITEBYTECODE=1
+
+USER appuser
+
+EXPOSE 8000
+
+# Python, not curl: the slim base image has no curl, so a curl check failed for ever and the
+# container never turned healthy.
+HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
+ CMD ["python", "-c", "import sys, urllib.request; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health/live', timeout=4).status == 200 else 1)"]
+
+# Which agents this process runs is the deployment's to say:
+#
+# docker run -e BLUEPRINT_AGENTS=order_processor,billing
+# docker run -v ./deployment-groups.yaml:/app/deployment-groups.yaml:ro \
+# -e BLUEPRINT_GROUP=
+#
+# Nothing in the image names a group, so one image serves every one of them.
+ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"]
diff --git a/src/blueprint/agent_generator/base_files/group_agents_toml.txt b/src/blueprint/agent_generator/base_files/group_agents_toml.txt
new file mode 100644
index 00000000..5af8a82a
--- /dev/null
+++ b/src/blueprint/agent_generator/base_files/group_agents_toml.txt
@@ -0,0 +1,43 @@
+# Which agents this image contains, and where each one's files and code live.
+#
+# Baked into the image on purpose: adding or removing an agent is a rebuild anyway. Which of
+# these agents a given *process* runs is a separate decision, made by the deployment rather
+# than by the image -- set BLUEPRINT_AGENTS to a comma-separated list, or mount a group file
+# and name the group with BLUEPRINT_GROUP. Nothing here says which agents run together.
+#
+# The name in brackets is the agent's namespace, and it is the agent's identity everywhere
+# outside this file: the registry key prefix, the NATS queue group, part of the JetStream
+# durable name, the cache partition, the OpenTelemetry service.name and the REST route prefix
+# (/api/). Renaming it after the first deploy is therefore a consumer migration, not a
+# rename. It must match [a-z][a-z0-9_]* -- lower case, no dashes.
+#
+# Each agent needs two keys, and both are required:
+#
+# root Where the agent's own directory is, relative to the image root -- the directory the
+# process runs in, which is normally the one this file sits in too. It is the image
+# root and not this file: BLUEPRINT_AGENT_MAP may put this file elsewhere, and moving
+# it must not move every agent. Its settings.toml and its src/prompts are read from
+# there. Stated rather than guessed from the module:
+# a root derived from where a declaration happens to sit is right for one layout and
+# silently wrong for every other, and an agent reading the group's defaults instead
+# of its own settings does not announce itself.
+# module "package.module:attribute", naming the AppBuilder that module assigns.
+#
+# An agent directory is created by running `asbs setup ` inside it, and is the same
+# directory whether it is hosted here or built as its own image -- it carries no agents.toml
+# of its own, which is what lets it move between the two untouched.
+#
+# This file starts empty. A group with no agents cannot run: the process refuses to start
+# rather than bind a port and consume nothing. Add an entry per agent, for example:
+#
+# [agents.order_processor]
+# root = "agents/order_processor"
+# module = "agents.order_processor.src.main:agent"
+#
+# [agents.billing]
+# root = "agents/some_topic/billing"
+# module = "agents.some_topic.billing.src.main:agent"
+#
+# Renaming or moving an agent directory means updating its entry here. That is deliberate:
+# the map is the one place the change has to be made on purpose, so a moved directory fails
+# loudly at startup instead of quietly removing an agent from the image.
diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt
index b2c1b3ee..8cd76a5a 100644
--- a/src/blueprint/agent_generator/base_files/settings.txt
+++ b/src/blueprint/agent_generator/base_files/settings.txt
@@ -2,16 +2,57 @@
app_name
app_version = "0.1.0"
app_description
-debug = true
model_provider = "vllm"
-model_base_url = "https://avs-vllm.q14.net/v1"
+model_base_url = "https://YOUR_VLLM_HOST/v1"
-[default.logging]
-level = "DEBUG"
-format = "json"
+# Event deduplication is off by default: a handler may be run more than once for the
+# same event, because delivery is at-least-once and an acknowledgement can always be
+# lost. Turn it on only after deciding it is what your handlers need -- see the DECIDE
+# comment in src/handlers/. idempotency_ttl is required when it is enabled, and must
+# outlast the broker redelivery window (nats_ack_wait * nats_max_deliver on JetStream);
+# the markers are kept in this agent's cache, so src/main.py needs .with_cache() as well.
+# Startup fails if either is missing.
+# idempotency_enabled = true
+# idempotency_ttl = 1500
-[default.observability]
+# Required as soon as a scheduler is registered -- it has no default, because neither
+# value is safe to inherit, and this template does not choose for you. "event" starts no
+# in-process timer: the tick arrives as an event on .scheduler.
+# (the application's name instead of the agent when it is served on its own), published
+# by an external CronJob, so exactly one replica runs it -- and it needs event_bus set.
+# "in_process" runs an APScheduler timer in every process and claims each tick in the
+# cache; it is right for local development and plain Docker, and it needs .with_cache()
+# or every replica runs every tick. The claim is atomic across processes only on Redis
+# ([default.cache] backend = "redis"); on the default disk cache it holds
+# within one process only, so two replicas sharing the cache directory can both run it.
+# scheduler_mode = "event"
+# scheduler_mode = "in_process"
+
+# Set this to publish events without consuming any -- a scheduler that reports what
+# it did, for instance. A handler already implies a client, so only publish-only
+# applications need it. Needs event_bus, and subscribes to nothing.
+# event_publishing_enabled = true
+
+# Logging and telemetry. These are flat keys, not sections: the framework reads
+# log_level, log_format, otel_enabled and token_metrics_enabled from the top level
+# of the environment table, so a [default.logging] or [default.observability]
+# section would be read by nothing at all.
+#
+# log_level and log_format describe the *process*, not this agent, so they are
+# commented out here: one process configures logging once, and a value set under an
+# agent is dropped before the merge with a warning naming the value actually used.
+#
+# Uncomment them only while this agent is deployed on its own, where its directory is
+# also the image. In a group they belong in the image's settings.toml, beside
+# agents.toml -- `asbs validate --group` reports them if they are left here.
+# log_level = "DEBUG"
+# log_format = "text"
+
+# otel_enabled turns OpenTelemetry on and needs otel_endpoint to have somewhere to
+# send to. token_metrics_enabled adds per-call token and latency metrics on top, and
+# is read only when otel_enabled is true.
otel_enabled = false
+# otel_endpoint = "http://localhost:4317"
token_metrics_enabled = true
agent_runtime_configs
diff --git a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt
index ae1095c6..75fb1570 100644
--- a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt
+++ b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt
@@ -19,34 +19,67 @@ on_startup
on_shutdown
async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- """Determine if this handler should process the event.
+ """Route: is this handler the one for this kind of event?
- This method should make all the necessary checks to determine if this handler should process the event.
+ Decide on the envelope only -- ``event.type``, ``event.source``, ``event.subject`` and the
+ context keys. No I/O and no service call here: whether *this* event needs work is the
+ service's decision, reported back through ``handle_event``.
Args:
event: The CloudEvent to potentially handle.
context: Processing context dictionary.
Returns:
- True if this handler can process the event, False otherwise.
+ True if this handler is responsible for the event, False otherwise.
"""
- # Simple example
- # if event.type == self._input_event_type:
+ # Example:
+ # return event.type == "order.placed"
raise NotImplementedError()
async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- """Handles the event. This is where the main business logic is implemented. This can a part of a chain of
- handlers. The chain continues based on the handlers priorities and until a handler returns a result.
+ """Translate the event into one service call and the service's answer into a result.
+
+ A handler translates, it never decides: three steps, nothing more.
+
+ 1. ``payload = self.extract_payload(event, MyEventDto)`` -- the typed, validated payload.
+ 2. **One** service call with domain values (ids, domain models; never the CloudEvent or
+ the DTO). All business logic lives behind it, including whether the event needs work
+ and the order of the steps; two service calls in a row are business logic already.
+ 3. The answer as a result: ``HandlerResult(event_type=..., data=...)`` to publish,
+ ``HandlerResult.skipped("reason")`` when the service found nothing to do, or ``None``
+ only when another handler should be offered the event.
+
+ No LLM call here: the service resolves and runs its agent.
Args:
event: The CloudEvent to process.
- context: Dictionary containing information from previous handlers. Can be extended to pass information to
- the following handlers.
+ context: Processing context dictionary (transport keys such as ``nats_subject``).
Returns:
- HandlerResult: The resulting event to publish, when the handlers work is done.
+ The result to publish, a skip, or None to pass the event to the next handler.
"""
+ # DECIDE: can the service run twice on the same event?
+ #
+ # Delivery is at-least-once. A redelivery arrives whenever an acknowledgement is
+ # lost -- a pod restart, a rolling deploy, a connection blip mid-run -- and the side
+ # effects of the first attempt have already happened by then. Running twice is not an
+ # edge case; it is the normal behaviour of the transport.
+ #
+ # Make the *service* safe to repeat (upsert instead of insert, key the outbound request
+ # on event.id -- pass it as a parameter), or switch the framework dedup on:
+ #
+ # settings.toml
+ # idempotency_enabled = true
+ # idempotency_ttl = 1500 # seconds; must outlast the redelivery window
+ #
+ # src/main.py
+ # .with_cache() # the markers live in this agent's cache
+ #
+ # Startup fails without the ttl or without the cache.
+ #
+ # Dedup keys on the event id and source and is best-effort: it narrows the window,
+ # it does not close it. Whichever you choose, delete this comment once you have.
logger.info("MyHandler processing event '%s'", event.type)
raise NotImplementedError()
diff --git a/src/blueprint/agent_generator/base_files/src/main.txt b/src/blueprint/agent_generator/base_files/src/main.txt
index a3b2bed8..50d5d316 100644
--- a/src/blueprint/agent_generator/base_files/src/main.txt
+++ b/src/blueprint/agent_generator/base_files/src/main.txt
@@ -1,19 +1,41 @@
"""
app_name
app_description
-"""
-from pathlib import Path
+This file is a *declaration*, not an application: every ``with_*`` call records what this
+agent is made of, and nothing is constructed until something calls ``build()``. That is what
+lets the same file be served on its own and be hosted alongside other agents in one process --
+the host decides the configuration and the namespace each component is built in, and this file
+never mentions either.
+
+Two ways to run it, and this directory is identical in both:
+
+- **On its own**, which is what the generated ``Dockerfile`` does::
+
+ uvicorn src.main:create_app --factory
+
+ ``create_app`` below builds this declaration with this directory's own settings. Nothing
+ group-related is involved: no agent map, no group file, no namespace. The components are
+ built at the root namespace, so the routes are the ones the API declares.
+
+- **As one agent of a group**, where an image's ``agents.toml`` names this module and
+ ``python -m blueprint.agents.entrypoint`` builds the same declaration under this agent's
+ namespace -- which is where the routes gain their ``/api/`` prefix. Nothing in this
+ directory changes to make that work; the image's map points at it.
+"""
imports
-# Initialize config
-config = Config(
- settings_files=[
- "settings.toml",
- "secrets.toml",
- ],
- root_path=Path(__file__).parent.parent
-)
+agent_declaration
+
+
+def create_app():
+ """Build this agent as an application of its own.
+
+ Only for running it standalone. A group never calls this: it builds the declaration above
+ itself, once per hosted agent, inside that agent's namespace.
-agents_and_app_initialization
+ Returns:
+ The FastAPI application, with every component built at the root namespace.
+ """
+ return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent)))
diff --git a/src/blueprint/agent_generator/base_files/src/services/service.txt b/src/blueprint/agent_generator/base_files/src/services/service.txt
index 84f995f6..03d0afd8 100644
--- a/src/blueprint/agent_generator/base_files/src/services/service.txt
+++ b/src/blueprint/agent_generator/base_files/src/services/service.txt
@@ -4,7 +4,6 @@ service_description
import logging
-from blueprint.agents.agent import AgentRuntime
from blueprint.agents.services import ServiceBase
imports
diff --git a/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt
new file mode 100644
index 00000000..d38691b9
--- /dev/null
+++ b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt
@@ -0,0 +1,62 @@
+# What must never reach the build context.
+#
+# The group image copies the whole `agents/` tree, because which agents a *process* runs is
+# decided at startup rather than at build time -- so the image has to contain all of them. That
+# makes this file load-bearing rather than tidy-up: a wholesale copy takes whatever is on disk.
+#
+# .gitignore does not help here. Docker's build context is the filesystem, not the repository,
+# so a file git has never seen is copied in anyway.
+
+# Secrets. The single most important line in this file: real API keys live in .secrets.toml
+# during development, git ignores them, and a COPY would bake them into a layer that anyone
+# who can pull the image can read. Secrets reach a container as environment variables or a
+# mounted file, never as a layer.
+**/.secrets.toml
+**/*.secrets.toml
+.env
+**/.env
+
+# Per-agent Dockerfiles. An agent may own one so it can be built as a single-agent image; it is
+# not part of the group image and only invalidates layers.
+agents/**/Dockerfile
+agents/**/.dockerignore
+
+# The deployment's group file. Which agents this process runs is a deployment decision, so it
+# arrives as a mount or as BLUEPRINT_AGENTS -- baking one in would make the image serve one
+# group only, which is the opposite of the point.
+deployment-groups.yaml
+deployment-groups.yml
+
+# These two lines cover the default name only. A repository that keeps several groups usually
+# keeps one file per group somewhere of its own choosing -- BLUEPRINT_GROUP_CONFIG takes a
+# path, so any layout works and the framework has no opinion about it. Whatever that layout
+# is, add it here: a folder of group files is not covered by the names above, and one that
+# reaches the build context is baked in, which makes the image serve the group that happened
+# to be on disk. Uncomment and adjust:
+#
+# deployment/groups/
+
+# Local environments and caches, which are large, machine-specific and often not even the right
+# platform.
+.venv/
+venv/
+**/__pycache__/
+**/*.py[cod]
+.pytest_cache/
+.mypy_cache/
+.ruff_cache/
+**/.cache/
+
+# Version control and CI
+.git/
+.gitignore
+.github/
+
+# Tests and docs do not run in the image
+**/tests/
+docs/
+
+# Editor and OS noise
+.idea/
+.vscode/
+.DS_Store
diff --git a/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt b/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt
index c3562ad4..af6a36c3 100644
--- a/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt
+++ b/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt
@@ -142,8 +142,8 @@ cython_debug/
# Generated Dapr components (from templates)
custom/dapr/components/rabbitmq-pubsub.yaml
-# Secrets
-**/secrets.toml
+# Secrets. Named exactly, not as a glob: the committed example template shares the prefix.
+**/.secrets.toml
.env.rabbitmq
uv.lock
diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md
index b7f30aef..57039147 100644
--- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md
+++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md
@@ -31,39 +31,60 @@ from blueprint.agents.models import GenericCloudEvent, HandlerResult, CloudEvent
4. **No global state** — no module-level component instances, no singletons.
5. **All components must implement `on_startup()` and `on_shutdown()`** — even if empty.
6. **Services contain ALL business logic** — handlers and APIs are thin delegation layers.
+7. **A handler translates, it never decides.** `can_handle_event` routes on the envelope only
+ (`event.type`, `event.source`, `event.subject`, the context keys) -- no I/O, no service call.
+ `handle_event` is three steps: `self.extract_payload(event, Dto)` -> **one** service call ->
+ translate the answer into a `HandlerResult`, `HandlerResult.skipped(reason)` or `None`.
+ Calling two services in a row is already business logic: give the service one method for it.
+8. **Relevance is the service's decision.** Whether *this* event needs work (a field changed, a
+ status reached) is checked by the service; a handler that was routed the event but has nothing
+ to do returns `HandlerResult.skipped(reason)`.
+9. **Handlers never call the LLM.** No `agent.run()`, no `registry.get_agent()`, no runtime taken
+ from `context` in a handler -- the service resolves its agent in `on_startup()` and runs it.
+10. **No run state on `self`.** Components are shared by every concurrent run; per-event values
+ live in locals and parameters. `self` holds only what `on_startup()` resolved.
## Wiring (main.py)
+`src/main.py` is a **declaration**, exactly as `asbs setup` writes it: no `Config`, no `build()`,
+components registered as **classes**. The host builds it -- `create_app()` when the agent runs on
+its own, `python -m blueprint.agents.entrypoint` when it is one agent of a group.
+
```python
from pathlib import Path
-from blueprint.agents import AppBuilder, Config, AgentBuilder
-config = Config(
- settings_files=["settings.toml", "secrets.toml"],
- root_path=Path(__file__).parent.parent,
-)
+from blueprint.agents import AgentBuilder, AppBuilder, Config
+
+from .api.order_api import OrderApi
+from .handlers.order_handler import OrderHandler
+from .services.order_service import OrderService
-my_agent = (
- AgentBuilder(config, runtime_name="my_agent")
- .with_model_from_config("my_agent")
- .with_system_prompt("system")
- .with_tools([...])
- .with_result_type(MyResultModel)
- .build(name="my_agent")
+order_agent = (
+ AgentBuilder(runtime_name="order_agent")
+ .with_model_from_config()
+ .with_system_prompt("order_agent_system")
)
-app = (
- AppBuilder(config)
- .with_service(MyService)
- .with_agent(my_agent)
- .with_handler(MyHandler)
- .with_rest_api(MyApi)
- .with_scheduler(MyScheduler)
- .with_cache()
- .build()
+agent = (
+ AppBuilder()
+ .with_service(OrderService)
+ .with_agent(order_agent, name="order_agent")
+ .with_handler(OrderHandler)
+ .with_rest_api(OrderApi)
)
+
+
+def create_app():
+ """Build this agent as an application of its own (standalone only)."""
+ return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent)))
```
+- Never build the `AgentBuilder` yourself and never pass an instance to a `with_*` call: a group
+ and `create_app()` (`agent.build(config)`) refuse instances, because a component constructed on
+ that line exists before any namespace does.
+- Keep one registration per line in dependency order (services, agents, handlers, APIs,
+ schedulers) -- `asbs create` rewrites the chain line by line.
+
## Component Patterns
### EventHandler
@@ -80,20 +101,32 @@ class OrderHandler(EventHandlerBase):
pass
async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool:
- return event.type == "order.placed"
+ return event.type == "order.placed" # routing on the envelope only -- no I/O
async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None:
- order = self.extract_payload(event, OrderModel) # Typed extraction with validation
- result = await self._service.process(order)
- return HandlerResult(event_type="order.processed", data=result)
+ payload = self.extract_payload(event, OrderPlacedEvent) # DTO: typed, validated
+ outcome = await self._service.on_order_placed(payload.order_id, event_id=event.id) # ONE call
+ if outcome is None:
+ return HandlerResult.skipped("order needs no processing")
+ return HandlerResult(event_type="order.processed", data=outcome.model_dump())
```
-- Return `None` → pass to next handler. Return `HandlerResult` → publish event, stop chain.
+- Results: `HandlerResult` → published (if its `event_type` is mapped), chain stops.
+ `HandlerResult.skipped(reason)` → this handler is responsible but the event needs nothing: chain
+ stops, the delivery is acknowledged, the reason is logged at INFO, nothing is published.
+ `None` → the event is offered to the next handler; if none takes it, the framework logs
+ "No handler processed event".
+- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). The *service* must be safe to repeat (check before you act, upsert rather than insert), or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source (and named connection, when it came from one) it has already dispatched, within that window. Dedup needs `.with_cache()` -- startup fails without one -- and holds across replicas only on a Redis cache: a disk cache's claim holds within one process, so replicas sharing a cache directory can both win it. Off by default on purpose: only you know whether replaying your side effects is acceptable.
- **`self.extract_payload(event, ModelType)`** — validates `event.data` against a Pydantic model and returns a typed instance. Raises `InvalidEventError` if data is missing or invalid (the framework handles this automatically).
+- **The service gets no CloudEvent and no DTO.** Translate the payload into domain values (ids, domain models) in the handler; that is what lets a REST API call the same service method.
+- **`context["runtime"]`** holds the agent runtime the chain bound for this handler. It is there for
+ framework plumbing; a handler never runs it (rule 9) -- the service resolves its own agent.
### Service
-Services contain ALL business logic. Each responsibility gets its own method.
+Services contain ALL business logic, including the decision whether an event needs work at all.
+Each responsibility gets its own method; the method a handler calls is the one entry point for that
+event (a facade that calls the others in order).
```python
class OrderService(ServiceBase):
@@ -103,6 +136,18 @@ class OrderService(ServiceBase):
async def on_shutdown(self) -> None:
pass
+ async def on_order_placed(self, order_id: str, event_id: str) -> OrderOutcome | None:
+ """Entry point for an order.placed event. None: the order needs no processing."""
+ order = await self.load(order_id)
+ if not self.is_relevant(order):
+ return None
+ await self.validate(order)
+ return await self.analyze(order)
+
+ def is_relevant(self, order: Order) -> bool:
+ """Pure check, testable without mocks."""
+ ...
+
async def validate(self, order: OrderModel) -> ValidationResult:
"""Validate order against business rules."""
...
@@ -155,27 +200,45 @@ class CleanupScheduler(SchedulerBase):
async def on_startup(self) -> None:
self._service = self.registry.get_service(CleanupService)
+ await super().on_startup() # required: without it the scheduler never runs
async def on_shutdown(self) -> None:
- pass
+ await super().on_shutdown()
async def tick(self) -> None:
"""Called on each cron interval."""
await self._service.cleanup()
```
+- **Override `on_startup` only if you also call `super().on_startup()`.** `build()` wires the
+ tick handler and registers `POST /api//trigger` (`/api//scheduler//trigger`
+ in a group); `super().on_startup()` starts the in-process timer and the tick-age gauge.
+- **`scheduler_mode` decides what calls `tick()`, and it is required.** It has no default:
+ registering a scheduler without setting it fails at startup, because neither value is safe to
+ inherit silently. `"event"` starts no timer in the process -- the tick arrives as an ordinary
+ event on `.scheduler.` (`app_name` instead of the agent at the root), published by an external `CronJob`, so the
+ queue group already guarantees that exactly one replica runs it; it needs `event_bus` set to
+ `"dapr"` or `"nats"`. `"in_process"` runs an APScheduler timer in **every** replica and
+ claims each tick in the cache so one replica runs it -- so it needs `.with_cache()` to fire a
+ tick once, and a Redis cache once more than one replica runs it: a disk cache's claim holds
+ within one process only, so replicas sharing a cache directory can both win a tick. Without a
+ cache every replica runs every tick, and startup says so.
+- The crontab stays declared here in both modes. In `"event"` mode the external `CronJob` must
+ publish on that schedule; nothing generates it.
+- **A scheduler that wants to *publish* an event needs `event_publishing_enabled = true`.** Consuming and publishing are separate: a handler implies a transport client, a scheduler does not. The key creates the client and subscribes to nothing, and it needs `event_bus` set.
+
### AgentRuntime (via AgentBuilder)
```python
-agent = (
- AgentBuilder(config, runtime_name="analyzer")
- .with_model_from_config("analyzer")
- .with_system_prompt("system") # Loads prompts/system.prompt (static, no dynamic inputs)
+analyzer = (
+ AgentBuilder(runtime_name="analyzer") # declared, not built: the host builds it
+ .with_model_from_config()
+ .with_system_prompt("analyzer_system") # Loads prompts/analyzer_system.prompt (static)
.with_tools([analyze_tool])
.with_result_type(AnalysisResult)
.with_metrics()
- .build(name="analyzer")
)
+# registered in main.py: AppBuilder()...with_agent(analyzer, name="analyzer")
```
**Prompt files** in `src/prompts/`:
@@ -213,12 +276,36 @@ model_provider = "openai"
model_name = "gpt-4"
model_max_tokens = 2000
+# Event deduplication -- off by default, both keys required to switch it on.
+# idempotency_enabled = true
+# idempotency_ttl = 1500 # seconds; must outlast the broker redelivery window
+
+# Required once a scheduler is registered; no default. "in_process" runs a timer in
+# every replica; "event" takes the tick as an event and needs event_bus set.
+scheduler_mode = "in_process"
+
[default.runtimes.my_agent] # Per-agent overrides
model_name = "gpt-4-turbo"
model_temperature = 0.5
```
-**secrets.toml** (never commit): `model_api_key = "sk-..."`
+**.secrets.toml** (never commit): `model_api_key = "sk-..."`
+
+## Documentation
+
+The full framework documentation ships inside the installed package -- no network needed. Locate a
+page with `asbs docs`, then read it:
+
+```bash
+asbs docs # list every page
+asbs docs guides/multi-agent-setup # print the path to one page
+asbs docs reference/configuration-keys --cat # print its contents
+```
+
+Prefer the matching skill (`blueprint-cli`, `blueprint-config`, `blueprint-events`,
+`blueprint-multi-agent`, `blueprint-migration`, `blueprint-testing`, `blueprint-deployment`,
+`blueprint-troubleshooting`); each one carries the rules that matter and points at the page for the
+detail. **Never guess a configuration key or a CLI flag** -- the reference is on disk.
## CLI (`asbs`)
@@ -229,8 +316,9 @@ asbs create service