Skip to content

App Context And Brownfield Adoption

Mozaiks should manage application context through one control-plane substrate for greenfield, brownfield, and hybrid apps. The same model should describe an app generated by Mozaiks, an existing enterprise app adopted by Mozaiks, and an app that gradually moves from discovered surfaces to Mozaiks-owned overlays or migrated modules.

This document is target architecture unless it explicitly says the behavior already exists. It does not change runtime routing, workflow sequences, generator behavior, or ExistingAppDiscovery behavior.

Core Decision

App and code context should become a first-class Studio/control-plane substrate. Workflows produce context artifacts. The control plane selects, versions, checks, and consumes the current context when it classifies and stages future changes.

The target durable object is AppContextVersion. The target graph intelligence artifact is AppContextGraph.

AppContextGraph is the primary code-context and app-context intelligence layer for Studio and the control plane. It powers LLM context planning, coding scope selection, impact explanation, related-file retrieval, and build review. It is still derived from canonical artifacts and source refs; runtime execution, permissions, artifact state, persistence, and route rendering continue to read their deterministic contracts directly.

FalkorDB and other graph databases are optional backends for mirroring and querying this graph at scale. They do not require a hosted API key when self-hosted, but they are operational infrastructure and should be configured as advanced backend choices rather than exposed as build-sequence decisions.

Contract Location

Typed target contracts live in mozaiksai/core/app_context/models.py.

That package defines the neutral app-context models and enums only. It does not wire persistence, workflow behavior, runtime routing, or graph database integration. Future slices should connect ExistingAppDiscovery, generated artifact summaries, and control-plane context selection to these contracts.

AppContextVersion

AppContextVersion is a versioned Studio/control-plane view of an application's known structure, sources, ownership, and evolution.

Target fields and concepts:

Field Meaning
context_version_id Stable id for this context version.
app_id Managed app id.
mode One of greenfield, brownfield, or hybrid.
source_refs Source inputs with source kind, repo or artifact ref, git ref or build id, checksums, scan policy, and indexed timestamp.
artifact_refs Current accepted ArtifactVersion refs such as concept, brand, design docs, workflow bundle, app bundle, discovery snapshot, and generated overlay.
ownership_boundaries Declared ownership class per file, route, module, integration, data surface, or generated artifact.
surface_indexes Indexed routes, pages, components, APIs, data entities, modules, workflows, integrations, events, and deployment boundaries.
validation_state Latest validation evidence, missing checks, warnings, and blocking failures.
staleness_state Whether the context is current, stale, partially stale, or unsafe because source refs changed or ownership is unknown.
review_state Human review, acceptance, promotion, PR, or rejection state for the context version.
graph_snapshot_ref Pointer to the deterministic AppContextGraph snapshot for this context version.
indexed_at Time this context version was built.

The control plane should own current_app_context_version_id or equivalent current context selection for each managed app. Workflows may create proposed context artifacts, but they should not independently decide which context is current for governed refinement.

AppContextGraph

AppContextGraph is a deterministic derived artifact and the canonical Context Graph contract. It does not require a graph database.

It should be built from authoritative source refs and accepted artifacts. Every node and edge should carry enough provenance to be audited back to a source file, database record, or artifact version.

Source-code symbol extraction should prefer Tree-sitter when the optional tree-sitter extra is installed. The default OSS path must still build a useful graph without that extra by falling back to deterministic Python AST extraction and conservative JavaScript/TypeScript parsing.

The code-intelligence pipeline is:

  1. Extract deterministic syntax facts from files: symbols, qualified names, imports, references, and call relationships.
  2. Map those facts onto Mozaiks contracts: module action handlers, services, repos, policies, schemas, page components, workflow tools, workflow agents, and declared module actions.
  3. Build bounded LLM semantic annotation requests from graph facts. The model may tag symbols with purpose, domain concepts, side effects, invariants, risk, and likely tests.
  4. Merge accepted annotations back as semantic_annotation metadata on symbol nodes. These annotations are advisory only; deterministic contracts and stores remain authoritative.

Neutral node examples:

  • app
  • repo
  • source_ref
  • artifact
  • file
  • route
  • page
  • component
  • api_endpoint
  • data_entity
  • integration
  • capability
  • module
  • workflow
  • agent
  • tool
  • symbol
  • config
  • prompt
  • generated_overlay
  • staged_patch
  • risk
  • unknown

