AgentGenerator Output Assembly Contract¶
Status: CANONICAL — describes what actually exists Last verified: 2026-11-30 Source files: - factory_app/workflows/AgentGenerator/tools/generate_and_download.py - factory_app/workflows/AgentGenerator/tools/pack_metadata.py - factory_app/workflows/AgentGenerator/tools/workflow_converter.py - factory_app/workflows/AgentGenerator/structured_outputs.yaml - factory_app/workflows/AgentGenerator/agents.yaml - factory_app/workflows/AgentGenerator/extended_orchestration/task_batches.yaml
Related:
structured-output-extraction-contract.md— the general runtime contract for structured outputs and auto-tool-call. This document covers the AgentGenerator-specific pattern where a task batch worker agent produces all workflow bundle files in a single structured output.
How This Works¶
InterviewAgent emits WorkflowInterviewResult: agent_message contains the user-facing question or confirmation, and outcome is needs_input or ready. record_workflow_interview accepts the explicit agent_message argument so the existing auto-tool event displays it in chat, checks it against the validated output, and records the typed readiness value. Chat text and routing markers are not readiness authority. An app without AI requirements returns ready with a brief confirmation instead of asking for an invented workflow.
AgentGenerator first validates and reviews the workflow partition:
PatternAgentemitsPatternSelection. Its tool validates the typed selection against the canonical DesignDocs workflow surface map before writingworkflows_spec. Module pricing selections are validated by the subscription designer and AppGenerator with their data contract; AgentGenerator does not revalidate them.- Invalid selections return validation feedback to
PatternAgent. Three total selection attempts are permitted per run; exhausted attempts fail rather than dispatching an invalid plan. ProjectOverviewAgentpresentsWorkflowPlanReview, except for a validated empty partition in explicit autonomous mode. Approval, request-changes, and cancellation are structured UI responses correlated byreview_idand the exact selection hash. Chat keywords cannot approve a plan.- For an approved non-empty partition,
PackBuildCoordinatorstartsworkflow_generation_tasks: oneWorkflowBundleBuilderAgentper workflow. - Each worker emits
WorkflowBundleBuilderOutputcontainingCodeFileentries. The runtime collects results inworkflow_bundle_results, keyed by task ID. PackMetadataAgentemits typedPackMetadataOutput. Its declaredrecord_pack_metadataauto tool first runs the existing workflow quality gate, including approved producer/consumer input contracts. Failed worker contracts schedule bounded bundle repair throughPackBuildCoordinator; this handoff preserves the separate metadata correction budget. The tool then decodes JSON object fields and validates the registry with the runtime pack schema. Workflow names, required dependencies, and startup modes must match the reviewed plan and generated bundles; artifact-family references and dependency cycles must close. The tool commitsworkflow_registrythrough deterministic writer authority. Rejections return focused feedback for at most three metadata attempts; conversation text cannot supply export metadata.generate_and_downloadvalidates both the workflow contracts and committed registry before writing accepted bundles, creating the ZIP, or presenting the download UI. Missing metadata blocks export. It writesextended_orchestration/extension_registry.jsonbeside the workflow folders and includes that path at the ZIP root.
The workflow BuildRecord stores the exact registry as workflow_registry and the lowercase hexadecimal SHA256 of its archived UTF-8 bytes as workflow_registry_sha256 in commit metadata. Its BuildRecord ID identifies the source version. App assembly mounts the archive under the workspace's workflows/ root; the registry remains sibling to individual workflow folders. An approved empty workflow partition needs no registry or archive.
Approved cross-workflow inputs[] are copied exactly from workflows_spec into the registry. Deterministic worker briefs include both consumer snapshot projections and every producer's downstream persisted-output obligations. The shared validator rejects undeclared or authoritative source values, missing required projections, known full-value type mismatches and an initial parallel phase without a serial seed workflow. Type aliases normalize; integer producers may feed number consumers. Nested property values are checked against their consumer type when the exact completed inputs are admitted by the router.
Workflow features are excluded from generated pricing until workflow launch enforces plan grants (#770). AgentGenerator rejects a saved contract that still selects a workflow pricing feature and asks for SubscriptionContractDesigner to rerun. Named event triggers carry an explicit capability ID regardless of pricing.
Automatic results on a triggering private record¶
An event workflow that saves a result on a newly created private record declares result_write_plans in its WorkflowInPack specification. Workflow plan review shows the source module action, event, collection, record key, receiving action, local agent, and allowed output fields. The review hash covers those values. The builder gives the specified agent a flat structured-output model with exactly the required result fields. The worker brief identifies the receiving module action and the host-supplied record key. The agent reads the module event's declared input fields from the host-seeded event_payload object exposed to it through context_variables.yaml with transition_router as its writer. Factory materializes that input and its exposure to the reviewed result agent. A BackendOnly workflow with an empty trigger list takes its events from the approved write plan. The roster in agents.yaml contains the agent's prompt and structured-output requirement. Each repair receives the original task, the current validation findings and bounded excerpts from the YAML files named in those findings. The agent's prompt requests only the approved result fields. The bundle omits worker-authored save tools and outcome plans for that agent. Other agents keep their declared tools and outcomes. Factory adds its workflow-local automatic tool and pins the result plan and the result agent's compiled output schema in the workflow bundle's integration metadata. AppGenerator compiles each receiving module's internal action from the hydrated workflow artifact. The module worker retains the design's custom reads and writes. Under the owning module task, Factory wires the pinned workflow capability and event reaction after the source action and event are declared. On a feature revision, Factory compares the approved result binding and public writes with the selected app version before dispatch. If an app-owned module needs a receiver or a new public write, its plan assigns the missing contract and implementation work to the module workers. The page worker receives the module contract as a direct dependency so it can bind controls to those public actions. When Factory can compile a module edit from the accepted source and approved fields, the module worker sees how the proposed actions, event declarations and reactions compare with the accepted version. The offer includes the complete request, the file dependencies and the module companions the build would carry forward. For example, the worker can inspect both the fields a person may edit and the fields a list action returns. The worker can select the proposal by digest or author the module. Both paths run the same file, ownership and schema checks. Page bindings and pricing use the public design inventory. App validation compares the closed receiver input with this schema, including nested properties, array items and enum values, and checks the result against the private collection's declared field types.
Every successful path goes through the result agent. Factory uses the agent's declared continuation after an applied write or an identical replay. A rejected write, unavailable receiver, or storage error ends the workflow as failed.
AppGenerator uses that same plan to compile the matching capability reaction and the internal module action's handler and service. Assembly checks both against the declared event, actions, and private data collection. During execution the host supplies the triggering record, checks the result against the receiver input schema, and dispatches the internal action. The generated service calls ctx.commit_workflow_result(values) with the validated fields.
Apps Without AI Workflows¶
An explicit workflows: [], is_multi_workflow: false, and non-empty pack_partition_reason is valid when the approved design requires only modules and pages. A missing or malformed selection is not equivalent to this decision. Unknown surface kinds and contradictions with DesignDocs fail validation.
When coding_participation is exactly autonomous, the validated empty partition records workflow_plan_review.status: not_required with its selection hash and rationale, without requesting or claiming human approval. Other modes retain the review. After that decision or human approval, the existing artifact recorder saves a workflow_bundle build record with workflows: [], the review disposition, and no workflow ZIP, primary workflow, API endpoint, or websocket endpoint. The stage completes only after this required save succeeds. It does not run the task batch or fabricate a workflow. Downstream AppGenerator consumes the same explicit empty integration metadata; prior workflow hints are cleared.
Review changes return to PatternAgent; at most three review attempts are allowed, with retries only after changes_requested. These limits are runtime execution guards, not freemium or subscription entitlements. Cancellation, stale approval, failed recording, and exhausted attempts fail the stage.
There are no sequential planning agents scraping MongoDB. Each WorkflowBundleBuilderAgent instance owns its full bundle output end-to-end.
Generated workflow bundles are staged at:
They do not become active runtime-loaded workflows until an explicit promotion step copies them into an active app root's workflows/ directory.
Agent Roster¶
| Agent | Role |
|---|---|
InterviewAgent | Clarifies missing AI requirements without inventing automation |
PatternAgent | Selects zero, one, or multiple workflows inside the approved design boundary |
ProjectOverviewAgent | Presents the draft-correlated workflow plan review |
PackBuildCoordinator | Starts the task batch for an approved non-empty partition |
WorkflowBundleBuilderAgent | Task batch worker — generates all YAML and code files for one workflow bundle |
PackMetadataAgent | Produces pack-level extension_registry.json metadata after workflow bundles complete |
DownloadAgent | Triggers generate_and_download after pack metadata is ready |
The download agent emits agent_message. The export tool reads the completed workflow files from workflow_bundle_results and asks for confirmation before creating the archive. External storage is disabled by default.
Task Batch: workflow_generation_tasks¶
Declared in extended_orchestration/task_batches.yaml.
source:
kind: context_variable
path: workflows_spec
task_model: WorkflowInPack
worker:
mode: ag2_agent
agent_field: initial_agent # WorkflowBundleBuilderAgent
prompt_field: initial_message
result:
context_key: workflow_bundle_results
status_key: workflow_bundle_status
Each task receives one WorkflowInPack entry from workflows_spec. Its optional design_surface_id references the approved DesignDocs workflow surface. The runtime injects it as context_variables["structured_output"] for the worker.
The reviewed depends_on values serve both generation and runtime contracts. The task batch uses them to schedule bundle-generation tasks within its configured concurrency limit. PackMetadataAgent copies the same prerequisites into the runtime registry. Required producers remain dependencies regardless of role: primary means user-facing, not prerequisite-free. An empty dependency list permits independent bundle generation; it does not start the generated workflow. Runtime sequences begin with one workflow and may fan out in later declared phases.
WorkflowBundleBuilderOutput¶
The serialized YAML inside each orchestrator.yaml file must declare top-level schema_version: mozaiks.orchestrator.v1; each structured_outputs.yaml file must declare schema_version: mozaiks.structured_outputs.v1. The assembler validates these document versions; the outer bundle is not their authority.
The worker emits a single WorkflowBundleBuilderOutput structured output:
workflow_name: str
outcome_plans: []
statusbar_middleware: []
files:
- filename: orchestrator.yaml
content: "..."
- filename: agents.yaml
content: "..."
- filename: transition_graph.yaml
content: "..."
- filename: context_variables.yaml
content: "..."
- filename: structured_outputs.yaml
content: "..."
- filename: tools.yaml
content: "..."
- filename: middleware.yaml
content: "..."
- filename: ui_config.yaml
content: "..."
- filename: tools/some_tool.py
content: "..."
- filename: ui/index.js
content: "..."
Each CodeFile has: - filename — workflow-local relative path (e.g., tools/save_result.py, ui/index.js) - content — full file content as a string
The outer structured response does not validate the YAML or Python inside content. The quality gate parses all eight required workflow documents, plus optional a2a.yaml, through the same schema parsers used by the runtime. It also checks context references, transition compilation, and task-batch contracts. Duplicate filenames, retired declarative JSON/YML variants, and unrendered .j2 files block export.
For long work, the bundle builder can declare ui_config.yaml progress.stages and implement reporting through the runtime's emit_tool_progress_event helper. The canonical WorkflowProgressConfig JSON schema is injected into its prompt. There is no duplicate progress plan in the outer response. The quality gate validates the YAML, literal tool stage references, and task-batch progress_stage references before packaging. Dynamic tool stage ids are checked when emitted. Counts come from executing code, not another model turn. A custom progress_stepper remains available for detailed workflow UI; the shared status strip stays owned by the framework. AppGenerator and AgentGenerator dogfood accepted task counts, while ExistingAppDiscovery reports indexing stages and settled source-file checks, including failed fetch attempts; these counts do not claim successful downloads.
Declared tools must have an included Python file and matching top-level function. Python syntax errors and unfinished tool implementations block export. Workers must implement the tool behavior; there is no later tool-implementation stage. These static checks do not prove arbitrary business logic or external integrations work. Functional execution tests remain necessary for those behaviors.
outcome_plans is a typed list of operation plans. Each plan names agent, function, context_key, attempts_key, result_field, error_value, max_attempts, retry_on, and routes: [{value, target_agent}]. Use an empty list only when no operation needs outcome-dependent routing. Business-specific outcomes are allowed; every outcome must have one known destination.
outcome_materialization.py deterministically generates the matching tool outcome binding, protected context definitions, and ordinary graph transitions. Workers omit these owned context definitions and source-agent transitions from their raw files. They still generate the operation's implementation, tool binding, agent definition, and structured input model. Quality gates validate the materialized files; downloads contain those files, not a runtime dependency on Factory or its build-time plans. Hand-authored workflows use the same runtime tools[].outcome contract documented in Workflow Authoring Contracts.
statusbar_middleware is a typed list of {agent, variables} entries. Use [] when no agent needs a concise view of current workflow state. Each entry names one exact local agent and a nonempty, unique list of existing context names. The names must be defined, exposed to that agent in context_variables.yaml, and effectively model_visible. Remote A2A agents and hidden context are invalid.
statusbar_materialization.py validates entries through the runtime's shared StatusbarMiddlewareSpec and middleware parser, then writes the list into the existing middleware.yaml while preserving prompt_middleware. Workers omit the raw statusbar_middleware declaration; a conflicting raw declaration fails assembly. Without the typed field, existing raw middleware remains unchanged. An explicitly supplied empty list emits statusbar_middleware: []. Materialization is idempotent, and the quality gate validates agent, exposure, and visibility references using the same cross-file contract as runtime loading.
Statusbars are transient model context. They do not create UI surfaces, context definitions, persisted plans, routing authority, or callback files. Generated bundles contain only the runtime middleware declaration and have no Factory dependency after assembly.
workflow_bundle_results Structure¶
After the task batch completes, context_variables["workflow_bundle_results"] is a dict:
{
"task_id_1": {
"workflow_name": "StoryCreator",
"files": [
{"filename": "orchestrator.yaml", "content": "..."},
{"filename": "agents.yaml", "content": "..."},
...
]
},
"task_id_2": {
"workflow_name": "ReviewWorkflow",
"files": [ ... ]
}
}
Keys starting with _ are internal meta entries and are skipped during assembly.
Assembly: generate_and_download¶
Reads workflow_bundle_results directly from context. For each bundle entry:
- Materialize operation plans and statusbar middleware, then validate the resulting workflow contracts.
- On failure, schedule bounded workflow repair or return to user attention.
_write_bundle_to_disk(wf_name, files, base_dir)writes accepted files underbase_dir/{wf_name}/._build_pack_zip(bundle_dirs, output_path)zips the workflow directories.use_ui_tool("DownloadCenter", ...)presents the download UI.
Assembly reads task-batch structured outputs directly from runtime context.
Workflow Integration Metadata¶
During bundle assembly, generate_and_download derives workflow_integration_metadata from each generated workflow's orchestrator.yaml:
workflow_name- stable
capability_iddeclared on every named event trigger of a generated workflow. Workflows without named event triggers use their kebab-case workflow name as their capability ID. workflow_startup_mode- event triggers from the
triggers[]block - caller-writable launch variable names and types, projected from the generated
context_variables.yamlthrough the runtime context authority policy. Secret defaults, configuration handles, and router/runtime-only state are omitted.
The normalized metadata is written back to context as:
workflow_integration_metadatagenerated_workflow_integrationsgenerated_workflow_namegenerated_workflow_capability_idgenerated_workflow_startup_modegenerated_workflow_trigger_events
AgentGenerator persists the same metadata on the workflow_bundle artifact. AppGenerator first looks for AgentGenerator output from the same app, registry, and build run. A refinement can also select a specific workflow bundle or inherit the workflow input recorded by its source app. A source app with no workflow input keeps that choice. Only an unbound build can look up the app's current workflow bundle. A pinned run must supply metadata from that exact workflow bundle to pass app acceptance. Archiving or deleting that input blocks subsequent refinements that depend on it. For new registry-bearing records, AppGenerator reads the registry from that record's manifest-verified archive. It supplies a bounded topology projection to its page and module workers, together with the actual allowed launch inputs. Workers bind persistent page actions to existing workflow IDs. They do not copy sequence order, dependency policy, or artifact state into page code. The saved app records the workflow source verified at acceptance, including when another workflow bundle becomes current before the app is registered. AppPlanAgent receives every workflow and assigns each named trigger to a module contract task. ConfigMiddlewareAgent declares the corresponding workflow capability in module.yaml and each assigned event-to-capability pair in contracts/reactions.yaml. When two workflows subscribe to the same event, the module declares both reactions. A workflow with no named event triggers has no generated event reaction. AgentGenerator returns unknown event namespaces and duplicate event-and-capability pairs to the workflow builder for repair. AppGenerator verifies the materialized bindings before export. A generated subscription to an external event also needs evidence from its publisher.
Smoke coverage:
python scripts/smoke_factory_artifact_lineage.py
python scripts/smoke_factory_artifact_lineage.py --real-store
python scripts/smoke_factory_artifact_lineage.py --real-store --live-agentgenerator --timeout-seconds 600
The first command runs the deterministic in-memory chain. The second uses the Mongo-backed BuildRecordStore. The third runs live AgentGenerator AG2 calls, persists the live workflow metadata through the real artifact store, hydrates AppGenerator from that workflow_bundle, and verifies app acceptance/export and runtime loader reaction wiring.
generate_and_download runs the workflow bundle quality gate before download, artifact registration, zip creation, or promotion. The gate writes workflow_bundle_validation_status, workflow_bundle_validation_errors, and workflow_bundle_semantic_drift to context. Blocking failures return status: blocked; the generated bundle is not packaged.
When blocking failures map to specific workflows, the metadata auto tool or generate_and_download schedules a bounded repair pass instead of broad regeneration. It writes workflow_bundle_repair_status: needs_revision, increments workflow_bundle_repair_count, preserves the full pre-repair workflow_bundle_results, narrows workflows_spec to the failed workflow specs, and routes back to PackBuildCoordinator. Each repaired worker receives the exact quality-gate failures in its scoped initial_message. Repair dispatch waits only for other failed workflows in that batch. Passing predecessor contracts are supplied as exact orchestrator, context and structured-output file text in the repair brief. The saved full plan retains the approved runtime dependencies and input bindings. After the repair task batch completes, WorkflowBundleMergeAgent invokes the deterministic merge_workflow_bundle_repair_results auto tool. It commits repaired workflow outputs together with the preserved successful outputs and restores the complete workflows_spec before PackMetadataAgent generates metadata and packaging runs again. The merge is not a prompt hook: workflow_bundle_results requires an authorized writer. Only a committed merged status advances to metadata; a refused write cannot report success. After the configured attempt limit, the status becomes blocked and the workflow returns to the user.
The live AgentGenerator pack smoke also emits the same semantic_drift report. That report is intentionally prompt-oriented: it flags generated workflow YAML that loads but no longer preserves the requested workflow meaning, such as event triggers with missing capability_id, generic trigger descriptions, or conveyor workflows that collapse downstream parallel work into one execution agent. Conveyor workflows that represent heavy downstream work must declare at least two distinct execution agents in extended_orchestration/task_batches.yaml; repeating the same worker name is semantic drift. Fix those failures in AgentGenerator prompt or structured-output contracts first, then rerun the live smoke.
Files Written¶
$MOZAIKS_GENERATED_ARTIFACTS_PATH/workflows/{app_id}/{build_id}/
├── extended_orchestration/
│ └── extension_registry.json ← validated pack routing and artifact topology
├── {WorkflowName}/
│ ├── orchestrator.yaml
│ ├── agents.yaml
│ ├── transition_graph.yaml
│ ├── context_variables.yaml
│ ├── structured_outputs.yaml
│ ├── tools.yaml
│ ├── middleware.yaml
│ ├── ui_config.yaml
│ ├── extended_orchestration/
│ │ └── task_batches.yaml ← if workflow uses task batches
│ ├── tools/
│ │ └── *.py ← tool implementations
│ └── ui/
│ ├── index.js ← component barrel
│ └── *.jsx ← workflow-local React components
└── {PackName}.zip ← all workflows bundled together
Generated workflow tools are workflow-local. Generated bundles must not reference workflows/_shared, sibling workflow tool folders, or root-level shared paths. Reusable framework-owned support code belongs under mozaiksai.core.*.
Workflow Name and Pack Name¶
bundle_nameis derived fromcontext_variables["pack_name"]if set, otherwise from the first workflow'sworkflow_name- All names are converted to PascalCase for the output folder and zip file name
Promotion Helper in workflow_converter.py¶
workflow_converter.py is a promotion helper — it does NOT do assembly. Functions exported:
| Function | Purpose |
|---|---|
promote_generated_workflow(source_dir, target_root) | Copy a generated workflow into the active workflows root |
Current Boundaries¶
AgentGenerator's runtime path is a compact task-batch workflow:
PatternAgentselects the workflow topology and AG2 network pattern.ProjectOverviewAgentpresents the generated-workflow plan for review.PackBuildCoordinatortriggersworkflow_generation_tasks.WorkflowBundleBuilderAgentworkers generate complete workflow bundles in parallel.WorkflowBundleMergeAgentrestores the full workflow set after a repair batch.PackMetadataAgentgenerates pack-level routing metadata.DownloadAgentpackages the generated artifacts.
Bundle assembly is context-first: generated workflow files come from workflow_bundle_results, and pack metadata comes from the committed, validated workflow_registry auto-tool result. Runtime loading still requires explicit promotion into an active workspace workflow root.
Cross References¶
- structured-output-extraction-contract.md — general auto-tool-call pattern
- workflow-authoring-contracts.md —
extended_orchestration/task_batches.yamlformat factory_app/workflows/AgentGenerator/tools/generate_and_download.py— assembly and downloadfactory_app/workflows/AgentGenerator/tools/workflow_converter.py— generated workflow promotion helperfactory_app/workflows/AgentGenerator/extended_orchestration/task_batches.yaml— task batch configfactory_app/workflows/AgentGenerator/structured_outputs.yaml—WorkflowBundleBuilderOutputmodel