AG2 Ownership Boundary¶
Mozaiks uses AG2 as the long-term agentic execution backbone. Mozaiks should not grow a parallel agent framework for primitives AG2 already owns or is the right upstream home for.
For the concrete runtime audit and shrink plan, see AG2 Execution Alignment Plan. For the living AG2 upgrade checklist and divergence log, see AG2 Update Watchpoints.
Boundary¶
AG2 owns generic agentic mechanics:
- agent primitives, model calls, tools, middleware, and task execution
- multi-agent network behavior, Hub, AgentClient, channels, adapters, and workflow state progression
- task delegation, task lifecycle observation, event mirroring, and generic runtime observability for agents
Mozaiks owns deterministic product and runtime contracts around AG2:
- declarative workflow files and strict structured-output validation
- canonical generated app, workflow, module, page, persistence, and secret artifact shapes
- app/runtime persistence, transport integration, tenant/session boundaries, Studio/platform lifecycle, and artifact promotion
- factory Refinement Engine policy and deterministic decomposition contracts that define the typed work AG2 agents execute
Runtime Handoff¶
Declared task batches execute after their trigger agent's validated output and auto tools, before AG2 folds that agent's outgoing packet. This applies at any point in the graph, including after an interview, human approval, or resume. The existing task-batch executor and AG2 Task adapter own worker execution; only declared result/status keys are committed with task-batch writer authority. AG2 then evaluates the original transition graph. Mozaiks must not replace the first turn with an artificial termination and a separately selected continuation. A failed required batch fails the run rather than advancing to assembly. The declared task retry budget covers response validation, deterministic file materialization, task identity, and file ownership. A rejected response supplies bounded validation feedback to the next attempt at the same task; it does not change the task's ownership or create an unlimited repair loop. For materialization/ownership failures, that retry also receives the rejected candidate as explicitly non-authoritative data: AG2 task attempts have independent streams, so error text alone cannot show the worker what needs correcting. The candidate is not committed as accepted output, and all original validation runs again. Retry limits and model-call admission still apply to the additional input. If an output hook fails after authorized tool or batch writes, the adapter commits those writes using AG2 EV_CONTEXT_SET without sending the failed reply packet. Failure evidence therefore survives WAL replay without advancing the graph. This uses AG2's existing channel context primitive, not a second persistence or routing authority.
Opted-in Factory recovery uses that same batch and checkpoint seam. The approved inventory and original DAG remain authoritative; accepted tasks are preserved, eligible rejected prerequisites receive one bounded correction, and descendants resume only after their prerequisites succeed. Pre-dispatch reservations and settled results use authorized EV_CONTEXT_SET writes. Missing evidence and uncertain interrupted attempts remain blocked. Factory selects repair policy; AG2 still executes workers and advances the declared graph. See ADR 0011 for contracts, budgets, acceptance, migration, and rollback.
For an agent with a declared self-edge, the packet adapter supplies an explicit audience containing all workflow participants, including the sender. AG2 1.0.3 excludes the sender from a default broadcast, otherwise leaving that self-edge without a delivery. Explicitly targeted packets are unchanged. AG2's default handler and can_send probe still select the authorized speaker; Mozaiks does not refold the graph or schedule an extra turn. Recheck this packet adaptation when upstream adds automatic self-edge notification.
Initial prompts and user replies are shared within their workflow channel. They use AG2's broadcast visibility, not a private audience containing only the next interviewer. Otherwise later planners cannot see the user's corrections in AG2's projected conversation. AG2 still owns turn selection; visibility does not grant permission to speak. Tests inspect both history and current-turn input.
Declarative workflow participants attach through AG2's public attach_plugin=False option. They keep AG2's default envelope handler, channel adapter, graph execution, and declared workflow tools, but do not automatically receive the optional NetworkPlugin tools (delegate, peers, channels, tasks, context). Those tools allow model-selected network work outside the declared workflow topology. Delegation inside a generated workflow must use its declared graph, task batches, or explicitly bound tools; prompts must not assume an implicit network-tool grant.
This uses AG2's supported network-tool opt-out, not a replacement scheduler or network implementation. The installed AG2 1.0.3 source and real AG2 tests with provider HTTP replaced verify that the default handler still runs without the plugin. Recheck this boundary when upgrading AG2.
An idle timeout (no channel progress within the idle budget), including during initial execution, is a failed run, not a human-input pause. The adapter returns a failed result and closes its live clients; transport then uses the existing failure event path. A timeout must not leave a reusable live-run handle or claim that the workflow is waiting for the user.
AG2 network packets are the source trace for agent execution, not automatically user-visible chat copy. Mozaiks owns the projection from AG2 packet history into transport events and replayed chat history because that projection enforces workflow contracts such as ui_hidden control signals and structured-output artifact rendering.
Control tokens such as NEXT may drive declarative transition/context state, but must not render as normal assistant messages when the matching trigger is marked ui_hidden. Structured-output JSON from registered structured-output agents must remain durable trace data and feed the declared artifact/tool path; it must not be projected as raw chat text. User-visible agent output should be narrative copy, Markdown, or an explicit UI artifact.
Design Rule¶
When a workflow feature needs agentic behavior, first ask whether AG2 already owns it. Prefer compiling Mozaiks declarations into AG2-native objects over adding Mozaiks-owned orchestration loops.
Custom Mozaiks logic is appropriate when it enforces Mozaiks-specific contracts, such as canonical artifact shapes, structured-output validation, app workspace boundaries, tenant/session persistence, or deterministic decomposition schemas. Custom logic is not appropriate when it is a generic replacement for AG2 Hub, AgentClient, network adapters, task streams, task observation, delegation engines, or agent scheduling.
Sandbox Execution Boundary¶
AG2 owns agent-level code and shell execution: SandboxCodeTool / SandboxShellTool over CodeEnvironment backends (local, docker, daytona, tenki) — the model writes a snippet or command, it runs, results return. Mozaiks agents that need shell access declare sandbox_shell: true and get the AG2 tool; do not build a Mozaiks snippet executor.
Mozaiks owns application-preview and build-validation sandboxes: SandboxPort and its e2b/docker adapters boot a full generated app — write the bundle, install, run the build, start a dev server, expose a preview URL, manage session lifecycle and cost. That is application-runtime behavior, not agent tooling, and AG2's execution surface deliberately does not provide it (no long-lived servers, no preview URLs).
Rules:
- Do not route app preview/validation through AG2 execution tools, and do not reimplement snippet execution behind
SandboxPort. - Every provider sandbox is created with identity metadata (app/chat or artifact id, purpose) and a provider-side kill deadline, and the session id that produced a validation outcome is persisted with the outcome. An orphaned sandbox must be attributable and self-terminating.
- Sandboxes are ephemeral workspaces, never truth stores — committed output must persist into artifact versions before the session dies (see the refinement engine's E2B contract).
- A validation strategy label on a build record must name an execution path that actually ran.
Watchpoint: if AG2 CodeEnvironment grows long-lived sessions with exposed ports, preview URLs, and per-session budgets, shrink SandboxPort adapters to request/result conversion (see ag2-update-watchpoints.md).
Missing AG2 Capability Process¶
If AG2 does not provide a required capability:
- Inspect AG2's current docs, APIs, and source shape before adding runtime code.
- Implement the smallest Mozaiks-owned layer that fits inside AG2's framework, preferably behind
mozaiksai.core.adaptersor another narrow boundary. - Document the intentional divergence in the relevant architecture doc and keep it visible as an AG2 compatibility watchpoint.
- Prefer raising an upstream AG2 issue or proposal when the missing capability is generic agent orchestration rather than Mozaiks-specific contract enforcement.
Task Decomposition¶
Workflow operation outcomes remain Mozaiks contracts in tools.yaml. Their finite return values, context ownership, and per-execution invocation budgets are validated before loading. Mozaiks dispatches validated output and auto-tools before committing the AG2 packet; AG2 then folds the resulting context and executes the declared graph. The tool outcome wrapper performs no scheduling, backoff loop, or autonomous repair. This adapter boundary is needed because AG2 does not own Mozaiks tool-result schemas or generated artifact acceptance. It does not make external side effects atomic with AG2's packet commit.
Mozaiks decomposition should stay contract-first:
user intent
-> DecompositionAgent structured output
-> validated typed task graph
-> AG2 agent/network execution
-> validated canonical artifacts
Mozaiks may own the typed task graph when the graph represents canonical build work. AG2 should own as much of the actual execution, lifecycle observation, and agent communication as its APIs allow.
Refinement Engine¶
Do not model the Mozaiks Refinement Engine as one free-running AG2 agent that launches workflows by tool call. The Refinement Engine is deterministic artifact-aware policy over generated app/workflow state: it classifies change scope, checks artifact lineage, chooses checkpoints, validates route decisions, and starts the selected workflow or scoped worker only after typed policy has accepted the decision.
AG2 should still execute the LLM portions of that pipeline. Refinement Engine checkpoints that need a model should use AG2 agent primitives through a narrow adapter, currently mozaiksai.core.adapters.AG2StructuredAgentRunner, and return strict structured outputs. Mozaiks then validates those outputs and performs routing, promotion, invalidation, staged execution, and workflow launching deterministically.
This keeps AG2 responsible for agent execution mechanics while keeping Mozaiks responsible for app-specific artifact and lifecycle policy.
AG2 KnowledgeStore Injection Seam¶
AG2's KnowledgeStore protocol (ag2.knowledge.KnowledgeStore) is the virtual path-based store for all agent workflow memory. AG2 owns this abstraction; Mozaiks must not create a parallel knowledge database layer.
The AG2NetworkRunnerRequest.knowledge_store field is the narrow injection point. When None (the default), AG2NetworkRunner creates a fresh MemoryKnowledgeStore() per Hub — the safe isolated default for local development and test runs. An operator or hosted deployment may supply any AG2-compatible implementation (Memory, Sqlite, Disk, Redis, Locked, or a custom duck-typed store) without modifying OSS code.
The canonical AG2OrchestrationAdapter injects the existing tenant/chat-scoped MongoAG2KnowledgeStore before reaching this seam. Its resume path requires the original channel. Factory task recovery binds evidence to the actual packet's channel ID, and the adapter hydrates the context bridge from current Hub state before agent execution and auto tools. A new channel or stale bridge cannot reset an interrupted attempt or a repair budget. Direct in-memory callers must retain their store and channel for recovery; no separate persistence layer is introduced.
Lifecycle contract: - One Hub is opened per workflow run (or per live session kept alive for paused runs). - Hub.close() does NOT close the store; store lifetime is owned by the caller that constructs it. - Two runs that receive distinct store instances share no AG2 workflow memory. A single shared store (e.g. Redis with a namespace prefix) may be passed intentionally across runs — namespace/tenant isolation is the operator's responsibility.
Security contract: - An injected KnowledgeStore is trusted operator runtime configuration. It can observe AG2 workflow/network memory for every run that uses it. - Production credentials must not flow into generated app bundles through this seam. - This seam does not grant Mozaiks tenant or platform authority.
Threading path:
run_workflow_orchestration(knowledge_store=...)
→ _run_ag2_network_phase(knowledge_store=...)
→ AG2NetworkRunnerRequest(knowledge_store=...)
→ Hub.open(request.knowledge_store or MemoryKnowledgeStore(), ...)
Reconnect Integration¶
Opening or switching to a saved chat is observation, not permission to execute an interrupted turn. Empty UI history alone does not establish a fresh run. Before a no-input start, the transport checks the owned session and build binding, validated UI state, history, and the orchestration adapter's read-only native persistence query. It repeats admission under the existing chat execution lease. Any native data, including a partial namespace, prevents automatic startup; unavailable or malformed state fails closed. AG2 retains ownership of its state and continuation mechanics. The check does not hydrate a Hub or call a model, and a refused open does not emit a workflow outcome or change status. Explicit user messages and declared initial-agent continuations keep their existing paths. An interrupted UI turn is not recovered by this guard: saved results may be inspected independently, but status-0 sessions do not gain a failed-workflow Retry action or become failed merely because they were opened.
The network adapter snapshots AG2's pending participants before calling its resume_pending_turns() API. It must not discover and replay downstream turns that are already advancing through live delivery, or send a new user message before the recovered workflow settles. AG2's pending-turn state, causation deduplication, turn probe, and graph remain authoritative.
Mozaiks serializes callbacks per attached client only while its mutable context bridge and temporary packet-send hook are installed. This prevents overlapping live/recovery notifications from nesting hooks or clearing another callback's context changes. It is not a workflow scheduler or a new replay ledger. Revisit this boundary if AG2 supplies an atomic per-client round hook or serialized concurrent redelivery in its default handler. See the upstream client handler contract and reconnect contract.
AgentSpec.pending_turn_replay declares allow (the default) or block. Before replaying pending turns, the adapter checks AG2's persisted pending records against this policy. A blocked participant stops resume with its agent and channel identified; a fresh delivery is unaffected. AppGenerator uses this for artifact workers whose interrupted execution must remain uncertain. AG2 continues to own pending records and replay; the policy adds no attempt store or scheduler.
Review Checklist¶
Before adding or changing workflow runtime code, confirm:
- The change does not replace an AG2 primitive that can be used directly.
- Any custom scheduler, adapter, or execution wrapper is Mozaiks-specific and documented.
- The implementation keeps AG2 imports behind existing adapter/runtime boundaries.
- Structured outputs and YAML contracts remain the source of truth for generated artifact shapes.
- AG2 upgrade watchpoints are documented wherever Mozaiks temporarily fills a missing AG2 capability.