Neutral edge examples:

  • declares
  • defines
  • contains
  • imports
  • renders
  • calls
  • reads
  • writes
  • references
  • depends_on
  • produces
  • consumes
  • triggers
  • uses_integration
  • protected_by
  • implements_capability
  • generated_from
  • staged_patch_touches
  • wraps
  • replaces
  • blocks

Each graph snapshot should carry:

  • source refs
  • checksums
  • indexed_at
  • artifact version refs
  • stale status
  • ownership class
  • validation evidence refs

The graph is used for impact explanation, scope selection, audit, agent retrieval, and Context Graph prompt packs. It must not replace deterministic config, source files, app bundle artifacts, workflow contracts, permissions, or control-plane records as authority.

Greenfield Context Producers

Greenfield apps already produce durable context, but the pieces are fragmented across workflow artifacts.

Workflow Context produced
ValueEngine Product concept, value manifest, concept blueprint, and surface candidate hints.
ThemeCapture Brand and theme context.
DesignDocs ExperienceSpec, design docs, surface_map, and data contract.
AgentGenerator Workflow bundle, agent roster, tools, handoffs, structured outputs, context variables, and workflow triggers.
AppGenerator Generated app context: app bundle, modules, pages, APIs, integration manifests, data contract, Data migrations, route manifests, shell config, and generated files.

AppGenerator produces generated app context, but AppGenerator is not the entire build system. It consumes upstream concept, brand, design, experience, database, and workflow context before producing concrete app artifacts.

The target next step is to compile these accepted artifacts into an AppContextVersion and deterministic AppContextGraph after generation and after accepted refinements.

Greenfield App Bundle Context Registration

The current OSS implementation derives greenfield app context from an app_bundle ArtifactVersion and its file manifest. This is exposed as an explicit helper in mozaiksai/core/app_context/store.py.

AppGenerator now calls that helper after it persists an app_bundle ArtifactVersion. This creates control-plane management state only: it does not change generated app files, AppGenerator prompts, workflow sequences, runtime routing, or the persisted bundle bytes.

Implemented greenfield helper behavior:

  • derive ApplicationInventory from generated bundle paths such as ui/pages/*.yaml, ui/route_manifest.json, modules/*/module.yaml, workflows/*/orchestrator.yaml, generated integration clients, database intent, Data migrations, app config, shell config, and theme config
  • create OwnershipBoundary records that default generated bundle files to generated_overlay
  • create external_system boundaries for external integrations referenced by generated integration surfaces
  • derive secret-free IntegrationInventory entries from generated integration client/config paths
  • create a low-risk RiskReport for missing integration config, migrations without data contract, or custom route files without route registration evidence
  • create a deterministic AppContextGraph from generated bundle manifest paths and, when manifest content is available, from lightweight structured files such as ui/route_manifest.json, page YAML, modules/*/module.yaml, config/data.json, and workflow YAML
  • add source-backed graph edges for route-to-page rendering, page-to-component rendering, page-to-module calls, module-to-integration usage, explicit module-to-data read/write intent, workflow-to-module dependencies, and generated-from provenance
  • persist the derived greenfield context artifacts and register a greenfield AppContextVersion
  • mark the new app_context_version current only through the explicit current selection helper

Greenfield registration derives a baseline graph from artifact manifests and structured files. Control-plane Context Graph tools can enrich that baseline from artifact workspace content, including Python, JavaScript, TypeScript, YAML, and JSON structure. This improves coding context and review quality, but it does not change route selection, workflow_sequence selection, affected_bundle_paths, generated app output, runtime authority, permission checks, or artifact promotion state.

The AppGenerator save-path registration is best-effort. If context registration fails because the app-context store is unavailable, the app bundle remains created and the workflow records a warning. Contract/schema errors should be caught by focused tests and corrected at the model or manifest boundary.

Greenfield and brownfield now converge on the same management substrate: greenfield starts from generated artifacts and app bundle refs; brownfield starts from discovery snapshots and source refs. Both become AppContextVersion plus AppContextGraph records for future control-plane impact and staleness work.

Workspace Snapshot Context Registration

For dogfooding and local product development, the control plane can register a local workspace directly as a code-context snapshot through mozaiksai/control_plane/workspace_snapshot.py.

Workspace snapshot registration:

  • scans local source roots through the shared Context Graph scan policy
  • excludes generated output, dependency directories, unsupported files, and secret-sensitive paths
  • prioritizes app modules, services, UI, config, workflows, and control-plane code before docs, tests, and scripts
  • persists a code-context app_bundle snapshot artifact with an artifact zip
  • builds an app_context_graph artifact from deterministic syntax and contract facts
  • registers a current hybrid AppContextVersion
  • records scan_health with selected file count, limit status, skipped-file counts, parser availability, and warnings
  • records a context_graph_health_report with healthy, warning, or blocked status based on indexed-file coverage, core-surface coverage, scan limits, sensitive-path skips, and parser fallback

This is the fastest path for using Mozaiks against its own local app workspace. It creates durable control-plane context for scoped coding and impact explanation without requiring ExistingAppDiscovery to rerun first.

The same path is available from the local developer CLI:

mozaiks context snapshot --app-id <app_id> --workspace <workspace_root> --json

The CLI is a dogfood/bootstrap convenience. Studio remains the management surface for reviewing app context, artifacts, run history, and promotion.

Control-Plane Consumption And Stale-Context Policy

The control plane can now read the current AppContextVersion as advisory context when building refinement dry-run or execution-plan payloads. The summary includes mode, source refs, artifact refs, ownership counts, ownership-boundary summaries, stale status, stale reasons, and warnings.

AppContextGraph impact hints are advisory only. The first helper derives related nodes, edges, safe additional path hints, ownership warnings, and risk warnings from an in-memory graph snapshot. It does not query artifact storage, run workflows, change route selection, change workflow_sequence selection, rewrite affected_bundle_paths, replace artifact_dependency_graph, replace promotion policy, or replace validation requirements. Stale, unsafe, or unknown graph data produces warnings and disables graph path expansion. Dry-run and execution plans may load the current graph snapshot and attach app_context_impact_hints, but deterministic routing, workflow sequence selection, and affected_bundle_paths remain authoritative.

Those graph hints may enrich the app-context policy result with warnings and explanations. Ownership warnings, risk warnings, stale-graph warnings, and graph match explanations can appear on context_policy_decision, but they do not create new blocking authority, merge extra paths into affected_bundle_paths, change route or workflow sequence selection, bypass validation, or alter promotion policy. Hard blocking still comes from the explicit app-context policy, ownership-boundary checks, validation requirements, and promotion gates.

The first stale-context enforcement slice is conservative and policy-driven. It does not change classifier behavior, route selection, workflow sequence selection, checkpoint re-entry, generated output, source ownership, or runtime routing. Low-risk UI patches and narrow leaf UI changes continue with warnings when app context is missing, stale, or unknown.

Risky refinements receive a context_policy_decision on the dry-run or execution-plan payload. Missing, stale, or unknown context can produce block_requires_context_refresh for data model migrations, architecture or conceptual replans, module/backend feature additions, integration changes, hosted capability changes, sensitive auth/permission/secret/deployment/CI surfaces, read-only discovered ownership boundaries, or brownfield source-affecting changes.

This is a planning/control-plane gate, not a graph-runtime dependency. It does not reroute and does not ask a graph backend for execution authority. Refresh execution is available only through an explicit operator/caller action.

Human Override For Context Policy Blocks

Context refresh is the preferred resolution for risky refinements blocked by missing, stale, or unknown app context. When an operator explicitly decides to override a block_requires_context_refresh decision, or when policy returns block_requires_human_override, the control plane can now create an AppContextPolicyOverride record in mozaiksai/control_plane/app_context_override.py.

The override record is explicit, audited, and scoped to an app id, request id, context version id, paths, change class, and refinement lane. It records the original policy decision, reviewer, reason, review timestamp, optional expiry, and one of three reviewer decisions: allow_with_warning, require_refresh_first, or reject.

Applying an allow_with_warning override to a dry-run or execution plan only changes the effective context-policy decision to a warning and attaches the override metadata. It does not mutate source files, run workflows, promote or restore artifacts, change route selection, change workflow_sequence selection, rewrite affected_bundle_paths, bypass validation requirements, or make promotion automatic. require_refresh_first and reject keep planning blocked. A graph backend may serve context queries, but it does not authorize the override.

Context Refresh Contract

The current control-plane contract can build a non-mutating context refresh plan when stale-context policy returns block_requires_context_refresh.

Typed refresh contracts live in mozaiksai/core/app_context/refresh.py. Control-plane planning helpers live in mozaiksai/control_plane/app_context_refresh.py. The explicit launch helper lives in mozaiksai/control_plane/app_context_refresh_execution.py.

ContextRefreshRequest records:

  • app_id
  • current_context_version_id
  • reason
  • source_refs
  • requested_by
  • refresh_scope
  • created_at

ContextRefreshPlan records:

  • app_id
  • current_context_version_id
  • target_source_refs
  • workflow_sequence, currently the registered sequence brownfield_discovery_refresh
  • required inputs such as source refs, scan policy or boundaries, and the current context version id or refresh reason
  • expected canonical artifacts: ApplicationInventory, OwnershipBoundary, IntegrationInventory, RiskReport, AdoptionPlan, BrownfieldRegistration, AppContextGraph, and AppContextVersion
  • mutation_allowed: false
  • warnings

ContextRefreshResult records status (completed, failed, no_change, or missing_context), the previous context version, new context version, whether the stale condition was resolved, warnings, and created artifact refs.

Planning does not execute discovery, mutate source code, change the current AppContextVersion, or apply a human override. launch_context_refresh_plan is the explicit/manual action that starts brownfield_discovery_refresh after a user or operator reviews source refs and scan boundaries. It creates a workflow session and passes refresh context into ExistingAppDiscovery; it does not wait for workflow completion.

Planned lifecycle:

risky refinement blocked by stale context
-> build ContextRefreshRequest
-> build non-mutating ContextRefreshPlan
-> review scan boundaries and source refs
-> run brownfield_discovery_refresh to rerun discovery/indexing
-> persist refreshed canonical context artifacts
-> register new AppContextVersion
-> retry refinement planning against fresh context

brownfield_discovery_refresh is now the first canonical refresh workflow_sequence. It contains ExistingAppDiscovery only, relies on that workflow's canonical app-context artifact persistence, and intentionally does not run AppGenerator, AgentGenerator, or DesignDocs.

The launch context passed to ExistingAppDiscovery includes:

  • context_refresh_request
  • current_context_version_id
  • source_refs
  • refresh_scope
  • refresh_reason
  • expected_artifacts

Completion creates the new AppContextVersion through the existing ExistingAppDiscovery save step when artifact persistence is available. Regular brownfield build/generation sequences remain separate and still need cleanup.

complete_context_refresh is the read-only result helper for the completion side. It reads the current AppContextVersion after ExistingAppDiscovery finishes, compares it with the previous context version id, and returns a ContextRefreshResult with status, stale_resolved, warnings, and created artifact refs. It does not run discovery, mutate the current context selection, launch a workflow, or retry the blocked refinement.

stale_resolved is true only when a new current context version exists, differs from the previous version, has current/fresh stale status, and includes the expected canonical artifacts. Missing current context, no context-version change, stale/unknown new context, or missing expected artifacts keep stale_resolved false.

A graph backend may mirror context refresh output for query and visualization. Context refresh must read and write deterministic app-context artifacts and source refs, not graph-backend authority.

Studio Operator API

Studio exposes a minimal manual API for app-context operator actions:

  • GET /api/studio/apps/{app_id}/context reads the current AppContextVersion summary, stale status, warnings, artifact refs, and ownership counts. It also returns a compact context_graph_status with graph availability, id, hash, stale status, node count, edge count, source ref count, and graph-load warnings.
  • POST /api/studio/apps/{app_id}/context/workspace-snapshot registers a local workspace as a deterministic code-context snapshot for dogfooding and scoped refinement. It creates a current app_bundle snapshot artifact, an app_context_graph artifact, and a current hybrid AppContextVersion. The response includes artifact ids, indexed file count, scan_health, health_report, warnings, and the generated snapshot artifact path.
  • POST /api/studio/apps/{app_id}/context/refresh-plan builds a non-mutating ContextRefreshRequest and ContextRefreshPlan. It does not launch a workflow.
  • POST /api/studio/apps/{app_id}/context/refresh-launch explicitly launches brownfield_discovery_refresh from a reviewed plan and requires confirm_launch=true.
  • POST /api/studio/apps/{app_id}/context/refresh-complete reads the current context after discovery completion and returns a ContextRefreshResult.
  • POST /api/studio/apps/{app_id}/context/override creates a scoped AppContextPolicyOverride record and can attach it to supplied dry-run or execution-plan metadata.

These endpoints are operator actions, not automatic policy side effects. They do not mutate source files, promote or restore artifacts, bypass validation requirements, bypass promotion gates, change route selection, change workflow_sequence selection, or change generated app behavior. Override records remain audited and non-mutating. Refresh and override decisions continue to use deterministic app-context artifacts and source refs. A graph backend may provide graph lookup context, but it does not authorize the decision.

Brownfield Context Producers

ExistingAppDiscovery should become the onboarding/indexing context producer for existing applications. Its target responsibility is to answer what exists, what Mozaiks may inspect, what is unknown, what is safe to augment, and how the app should enter governed refinement.

Target brownfield outputs:

  • ApplicationInventory
  • IntegrationInventory
  • OwnershipBoundary
  • RiskReport
  • AdoptionPlan
  • BrownfieldRegistration
  • initial AppContextGraph

Current ExistingAppDiscovery still primarily produces workflow-local discovery outputs such as ExistingProductSpec, CapabilitySpec[], AgentAugmentationPlan, and an optional decomposition plan. The save step now derives draft app-context artifacts from those outputs where enough evidence exists. The historical outputs remain useful implementation evidence, but they are not the canonical app-context architecture.

ExistingAppDiscovery Persistence Target

The first implementation slice for brownfield context persistence is additive: ExistingAppDiscovery continues to emit its existing workflow-local outputs, and the save step also derives draft ArtifactVersion records for the canonical app-context contracts where enough evidence exists.

Canonical draft artifact kinds:

  • application_inventory
  • ownership_boundary
  • integration_inventory
  • risk_report
  • adoption_plan
  • brownfield_registration
  • app_context_graph

Prior discovery fields such as module_decomposition_plan remain evidence for these contracts. They are not canonical artifact kinds and should not become control-plane source of truth. Workflow sequence cleanup and brownfield sequence renaming remain later work.

Brownfield AppContextGraph edges start from discovery evidence that ExistingAppDiscovery already has: product/spec surfaces, CapabilitySpec[], detected integrations, data entity evidence, ownership boundaries, risks, and unknowns. The graph can connect capabilities to explicit API, integration, and data evidence, connect discovered route/API overlaps, and attach risk or unknown nodes to affected capabilities or source areas. Internal module_decomposition_plan context may add candidate module, page, adapter, or workflow nodes marked as internal_evidence, but it remains workflow-local evidence rather than a canonical artifact. When source refs or artifact workspaces are available, the shared Context Graph builder can add file, symbol, import, agent, tool, module, page, and workflow nodes.

These brownfield graph enrichments are provenance-backed and advisory. They do not mutate source repositories, change workflow sequence routing, replace deterministic affected-path logic, or give a graph backend execution authority.

AppContextVersion Registration

The current OSS implementation can register a brownfield AppContextVersion after ExistingAppDiscovery persists the canonical draft artifacts. The helper surface lives in mozaiksai/core/app_context/store.py.

Implemented helper responsibilities:

  • build a brownfield AppContextVersion from persisted artifact version refs
  • persist that context version as an ArtifactVersion with kind app_context_version
  • mark one app-context version artifact as CURRENT through explicit current selection
  • retrieve the current app-context version payload for an app

ExistingAppDiscovery now uses this helper after draft context artifacts are created. The resulting AppContextVersion references those artifacts, carries the source refs and ownership boundaries, points graph_snapshot_ref at the app_context_graph artifact version, and uses brownfield mode.

Current context selection is management state only. It does not change runtime routing, workflow sequence routing, generated app persistence, source repo ownership, or KG authority. The first stale-context policy gate can require a context refresh for risky refinements, and refresh execution is available only through an explicit operator/caller launch helper. The initial discovered context starts as current unless later source checks mark it stale.

Control-Plane Responsibilities

The control plane should own the governed use of app context:

  • current_app_context_version_id
  • context version selection
  • stale context checks
  • impact analysis
  • workflow sequence routing
  • validation requirements
  • staging, review, and promotion boundaries
  • ownership-boundary enforcement

ImpactSet should be derived from the active app context, artifact metadata, source checksums, ownership boundaries, and the classified user request.

Stale context should block risky refinements. A control-plane implementation may still allow low-risk planning or read-only analysis against stale context, but it should clearly mark the result as unsafe to apply until context is refreshed.

Source Of Truth

For greenfield apps, accepted generated ArtifactVersion records and promoted app roots are truth for Mozaiks-owned surfaces. Generated app files are not current until accepted and promoted through the lifecycle.

For brownfield apps, the brownfield existing repo remains the source of truth until explicit transfer. Discovery snapshots are evidence, not authority. Generated overlays are Mozaiks-owned only for overlay artifacts. Staged patches are proposals. A migrated surface becomes migrated_owned only after explicit approval, merge, or promotion.

Graph backend mirrors are never source of truth for runtime execution, permissions, secrets, artifact state, or route rendering. They are allowed to be the backing store for graph-scale code-context queries when configured.

Ownership Classes

Every indexed surface should carry one ownership class:

Ownership class Meaning
read_only_discovered Existing code or app behavior Mozaiks may inspect but does not own.
generated_overlay Mozaiks-generated overlay, adapter, module, workflow, or page that augments an existing app without replacing the source surface.
staged_patch Proposed change staged for review. It is not source of truth until accepted and applied through the chosen promotion or PR path.
migrated_owned Surface explicitly transferred into Mozaiks ownership after approval, merge, or promotion.
external_system Third-party or enterprise-managed system that Mozaiks may integrate with but must not own or mutate.

Ownership boundaries prevent Mozaiks from silently taking over code it merely discovered. They also define which validation and approval gates are required before a staged change can be promoted.

Enterprise Value

For enterprises with existing applications, Mozaiks provides:

  • AI-native application understanding
  • context management
  • governed staged refinement
  • gradual modernization
  • overlays, adapters, and modules where safe
  • validation evidence
  • PR or artifact promotion handoff

Mozaiks does not promise automatic takeover or rewrite. Existing systems remain primary until the enterprise explicitly approves a generated overlay, staged patch, migrated module, or replacement surface.

Brownfield Lifecycle

Canonical brownfield lifecycle:

connect repo/app
-> configure scan boundaries
-> discover
-> persist discovery snapshot
-> build AppContextGraph
-> register AppContextVersion
-> review AdoptionPlan
-> request change
-> control plane derives ImpactSet
-> stage overlay/adapter/module/migration plan
-> validate
-> human approval
-> promote or PR

The same loop applies to generated apps after their first accepted AppContextVersion exists. Greenfield and brownfield diverge during onboarding; they converge once the control plane has current app context.

Placeholder Concepts To Replace Later

The following current concepts are implementation evidence, not canonical architecture. Do not preserve them as source of truth when the app-context contract is implemented.

Current concept Replacement direction
brownfield_build_light Renamed to brownfield_overlay_generation for the current overlay-oriented generation path. The name is cleaner, but deeper brownfield generation semantics still need later lifecycle cleanup around ownership, impact, and adoption plan.
brownfield_build_full Renamed to brownfield_module_generation for the current full DesignDocs -> AgentGenerator -> AppGenerator path. The name is cleaner, but deeper brownfield generation semantics still need later lifecycle cleanup around ownership, impact, and adoption plan.
native_migration as a top-level adoption level Replace with an AdoptionPlan plus explicit modernization or migration phases.
module_decomposition_plan as the canonical brownfield artifact Replace with typed inventory, ownership, graph, adoption, and modernization contracts.
workspace_app private sibling discovery shortcut Replace with neutral source refs, scan policies, and explicit repo/app connection inputs.
AppGenerator-local code_context package and stale workflow-artifact indexing hooks Removed. Shared Context Graph builders and control-plane tools own code-context retrieval.

These replacements are owned by the shared Context Graph and AppContextVersion contracts rather than workflow-local context systems.