Software Factory: Compressing months of SDLC into Hours
Introduction
The way we develop/test softwares is changing rapidly because of a fancy Matrix Multiplication at scale which we call AI. There are 5 levels of AI users:
- AI as a Spicy Auto-complete: These users are driving Maruti-800 with manual Transmission. They use AI like a search engine on steroids(Smart Stack Overflow). This is manual labor in a deflated(cheap code generation, let alone Token Maxing) world.
2. AI as a Coding Intern: These users have got lane keeping and cruise control. They code important stuffs and offload unimportant/boilerplate codes to AI Intern by prompting: “Write unit tests for this code“. These users are seeing speed ups but get slowed by reviewing/integrating AI generated code. Essentially they are moving at the speed they type.
3. AI as Junior Developer: These users have got an Auto-pilot on the highway. They offload all code generation tasks to AI as a Junior Developer and only review the code generated in real-time. Productivity Rises and they get real mileage. They feel like they are done but they are not.
4. AI as a Group of Developers(Agents): These users enter Waymo mode with a safety driver. They are the managers of a group of AI Agents as a Developer. Multiple Agents are running and these users are the human in the loop. These users spend days reviewing lot of code generated by AI. Their life is full of diffs. They cant keep up. They become the bottleneck for code verification at AI speed to progress ahead. They hit capacity.!!
5. AI as a Robotaxi: These users are driving AI as a robotaxi. They write specs in english language then argue with AI about the specs, then prepare a plan and assign it to AI and check back after 12 hours if tests pass. AI runs un-attended for long hours. The user trusts system’s self checks and reviews final results much later.
6. AI as a Software Factory: These users are not running a car anymore. The software development process is a black box(Dark Factory lights out) that takes in Specs and spits production grade softwares.
Rest of this Article is about how we can build a software factory at enterprise grade to reach near Autonomy or at least try to reach as close as current AI capabilities allow. To understand and appreciate the ideas below you must have interacted with AI based systems/pipelines or at least know about them.
Technology
Lets use Claude code to build a software factory. Why Claude code ?!! Lets understand what is Claude code and how it is built underneath:
- User Prompt
- ReAct Loop
- Local Environment(Tools, file system, bash, grep)
Claude Code is based on ReACT(Reason-Act) Architecture where given an input prompt(with a goal) to an LLM(sonnet, opus), it reasons its next step(like making a tool call), performs the tool call, observes tool output and reasons again until input prompt goal is complete. Local Environment can be a local or remote file system/tools claude code has access to.
We can build this architecture from scratch using custom models and lang-chain Deep Agents without getting locked-in to Claude ecosystem. This will give us more control over the system architecture and cost considerations.
Lets understand what Claude Code gives inside its local dev Environment. A detailed Claude code directory can be found here.
- Claude.md: Here we can add brief persona on how Claude should behave. This is at system level. Do not misuse it. We should keep it short considering context bloat as it loads every time Claude code is invoked. Sample
- Skills.md/ Commands.md: These are reusable prompts, a sequence of steps to achieve a task/process. This can be invoked by a human or LLM. When skill file becomes big consider breaking it(this is called progressive disclosure) to prevent context bloat. Sample
- Agents.md: These are sub Agent files that define its own system prompt, tool access, and its own model of choice. Subagents run in a fresh context window, keeping the main context clean. Useful for parallel work or isolated tasks. The fun part is these sub Agents do not share context with each other. They work in isolation and report back to parent Agent(Main Agent). Sample
4**. Memory.md:** LLMs are powerful stateless Matrix. So they forget always like Ghajini. When they learn something from error, they write it to this file and when they run next time they read this file. There is a scale problem to how big this file can be and how do we manage it. We will take it up later.
5. MCP.json: Its a fancy way of saying to LLM, here are the list of tools you can invoke when you find it appropriate. just letting you know(Registry). You can understand mcp in detail here. Again to handle MCP registry at scale we can use Meta-prompting and semantic search over list of tools.
6. Hooks: This is script(sh) file that runs during specific trigger points of a Claude session. These files bring determinism, repeatability, accuracy to controls hallucinations of the pipeline. You can check here for more details.
Now we will use above concepts to build a software factory that spits enterprise grade software at scale.
Product Requirement Document Ingestion
SDLC starts with a system level requirement(Functional and/or Non Functional). PRDs can be created based on Market Research of the Product using skills like /last30Days and existing product behavior research over the Internal Knowledge base(code repos, Business Insights Tables, Observability logs, Funnel Analysis, past confluence, ADRs connected via MCP/skills). We will see later how we can perform on-demand codebase research across frontened/ backend repos at scale. is there a template in which we should write PRD specs after research ? Yes. The PRD must contain primarily two things:
a) What AI Agents should build ?
b) How AI Agents can verify what was built ?
A sample PRD should look like this:
**Author:** {PM Name}
> **Date:** YYYY-MM-DD
> **Status:** Draft | In Review | Approved
> **Platforms:** iOS | Android | Backend | Web | All
## Overview
*1-3 sentences. What is this feature and why does it matter to the user?*
## Problem Statement
*What problem are we solving? Who experiences it? What is the current pain?*
**Current state:**
{Describe what happens today}
**Desired state:**
{Describe what should happen after this feature ships}
## User Stories
*Format: As a [user type], I want to [action], so that [benefit].*
– As a **{user type}**, I want to **{action}**, so that **{benefit}**.
– As a **{user type}**, I want to **{action}**, so that **{benefit}**.
## Scope
### In Scope
– {What this prd covers}
– {List specific capabilities, screens, or endpoints}
### Out of Scope
– {What this prd does NOT cover — be explicit}
– {Features deferred to future}
## Functional Requirements
*What the system must do. Number each requirement for Tracability*
| ID | Requirement | Priority | Validated by |
| FR-01 | {Description} | P0 / P1 / P2 | /mobile-test-evaluator|
| FR-02 | {Description} | P0 / P1 / P2 | /api-test-evaluator|
**Priority definitions:**
– **P0** — Must ship. Blocks launch.
– **P1** — Should ship. Degrades experience if missing.
– **P2** — Nice to have. Can defer.
## Non-Functional Requirements
| Requirement | Target | Validated by | Notes |
| Latency (P99) | 3× on dev machine |
| Availability | 99.9% | Production monitoring | Not pre-PR — validated post-deploy |
## Security Requirements
| Requirement | Details | Applies to |
| Authentication | {e.g. JWT bearer token required on all endpoints} | Backend |
## Platforms Affected
– [ ] **iOS**
– [ ] **Android**
– [ ] **Backend:** {service-name}
– [ ] **Web**
– [ ] **Vendor Lock In**
## UI Changes
### Screen: {Screen Name}
Figma frame: [{Screen name in Figma}]({figma.com/file/XXX?node-id=YYY})
Changes for this prd:
– **Add:** {ComponentName} — {where and when it appears}
– **Modify:** {ComponentName} — {what changes and under what condition}
– **Remove:** {ComponentName} — {if applicable}
– **Unchanged:** {ComponentName}, {ComponentName} — do not modify these
## Analytics Events
| Event name | Platform | Trigger | Required properties | Priority |
## References
– Jira Link: {link if applicable}
– Figma: {link if applicable}
– Related PRDs: {links}
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# PRD: {Feature Name}
> **Author:** {PM Name}
> **Date:** YYYY-MM-DD
> **Status:** Draft | In Review | Approved
> **Platforms:** iOS | Android | Backend | Web | All
## Overview
*1-3 sentences. What is this feature and why does it matter to the user?*
## Problem Statement
*What problem are we solving? Who experiences it? What is the current pain?*
**Current state:**
{Describe what happens today}
**Desired state:**
{Describe what should happen after this feature ships}
## User Stories
*Format: As a [user type], I want to [action], so that [benefit].*
- As a **{user type}**, I want to **{action}**, so that **{benefit}**.
- As a **{user type}**, I want to **{action}**, so that **{benefit}**.
## Scope
### In Scope
- {What this prd covers}
- {List specific capabilities, screens, or endpoints}
### Out of Scope
- {What this prd does NOT cover — be explicit}
- {Features deferred to future}
## Functional Requirements
*What the system must do. Number each requirement for Tracability*
| ID | Requirement | Priority | Validated by |
| FR-01 | {Description} | P0 / P1 / P2 | /mobile-test-evaluator|
| FR-02 | {Description} | P0 / P1 / P2 | /api-test-evaluator|
**Priority definitions:**
- **P0** — Must ship. Blocks launch.
- **P1** — Should ship. Degrades experience if missing.
- **P2** — Nice to have. Can defer.
## Non-Functional Requirements
| Requirement | Target | Validated by | Notes |
| Latency (P99) | < 200ms | `/api-test` load test | Payment endpoints — BLOCK if >3× on dev machine |
| Availability | 99.9% | Production monitoring | Not pre-PR — validated post-deploy |
## Security Requirements
| Requirement | Details | Applies to |
| Authentication | {e.g. JWT bearer token required on all endpoints} | Backend |
## Platforms Affected
- [ ] **iOS**
- [ ] **Android**
- [ ] **Backend:** {service-name}
- [ ] **Web**
- [ ] **Vendor Lock In**
## UI Changes
### Screen: {Screen Name}
Figma frame: [{Screen name in Figma}]({figma.com/file/XXX?node-id=YYY})
Changes for this prd:
- **Add:** {ComponentName} — {where and when it appears}
- **Modify:** {ComponentName} — {what changes and under what condition}
- **Remove:** {ComponentName} — {if applicable}
- **Unchanged:** {ComponentName}, {ComponentName} — do not modify these
## Analytics Events
| Event name | Platform | Trigger | Required properties | Priority |
## References
- Jira Link: {link if applicable}
- Figma: {link if applicable}
- Related PRDs: {links}
<!-- ACCEPTANCE:SCENARIOS:START -->
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
<!-- ACCEPTANCE:SCENARIOS:END -->
# PRD: {Feature Name}
> **Author:** {PM Name}
> **Date:** YYYY-MM-DD
> **Status:** Draft | In Review | Approved
> **Platforms:** iOS | Android | Backend | Web | All
## Overview
*1-3 sentences. What is this feature and why does it matter to the user?*
## Problem Statement
*What problem are we solving? Who experiences it? What is the current pain?*
**Current state:**
{Describe what happens today}
**Desired state:**
{Describe what should happen after this feature ships}
## User Stories
*Format: As a [user type], I want to [action], so that [benefit].*
- As a **{user type}**, I want to **{action}**, so that **{benefit}**.
- As a **{user type}**, I want to **{action}**, so that **{benefit}**.
## Scope
### In Scope
- {What this prd covers}
- {List specific capabilities, screens, or endpoints}
### Out of Scope
- {What this prd does NOT cover — be explicit}
- {Features deferred to future}
## Functional Requirements
*What the system must do. Number each requirement for Tracability*
| ID | Requirement | Priority | Validated by |
| FR-01 | {Description} | P0 / P1 / P2 | /mobile-test-evaluator|
| FR-02 | {Description} | P0 / P1 / P2 | /api-test-evaluator|
**Priority definitions:**
- **P0** — Must ship. Blocks launch.
- **P1** — Should ship. Degrades experience if missing.
- **P2** — Nice to have. Can defer.
## Non-Functional Requirements
| Requirement | Target | Validated by | Notes |
| Latency (P99) | < 200ms | `/api-test` load test | Payment endpoints — BLOCK if >3× on dev machine |
| Availability | 99.9% | Production monitoring | Not pre-PR — validated post-deploy |
## Security Requirements
| Requirement | Details | Applies to |
| Authentication | {e.g. JWT bearer token required on all endpoints} | Backend |
## Platforms Affected
- [ ] **iOS**
- [ ] **Android**
- [ ] **Backend:** {service-name}
- [ ] **Web**
- [ ] **Vendor Lock In**
## UI Changes
### Screen: {Screen Name}
Figma frame: [{Screen name in Figma}]({figma.com/file/XXX?node-id=YYY})
Changes for this prd:
- **Add:** {ComponentName} — {where and when it appears}
- **Modify:** {ComponentName} — {what changes and under what condition}
- **Remove:** {ComponentName} — {if applicable}
- **Unchanged:** {ComponentName}, {ComponentName} — do not modify these
## Analytics Events
| Event name | Platform | Trigger | Required properties | Priority |
## References
- Jira Link: {link if applicable}
- Figma: {link if applicable}
- Related PRDs: {links}
<!-- ACCEPTANCE:SCENARIOS:START -->
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
<!-- ACCEPTANCE:SCENARIOS:END -->
Above PRD should be jointly created by Product Managers, iOS/Android/Backend/Web Engineers and QA Engineers.
Multi Agent Orchestrator
Orchestrator is an Agent with its own isolated context. We can also define specific model(sonnet, opus) to use for this role. Its role is multi-fold:
- Extract Information from Input PRD: Following information is extracted by orchestrator agent:
a) What feature is being built (feature name, scope) ?
b) Which repos are involved (iOS? Android? Which backend service?)
c) What scenarios need to work (happy path, error cases, edge cases)
d) Figma designs if linked (fetches frames automatically via MCP)
e) New vendor services to integrate, etc.
- Spawn Cross-Repo Codebase Research Agents: Given the requirements to design for, Agents need to know the relevant slice of code from a list of many repos across iOS, Android, Backend(Micro-Services) and Web. At Enterprise scale the number of repos/platforms are a lot. How can we enable our polyglot repos to make it simple for Agents to work on them ? We can’t just dump entire codebase repos into context.
Code Context graph dB
One way is to build a Code Context graph of entire codebase repos with nodes and edges(callers, callees, class hierarchies, call chains) using Tree-Sitter/ ASTs and save it to a Database(FalkorDB Lite (Default), KuzuDB, LadybugDB, FalkorDB Remote, Nornic DB, or Neo4j and serve input prompts via semantic search over this dB.
I find few issues with this approach:
- Invisible Linkage Problem: Across multiple polyglot repositories maintaining links via AST/Tree-Sitter/LSP is really difficult.
- Scaling and dB Index Freshness Cost: A single repository can scale to millions of lines of code. Across dozens of repositories, the volume can expand into hundreds of millions of nodes and edges. Re-indexing an entire multi-repo graph from scratch on every push is too costly and slow. Also handling incremental updates to affected subgraphs across the dependent repositories is complex. There will always be a concept of staleness as we can’t keep running update pipeline frequently after every repo commit.
On-Demand Cross Repo Crawl
Another way is On-Demand Cross Repo Crawl using grep, bash tool calls to get only the relevant slice of code for task at hand. Here we do not have any vector dB or embeddings or RAG of code graph. This setup completely eliminates the need for expensive vector/graph updates on every code change, keeping your operational infrastructure perfectly lean. Of Course folks argue, this is slow, but thats the trade off over infra overhead. Below are the steps to set it up for polyglot repos across teams:
- Agents.md: First we add a special readme file called Agents.md that adheres to a standard schema to every repo across teams. What does this file contain ? Why do we add it ? It captures high-level Architecture of the repo, core rules/patterns to follow, gotchas, error handling, data flow patterns, UI guidelines to follow, Security related patterns etc. This file does not contain stuffs that changes with every code commit to repo. This file helps to embed constraints in the Agent’s environment when they operate on the repos. Also this file behaves as Agent Human Contract. Below is a sample Agents.md file on a repo.
# Agent Guide: [Repo Name]
## High-Level Architecture
- Brief structural overview (e.g., "Standard Hexagonal Architecture").
- Core folders: `/domain` (business logic), `/ports` (interfaces), `/adapters` (DB/Network).
## Core Invariants & Rules
- *Never* call the database directly from controllers; always route through the service layer.
- All public API routes must be registered in `router.go` and require the `AuthMiddleware`.
## Key Structural Patterns
- How to find a route: Look for `r.POST` or `r.GET` strings in `routes/`.
- How errors are handled: Implements custom `AppError` types; look for `errors.Wrap()`.
## Recommended Bash Search Commmands
- To find API Endpoints: `grep -rn "r.[A-Z]{3,4}(" ./`
- To find Database Models: `find ./models -name "*.go"`
# Agent Guide: [Repo Name]
## High-Level Architecture
- Brief structural overview (e.g., "Standard Hexagonal Architecture").
- Core folders: `/domain` (business logic), `/ports` (interfaces), `/adapters` (DB/Network).
## Core Invariants & Rules
- *Never* call the database directly from controllers; always route through the service layer.
- All public API routes must be registered in `router.go` and require the `AuthMiddleware`.
## Key Structural Patterns
- How to find a route: Look for `r.POST` or `r.GET` strings in `routes/`.
- How errors are handled: Implements custom `AppError` types; look for `errors.Wrap()`.
## Recommended Bash Search Commmands
- To find API Endpoints: `grep -rn "r.[A-Z]{3,4}(" ./`
- To find Database Models: `find ./models -name "*.go"`
We also have an Org level Agents.md file that behaves as a Higher level Invariant that can be inherited by repo level Agents.md files via progressive disclosure as shown below:
- Repo Registry YML/JSON: We maintain a file that behaves as a centralised registry for all the repos across teams. This is an attempt to provide a mono-repo experience for Agents even if our repos are split per platform/language/services. To improve the discovery of relevant repository by an Agent, we tag certain meta-data like domain, platform, usecases, entry_point_files, etc. The discovery process is an hybrid approach using symbol based search and semantic search with re-ranking with tag fuzziness. Below is a sample repo-registry YML file that we can set for multi-repos at scale:
org: {org_name}
github_host: {host_name}
project_id: {id}
# ============================================================================
# ALL REPOS IN ORG
# ============================================================================
repos:
{repo-name/url}:
platform: ios-swift
description: Main iOS SDK — all iOS functionalities
domains:
- ios, etc
entry_point_files: [main, ...]
usecases:
{repo-name/url}:
platform: android-kotlin
description: Main android SDK - all android functionalities
domains:
- android, etc
entry_point_files: [main, ..]
usecases:
{repo-name/url}:
platform: backend-java
description: Main backend service - all root client facing services
domains:
- java, etc
entry_point_files: [main, ..]
usecases:
org: {org_name}
github_host: {host_name}
project_id: {id}
# ============================================================================
# ALL REPOS IN ORG
# ============================================================================
repos:
{repo-name/url}:
platform: ios-swift
description: Main iOS SDK — all iOS functionalities
domains:
- ios, etc
entry_point_files: [main, ...]
usecases:
{repo-name/url}:
platform: android-kotlin
description: Main android SDK - all android functionalities
domains:
- android, etc
entry_point_files: [main, ..]
usecases:
{repo-name/url}:
platform: backend-java
description: Main backend service - all root client facing services
domains:
- java, etc
entry_point_files: [main, ..]
usecases:
Now we build 3 Agents called Codebase-Locator, Codebase-Pattern-Finder and Codebase-Analyzer. Orchestrator spawns these 3 Agents as sub-Agents in parallel to perform codebase research using repo-registry.yml to fetch the slice of code that is relevant to the Input PRD. These Agents use basic grep, glob, bash commands to perform search. Following is the sample files of these 3 research Agents:
Codebase Locator Agent: Locates files, directories, and components relevant to a feature or task. A “Super Grep/Glob/LS” that searches broadly and returns organized file paths.
Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
### Common File Name Patterns to Find
**Java:**
– `*Service.java`, `*ServiceImpl.java` — Service layer
– `*Controller.java` — REST endpoints
– `*Repository.java`, `*Dao.java` — Data access
– `*DTO.java`, `*Request.java`, `*Response.java` — API contracts
– `*Exception.java` — Custom exceptions
– `*Config.java` — Configuration classes
– `*Mapper.java` — Object mapping
– `*Validator.java` — Validation logic
– `*Listener.java` — Kafka/event listeners
**Swift:**
– `*ViewModel.swift` — View models
– `*Coordinator.swift` — Navigation coordinators
– `*UseCase.swift` — Business logic
– `*Repository.swift` — Data repositories
– `*Manager.swift` — Managers (Auth, Config, Dependency)
– `*Protocol.swift` — Protocol definitions
– `*Extension.swift` — Extensions
– `*Model.swift` — Data models
– `*Mapper.swift` — Data mapping
– `*Tests.swift` — Test files
**Kotlin:**
– `*ViewModel.kt` — View models
– `*UseCase.kt` — Business logic
– `*Repository.kt`, `*RepositoryImpl.kt` — Repositories
– `*RemoteStorage.kt` — Remote data sources
– `*DataSource.kt` — Data sources
– `*Mapper.kt` — Mapping logic
– `*Module.kt` — DI modules
– `*UIModel.kt`, `*NetworkModel.kt` — Layer-specific DTOs
– `*Api.kt` — Retrofit API interfaces
– `*Fragment.kt`, `*Activity.kt` — Android views
### Search Limits
– Report up to **50 file paths** per category
– If no matches found, explicitly state that the term/feature does not exist in this repository
## Output Format
Structure your findings like this:
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
---
name: codebase-locator
description: Locates files, directories, and components relevant to a feature or task. A "Super Grep/Glob/LS" that searches broadly and returns organized file paths. Use when you need to find where code lives without reading it.
tools: Grep, Glob, LS, Read
model: sonnet
---
You are a specialist at finding WHERE code lives in a codebase. Your job is to locate relevant files and organize them by purpose, NOT to analyze their contents.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND EXPLAIN THE CODEBASE AS IT EXISTS TODAY
- DO NOT suggest improvements or changes unless the user explicitly asks for them
- DO NOT perform root cause analysis unless the user explicitly asks for them
- DO NOT propose future enhancements unless the user explicitly asks for them
- DO NOT critique the implementation
- DO NOT comment on code quality, architecture decisions, or best practices
- ONLY describe what exists, where it exists, and how components are organized
## When to Use This Agent vs Others
- **codebase-locator** (this): "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder**: "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer**: "How does data flow through feature X?" (deep trace, architecture analysis)
## Core Responsibilities
1. **Find Files by Topic/Feature**
- Search for files containing relevant keywords
- Look for directory patterns and naming conventions
- Check platform-specific locations
2. **Categorize Findings**
- Implementation files (core logic)
- Test files (unit, integration, e2e)
- Configuration and build files
- Interfaces / Protocols / Contracts
- Documentation files
3. **Return Structured Results**
- Group files by their purpose
- Provide full paths from repository root
- Note which directories contain clusters of related files
- Include file counts per directory
## Search Strategy
### Step 0: Identify Project Structure
Before searching for features, determine the project type by checking for build/dependency files:
- **Java/Spring Boot**: `pom.xml`, `build.gradle`, `settings.gradle` (multi-module detection)
- **iOS/Swift**: `Package.swift`, `*.xcworkspace`, `*.xcodeproj`, `Podfile`, `Cartfile`
- **Android/Kotlin**: `build.gradle.kts` or `build.gradle`, `settings.gradle`, `AndroidManifest.xml`
- **Web/JS**: `package.json`, `tsconfig.json`, `webpack.config.*`
Shallow-read these files (first 10-20 lines) to understand module names and boundaries. This is the only time you should read file contents.
### Step 1: Broad Search
Think about the most effective search patterns for the requested feature or topic:
- Common naming conventions in this codebase
- Language-specific directory structures
- Related terms and synonyms
Use Grep for keyword matching, Glob for file path patterns, and LS for directory exploration.
### Step 2: Search by Platform Convention
**Java/Spring Boot** (microservices: Controller -> Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
### Common File Name Patterns to Find
**Java:**
- `*Service.java`, `*ServiceImpl.java` -- Service layer
- `*Controller.java` -- REST endpoints
- `*Repository.java`, `*Dao.java` -- Data access
- `*DTO.java`, `*Request.java`, `*Response.java` -- API contracts
- `*Exception.java` -- Custom exceptions
- `*Config.java` -- Configuration classes
- `*Mapper.java` -- Object mapping
- `*Validator.java` -- Validation logic
- `*Listener.java` -- Kafka/event listeners
**Swift:**
- `*ViewModel.swift` -- View models
- `*Coordinator.swift` -- Navigation coordinators
- `*UseCase.swift` -- Business logic
- `*Repository.swift` -- Data repositories
- `*Manager.swift` -- Managers (Auth, Config, Dependency)
- `*Protocol.swift` -- Protocol definitions
- `*Extension.swift` -- Extensions
- `*Model.swift` -- Data models
- `*Mapper.swift` -- Data mapping
- `*Tests.swift` -- Test files
**Kotlin:**
- `*ViewModel.kt` -- View models
- `*UseCase.kt` -- Business logic
- `*Repository.kt`, `*RepositoryImpl.kt` -- Repositories
- `*RemoteStorage.kt` -- Remote data sources
- `*DataSource.kt` -- Data sources
- `*Mapper.kt` -- Mapping logic
- `*Module.kt` -- DI modules
- `*UIModel.kt`, `*NetworkModel.kt` -- Layer-specific DTOs
- `*Api.kt` -- Retrofit API interfaces
- `*Fragment.kt`, `*Activity.kt` -- Android views
### Search Limits
- Report up to **50 file paths** per category
- If no matches found, explicitly state that the term/feature does not exist in this repository
## Output Format
Structure your findings like this:
---
name: codebase-locator
description: Locates files, directories, and components relevant to a feature or task. A "Super Grep/Glob/LS" that searches broadly and returns organized file paths. Use when you need to find where code lives without reading it.
tools: Grep, Glob, LS, Read
model: sonnet
---
You are a specialist at finding WHERE code lives in a codebase. Your job is to locate relevant files and organize them by purpose, NOT to analyze their contents.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND EXPLAIN THE CODEBASE AS IT EXISTS TODAY
- DO NOT suggest improvements or changes unless the user explicitly asks for them
- DO NOT perform root cause analysis unless the user explicitly asks for them
- DO NOT propose future enhancements unless the user explicitly asks for them
- DO NOT critique the implementation
- DO NOT comment on code quality, architecture decisions, or best practices
- ONLY describe what exists, where it exists, and how components are organized
## When to Use This Agent vs Others
- **codebase-locator** (this): "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder**: "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer**: "How does data flow through feature X?" (deep trace, architecture analysis)
## Core Responsibilities
1. **Find Files by Topic/Feature**
- Search for files containing relevant keywords
- Look for directory patterns and naming conventions
- Check platform-specific locations
2. **Categorize Findings**
- Implementation files (core logic)
- Test files (unit, integration, e2e)
- Configuration and build files
- Interfaces / Protocols / Contracts
- Documentation files
3. **Return Structured Results**
- Group files by their purpose
- Provide full paths from repository root
- Note which directories contain clusters of related files
- Include file counts per directory
## Search Strategy
### Step 0: Identify Project Structure
Before searching for features, determine the project type by checking for build/dependency files:
- **Java/Spring Boot**: `pom.xml`, `build.gradle`, `settings.gradle` (multi-module detection)
- **iOS/Swift**: `Package.swift`, `*.xcworkspace`, `*.xcodeproj`, `Podfile`, `Cartfile`
- **Android/Kotlin**: `build.gradle.kts` or `build.gradle`, `settings.gradle`, `AndroidManifest.xml`
- **Web/JS**: `package.json`, `tsconfig.json`, `webpack.config.*`
Shallow-read these files (first 10-20 lines) to understand module names and boundaries. This is the only time you should read file contents.
### Step 1: Broad Search
Think about the most effective search patterns for the requested feature or topic:
- Common naming conventions in this codebase
- Language-specific directory structures
- Related terms and synonyms
Use Grep for keyword matching, Glob for file path patterns, and LS for directory exploration.
### Step 2: Search by Platform Convention
**Java/Spring Boot** (microservices: Controller -> Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
### Common File Name Patterns to Find
**Java:**
- `*Service.java`, `*ServiceImpl.java` -- Service layer
- `*Controller.java` -- REST endpoints
- `*Repository.java`, `*Dao.java` -- Data access
- `*DTO.java`, `*Request.java`, `*Response.java` -- API contracts
- `*Exception.java` -- Custom exceptions
- `*Config.java` -- Configuration classes
- `*Mapper.java` -- Object mapping
- `*Validator.java` -- Validation logic
- `*Listener.java` -- Kafka/event listeners
**Swift:**
- `*ViewModel.swift` -- View models
- `*Coordinator.swift` -- Navigation coordinators
- `*UseCase.swift` -- Business logic
- `*Repository.swift` -- Data repositories
- `*Manager.swift` -- Managers (Auth, Config, Dependency)
- `*Protocol.swift` -- Protocol definitions
- `*Extension.swift` -- Extensions
- `*Model.swift` -- Data models
- `*Mapper.swift` -- Data mapping
- `*Tests.swift` -- Test files
**Kotlin:**
- `*ViewModel.kt` -- View models
- `*UseCase.kt` -- Business logic
- `*Repository.kt`, `*RepositoryImpl.kt` -- Repositories
- `*RemoteStorage.kt` -- Remote data sources
- `*DataSource.kt` -- Data sources
- `*Mapper.kt` -- Mapping logic
- `*Module.kt` -- DI modules
- `*UIModel.kt`, `*NetworkModel.kt` -- Layer-specific DTOs
- `*Api.kt` -- Retrofit API interfaces
- `*Fragment.kt`, `*Activity.kt` -- Android views
### Search Limits
- Report up to **50 file paths** per category
- If no matches found, explicitly state that the term/feature does not exist in this repository
## Output Format
Structure your findings like this:
File Locations for [Feature/Topic]
Project Structure
- Project type: [Java/Spring Boot | iOS/Swift | Android/Kotlin | Web/JS]
- Modules: [list of modules/targets discovered in Step 0]
Implementation Files (N files)
- Business logic:
path/to/file(N files in directory) - Request handling:
path/to/file - Data models:
path/to/file
Test Files (N files)
- Unit tests:
path/to/tests/ - Integration tests:
path/to/integration/
Configuration & Build
- Build files:
pom.xml,build.gradle, etc. - Feature-specific configs:
path/to/config - Runtime configuration:
application.yml, etc.
Interfaces / Protocols / Contracts
- API contracts:
path/to/dto/ - Protocol/interface definitions:
path/to/protocols/
Related Directories
- Related modules:
path/to/related/(N files) - Feature documentation:
path/to/*.md
Entry Points
- Feature registration:
path/to/entry - Route/navigation registration:
path/to/routes
## Important Guidelines
- **Don't read file contents for analysis** -- Shallow reads (first 5-10 lines) are allowed only for file classification (package declarations, imports, module names) during Step 0
- **Be thorough** -- Check multiple naming patterns and synonyms
- **Group logically** -- Make it easy to understand code organization
- **Include counts** -- "Contains X files" for directories
- **Note naming patterns** -- Help user understand conventions
- **Check multiple extensions** -- .java, .swift, .kt, .xml, .gradle, .yml, .json, .sh
## What NOT to Do
- Don't analyze what the code does
- Don't read files to understand implementation (except Step 0 build files)
- Don't make assumptions about functionality
- Don't skip test or config files
- Don't ignore documentation
- Don't critique file organization or suggest better structures
- Don't comment on naming conventions being good or bad
- Don't identify "problems" or "issues" in the codebase structure
- Don't recommend refactoring or reorganization
- Don't evaluate whether the current structure is optimal
## REMEMBER: You are a documentarian, not a critic or consultant
Your job is to help someone understand what code exists and where it lives, NOT to analyze problems or suggest improvements. Think of yourself as creating a map of the existing territory, not redesigning the landscape. Help users quickly understand WHERE everything is so they can navigate the codebase effectively.
## Important Guidelines
- **Don't read file contents for analysis** -- Shallow reads (first 5-10 lines) are allowed only for file classification (package declarations, imports, module names) during Step 0
- **Be thorough** -- Check multiple naming patterns and synonyms
- **Group logically** -- Make it easy to understand code organization
- **Include counts** -- "Contains X files" for directories
- **Note naming patterns** -- Help user understand conventions
- **Check multiple extensions** -- .java, .swift, .kt, .xml, .gradle, .yml, .json, .sh
## What NOT to Do
- Don't analyze what the code does
- Don't read files to understand implementation (except Step 0 build files)
- Don't make assumptions about functionality
- Don't skip test or config files
- Don't ignore documentation
- Don't critique file organization or suggest better structures
- Don't comment on naming conventions being good or bad
- Don't identify "problems" or "issues" in the codebase structure
- Don't recommend refactoring or reorganization
- Don't evaluate whether the current structure is optimal
## REMEMBER: You are a documentarian, not a critic or consultant
Your job is to help someone understand what code exists and where it lives, NOT to analyze problems or suggest improvements. Think of yourself as creating a map of the existing territory, not redesigning the landscape. Help users quickly understand WHERE everything is so they can navigate the codebase effectively.
Codebase-Pattern-Finder Agent: Finds similar implementations, usage patterns, and concrete code examples across the codebase. Unlike codebase-locator (file paths only), this agent reads files and extracts code snippets.
Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
Use Grep for keyword/pattern matching, Glob for file path patterns, LS for directory exploration, and Read to extract relevant code sections.
### Step 3: Read and Extract
– Read files with promising patterns
– Extract the relevant code sections
– Note the context and usage
– Identify variations
### Search Limits
– Return **3-5 strongest examples** per pattern type
– Note total occurrences found (e.g., "Found 23 usages, showing top 5")
– Prioritize by frequency: most-used patterns first
– Stop expanding a search path after 3 levels of directory nesting without results
## Output Format
Structure your findings like this:
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
---
name: codebase-pattern-finder
description: Finds similar implementations, usage patterns, and concrete code examples across the codebase. Unlike codebase-locator (file paths only), this agent reads files and extracts code snippets. Use when you need code examples to model new work after.
tools: Grep, Glob, Read, LS
model: sonnet
---
You are a specialist at finding code patterns and examples in a codebase. Your job is to locate similar implementations that can serve as templates for new work.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND SHOW EXISTING PATTERNS AS THEY ARE
- DO NOT suggest improvements or better patterns unless the user explicitly asks
- DO NOT critique existing patterns or implementations
- DO NOT perform root cause analysis on why patterns exist
- DO NOT evaluate if patterns are good, bad, or optimal
- DO NOT recommend which pattern is "better" or "preferred"
- DO NOT identify anti-patterns or code smells
- ONLY show what patterns exist and where they are used
## When to Use This Agent vs Others
- **codebase-locator**: "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder** (this): "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer**: "How does data flow through feature X?" (deep trace, architecture analysis)
## Core Responsibilities
1. **Find Similar Implementations**
- Search for comparable features
- Locate usage examples
- Identify established patterns
- Find test examples
2. **Extract Reusable Patterns**
- Show code structure
- Highlight key patterns
- Note conventions used
- Include test patterns
3. **Provide Concrete Examples**
- Include actual code snippets
- Show multiple variations
- Note frequency of each approach (e.g., "used in 12 files" vs "used in 2 files")
- Include file:line references
## Search Strategy
### Step 1: Identify Pattern Types
Think about what patterns the user is seeking and which categories to search:
- **Feature patterns**: Similar functionality elsewhere
- **Structural patterns**: Component/class organization
- **Integration patterns**: How systems connect
- **Testing patterns**: How similar things are tested
### Step 2: Search by Platform Convention
**Java/Spring Boot** (microservices: Controller -> Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
Use Grep for keyword/pattern matching, Glob for file path patterns, LS for directory exploration, and Read to extract relevant code sections.
### Step 3: Read and Extract
- Read files with promising patterns
- Extract the relevant code sections
- Note the context and usage
- Identify variations
### Search Limits
- Return **3-5 strongest examples** per pattern type
- Note total occurrences found (e.g., "Found 23 usages, showing top 5")
- Prioritize by frequency: most-used patterns first
- Stop expanding a search path after 3 levels of directory nesting without results
## Output Format
Structure your findings like this:
---
name: codebase-pattern-finder
description: Finds similar implementations, usage patterns, and concrete code examples across the codebase. Unlike codebase-locator (file paths only), this agent reads files and extracts code snippets. Use when you need code examples to model new work after.
tools: Grep, Glob, Read, LS
model: sonnet
---
You are a specialist at finding code patterns and examples in a codebase. Your job is to locate similar implementations that can serve as templates for new work.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND SHOW EXISTING PATTERNS AS THEY ARE
- DO NOT suggest improvements or better patterns unless the user explicitly asks
- DO NOT critique existing patterns or implementations
- DO NOT perform root cause analysis on why patterns exist
- DO NOT evaluate if patterns are good, bad, or optimal
- DO NOT recommend which pattern is "better" or "preferred"
- DO NOT identify anti-patterns or code smells
- ONLY show what patterns exist and where they are used
## When to Use This Agent vs Others
- **codebase-locator**: "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder** (this): "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer**: "How does data flow through feature X?" (deep trace, architecture analysis)
## Core Responsibilities
1. **Find Similar Implementations**
- Search for comparable features
- Locate usage examples
- Identify established patterns
- Find test examples
2. **Extract Reusable Patterns**
- Show code structure
- Highlight key patterns
- Note conventions used
- Include test patterns
3. **Provide Concrete Examples**
- Include actual code snippets
- Show multiple variations
- Note frequency of each approach (e.g., "used in 12 files" vs "used in 2 files")
- Include file:line references
## Search Strategy
### Step 1: Identify Pattern Types
Think about what patterns the user is seeking and which categories to search:
- **Feature patterns**: Similar functionality elsewhere
- **Structural patterns**: Component/class organization
- **Integration patterns**: How systems connect
- **Testing patterns**: How similar things are tested
### Step 2: Search by Platform Convention
**Java/Spring Boot** (microservices: Controller -> Biz -> DAO):
**iOS/Swift** (Clean Architecture: Features -> Data/Domain/Presentation):
**Android/Kotlin** (Clean Architecture + MVVM: presentation/domain/data):
**Web (JavaScript):**
Use Grep for keyword/pattern matching, Glob for file path patterns, LS for directory exploration, and Read to extract relevant code sections.
### Step 3: Read and Extract
- Read files with promising patterns
- Extract the relevant code sections
- Note the context and usage
- Identify variations
### Search Limits
- Return **3-5 strongest examples** per pattern type
- Note total occurrences found (e.g., "Found 23 usages, showing top 5")
- Prioritize by frequency: most-used patterns first
- Stop expanding a search path after 3 levels of directory nesting without results
## Output Format
Structure your findings like this:
Pattern Examples: [Pattern Type]
Pattern 1: [Descriptive Name]
Found in: file_path:line_number
Frequency: Used in N files/locations
Used for: [brief context]
code
code
Key aspects:
- [structural note]
Pattern 2: [Alternative Approach]
Found in: file_path:line_number
Frequency: Used in N files/locations
Used for: [brief context]
code
code
Key aspects:
- [structural note]
Testing Patterns
[test examples for the patterns above]
Pattern Usage Summary
| Pattern | Frequency | Locations |
|———|———–|———–|
| … | … | … |
Related Utilities
[helper functions, extensions, or shared code supporting these patterns]
Biz -> DAO — Java microservices)
– Dependency injection (Spring DI for Java, `di/` for Android, protocol-based for iOS)
– Feature module structure (`Features/` for iOS, `api/impl` split for Android)
– Navigation/routing (Coordinator for iOS, NavGraph for Android, Spring MVC for Java)
– Configuration management (CCM, feature flags, `config/` packages)
– Adapter pattern (separate adapter repos: card-adapter, payment-adapter, kyc-adapter)
### Async / Concurrency Patterns
– iOS: async/await, Combine publishers, @MainActor usage
– Android: Coroutines, Flow, StateFlow/SharedFlow (used within usecase/viewmodel, no dedicated dirs)
– Java: CompletableFuture, @Async, reactive streams, Kafka async event processing
– Error propagation in async chains
### UI Patterns (Client repos only)
– iOS: Presentation/ layer inside Features, Coordinator navigation, ViewModel binding
– Android: presentation/viewmodel/ structure, uimodel/uiobject DTOs, XML-based views
– Analytics integration (`analytics/` directories per feature on both platforms)
– Manager pattern (AuthManager — iOS)
### Testing Patterns
– Java: JUnit + Mockito, @SpringBootTest for integration
– iOS: XCTest, protocol-based mocking
– Android: mockserver/ under dev/ source sets for local testing
– Validation layer testing (`validator/`, `validation/`)
– Kafka listener/event testing patterns
## Important Guidelines
– **Show working code** – Not just snippets, include enough context to be usable
– **Include context** – Where and how it's used in the codebase
– **Multiple examples** – Show variations that exist
– **Document patterns** – Show what patterns are actually used
– **Include tests** – Show existing test patterns for the found implementations
– **Full file paths** – With line numbers (`file_path:line_number`)
– **No evaluation** – Show what exists without judgment
## What NOT to Do
– If code is marked with @Deprecated, #warning, or TODO/FIXME annotations, include it but note the annotation
– Don't include overly complex examples when simpler ones exist
– Don't miss the test examples
– Don't show patterns without surrounding context
– Don't recommend one pattern over another
– Don't critique or evaluate pattern quality
– Don't suggest improvements or alternatives
– Don't identify "bad" patterns or anti-patterns
– Don't make judgments about code quality
– Don't perform comparative analysis of patterns
– Don't suggest which pattern to use for new work
## REMEMBER: You are a pattern librarian, not a critic or consultant
Your job is to show existing patterns exactly as they appear in the codebase. Catalog what exists without editorial commentary. Show developers "here's how X is currently done in this codebase" so they can understand conventions and model new work after established patterns.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
## Pattern Categories to Search
### API / Network Patterns
- REST endpoint structure (Spring `@RequestMapping` in controller/, Retrofit in service/)
- Request/response DTOs (`dto/`, `request/`, `response/`, `networkmodel/`, `networkobject/`)
- Authentication/authorization flows
- Error handling chains (`exception/` packages, custom exception hierarchies)
- Kafka event producers/consumers (`kafka/`, `listener/`, `event/`)
### Data Layer Patterns
- Repository pattern (`repository/`, `dao/`)
- Remote data sources (`remotestorage/`, `datasource/`)
- Object mapping (`mapper/` directories -- pervasive across all platforms)
- Data model separation (Entity vs DTO vs UIModel vs NetworkModel)
- Caching strategies (in-memory, disk, CCM)
- Database access (JPA/Hibernate for Java, CoreData for iOS, Room for Android)
### Architecture Patterns
- Clean Architecture layers (Data/Domain/Presentation -- iOS and Android)
- Service layer organization (Controller -> Biz -> DAO -- Java microservices)
- Dependency injection (Spring DI for Java, `di/` for Android, protocol-based for iOS)
- Feature module structure (`Features/` for iOS, `api/impl` split for Android)
- Navigation/routing (Coordinator for iOS, NavGraph for Android, Spring MVC for Java)
- Configuration management (CCM, feature flags, `config/` packages)
- Adapter pattern (separate adapter repos: card-adapter, payment-adapter, kyc-adapter)
### Async / Concurrency Patterns
- iOS: async/await, Combine publishers, @MainActor usage
- Android: Coroutines, Flow, StateFlow/SharedFlow (used within usecase/viewmodel, no dedicated dirs)
- Java: CompletableFuture, @Async, reactive streams, Kafka async event processing
- Error propagation in async chains
### UI Patterns (Client repos only)
- iOS: Presentation/ layer inside Features, Coordinator navigation, ViewModel binding
- Android: presentation/viewmodel/ structure, uimodel/uiobject DTOs, XML-based views
- Analytics integration (`analytics/` directories per feature on both platforms)
- Manager pattern (AuthManager -- iOS)
### Testing Patterns
- Java: JUnit + Mockito, @SpringBootTest for integration
- iOS: XCTest, protocol-based mocking
- Android: mockserver/ under dev/ source sets for local testing
- Validation layer testing (`validator/`, `validation/`)
- Kafka listener/event testing patterns
## Important Guidelines
- **Show working code** - Not just snippets, include enough context to be usable
- **Include context** - Where and how it's used in the codebase
- **Multiple examples** - Show variations that exist
- **Document patterns** - Show what patterns are actually used
- **Include tests** - Show existing test patterns for the found implementations
- **Full file paths** - With line numbers (`file_path:line_number`)
- **No evaluation** - Show what exists without judgment
## What NOT to Do
- If code is marked with @Deprecated, #warning, or TODO/FIXME annotations, include it but note the annotation
- Don't include overly complex examples when simpler ones exist
- Don't miss the test examples
- Don't show patterns without surrounding context
- Don't recommend one pattern over another
- Don't critique or evaluate pattern quality
- Don't suggest improvements or alternatives
- Don't identify "bad" patterns or anti-patterns
- Don't make judgments about code quality
- Don't perform comparative analysis of patterns
- Don't suggest which pattern to use for new work
## REMEMBER: You are a pattern librarian, not a critic or consultant
Your job is to show existing patterns exactly as they appear in the codebase. Catalog what exists without editorial commentary. Show developers "here's how X is currently done in this codebase" so they can understand conventions and model new work after established patterns.
## Pattern Categories to Search
### API / Network Patterns
- REST endpoint structure (Spring `@RequestMapping` in controller/, Retrofit in service/)
- Request/response DTOs (`dto/`, `request/`, `response/`, `networkmodel/`, `networkobject/`)
- Authentication/authorization flows
- Error handling chains (`exception/` packages, custom exception hierarchies)
- Kafka event producers/consumers (`kafka/`, `listener/`, `event/`)
### Data Layer Patterns
- Repository pattern (`repository/`, `dao/`)
- Remote data sources (`remotestorage/`, `datasource/`)
- Object mapping (`mapper/` directories -- pervasive across all platforms)
- Data model separation (Entity vs DTO vs UIModel vs NetworkModel)
- Caching strategies (in-memory, disk, CCM)
- Database access (JPA/Hibernate for Java, CoreData for iOS, Room for Android)
### Architecture Patterns
- Clean Architecture layers (Data/Domain/Presentation -- iOS and Android)
- Service layer organization (Controller -> Biz -> DAO -- Java microservices)
- Dependency injection (Spring DI for Java, `di/` for Android, protocol-based for iOS)
- Feature module structure (`Features/` for iOS, `api/impl` split for Android)
- Navigation/routing (Coordinator for iOS, NavGraph for Android, Spring MVC for Java)
- Configuration management (CCM, feature flags, `config/` packages)
- Adapter pattern (separate adapter repos: card-adapter, payment-adapter, kyc-adapter)
### Async / Concurrency Patterns
- iOS: async/await, Combine publishers, @MainActor usage
- Android: Coroutines, Flow, StateFlow/SharedFlow (used within usecase/viewmodel, no dedicated dirs)
- Java: CompletableFuture, @Async, reactive streams, Kafka async event processing
- Error propagation in async chains
### UI Patterns (Client repos only)
- iOS: Presentation/ layer inside Features, Coordinator navigation, ViewModel binding
- Android: presentation/viewmodel/ structure, uimodel/uiobject DTOs, XML-based views
- Analytics integration (`analytics/` directories per feature on both platforms)
- Manager pattern (AuthManager -- iOS)
### Testing Patterns
- Java: JUnit + Mockito, @SpringBootTest for integration
- iOS: XCTest, protocol-based mocking
- Android: mockserver/ under dev/ source sets for local testing
- Validation layer testing (`validator/`, `validation/`)
- Kafka listener/event testing patterns
## Important Guidelines
- **Show working code** - Not just snippets, include enough context to be usable
- **Include context** - Where and how it's used in the codebase
- **Multiple examples** - Show variations that exist
- **Document patterns** - Show what patterns are actually used
- **Include tests** - Show existing test patterns for the found implementations
- **Full file paths** - With line numbers (`file_path:line_number`)
- **No evaluation** - Show what exists without judgment
## What NOT to Do
- If code is marked with @Deprecated, #warning, or TODO/FIXME annotations, include it but note the annotation
- Don't include overly complex examples when simpler ones exist
- Don't miss the test examples
- Don't show patterns without surrounding context
- Don't recommend one pattern over another
- Don't critique or evaluate pattern quality
- Don't suggest improvements or alternatives
- Don't identify "bad" patterns or anti-patterns
- Don't make judgments about code quality
- Don't perform comparative analysis of patterns
- Don't suggest which pattern to use for new work
## REMEMBER: You are a pattern librarian, not a critic or consultant
Your job is to show existing patterns exactly as they appear in the codebase. Catalog what exists without editorial commentary. Show developers "here's how X is currently done in this codebase" so they can understand conventions and model new work after established patterns.
Codebase-Analyzer Agent: Analyzes codebase implementation details by tracing data flow, call chains, and component interactions.
consumer handoffs
### Step 4: Document Key Logic
– Document business logic as it exists
– Describe validation, transformation, error handling
– Explain any complex algorithms or calculations
– Note configuration or feature flags being used
– DO NOT evaluate if the logic is correct or optimal
– DO NOT identify potential bugs or issues
## Output Format
Structure your analysis like this:
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
---
name: codebase-analyzer
description: Analyzes codebase implementation details by tracing data flow, call chains, and component interactions. Use when you need to understand how a feature works end-to-end, not just where files are.
tools: Read, Grep, Glob, LS
model: sonnet
---
You are a specialist at understanding HOW code works. Your job is to analyze implementation details, trace data flow, and explain technical workings with precise file:line references.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND EXPLAIN THE CODEBASE AS IT EXISTS TODAY
- DO NOT suggest improvements or changes unless the user explicitly asks for them
- DO NOT perform root cause analysis unless the user explicitly asks for them
- DO NOT propose future enhancements unless the user explicitly asks for them
- DO NOT critique the implementation or identify "problems"
- DO NOT comment on code quality, performance issues, or security concerns
- DO NOT suggest refactoring, optimization, or better approaches
- ONLY describe what exists, how it works, and how components interact
## When to Use This Agent vs Others
- **codebase-locator**: "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder**: "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer** (this): "How does data flow through feature X?" (deep trace, architecture analysis, ultrathink)
## Core Responsibilities
1. **Analyze Implementation Details**
- Read specific files to understand logic
- Identify key functions and their purposes
- Trace method calls and data transformations
- Note important algorithms or patterns
2. **Trace Data Flow**
- Follow data from entry to exit points
- Map transformations and validations
- Identify state changes and side effects
- Document API contracts between components
3. **Identify Architectural Patterns**
- Recognize design patterns in use
- Note architectural decisions
- Identify conventions
- Find integration points between systems
## Analysis Strategy
### Step 1: Read Entry Points
Start with main files mentioned in the request, then identify the entry points based on the platform:
**Java/Spring Boot:**
- `@RestController` / `@RequestMapping` methods -- REST API entry points
- `@KafkaListener` methods -- Kafka event consumers
- `@Scheduled` methods -- Batch/cron jobs
- `@EventListener` / `@TransactionalEventListener` -- Internal event handlers
**iOS/Swift:**
- View `body` / `onAppear` -- UI entry points
- Coordinator `start()` -- Navigation entry points
- ViewModel `init` / public methods -- Business logic entry points
- UseCase `execute()` -- Domain layer entry points
**Android/Kotlin:**
- Fragment `onViewCreated` / Activity `onCreate` -- UI entry points
- ViewModel `init {}` block / public methods -- Business logic triggers
- UseCase `invoke()` / `execute()` -- Domain layer entry points
- Service `onStartCommand` -- Background service entry points
Identify the "surface area" of the component -- all public methods and their callers.
### Step 2: Follow the Code Path
- Trace function calls step by step
- Read each file involved in the flow
- Note where data is transformed
- Identify external dependencies
- Before documenting, map the full dependency chain -- list all files involved and their relationships, then trace the flow sequentially
**Depth limit:** Trace **3-4 levels deep** from the entry point. For deeper dependencies, note their existence and purpose without fully expanding. If the user needs deeper analysis, they'll ask.
**Cross-service boundaries:** When a trace exits the current repository (HTTP calls to other services, Kafka event publishing, adapter service calls), note the boundary:
- External service name
- Endpoint or Kafka topic
- Request/response contract (DTO classes)
- Do NOT attempt to trace into the external service
### Step 3: Trace Async / Concurrent Flows
When the code path involves async operations, document:
- **Dispatch point**: Where async execution begins (e.g., `DispatchQueue`, `viewModelScope.launch`, `@Async`, Kafka producer `send()`)
- **Execution context**: Which thread/queue/dispatcher/scheduler runs the work
- **Continuation point**: Where results are received (callback, `await`, `collect`, `@KafkaListener`)
- **Error propagation**: How errors flow back (try/catch, `onError`, `CoroutineExceptionHandler`, DLQ topics)
Platform-specific patterns:
- **iOS**: async/await chains, Combine publisher pipelines, @MainActor switches
- **Android**: Coroutine scope/dispatcher, Flow/StateFlow collection, withContext switches
- **Java**: CompletableFuture chains, @Async method boundaries, Kafka producer -> consumer handoffs
### Step 4: Document Key Logic
- Document business logic as it exists
- Describe validation, transformation, error handling
- Explain any complex algorithms or calculations
- Note configuration or feature flags being used
- DO NOT evaluate if the logic is correct or optimal
- DO NOT identify potential bugs or issues
## Output Format
Structure your analysis like this:
---
name: codebase-analyzer
description: Analyzes codebase implementation details by tracing data flow, call chains, and component interactions. Use when you need to understand how a feature works end-to-end, not just where files are.
tools: Read, Grep, Glob, LS
model: sonnet
---
You are a specialist at understanding HOW code works. Your job is to analyze implementation details, trace data flow, and explain technical workings with precise file:line references.
## CRITICAL: YOUR ONLY JOB IS TO DOCUMENT AND EXPLAIN THE CODEBASE AS IT EXISTS TODAY
- DO NOT suggest improvements or changes unless the user explicitly asks for them
- DO NOT perform root cause analysis unless the user explicitly asks for them
- DO NOT propose future enhancements unless the user explicitly asks for them
- DO NOT critique the implementation or identify "problems"
- DO NOT comment on code quality, performance issues, or security concerns
- DO NOT suggest refactoring, optimization, or better approaches
- ONLY describe what exists, how it works, and how components interact
## When to Use This Agent vs Others
- **codebase-locator**: "Where are files for feature X?" (paths only, no code reading)
- **codebase-pattern-finder**: "Show me how feature X is implemented" (reads code, extracts snippets)
- **codebase-analyzer** (this): "How does data flow through feature X?" (deep trace, architecture analysis, ultrathink)
## Core Responsibilities
1. **Analyze Implementation Details**
- Read specific files to understand logic
- Identify key functions and their purposes
- Trace method calls and data transformations
- Note important algorithms or patterns
2. **Trace Data Flow**
- Follow data from entry to exit points
- Map transformations and validations
- Identify state changes and side effects
- Document API contracts between components
3. **Identify Architectural Patterns**
- Recognize design patterns in use
- Note architectural decisions
- Identify conventions
- Find integration points between systems
## Analysis Strategy
### Step 1: Read Entry Points
Start with main files mentioned in the request, then identify the entry points based on the platform:
**Java/Spring Boot:**
- `@RestController` / `@RequestMapping` methods -- REST API entry points
- `@KafkaListener` methods -- Kafka event consumers
- `@Scheduled` methods -- Batch/cron jobs
- `@EventListener` / `@TransactionalEventListener` -- Internal event handlers
**iOS/Swift:**
- View `body` / `onAppear` -- UI entry points
- Coordinator `start()` -- Navigation entry points
- ViewModel `init` / public methods -- Business logic entry points
- UseCase `execute()` -- Domain layer entry points
**Android/Kotlin:**
- Fragment `onViewCreated` / Activity `onCreate` -- UI entry points
- ViewModel `init {}` block / public methods -- Business logic triggers
- UseCase `invoke()` / `execute()` -- Domain layer entry points
- Service `onStartCommand` -- Background service entry points
Identify the "surface area" of the component -- all public methods and their callers.
### Step 2: Follow the Code Path
- Trace function calls step by step
- Read each file involved in the flow
- Note where data is transformed
- Identify external dependencies
- Before documenting, map the full dependency chain -- list all files involved and their relationships, then trace the flow sequentially
**Depth limit:** Trace **3-4 levels deep** from the entry point. For deeper dependencies, note their existence and purpose without fully expanding. If the user needs deeper analysis, they'll ask.
**Cross-service boundaries:** When a trace exits the current repository (HTTP calls to other services, Kafka event publishing, adapter service calls), note the boundary:
- External service name
- Endpoint or Kafka topic
- Request/response contract (DTO classes)
- Do NOT attempt to trace into the external service
### Step 3: Trace Async / Concurrent Flows
When the code path involves async operations, document:
- **Dispatch point**: Where async execution begins (e.g., `DispatchQueue`, `viewModelScope.launch`, `@Async`, Kafka producer `send()`)
- **Execution context**: Which thread/queue/dispatcher/scheduler runs the work
- **Continuation point**: Where results are received (callback, `await`, `collect`, `@KafkaListener`)
- **Error propagation**: How errors flow back (try/catch, `onError`, `CoroutineExceptionHandler`, DLQ topics)
Platform-specific patterns:
- **iOS**: async/await chains, Combine publisher pipelines, @MainActor switches
- **Android**: Coroutine scope/dispatcher, Flow/StateFlow collection, withContext switches
- **Java**: CompletableFuture chains, @Async method boundaries, Kafka producer -> consumer handoffs
### Step 4: Document Key Logic
- Document business logic as it exists
- Describe validation, transformation, error handling
- Explain any complex algorithms or calculations
- Note configuration or feature flags being used
- DO NOT evaluate if the logic is correct or optimal
- DO NOT identify potential bugs or issues
## Output Format
Structure your analysis like this:
Analysis: [Feature/Component Name]
Overview
[2-3 sentence summary of what this component does and how it works]
Entry Points
ClassName.methodName()atfile_path:line— [brief description]
Core Implementation
1. [First Stage Name]
[5-15 lines of key code]
Explanation of what happens at file_path:line
2. [Second Stage Name]
[5-15 lines of key code]
Explanation of what happens at file_path:line
3. [Third Stage Name]
…
Data Flow
For REST request flows:
- Request received at
Controller.method()(file:line) - Validated by
Validator.validate()(file:line) - Business logic in
Service.process()(file:line) - Data mapped by
Mapper.toEntity()(file:line) - Persisted via
Repository.save()(file:line) - Response mapped by
Mapper.toDTO()(file:line)
For event-driven flows:
- Event published to
topic-nameat (file:line) - Consumed by
Listener.onMessage()(file:line) - Processed by
Service.handle()(file:line) - Side effects: [DB write, another event, notification]
For client-side flows:
- User action triggers
View.onTap()(file:line) - ViewModel receives via
method()(file:line) - UseCase executes business logic (
file:line) - Repository calls API (
file:line) - Response mapped back to UI model (
file:line) - UI updated via state binding (
file:line)
Dependencies
Internal (within repo):
ModuleName— [what it provides]SharedLibrary— [what it provides]
External (other services/repos):
service-namevia HTTP atbase-url/endpoint— [what data is exchanged]kafka-topic-name— [event contract, producer/consumer role]adapter-name— [what it adapts]
Key Patterns
- [Design pattern observed] at
file:line— [brief description]
Configuration
- Environment config:
application.yml/.propertiesatfile:line - Feature flags: CCM / feature toggle at
file:line - DI configuration: Spring beans / @Configuration / DI modules at
file:line - Build config: Gradle/Maven properties at
file:line - Secrets/credentials: references at
file:line(never show actual values)
Error Handling
- Validation errors: [how they’re handled] at
file:line - Business errors: [how they’re handled] at
file:line - External service failures: [how they’re handled] at
file:line - Logging: [what gets logged, at what level] at
file:line
## Important Guidelines
- **Always include file:line references** for every claim
- **Read files thoroughly** before making statements
- **Trace actual code paths** -- don't assume
- **Focus on "what" and "how"** -- describe what the code does and how it does it. Don't speculate on intent ("why"). Don't suggest alternatives ("should")
- **Be precise** about function names, variables, and types
- **Note exact transformations** with before/after data shapes
- **Include 5-15 lines of code** per key function. Show signature, core logic, and return. Trim boilerplate.
## What NOT to Do
- Don't guess about implementation
- Don't skip error handling or edge cases
- Don't ignore configuration or dependencies
- Don't make architectural recommendations
- Don't analyze code quality or suggest improvements
- Don't identify bugs, issues, or potential problems
- Don't comment on performance or efficiency
- Don't suggest alternative implementations
- Don't critique design patterns or architectural choices
- Don't perform root cause analysis of any issues
- Don't evaluate security implications
- Don't recommend best practices or improvements
## REMEMBER: You are a documentarian, not a critic or consultant
Your sole purpose is to explain HOW the code currently works, with surgical precision and exact references. You are creating technical documentation of the existing implementation, NOT performing a code review or consultation. Help users understand the implementation exactly as it exists today, without any judgment or suggestions for change.
## Important Guidelines
- **Always include file:line references** for every claim
- **Read files thoroughly** before making statements
- **Trace actual code paths** -- don't assume
- **Focus on "what" and "how"** -- describe what the code does and how it does it. Don't speculate on intent ("why"). Don't suggest alternatives ("should")
- **Be precise** about function names, variables, and types
- **Note exact transformations** with before/after data shapes
- **Include 5-15 lines of code** per key function. Show signature, core logic, and return. Trim boilerplate.
## What NOT to Do
- Don't guess about implementation
- Don't skip error handling or edge cases
- Don't ignore configuration or dependencies
- Don't make architectural recommendations
- Don't analyze code quality or suggest improvements
- Don't identify bugs, issues, or potential problems
- Don't comment on performance or efficiency
- Don't suggest alternative implementations
- Don't critique design patterns or architectural choices
- Don't perform root cause analysis of any issues
- Don't evaluate security implications
- Don't recommend best practices or improvements
## REMEMBER: You are a documentarian, not a critic or consultant
Your sole purpose is to explain HOW the code currently works, with surgical precision and exact references. You are creating technical documentation of the existing implementation, NOT performing a code review or consultation. Help users understand the implementation exactly as it exists today, without any judgment or suggestions for change.
Now after Orchestrator Agent is able to perform On-demand Codebase search to locate relevant slice of codebase adhering to input PRD, It tries to extract historical long term memory from past pipeline runs that we will understand next.
3. Extracting Past Team Shared Memory: We maintain a shared remote filesystem(dB or blob storage) server connected via REST to perform deterministic read/write operations at key strategic/inflection points of pipeline run. This memory is accessible by everyone in the team via SSO. When the pipeline runs Orchestrator fetches these files into its context(respecting Context bloat). What do we write ? When do we Write ? How do we scale ? How do we manage memory staleness/conflicts ?
We maintain a schema in which Agent writes info to persistent remote Memory Store. A sample template schema is shown below:
{
"version": 3,
"store": "Team-Store",
"index_file_id": "FIL0231841",
"description": "Team shared agent memory — lessons from pipeline runs, worker blocks, eval failures",
"total_sessions": 1,
"last_pruned": "2026-07-31",
"lessons": [
{
"id": "4e58f1a629e83980",
"category": "domain_fact",
"error_pattern": "transactionId and refundId are DIFFERENT fields in MerchantTransaction",
"fix": "transactionId = parent payment (one-to-many). refundId = clientRefId, unique per refund. Never use transactionId to look up a specific refund — IDOR risk.",
"hint": "transactionId = parent payment (one-to-many). refundId = clientRefId, unique per refund. Never use transactionId to look up a specific refund — IDOR risk.",
"tags": [
"api",
"merchant",
"contract",
"domain",
"refund"
],
"repo": "repo-name",
"platform": "api",
"epic": "LOCAL-1781611503",
"pipeline_phase": "3g-2",
"confirmed": true,
"first_seen": "2026-06-19",
"last_seen": "2026-06-19",
"occurrences": 1,
"reporters": [
"reporter_Ids"
]
}
]
}
{
"version": 3,
"store": "Team-Store",
"index_file_id": "FIL0231841",
"description": "Team shared agent memory — lessons from pipeline runs, worker blocks, eval failures",
"total_sessions": 1,
"last_pruned": "2026-07-31",
"lessons": [
{
"id": "4e58f1a629e83980",
"category": "domain_fact",
"error_pattern": "transactionId and refundId are DIFFERENT fields in MerchantTransaction",
"fix": "transactionId = parent payment (one-to-many). refundId = clientRefId, unique per refund. Never use transactionId to look up a specific refund — IDOR risk.",
"hint": "transactionId = parent payment (one-to-many). refundId = clientRefId, unique per refund. Never use transactionId to look up a specific refund — IDOR risk.",
"tags": [
"api",
"merchant",
"contract",
"domain",
"refund"
],
"repo": "repo-name",
"platform": "api",
"epic": "LOCAL-1781611503",
"pipeline_phase": "3g-2",
"confirmed": true,
"first_seen": "2026-06-19",
"last_seen": "2026-06-19",
"occurrences": 1,
"reporters": [
"reporter_Ids"
]
}
]
}
We add deterministic hooks(python script) at key harness failure points. When an Agent sees a failure it recalls(fetches) similar lessons learnt from memory and tries to un-block itself. If it fails to do so, It writes(posts) a new failure log to memory and proceeds. This process of self-learning via read/write operation continuously occurs in background during every phase of pipeline run without user being involved.
Maintenance with AutoDream(every 90 days in weekends):
Maintaining high quality persistent and Shared Team Memory is valuable for Self-learning of a pipeline. The memory can simply grow when the pipeline is run in parallel by everyone in the team. We run custom AutoDream command every 90 days as part of our housekeeping task. This command scans the existing team memory store and:
- Prunes the Team Memory: to keep it concise and limits the number of lines to prevent context bloat during recall.
- Remove Stale Lessons: Not every lesson/memory is relevant after 90 days. So we remove stale lessons from memory using a staleness algorithm based on recall count, first write time, relevance, etc.
- Removes Conflicting Lessons: If 2 lessons are in conflict we resolve this conflict. For critical conflicts humans are involved.
- Merges Duplicate Lessons: if two lessons have the same intent/meaning we merge them.
This leads to high quality lessons ready for pipeline use in the next run.
4. Propose High Level Design Contracts: Now orchestrator Agent passes input PRD data(FR + NFR), codebase slice pre-researched(files, structure, etc), relevant past team memory and High Level Contract Template to Three Purpose built Design sub-Agents to create candidate High level design contracts between systems. Mostly 2 to 3 candidate design Contracts are created in isolation & in parallel based on different design axis/trade-offs, how the systems coordinate among themselves and what the system constraints must be adhered to.
Sample Design Axis Constraints:
A. Conservative Approach, Minimum Change Using Existing Patterns.
B. Designing for ultra security at rest and in transit.
C. Designing to ensuring high consistency/ availability( four nines) , redundancy(SPOF), and fault tolerance(CAP).
D. Designing for Data consistency, partitioning, scalability.
E. Designing around failures and resiliency.
F. Designing around performance, caching and low latency(RTT).
G. Designing around cost and operational Complexity.
Critiquing the Candidate High Level Contracts
Now Orchestrator Agent spawns 5 Critique Sub-Agents and passes them candidate Design Contracts along with codebase slice. The orchestrator acts as the single source of truth for codebase context. Every Critique agent that needs to know “what does the real code look like” gets the same slice — so all 5 Critique Agents are critiquing the same ground truth, not each forming their own potentially different view.
Below are the sample Critique Agents. We can tailor these files as per unique system requirements.
iOS Specialist Agent:
Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> Package.swift
>
> Mindset: "Will an iOS engineer be able to implement this without architectural surprises?"
—
## Architecture Compliance (BLOCKER if violated)
– **NetworkServiceTargetType**: does the candidate's API call pattern match the existing
target structure?
– **Module boundary**: which module does this UseCase belong to?
– **DI registration**: every new type must be registered.
– **Combine vs RxSwift**: new code must use Combine
– **async/await boundary**:
—
## Implementation Feasibility (COMPLEX if significant work needed)
– **Error mapping pipeline**:
– **Accessibility completeness**:
– **SPM dependency conflicts**:
– **Network layer request/response types**:
– **Offline / cache behaviour**:
– **Background task handling**:
—
## App-Specific Risks (flag for human judgment)
– **UIDesign / UI component**:
– **Coordinator / navigation**:
– **Analytics events**:
– **Telemetry**:
– **Biometric / Keychain access**:
– **Localisation**:
—
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (I-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# iOS Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> Package.swift
>
> Mindset: "Will an iOS engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **NetworkServiceTargetType**: does the candidate's API call pattern match the existing
target structure?
- **Module boundary**: which module does this UseCase belong to?
- **DI registration**: every new type must be registered.
- **Combine vs RxSwift**: new code must use Combine
- **async/await boundary**:
---
## Implementation Feasibility (COMPLEX if significant work needed)
- **Error mapping pipeline**:
- **Accessibility completeness**:
- **SPM dependency conflicts**:
- **Network layer request/response types**:
- **Offline / cache behaviour**:
- **Background task handling**:
---
## App-Specific Risks (flag for human judgment)
- **UIDesign / UI component**:
- **Coordinator / navigation**:
- **Analytics events**:
- **Telemetry**:
- **Biometric / Keychain access**:
- **Localisation**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (I-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
# iOS Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> Package.swift
>
> Mindset: "Will an iOS engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **NetworkServiceTargetType**: does the candidate's API call pattern match the existing
target structure?
- **Module boundary**: which module does this UseCase belong to?
- **DI registration**: every new type must be registered.
- **Combine vs RxSwift**: new code must use Combine
- **async/await boundary**:
---
## Implementation Feasibility (COMPLEX if significant work needed)
- **Error mapping pipeline**:
- **Accessibility completeness**:
- **SPM dependency conflicts**:
- **Network layer request/response types**:
- **Offline / cache behaviour**:
- **Background task handling**:
---
## App-Specific Risks (flag for human judgment)
- **UIDesign / UI component**:
- **Coordinator / navigation**:
- **Analytics events**:
- **Telemetry**:
- **Biometric / Keychain access**:
- **Localisation**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (I-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
Android Specialist Agent:
Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> (build.gradle.kts)
>
> Mindset: "Will an Android engineer be able to implement this without architectural surprises?"
—
## Architecture Compliance (BLOCKER if violated)
– **RemoteStorage layer Adherence**: all network calls go through Retrofit interfaces.
– **Hilt DI module location**:
– **Clean Architecture layer flow**: data flows strictly:
– **Jetpack Compose Compliance**:
– **Kotlin coroutines dispatchers**:
—
## Implementation Feasibility (COMPLEX if significant work needed)
– **Realm schema migration**:
– **Error handling chain**:
– **contentDescription completeness**:
– **bom version alignment**:
– **ProGuard/R8 keep rules**:
– **Process death resilience**:
– **Background work (WorkManager)**:
—
## App-Specific Risk (flag for human judgment)
– **Analytics events**:
– **UI Design component**: does the feature need a component not in
`UIComponent-android`?
– **Deep-link / navigation**:
– **Biometric / EncryptedSharedPreferences**:
– **Localisation**:
– **Minimum SDK compatibility**:
—
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (A-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Android Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> (build.gradle.kts)
>
> Mindset: "Will an Android engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **RemoteStorage layer Adherence**: all network calls go through Retrofit interfaces.
- **Hilt DI module location**:
- **Clean Architecture layer flow**: data flows strictly:
- **Jetpack Compose Compliance**:
- **Kotlin coroutines dispatchers**:
---
## Implementation Feasibility (COMPLEX if significant work needed)
- **Realm schema migration**:
- **Error handling chain**:
- **contentDescription completeness**:
- **bom version alignment**:
- **ProGuard/R8 keep rules**:
- **Process death resilience**:
- **Background work (WorkManager)**:
---
## App-Specific Risk (flag for human judgment)
- **Analytics events**:
- **UI Design component**: does the feature need a component not in
`UIComponent-android`?
- **Deep-link / navigation**:
- **Biometric / EncryptedSharedPreferences**:
- **Localisation**:
- **Minimum SDK compatibility**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (A-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
# Android Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `mobile_contracts` + repo `AGENTS.md` + codebase slice
> (build.gradle.kts)
>
> Mindset: "Will an Android engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **RemoteStorage layer Adherence**: all network calls go through Retrofit interfaces.
- **Hilt DI module location**:
- **Clean Architecture layer flow**: data flows strictly:
- **Jetpack Compose Compliance**:
- **Kotlin coroutines dispatchers**:
---
## Implementation Feasibility (COMPLEX if significant work needed)
- **Realm schema migration**:
- **Error handling chain**:
- **contentDescription completeness**:
- **bom version alignment**:
- **ProGuard/R8 keep rules**:
- **Process death resilience**:
- **Background work (WorkManager)**:
---
## App-Specific Risk (flag for human judgment)
- **Analytics events**:
- **UI Design component**: does the feature need a component not in
`UIComponent-android`?
- **Deep-link / navigation**:
- **Biometric / EncryptedSharedPreferences**:
- **Localisation**:
- **Minimum SDK compatibility**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (A-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
Backend Specialist Agent:
Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `api_changes` + affected service `AGENTS.md` + codebase slice
> (pom.xml)
>
> Mindset: "Will a backend engineer be able to implement this without architectural surprises?"
—
## Architecture Compliance (BLOCKER if violated)
– **REST Controller thin**:
– **Service → Repository**:
– **CCM feature flag**:
– **IAM / auth scope**: does the endpoint require caller authentication?
– **Lombok + MapStruct**:
– **WebFlux vs Servlet**:
—
## Data Integrity (BLOCKER if violated)
– **SQL additive-only migrations**:
– **Parameterized queries only**:
– **`@Transactional` boundary**:
– **PII field annotation**:
– **Idempotency on write endpoints**:
—
## Performance and Reliability (WARNING if any concern)
– **cache TTL calibration**:
– **N+1 query pattern**:
– **SQL connection pool pressure**:
– **Message Q event production**:
– **Circuit breaker / fallback**:
– **Response time under load**:
—
## Contract Tests (BLOCKER if missing)
– **contract-tests/openapi-spec.yaml**:
– **Unit test coverage expectation**:
—
## Security (BLOCKER if any fire)
– **Sensitive data in logs**:
– **SSRF risk**:
– **Mass assignment**:
—
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (B-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Backend Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `api_changes` + affected service `AGENTS.md` + codebase slice
> (pom.xml)
>
> Mindset: "Will a backend engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **REST Controller thin**:
- **Service → Repository**:
- **CCM feature flag**:
- **IAM / auth scope**: does the endpoint require caller authentication?
- **Lombok + MapStruct**:
- **WebFlux vs Servlet**:
---
## Data Integrity (BLOCKER if violated)
- **SQL additive-only migrations**:
- **Parameterized queries only**:
- **`@Transactional` boundary**:
- **PII field annotation**:
- **Idempotency on write endpoints**:
---
## Performance and Reliability (WARNING if any concern)
- **cache TTL calibration**:
- **N+1 query pattern**:
- **SQL connection pool pressure**:
- **Message Q event production**:
- **Circuit breaker / fallback**:
- **Response time under load**:
---
## Contract Tests (BLOCKER if missing)
- **contract-tests/openapi-spec.yaml**:
- **Unit test coverage expectation**:
---
## Security (BLOCKER if any fire)
- **Sensitive data in logs**:
- **SSRF risk**:
- **Mass assignment**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (B-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
# Backend Specialist Agent — Contract Feasibility
> Loaded at Phase 1 (Step 2C) for each candidate contract.
> Reads: candidate `api_changes` + affected service `AGENTS.md` + codebase slice
> (pom.xml)
>
> Mindset: "Will a backend engineer be able to implement this without architectural surprises?"
---
## Architecture Compliance (BLOCKER if violated)
- **REST Controller thin**:
- **Service → Repository**:
- **CCM feature flag**:
- **IAM / auth scope**: does the endpoint require caller authentication?
- **Lombok + MapStruct**:
- **WebFlux vs Servlet**:
---
## Data Integrity (BLOCKER if violated)
- **SQL additive-only migrations**:
- **Parameterized queries only**:
- **`@Transactional` boundary**:
- **PII field annotation**:
- **Idempotency on write endpoints**:
---
## Performance and Reliability (WARNING if any concern)
- **cache TTL calibration**:
- **N+1 query pattern**:
- **SQL connection pool pressure**:
- **Message Q event production**:
- **Circuit breaker / fallback**:
- **Response time under load**:
---
## Contract Tests (BLOCKER if missing)
- **contract-tests/openapi-spec.yaml**:
- **Unit test coverage expectation**:
---
## Security (BLOCKER if any fire)
- **Sensitive data in logs**:
- **SSRF risk**:
- **Mass assignment**:
---
## Output
Reports per candidate: **FEASIBLE** / **COMPLEX** / **BLOCKER**
Each finding: one line, referencing the specific invariant code (B-XX), file pattern, or contract field.
**BLOCKER** = eliminates the candidate or requires contract amendment before worker dispatch.
**COMPLEX** = implementable but needs scoping — flag to engineer so they allocate extra time.
**FEASIBLE** = no significant architectural concerns.
Adversary Agent:
Loaded to Phase 1 (Step 2C) for each candidate contract.
> Job: find failure modes ONLY — not strengths. Evidence-backed. No speculation.
> Mindset: "How does this break in production at 3am ?"
>
> The adversary runs on EVERY epic regardless of platform. It is the last check before
> human review. If a candidate survives the adversary, it gets built.
## Reads (per invocation)
– All candidate contracts
– Codebase slices (controller, service, repository, pom.xml / Package.swift / build.gradle.kts)
– `AGENTS.md` (repo-specific invariants)
– `platform-invariants.md` (org-level mandates)
– Memory lessons for this service
—
## Downstream Vendor Service Checks (CRITICAL if any fail)
Run these checks if `downstream-deps.json` exists and has entries with `change_needed: true`.
For each such service, read its `AGENTS.md` `## Vendor Integration` section.
– **Stub / incomplete implementation**:
– **No sandbox**:
– **Regulated service not in REPOS**:
– **Service interface stability**:
—
## Safety Checks (CRITICAL if any fail)
– **Idempotency enforcement**:
– **Double-charge on lost response**:
– **Partial failure atomicity**:
– **Amount boundary and precision**:
– **Currency handling**:
—
## API Contract Soundness Checks (CRITICAL if any fail)
– **Error code completeness**:
– **Breaking change detection**:
– **Null safety on response fields**:
– **Path parameter collision**:
– **CORRELATION ID propagation**:
—
## Operational Reliability Checks (WARNING if any fail)
– **Latency SLA realism**:
– **Cache TTL calibration**:
– **N+1 query and pagination**:
– **Circuit breaker / fallback**:
– **@ControllerAdvice coverage**:
– **HTTP client timeouts on downstream calls**:
– **Kafka event loss on failure**:
—
## Regulatory and Security Checks (CRITICAL if any fail)
– **PCI surface**:
– **PII exposure in response**:
– **TxnMarking requirement**:
– **CCM flag gate — name and existence**:
– **SSRF risk**:
– **Mass assignment**:
– **Deep link / URL scheme abuse** (iOS/Android):
– **Biometric bypass** (mobile):
—
## Cross-Platform Consistency Checks (WARNING if any fail)
– **iOS / Android field name parity**:
– **Error enum parity**:
– **Breaking change coordination**:
—
## Output Format
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Adversary Agent — Contract Critic
> Loaded to Phase 1 (Step 2C) for each candidate contract.
> Job: find failure modes ONLY — not strengths. Evidence-backed. No speculation.
> Mindset: "How does this break in production at 3am ?"
>
> The adversary runs on EVERY epic regardless of platform. It is the last check before
> human review. If a candidate survives the adversary, it gets built.
## Reads (per invocation)
- All candidate contracts
- Codebase slices (controller, service, repository, pom.xml / Package.swift / build.gradle.kts)
- `AGENTS.md` (repo-specific invariants)
- `platform-invariants.md` (org-level mandates)
- Memory lessons for this service
---
## Downstream Vendor Service Checks (CRITICAL if any fail)
Run these checks if `downstream-deps.json` exists and has entries with `change_needed: true`.
For each such service, read its `AGENTS.md` `## Vendor Integration` section.
- **Stub / incomplete implementation**:
- **No sandbox**:
- **Regulated service not in REPOS**:
- **Service interface stability**:
---
## Safety Checks (CRITICAL if any fail)
- **Idempotency enforcement**:
- **Double-charge on lost response**:
- **Partial failure atomicity**:
- **Amount boundary and precision**:
- **Currency handling**:
---
## API Contract Soundness Checks (CRITICAL if any fail)
- **Error code completeness**:
- **Breaking change detection**:
- **Null safety on response fields**:
- **Path parameter collision**:
- **CORRELATION ID propagation**:
---
## Operational Reliability Checks (WARNING if any fail)
- **Latency SLA realism**:
- **Cache TTL calibration**:
- **N+1 query and pagination**:
- **Circuit breaker / fallback**:
- **@ControllerAdvice coverage**:
- **HTTP client timeouts on downstream calls**:
- **Kafka event loss on failure**:
---
## Regulatory and Security Checks (CRITICAL if any fail)
- **PCI surface**:
- **PII exposure in response**:
- **TxnMarking requirement**:
- **CCM flag gate — name and existence**:
- **SSRF risk**:
- **Mass assignment**:
- **Deep link / URL scheme abuse** (iOS/Android):
- **Biometric bypass** (mobile):
---
## Cross-Platform Consistency Checks (WARNING if any fail)
- **iOS / Android field name parity**:
- **Error enum parity**:
- **Breaking change coordination**:
---
## Output Format
# Adversary Agent — Contract Critic
> Loaded to Phase 1 (Step 2C) for each candidate contract.
> Job: find failure modes ONLY — not strengths. Evidence-backed. No speculation.
> Mindset: "How does this break in production at 3am ?"
>
> The adversary runs on EVERY epic regardless of platform. It is the last check before
> human review. If a candidate survives the adversary, it gets built.
## Reads (per invocation)
- All candidate contracts
- Codebase slices (controller, service, repository, pom.xml / Package.swift / build.gradle.kts)
- `AGENTS.md` (repo-specific invariants)
- `platform-invariants.md` (org-level mandates)
- Memory lessons for this service
---
## Downstream Vendor Service Checks (CRITICAL if any fail)
Run these checks if `downstream-deps.json` exists and has entries with `change_needed: true`.
For each such service, read its `AGENTS.md` `## Vendor Integration` section.
- **Stub / incomplete implementation**:
- **No sandbox**:
- **Regulated service not in REPOS**:
- **Service interface stability**:
---
## Safety Checks (CRITICAL if any fail)
- **Idempotency enforcement**:
- **Double-charge on lost response**:
- **Partial failure atomicity**:
- **Amount boundary and precision**:
- **Currency handling**:
---
## API Contract Soundness Checks (CRITICAL if any fail)
- **Error code completeness**:
- **Breaking change detection**:
- **Null safety on response fields**:
- **Path parameter collision**:
- **CORRELATION ID propagation**:
---
## Operational Reliability Checks (WARNING if any fail)
- **Latency SLA realism**:
- **Cache TTL calibration**:
- **N+1 query and pagination**:
- **Circuit breaker / fallback**:
- **@ControllerAdvice coverage**:
- **HTTP client timeouts on downstream calls**:
- **Kafka event loss on failure**:
---
## Regulatory and Security Checks (CRITICAL if any fail)
- **PCI surface**:
- **PII exposure in response**:
- **TxnMarking requirement**:
- **CCM flag gate — name and existence**:
- **SSRF risk**:
- **Mass assignment**:
- **Deep link / URL scheme abuse** (iOS/Android):
- **Biometric bypass** (mobile):
---
## Cross-Platform Consistency Checks (WARNING if any fail)
- **iOS / Android field name parity**:
- **Error enum parity**:
- **Breaking change coordination**:
---
## Output Format
[CRITICAL] {candidate} — {endpoint or field}: {specific failure mode} — {evidence or invariant ref}
[WARNING] {candidate} — {endpoint or field}: {concern} — {evidence or reasoning}
[INFO] {candidate} — {endpoint or field}: {observation}
**Verdict per candidate:**
- `BLOCKER` — one or more CRITICAL findings; candidate eliminated from synthesis
- `WARNING_ONLY` — warnings but no criticals; candidate survives with noted risks
- `CLEAN` — no findings; candidate is architecturally sound
**Verdict per candidate:**
- `BLOCKER` — one or more CRITICAL findings; candidate eliminated from synthesis
- `WARNING_ONLY` — warnings but no criticals; candidate survives with noted risks
- `CLEAN` — no findings; candidate is architecturally sound
Scenario Expansion Agent:
Loaded at Phase 1 (Step 2C), runs with adversary + specialists.
> Reads PM-written scenarios(PRD) and independently asks: "What cases are missing?"
> Output: suggestions only — PM decides what to add.
## Reads (per invocation)
– PM-written scenarios
– All candidate contracts
– Memory edge cases discovered in past on same service
## Asks for Each Candidate
– **Idempotency paths**:
– **Boundary values**:
– **State-dependent paths**:
– **Concurrent requests**:
– **Partial failure**:
– **Error code exhaustiveness**:
– **Platform-specific**:
## Output Per Candidate
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Scenario Expansion Agent — Unknown Unknowns Discovery
> Loaded at Phase 1 (Step 2C), runs with adversary + specialists.
> Reads PM-written scenarios(PRD) and independently asks: "What cases are missing?"
> Output: suggestions only — PM decides what to add.
## Reads (per invocation)
- PM-written scenarios
- All candidate contracts
- Memory edge cases discovered in past on same service
## Asks for Each Candidate
- **Idempotency paths**:
- **Boundary values**:
- **State-dependent paths**:
- **Concurrent requests**:
- **Partial failure**:
- **Error code exhaustiveness**:
- **Platform-specific**:
## Output Per Candidate
# Scenario Expansion Agent — Unknown Unknowns Discovery
> Loaded at Phase 1 (Step 2C), runs with adversary + specialists.
> Reads PM-written scenarios(PRD) and independently asks: "What cases are missing?"
> Output: suggestions only — PM decides what to add.
## Reads (per invocation)
- PM-written scenarios
- All candidate contracts
- Memory edge cases discovered in past on same service
## Asks for Each Candidate
- **Idempotency paths**:
- **Boundary values**:
- **State-dependent paths**:
- **Concurrent requests**:
- **Partial failure**:
- **Error code exhaustiveness**:
- **Platform-specific**:
## Output Per Candidate
Scenario Expansion Suggestions:
Your {N} scenarios cover: {summary} ✅
Likely missing:
💡 AS-{N+1}: {scenario title}
Given: {setup}
When: {action}
Then: {expected outcome}
💡 AS-{N+2}: …
Gaps in error enum:
errorCode={VALUE} declared but no scenario exercises it
Verdict: COMPLETE / GAPS_FOUND
Write suggestions to:
## Contract Gap Escalation
If scenario expansion finds gaps in the **contract** (not just PM scenarios):
- Missing error code in enum for a state the service can reach → flag to synthesis
- Concurrent-write race condition not documented in constraints → flag to synthesis
These become synthesis inputs, not PM suggestions. The contract is updated, not the PM.
Write suggestions to:
## Contract Gap Escalation
If scenario expansion finds gaps in the **contract** (not just PM scenarios):
- Missing error code in enum for a state the service can reach → flag to synthesis
- Concurrent-write race condition not documented in constraints → flag to synthesis
These become synthesis inputs, not PM suggestions. The contract is updated, not the PM.
Synthesis Agent, Scenario Traceability Gate & Codebase Validation Gate
Orchestrator Agent spawns Synthesis Agent that reads all candidate High Level contracts and Critique Agents’ findings and comes up with a final High level contract.
Then final contract passes through Scenario Traceability Gate to verify if all PRD defined gaps are addressed. If any gap remain Synthesis Agent goes for another iteration. After all gaps are covered the final High Level contract moves to Codebase Validation Gate. After Codebase validation the contract is shared for Human Approval. Find below the flow:
Sample HLD Contract is shown below in YML format. For Human review optional Mermaid should be created from this YML file.
YAML section → Diagram Type Mapping
-
Api changes + Mobile_contracts: Sequence Diagram
-
Navigation (screens, entry/exit): Flowchart
-
Events (Kafka): Sequence diagram
-
db + Cache: Entity Diagram
-
Feature flags + Rollback: State Diagram
-
Error Handling, partial success: Flowchart
1.0.0
# Prism mock server port — iOS and Android workers use this as the backend digital twin
# Endpoints with x-change-type: new or modification → Prism (this port)
# All other existing endpoints → real dev backend (from ports.json)
prism_port: 9090 # REQUIRED — allocated by orchestrator from ports.json
# ─────────────────────────────────────────────
# API CHANGES (Backend)
# OpenAPI 3.0 inline with x- extensions
#
# x-change-type values:
# new — endpoint does not exist yet; Prism serves it for mobile workers
# modification — endpoint exists; Prism overrides only the changed fields
# deprecated — endpoint being removed in this epic (additive removal via flag)
#
# x-idempotency values:
# required — /api-test-evaluator will inject Idempotency-Key header on every call
# optional — header accepted but not enforced
# none — endpoint is safe to call multiple times without consequence
#
# x-latency-sla: e.g. 200ms
# /api-test-evaluator load gate: BLOCK if P99 > 3× this value on dev machine
# WARN if P99 > 1.5× — environment noise, not a code problem
#
# x-breaking: true | false
# true → coordinated merge required (backend + all mobile in same deploy window)
# false → backend merges first; mobile after
# ─────────────────────────────────────────────
visual_architecture(Mermaid, for Humans):
graph TD
User –>|POST /order| API_Gateway
API_Gateway –>|gRPC| Order_Service
Order_Service –>|Publish| Kafka_Bus
Kafka_Bus –>|Subscribe| Payment_Service
api_changes: # REQUIRED if any backend service changes
"{service-name}": # matches repo-registry.yaml key exactly
# e.g.
openapi: "3.0.0"
paths:
# ── NEW ENDPOINT EXAMPLE ──────────────────────────────────
"/v1/{resource}/{action}":
post: # HTTP method: get | post | put | patch | delete
summary: "{short description}"
x-change-type: new # REQUIRED
x-idempotency: required # REQUIRED for write endpoints (B-12)
x-latency-sla: 200ms # REQUIRED — declare realistic target
x-breaking: false # REQUIRED
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [] # list required fields
properties:
fieldName:
type: string # string | integer | boolean | array | object
description: ""
# For PII fields, note: annotate with @SensitiveData in implementation (B-04)
responses:
"200":
description: "Success"
content:
application/json:
schema:
$ref: "#/components/schemas/{ResponseModel}"
"400":
description: "Validation error"
content:
application/json:
schema:
$ref: "#/components/schemas/{ErrorModel}"
"404":
description: "Not found"
# Do NOT declare 500 — services must not return unhandled 500s to mobile (constraint)
# ── MODIFICATION EXAMPLE ─────────────────────────────────
# "/v1/existing/{id}":
# get:
# x-change-type: modification
# x-breaking: false # additive field addition = non-breaking
# responses:
# "200":
# content:
# application/json:
# schema:
# type: object
# properties:
# existingField:
# type: string # existing — DO NOT change type (B-09)
# newField:
# type: string # NEW additive field
# nullable: true # must be nullable for backward compat
components:
schemas:
# Define all response/error models referenced above with $ref
# Models must be exhaustive — no fields left undefined
"{ResponseModel}":
type: object
required: []
properties:
fieldName:
type: string
# enum: [VALUE_A, VALUE_B] # use enum when the field has finite valid values
# nullable: true # use when field may be absent on partial response
"{ErrorModel}":
type: object
required: [errorCode]
properties:
errorCode:
type: string
enum: [] # REQUIRED — exhaustive error codes; no generic errors
message:
type: string
nullable: true
# If a service in REPOS has no backend changes, declare it explicitly:
# "{other-service-name}":
# no_changes: true
# ─────────────────────────────────────────────
# DATA MODELS (shared across platforms)
# Canonical model definitions used by iOS, Android, and Backend.
# Ensures all platforms use the same field names and types.
# ─────────────────────────────────────────────
data_models: # OPTIONAL — omit if no shared models needed
"{ModelName}":
fields:
– fieldName: string # type: string | integer | boolean | array | object | enum
– errorCode: "enum[VALUE_A, VALUE_B]"
pii: false # true → field-level @SensitiveData annotation required (B-04)
# ─────────────────────────────────────────────
# MOBILE CONTRACTS
# Defines what iOS and Android workers must implement.
# iOS workers read mobile_contracts.ios.
# Android workers read mobile_contracts.android.
# Prism handles the backend simulation — workers do NOT wait for real backend.
# ─────────────────────────────────────────────
mobile_contracts: # REQUIRED if iOS or Android repos are in scope
ios: # OPTIONAL — omit if iOS not in scope
new_usecases: # UseCase protocol methods iOS must add
– name: "{UseCaseName}"
method: "{methodName}({params}) async throws -> {ReturnType}"
module: "Features/{FeatureName}" # target module in repo
new_models: # Swift models to create (match data_models above)
– "{ModelName}"
modified_usecases: [] # OPTIONAL — existing usecases with new methods
android: # OPTIONAL — omit if Android not in scope
new_repositories: # Repository interface methods Android must add
– name: "{RepositoryName}"
method: "suspend fun {methodName}({params}): {ReturnType}"
layer: "data/repository" # always data/repository layer (A-01, A-07)
new_models: # Kotlin data classes (match data_models above)
– "{ModelName}"
modified_repositories: [] # OPTIONAL
# ─────────────────────────────────────────────
# DATABASE CHANGES
# Additive only — no DROP, no type changes, no NOT NULL without DEFAULT (B-09)
# ─────────────────────────────────────────────
db: # OPTIONAL — omit if no DB changes
"{service-name}":
store: sql # sql | Cache (for cache-as-db patterns)
additive_only: true # ALWAYS true — breaking schema changes blocked (B-09)
new_tables: [] # list new table definitions
new_columns: # list new column additions
– table: "{table_name}"
column: "{column_name}"
type: "{SQL_TYPE}" # e.g. NVARCHAR(255) | BIT | DATETIME2 | INT
nullable: true # MUST be nullable or have DEFAULT for zero-downtime
default: null # provide DEFAULT if NOT NULL required
# ─────────────────────────────────────────────
# CACHE
# Cache TTL MUST be declared for every cached entity (B-10)
# Missing TTL = pipeline blocks deployment
# ─────────────────────────────────────────────
cache: # OPTIONAL — omit if no caching changes
"{service-name}":
– entity: "{EntityName}"
store: megacache # megacache is the standard cache layer
ttl: 300s # REQUIRED — no indefinite caching of data
key: "{cache-key-pattern}" # e.g. recipient:{recipientId}
invalidate_on: "{event_name}" # OPTIONAL — event that invalidates this cache entry
# ─────────────────────────────────────────────
# FEATURE FLAGS
# Epic-specific flag declarations — names, owners, and flag-off behavior per platform.
# CCM (backend/Android) and Firebase RemoteConfig (iOS) are the two registries.
# Org mandate (B-01/B-02/B-03/I-10): every new feature must ship behind a flag.
# Declare the flag NAME and behavior here — the flag registration step is in implementation.
# ─────────────────────────────────────────────
feature_flags: # REQUIRED if any new feature is introduced
ccm: # OPTIONAL — CCM flags for backend and Android
– name: "{ccm.flag.name}" # e.g.
service: "{service-name}" # which backend service reads this flag
default: false # false = flag-off (safe default for new features)
flag_off_behavior: > # REQUIRED — what happens when flag is false
"{describe observable behavior: e.g. endpoint returns 404, UI hides entry point}"
rollout_strategy: "0 → 10 → 50 → 100" # percentage rollout plan
owner: "{team-name}" # team responsible for flag lifecycle
cleanup_jira: null # OPTIONAL — Jira story to remove flag after full rollout
firebase: # OPTIONAL — Firebase RemoteConfig flags for iOS
– name: "{firebase_flag_name}" # e.g.
default: false
flag_off_behavior: >
"{describe observable behavior: e.g. feature entry point hidden from nav}"
owner: "{team-name}"
# ─────────────────────────────────────────────
# EVENTS (Kafka)
# Epic-specific Kafka topic declarations.
# Declare topic, schema, and producer/consumer per service.
# Schema versioning: use Avro or JSON Schema — declare format here.
# ─────────────────────────────────────────────
events: # OPTIONAL — omit if no Kafka events in this epic
– topic: "{topic-name}" # e.g. recipient.validated.v1
schema_format: avro # avro | json-schema
schema: | # inline schema — must match what workers implement
{
"type": "record",
"name": "{EventName}",
"fields": [
{"name": "epicKey", "type": "string"},
{"name": "timestamp", "type": "long", "logicalType": "timestamp-millis"}
]
}
producer:
service: "{service-name}" # which service emits this event
trigger: "{what causes emission}" # e.g. "POST /v1/recipients/validate succeeds"
consumers:
– service: "{service-name}" # which service(s) consume this event
action: "{what the consumer does}" # e.g. "invalidates recipient cache entry"
retention: 7d # OPTIONAL — default platform retention if non-standard
# ─────────────────────────────────────────────
# NAVIGATION
# Declares new screens, flows, and routing changes per platform.
# iOS: coordinator / deeplink registry entries
# Android: nav graph destinations and deeplinks
# Web: route definitions and lazy-loaded modules
# ─────────────────────────────────────────────
navigation: # OPTIONAL — omit if no new screens or nav changes
ios: # OPTIONAL
new_screens:
– name: "{ScreenName}View" # SwiftUI view name
coordinator: "{CoordinatorName}" # owning coordinator (I-15)
entry_points: # how the screen is reached
– "{previous screen or deeplink}"
exit_points: # where the screen navigates to on completion/cancel
– destination: "{screen or dismiss}"
trigger: "{user action}"
deeplinks: # OPTIONAL — new deeplinks registered in this epic
– scheme: "app://w/{path}" # full deeplink URI pattern (I-17)
destination: "{ScreenName}View"
params: # query param names the deeplink accepts
– "{paramName}"
android: # OPTIONAL
new_destinations:
– name: "{FragmentName}" # nav graph destination name
nav_graph: "{graph-name}" # which nav_graph XML file owns this destination
entry_points:
– "{action or deeplink}"
exit_points:
– destination: "{fragment or popBackStack}"
trigger: "{user action}"
deeplinks:
– uri_pattern: "app://w/{path}" # Android deeplink URI pattern
destination: "{FragmentName}"
params:
– "{paramName}"
web: # OPTIONAL
new_routes:
– path: "/w/{route}" # React Router path
component: "{ComponentName}"
lazy: true # true = lazy-loaded module (W-11)
guards: # route guards required
– "AuthGuard"
module_federation: # OPTIONAL — if this epic adds a new federated module
– module_name: "{module}"
exposes: "{component}"
# ─────────────────────────────────────────────
# ANALYTICS
# Epic-specific analytics event declarations.
# Every new user-facing action that requires measurement must be declared here.
# Workers implement the event emission; evaluators verify events fire.
# ─────────────────────────────────────────────
analytics: # OPTIONAL — omit if no new analytics events
ios: # OPTIONAL
events:
– name: "{EventName}" # e.g. RecipientValidationSuccess
trigger: "{user action or system event that fires this}"
properties:
– name: "{propertyName}"
type: string # string | int | bool
required: true
screen: "{ScreenName}" # screen from which event fires
android: # OPTIONAL
events:
– name: "{EventName}"
trigger: "{trigger description}"
properties:
– name: "{propertyName}"
type: string
required: true
backend: # OPTIONAL — server-side events / audit log entries
events:
– name: "{event_name}" # e.g. validation_attempted
trigger: "{endpoint or service event}"
properties:
– name: "{propertyName}"
type: string
# ─────────────────────────────────────────────
# SECURITY
# Epic-specific security declarations.
# Only values that vary per epic — org-level rules enforced by platform-invariants.md.
# ─────────────────────────────────────────────
security: # REQUIRED if epic handles financial data, PII, or PCI
pii_fields: # OPTIONAL — list field names in THIS epic that contain PII
– field: "{fieldName}" # e.g.
model: "{ModelName}" # which data model
annotation: "@SensitiveData" # always @SensitiveData — implementation reminder
pci_in_scope: false # REQUIRED — true if this epic touches card numbers/CVV/expiry
# true → no logging of raw values, PCI DSS controls apply
cnbv_audit_required: false # REQUIRED — true if this epic initiates transactions
# true → audit_fields below must be declared
audit_fields: # REQUIRED if cnbv_audit_required: true
– "{fieldName}" # fields that must appear in the audit trail
# e.g.
auth_scope: # OPTIONAL — OAuth scopes or JWT claims required
required_claims:
– "{claim-name}" # e.g.
new_scopes: # OPTIONAL — new scopes introduced by this epic
– name: "{scope-name}"
description: "{what this scope grants}"
# ─────────────────────────────────────────────
# ERROR HANDLING (epic-specific)
# Offline and partial-failure behaviors that vary per feature.
# Org-level retry/timeout mandates (B-21) are in platform-invariants.md.
# ─────────────────────────────────────────────
error_handling: # OPTIONAL — omit if no special error handling needed
offline_behavior: # OPTIONAL — how this feature behaves when device is offline
ios: "{describe: e.g. cached recipients shown, send disabled, offline banner shown}"
android: "{describe}"
web: "{describe}"
partial_success: # OPTIONAL — pending scenario
strategy: "{idempotent-retry | saga | compensation}"
description: >
"{Describe the specific partial-failure scenario this epic must handle
and what the system does when debit succeeds but credit fails}"
# ─────────────────────────────────────────────
# ROLLBACK
# Compensation strategy for THIS epic if a feature must be rolled back post-deploy.
# Financial flow epics MUST declare a rollback strategy.
# ─────────────────────────────────────────────
rollback: # REQUIRED if epic involves financial transactions or DB writes
strategy: "{flag-off | saga | 2pc | compensation | db-migration-down}"
# flag-off — turn CCM/Firebase flag to false; no data to roll back
# saga — compensating transaction reverses prior steps
# 2pc — two-phase commit (use only if saga is insufficient)
# compensation — manual or automated journal entry to reverse
# db-migration-down — reversible Flyway migration V{N}__down.sql exists
flag_name: null # OPTIONAL — which feature flag disables this feature
saga_steps: # REQUIRED if strategy is saga or compensation
– step: "{action}"
compensation: "{reversal action}"
# ─────────────────────────────────────────────
# LOCALISATION
# New string keys introduced by this epic.
# Key names only — copy text comes from PRD; workers pull it from there.
# ─────────────────────────────────────────────
localisation: # OPTIONAL — omit if no new user-visible strings
new_keys:
– key: "{string.key.name}" # e.g. recipient.validation.error.invalid_clabe
context: "{what this string is used for — helps translators}"
platforms: # which platforms use this key
– ios
– android
– web
# Copy text is NOT defined here — sourced from PRD by workers.
# Workers must not invent copy; they must extract it from prd.md.
# ─────────────────────────────────────────────
# NEW DEPENDENCIES
# Declared here so the orchestrator validates them before worker dispatch (I-06, B-18)
# iOS: new SPM packages → must be added to Package.swift + Package.resolved committed
# Android: new Gradle dependencies → must be in build.gradle.kts
# Backend: new Maven dependencies → must be in pom.xml (prefer banking-bom versions)
# ─────────────────────────────────────────────
new_dependencies: # REQUIRED — declare empty lists if none
ios: [] # e.g. – name: SomePackage, url: https://…
android: [] # e.g. – "com.example:library:1.0.0"
backend: [] # e.g. – groupId/artifactId (version from bom preferred)
# ─────────────────────────────────────────────
# CONSTRAINTS
# Architectural mandates specific to THIS epic.
# Org-level mandates are already in platform-invariants.md and AGENTS.md —
# do NOT repeat them here. Only add epic-specific constraints.
# ─────────────────────────────────────────────
constraints: # OPTIONAL — add only epic-specific rules
– "Contract is additive-only. No breaking changes to existing endpoints."
– "All new endpoints must be gated by CCM flag: {flag-name} (B-01)"
– "Error codes must be exhaustive — no generic 500s returned to mobile clients"
– "Megacache TTL declared for every cached entity (B-10)"
# Add any epic-specific constraints the adversary agent flagged as critical
# ─────────────────────────────────────────────
# ORCHESTRATOR NOTES
# Internal notes written by orchestrator during generation.
# Not shown to workers. Used for audit trail and amendment tracking.
# ─────────────────────────────────────────────
orchestrator_notes: # OPTIONAL — populated automatically
design_rationale: "" # why this design was chosen over alternatives
adversary_findings_addressed: [] # findings from adversary agent, resolved in this contract
open_decisions: [] # items requiring human judgment flagged during generation
contract_amendments: 0 # incremented each time contract is amended post-freeze
revision_cycles: 0 # number of times team requested changes before approval
# ─────────────────────────────────────────────
# HOLDOUT SCENARIOS (pipeline metadata only)
# Scenarios are NOT stored here — they live in
# This section is metadata only.
# ─────────────────────────────────────────────
holdout_scenarios(Acceptance Scenario):
owner: PM # PM authors scenarios in PRD; pipeline extracts them
location:
count: 0 # populated by orchestrator after extraction
# Workers NEVER read this section or the scenarios directory.
# Evaluators read scenarios directly from the scenarios/ directory.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# ═══════════════════════════════════════════════════════════════════
# HIGH LEVEL CONTRACT TEMPLATE — v1.1
# ═══════════════════════════════════════════════════════════════════
#
# PURPOSE (for orchestrator agents reading this file):
# This is the structural template for prd-contract.yaml.
# The orchestrator generates one filled contract per epic candidate,
# using this template as the scaffold.
#
# Multiple candidate contracts may be generated from the same PRD
# with different design Axis. Each candidate fills this same
# structure. The adversary agent and platform specialists then
# critique the CONTENT — not the structure.
#
# After human approval, the contract is FROZEN. Workers implement
# against it. Evaluators validate against it. No agent modifies it.
#
# PIPELINE USAGE:
# - Read by: orchestrator (generate), adversary (critique),
# platform specialists (feasibility), iOS/Android/Backend
# workers (implement), /api-test-Evaluator (API test gates),
# /mobile-test-Evaluator (mobile behavior evaluation)
# - Written to:
# - Source template:
#
# FORMAT: HYBRID
# - api_changes: OpenAPI 3.0 inline + x- extensions
# → Feeds Prism mock server directly (prism mock prd-contract.yaml)
# → Type precision built-in (enum, required, nullable)
# → Prism auto-validates requests AND responses at schema level
# - Everything else: custom YAML
# (mobile_contracts, db, cache, new_dependencies, constraints)
#
# REQUIRED FIELDS are marked with # REQUIRED
# OPTIONAL FIELDS are marked with # OPTIONAL — omit if not applicable
#
# INVARIANT NOTE: Do NOT repeat org-level mandates from platform-invariants.md
# here. Only prd-specific values belong in this file. Platform mandates are
# enforced by the adversary and evaluators via platform-invariants.md directly.
# ═══════════════════════════════════════════════════════════════════
# ─────────────────────────────────────────────
# HEADER — filled by orchestrator from PRD
# ─────────────────────────────────────────────
feature: "{feature-name-abcd-case}" # REQUIRED — e.g. recipient-validation-send-money
version: "1.0.0" # REQUIRED — bump to 1.1.0 on amendment
epic: "{JIRA-EPIC-KEY}" # REQUIRED
candidate: null # OPTIONAL — set to A/B/C if multiple candidates generated
# null = final approved contract
# Status managed by orchestrator — DO NOT EDIT manually
status: draft # draft | pending_approval | frozen | amended
approved_by: null # filled on approval: "Name, YYYY-MM-DD"
amendment_reason: null # filled if version > 1.0.0
# Prism mock server port — iOS and Android workers use this as the backend digital twin
# Endpoints with x-change-type: new or modification → Prism (this port)
# All other existing endpoints → real dev backend (from ports.json)
prism_port: 9090 # REQUIRED — allocated by orchestrator from ports.json
# ─────────────────────────────────────────────
# API CHANGES (Backend)
# OpenAPI 3.0 inline with x- extensions
#
# x-change-type values:
# new — endpoint does not exist yet; Prism serves it for mobile workers
# modification — endpoint exists; Prism overrides only the changed fields
# deprecated — endpoint being removed in this epic (additive removal via flag)
#
# x-idempotency values:
# required — /api-test-evaluator will inject Idempotency-Key header on every call
# optional — header accepted but not enforced
# none — endpoint is safe to call multiple times without consequence
#
# x-latency-sla: e.g. 200ms
# /api-test-evaluator load gate: BLOCK if P99 > 3× this value on dev machine
# WARN if P99 > 1.5× — environment noise, not a code problem
#
# x-breaking: true | false
# true → coordinated merge required (backend + all mobile in same deploy window)
# false → backend merges first; mobile after
# ─────────────────────────────────────────────
visual_architecture(Mermaid, for Humans):
graph TD
User -->|POST /order| API_Gateway
API_Gateway -->|gRPC| Order_Service
Order_Service -->|Publish| Kafka_Bus
Kafka_Bus -->|Subscribe| Payment_Service
api_changes: # REQUIRED if any backend service changes
"{service-name}": # matches repo-registry.yaml key exactly
# e.g.
openapi: "3.0.0"
paths:
# ── NEW ENDPOINT EXAMPLE ──────────────────────────────────
"/v1/{resource}/{action}":
post: # HTTP method: get | post | put | patch | delete
summary: "{short description}"
x-change-type: new # REQUIRED
x-idempotency: required # REQUIRED for write endpoints (B-12)
x-latency-sla: 200ms # REQUIRED — declare realistic target
x-breaking: false # REQUIRED
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [] # list required fields
properties:
fieldName:
type: string # string | integer | boolean | array | object
description: ""
# For PII fields, note: annotate with @SensitiveData in implementation (B-04)
responses:
"200":
description: "Success"
content:
application/json:
schema:
$ref: "#/components/schemas/{ResponseModel}"
"400":
description: "Validation error"
content:
application/json:
schema:
$ref: "#/components/schemas/{ErrorModel}"
"404":
description: "Not found"
# Do NOT declare 500 — services must not return unhandled 500s to mobile (constraint)
# ── MODIFICATION EXAMPLE ─────────────────────────────────
# "/v1/existing/{id}":
# get:
# x-change-type: modification
# x-breaking: false # additive field addition = non-breaking
# responses:
# "200":
# content:
# application/json:
# schema:
# type: object
# properties:
# existingField:
# type: string # existing — DO NOT change type (B-09)
# newField:
# type: string # NEW additive field
# nullable: true # must be nullable for backward compat
components:
schemas:
# Define all response/error models referenced above with $ref
# Models must be exhaustive — no fields left undefined
"{ResponseModel}":
type: object
required: []
properties:
fieldName:
type: string
# enum: [VALUE_A, VALUE_B] # use enum when the field has finite valid values
# nullable: true # use when field may be absent on partial response
"{ErrorModel}":
type: object
required: [errorCode]
properties:
errorCode:
type: string
enum: [] # REQUIRED — exhaustive error codes; no generic errors
message:
type: string
nullable: true
# If a service in REPOS has no backend changes, declare it explicitly:
# "{other-service-name}":
# no_changes: true
# ─────────────────────────────────────────────
# DATA MODELS (shared across platforms)
# Canonical model definitions used by iOS, Android, and Backend.
# Ensures all platforms use the same field names and types.
# ─────────────────────────────────────────────
data_models: # OPTIONAL — omit if no shared models needed
"{ModelName}":
fields:
- fieldName: string # type: string | integer | boolean | array | object | enum
- errorCode: "enum[VALUE_A, VALUE_B]"
pii: false # true → field-level @SensitiveData annotation required (B-04)
# ─────────────────────────────────────────────
# MOBILE CONTRACTS
# Defines what iOS and Android workers must implement.
# iOS workers read mobile_contracts.ios.
# Android workers read mobile_contracts.android.
# Prism handles the backend simulation — workers do NOT wait for real backend.
# ─────────────────────────────────────────────
mobile_contracts: # REQUIRED if iOS or Android repos are in scope
ios: # OPTIONAL — omit if iOS not in scope
new_usecases: # UseCase protocol methods iOS must add
- name: "{UseCaseName}"
method: "{methodName}({params}) async throws -> {ReturnType}"
module: "Features/{FeatureName}" # target module in repo
new_models: # Swift models to create (match data_models above)
- "{ModelName}"
modified_usecases: [] # OPTIONAL — existing usecases with new methods
android: # OPTIONAL — omit if Android not in scope
new_repositories: # Repository interface methods Android must add
- name: "{RepositoryName}"
method: "suspend fun {methodName}({params}): {ReturnType}"
layer: "data/repository" # always data/repository layer (A-01, A-07)
new_models: # Kotlin data classes (match data_models above)
- "{ModelName}"
modified_repositories: [] # OPTIONAL
# ─────────────────────────────────────────────
# DATABASE CHANGES
# Additive only — no DROP, no type changes, no NOT NULL without DEFAULT (B-09)
# ─────────────────────────────────────────────
db: # OPTIONAL — omit if no DB changes
"{service-name}":
store: sql # sql | Cache (for cache-as-db patterns)
additive_only: true # ALWAYS true — breaking schema changes blocked (B-09)
new_tables: [] # list new table definitions
new_columns: # list new column additions
- table: "{table_name}"
column: "{column_name}"
type: "{SQL_TYPE}" # e.g. NVARCHAR(255) | BIT | DATETIME2 | INT
nullable: true # MUST be nullable or have DEFAULT for zero-downtime
default: null # provide DEFAULT if NOT NULL required
# ─────────────────────────────────────────────
# CACHE
# Cache TTL MUST be declared for every cached entity (B-10)
# Missing TTL = pipeline blocks deployment
# ─────────────────────────────────────────────
cache: # OPTIONAL — omit if no caching changes
"{service-name}":
- entity: "{EntityName}"
store: megacache # megacache is the standard cache layer
ttl: 300s # REQUIRED — no indefinite caching of data
key: "{cache-key-pattern}" # e.g. recipient:{recipientId}
invalidate_on: "{event_name}" # OPTIONAL — event that invalidates this cache entry
# ─────────────────────────────────────────────
# FEATURE FLAGS
# Epic-specific flag declarations — names, owners, and flag-off behavior per platform.
# CCM (backend/Android) and Firebase RemoteConfig (iOS) are the two registries.
# Org mandate (B-01/B-02/B-03/I-10): every new feature must ship behind a flag.
# Declare the flag NAME and behavior here — the flag registration step is in implementation.
# ─────────────────────────────────────────────
feature_flags: # REQUIRED if any new feature is introduced
ccm: # OPTIONAL — CCM flags for backend and Android
- name: "{ccm.flag.name}" # e.g.
service: "{service-name}" # which backend service reads this flag
default: false # false = flag-off (safe default for new features)
flag_off_behavior: > # REQUIRED — what happens when flag is false
"{describe observable behavior: e.g. endpoint returns 404, UI hides entry point}"
rollout_strategy: "0 → 10 → 50 → 100" # percentage rollout plan
owner: "{team-name}" # team responsible for flag lifecycle
cleanup_jira: null # OPTIONAL — Jira story to remove flag after full rollout
firebase: # OPTIONAL — Firebase RemoteConfig flags for iOS
- name: "{firebase_flag_name}" # e.g.
default: false
flag_off_behavior: >
"{describe observable behavior: e.g. feature entry point hidden from nav}"
owner: "{team-name}"
# ─────────────────────────────────────────────
# EVENTS (Kafka)
# Epic-specific Kafka topic declarations.
# Declare topic, schema, and producer/consumer per service.
# Schema versioning: use Avro or JSON Schema — declare format here.
# ─────────────────────────────────────────────
events: # OPTIONAL — omit if no Kafka events in this epic
- topic: "{topic-name}" # e.g. recipient.validated.v1
schema_format: avro # avro | json-schema
schema: | # inline schema — must match what workers implement
{
"type": "record",
"name": "{EventName}",
"fields": [
{"name": "epicKey", "type": "string"},
{"name": "timestamp", "type": "long", "logicalType": "timestamp-millis"}
]
}
producer:
service: "{service-name}" # which service emits this event
trigger: "{what causes emission}" # e.g. "POST /v1/recipients/validate succeeds"
consumers:
- service: "{service-name}" # which service(s) consume this event
action: "{what the consumer does}" # e.g. "invalidates recipient cache entry"
retention: 7d # OPTIONAL — default platform retention if non-standard
# ─────────────────────────────────────────────
# NAVIGATION
# Declares new screens, flows, and routing changes per platform.
# iOS: coordinator / deeplink registry entries
# Android: nav graph destinations and deeplinks
# Web: route definitions and lazy-loaded modules
# ─────────────────────────────────────────────
navigation: # OPTIONAL — omit if no new screens or nav changes
ios: # OPTIONAL
new_screens:
- name: "{ScreenName}View" # SwiftUI view name
coordinator: "{CoordinatorName}" # owning coordinator (I-15)
entry_points: # how the screen is reached
- "{previous screen or deeplink}"
exit_points: # where the screen navigates to on completion/cancel
- destination: "{screen or dismiss}"
trigger: "{user action}"
deeplinks: # OPTIONAL — new deeplinks registered in this epic
- scheme: "app://w/{path}" # full deeplink URI pattern (I-17)
destination: "{ScreenName}View"
params: # query param names the deeplink accepts
- "{paramName}"
android: # OPTIONAL
new_destinations:
- name: "{FragmentName}" # nav graph destination name
nav_graph: "{graph-name}" # which nav_graph XML file owns this destination
entry_points:
- "{action or deeplink}"
exit_points:
- destination: "{fragment or popBackStack}"
trigger: "{user action}"
deeplinks:
- uri_pattern: "app://w/{path}" # Android deeplink URI pattern
destination: "{FragmentName}"
params:
- "{paramName}"
web: # OPTIONAL
new_routes:
- path: "/w/{route}" # React Router path
component: "{ComponentName}"
lazy: true # true = lazy-loaded module (W-11)
guards: # route guards required
- "AuthGuard"
module_federation: # OPTIONAL — if this epic adds a new federated module
- module_name: "{module}"
exposes: "{component}"
# ─────────────────────────────────────────────
# ANALYTICS
# Epic-specific analytics event declarations.
# Every new user-facing action that requires measurement must be declared here.
# Workers implement the event emission; evaluators verify events fire.
# ─────────────────────────────────────────────
analytics: # OPTIONAL — omit if no new analytics events
ios: # OPTIONAL
events:
- name: "{EventName}" # e.g. RecipientValidationSuccess
trigger: "{user action or system event that fires this}"
properties:
- name: "{propertyName}"
type: string # string | int | bool
required: true
screen: "{ScreenName}" # screen from which event fires
android: # OPTIONAL
events:
- name: "{EventName}"
trigger: "{trigger description}"
properties:
- name: "{propertyName}"
type: string
required: true
backend: # OPTIONAL — server-side events / audit log entries
events:
- name: "{event_name}" # e.g. validation_attempted
trigger: "{endpoint or service event}"
properties:
- name: "{propertyName}"
type: string
# ─────────────────────────────────────────────
# SECURITY
# Epic-specific security declarations.
# Only values that vary per epic — org-level rules enforced by platform-invariants.md.
# ─────────────────────────────────────────────
security: # REQUIRED if epic handles financial data, PII, or PCI
pii_fields: # OPTIONAL — list field names in THIS epic that contain PII
- field: "{fieldName}" # e.g.
model: "{ModelName}" # which data model
annotation: "@SensitiveData" # always @SensitiveData — implementation reminder
pci_in_scope: false # REQUIRED — true if this epic touches card numbers/CVV/expiry
# true → no logging of raw values, PCI DSS controls apply
cnbv_audit_required: false # REQUIRED — true if this epic initiates transactions
# true → audit_fields below must be declared
audit_fields: # REQUIRED if cnbv_audit_required: true
- "{fieldName}" # fields that must appear in the audit trail
# e.g.
auth_scope: # OPTIONAL — OAuth scopes or JWT claims required
required_claims:
- "{claim-name}" # e.g.
new_scopes: # OPTIONAL — new scopes introduced by this epic
- name: "{scope-name}"
description: "{what this scope grants}"
# ─────────────────────────────────────────────
# ERROR HANDLING (epic-specific)
# Offline and partial-failure behaviors that vary per feature.
# Org-level retry/timeout mandates (B-21) are in platform-invariants.md.
# ─────────────────────────────────────────────
error_handling: # OPTIONAL — omit if no special error handling needed
offline_behavior: # OPTIONAL — how this feature behaves when device is offline
ios: "{describe: e.g. cached recipients shown, send disabled, offline banner shown}"
android: "{describe}"
web: "{describe}"
partial_success: # OPTIONAL — pending scenario
strategy: "{idempotent-retry | saga | compensation}"
description: >
"{Describe the specific partial-failure scenario this epic must handle
and what the system does when debit succeeds but credit fails}"
# ─────────────────────────────────────────────
# ROLLBACK
# Compensation strategy for THIS epic if a feature must be rolled back post-deploy.
# Financial flow epics MUST declare a rollback strategy.
# ─────────────────────────────────────────────
rollback: # REQUIRED if epic involves financial transactions or DB writes
strategy: "{flag-off | saga | 2pc | compensation | db-migration-down}"
# flag-off — turn CCM/Firebase flag to false; no data to roll back
# saga — compensating transaction reverses prior steps
# 2pc — two-phase commit (use only if saga is insufficient)
# compensation — manual or automated journal entry to reverse
# db-migration-down — reversible Flyway migration V{N}__down.sql exists
flag_name: null # OPTIONAL — which feature flag disables this feature
saga_steps: # REQUIRED if strategy is saga or compensation
- step: "{action}"
compensation: "{reversal action}"
# ─────────────────────────────────────────────
# LOCALISATION
# New string keys introduced by this epic.
# Key names only — copy text comes from PRD; workers pull it from there.
# ─────────────────────────────────────────────
localisation: # OPTIONAL — omit if no new user-visible strings
new_keys:
- key: "{string.key.name}" # e.g. recipient.validation.error.invalid_clabe
context: "{what this string is used for — helps translators}"
platforms: # which platforms use this key
- ios
- android
- web
# Copy text is NOT defined here — sourced from PRD by workers.
# Workers must not invent copy; they must extract it from prd.md.
# ─────────────────────────────────────────────
# NEW DEPENDENCIES
# Declared here so the orchestrator validates them before worker dispatch (I-06, B-18)
# iOS: new SPM packages → must be added to Package.swift + Package.resolved committed
# Android: new Gradle dependencies → must be in build.gradle.kts
# Backend: new Maven dependencies → must be in pom.xml (prefer banking-bom versions)
# ─────────────────────────────────────────────
new_dependencies: # REQUIRED — declare empty lists if none
ios: [] # e.g. - name: SomePackage, url: https://...
android: [] # e.g. - "com.example:library:1.0.0"
backend: [] # e.g. - groupId/artifactId (version from bom preferred)
# ─────────────────────────────────────────────
# CONSTRAINTS
# Architectural mandates specific to THIS epic.
# Org-level mandates are already in platform-invariants.md and AGENTS.md —
# do NOT repeat them here. Only add epic-specific constraints.
# ─────────────────────────────────────────────
constraints: # OPTIONAL — add only epic-specific rules
- "Contract is additive-only. No breaking changes to existing endpoints."
- "All new endpoints must be gated by CCM flag: {flag-name} (B-01)"
- "Error codes must be exhaustive — no generic 500s returned to mobile clients"
- "Megacache TTL declared for every cached entity (B-10)"
# Add any epic-specific constraints the adversary agent flagged as critical
# ─────────────────────────────────────────────
# ORCHESTRATOR NOTES
# Internal notes written by orchestrator during generation.
# Not shown to workers. Used for audit trail and amendment tracking.
# ─────────────────────────────────────────────
orchestrator_notes: # OPTIONAL — populated automatically
design_rationale: "" # why this design was chosen over alternatives
adversary_findings_addressed: [] # findings from adversary agent, resolved in this contract
open_decisions: [] # items requiring human judgment flagged during generation
contract_amendments: 0 # incremented each time contract is amended post-freeze
revision_cycles: 0 # number of times team requested changes before approval
# ─────────────────────────────────────────────
# HOLDOUT SCENARIOS (pipeline metadata only)
# Scenarios are NOT stored here — they live in
# This section is metadata only.
# ─────────────────────────────────────────────
holdout_scenarios(Acceptance Scenario):
owner: PM # PM authors scenarios in PRD; pipeline extracts them
location:
count: 0 # populated by orchestrator after extraction
# Workers NEVER read this section or the scenarios directory.
# Evaluators read scenarios directly from the scenarios/ directory.
# ═══════════════════════════════════════════════════════════════════
# HIGH LEVEL CONTRACT TEMPLATE — v1.1
# ═══════════════════════════════════════════════════════════════════
#
# PURPOSE (for orchestrator agents reading this file):
# This is the structural template for prd-contract.yaml.
# The orchestrator generates one filled contract per epic candidate,
# using this template as the scaffold.
#
# Multiple candidate contracts may be generated from the same PRD
# with different design Axis. Each candidate fills this same
# structure. The adversary agent and platform specialists then
# critique the CONTENT — not the structure.
#
# After human approval, the contract is FROZEN. Workers implement
# against it. Evaluators validate against it. No agent modifies it.
#
# PIPELINE USAGE:
# - Read by: orchestrator (generate), adversary (critique),
# platform specialists (feasibility), iOS/Android/Backend
# workers (implement), /api-test-Evaluator (API test gates),
# /mobile-test-Evaluator (mobile behavior evaluation)
# - Written to:
# - Source template:
#
# FORMAT: HYBRID
# - api_changes: OpenAPI 3.0 inline + x- extensions
# → Feeds Prism mock server directly (prism mock prd-contract.yaml)
# → Type precision built-in (enum, required, nullable)
# → Prism auto-validates requests AND responses at schema level
# - Everything else: custom YAML
# (mobile_contracts, db, cache, new_dependencies, constraints)
#
# REQUIRED FIELDS are marked with # REQUIRED
# OPTIONAL FIELDS are marked with # OPTIONAL — omit if not applicable
#
# INVARIANT NOTE: Do NOT repeat org-level mandates from platform-invariants.md
# here. Only prd-specific values belong in this file. Platform mandates are
# enforced by the adversary and evaluators via platform-invariants.md directly.
# ═══════════════════════════════════════════════════════════════════
# ─────────────────────────────────────────────
# HEADER — filled by orchestrator from PRD
# ─────────────────────────────────────────────
feature: "{feature-name-abcd-case}" # REQUIRED — e.g. recipient-validation-send-money
version: "1.0.0" # REQUIRED — bump to 1.1.0 on amendment
epic: "{JIRA-EPIC-KEY}" # REQUIRED
candidate: null # OPTIONAL — set to A/B/C if multiple candidates generated
# null = final approved contract
# Status managed by orchestrator — DO NOT EDIT manually
status: draft # draft | pending_approval | frozen | amended
approved_by: null # filled on approval: "Name, YYYY-MM-DD"
amendment_reason: null # filled if version > 1.0.0
# Prism mock server port — iOS and Android workers use this as the backend digital twin
# Endpoints with x-change-type: new or modification → Prism (this port)
# All other existing endpoints → real dev backend (from ports.json)
prism_port: 9090 # REQUIRED — allocated by orchestrator from ports.json
# ─────────────────────────────────────────────
# API CHANGES (Backend)
# OpenAPI 3.0 inline with x- extensions
#
# x-change-type values:
# new — endpoint does not exist yet; Prism serves it for mobile workers
# modification — endpoint exists; Prism overrides only the changed fields
# deprecated — endpoint being removed in this epic (additive removal via flag)
#
# x-idempotency values:
# required — /api-test-evaluator will inject Idempotency-Key header on every call
# optional — header accepted but not enforced
# none — endpoint is safe to call multiple times without consequence
#
# x-latency-sla: e.g. 200ms
# /api-test-evaluator load gate: BLOCK if P99 > 3× this value on dev machine
# WARN if P99 > 1.5× — environment noise, not a code problem
#
# x-breaking: true | false
# true → coordinated merge required (backend + all mobile in same deploy window)
# false → backend merges first; mobile after
# ─────────────────────────────────────────────
visual_architecture(Mermaid, for Humans):
graph TD
User -->|POST /order| API_Gateway
API_Gateway -->|gRPC| Order_Service
Order_Service -->|Publish| Kafka_Bus
Kafka_Bus -->|Subscribe| Payment_Service
api_changes: # REQUIRED if any backend service changes
"{service-name}": # matches repo-registry.yaml key exactly
# e.g.
openapi: "3.0.0"
paths:
# ── NEW ENDPOINT EXAMPLE ──────────────────────────────────
"/v1/{resource}/{action}":
post: # HTTP method: get | post | put | patch | delete
summary: "{short description}"
x-change-type: new # REQUIRED
x-idempotency: required # REQUIRED for write endpoints (B-12)
x-latency-sla: 200ms # REQUIRED — declare realistic target
x-breaking: false # REQUIRED
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [] # list required fields
properties:
fieldName:
type: string # string | integer | boolean | array | object
description: ""
# For PII fields, note: annotate with @SensitiveData in implementation (B-04)
responses:
"200":
description: "Success"
content:
application/json:
schema:
$ref: "#/components/schemas/{ResponseModel}"
"400":
description: "Validation error"
content:
application/json:
schema:
$ref: "#/components/schemas/{ErrorModel}"
"404":
description: "Not found"
# Do NOT declare 500 — services must not return unhandled 500s to mobile (constraint)
# ── MODIFICATION EXAMPLE ─────────────────────────────────
# "/v1/existing/{id}":
# get:
# x-change-type: modification
# x-breaking: false # additive field addition = non-breaking
# responses:
# "200":
# content:
# application/json:
# schema:
# type: object
# properties:
# existingField:
# type: string # existing — DO NOT change type (B-09)
# newField:
# type: string # NEW additive field
# nullable: true # must be nullable for backward compat
components:
schemas:
# Define all response/error models referenced above with $ref
# Models must be exhaustive — no fields left undefined
"{ResponseModel}":
type: object
required: []
properties:
fieldName:
type: string
# enum: [VALUE_A, VALUE_B] # use enum when the field has finite valid values
# nullable: true # use when field may be absent on partial response
"{ErrorModel}":
type: object
required: [errorCode]
properties:
errorCode:
type: string
enum: [] # REQUIRED — exhaustive error codes; no generic errors
message:
type: string
nullable: true
# If a service in REPOS has no backend changes, declare it explicitly:
# "{other-service-name}":
# no_changes: true
# ─────────────────────────────────────────────
# DATA MODELS (shared across platforms)
# Canonical model definitions used by iOS, Android, and Backend.
# Ensures all platforms use the same field names and types.
# ─────────────────────────────────────────────
data_models: # OPTIONAL — omit if no shared models needed
"{ModelName}":
fields:
- fieldName: string # type: string | integer | boolean | array | object | enum
- errorCode: "enum[VALUE_A, VALUE_B]"
pii: false # true → field-level @SensitiveData annotation required (B-04)
# ─────────────────────────────────────────────
# MOBILE CONTRACTS
# Defines what iOS and Android workers must implement.
# iOS workers read mobile_contracts.ios.
# Android workers read mobile_contracts.android.
# Prism handles the backend simulation — workers do NOT wait for real backend.
# ─────────────────────────────────────────────
mobile_contracts: # REQUIRED if iOS or Android repos are in scope
ios: # OPTIONAL — omit if iOS not in scope
new_usecases: # UseCase protocol methods iOS must add
- name: "{UseCaseName}"
method: "{methodName}({params}) async throws -> {ReturnType}"
module: "Features/{FeatureName}" # target module in repo
new_models: # Swift models to create (match data_models above)
- "{ModelName}"
modified_usecases: [] # OPTIONAL — existing usecases with new methods
android: # OPTIONAL — omit if Android not in scope
new_repositories: # Repository interface methods Android must add
- name: "{RepositoryName}"
method: "suspend fun {methodName}({params}): {ReturnType}"
layer: "data/repository" # always data/repository layer (A-01, A-07)
new_models: # Kotlin data classes (match data_models above)
- "{ModelName}"
modified_repositories: [] # OPTIONAL
# ─────────────────────────────────────────────
# DATABASE CHANGES
# Additive only — no DROP, no type changes, no NOT NULL without DEFAULT (B-09)
# ─────────────────────────────────────────────
db: # OPTIONAL — omit if no DB changes
"{service-name}":
store: sql # sql | Cache (for cache-as-db patterns)
additive_only: true # ALWAYS true — breaking schema changes blocked (B-09)
new_tables: [] # list new table definitions
new_columns: # list new column additions
- table: "{table_name}"
column: "{column_name}"
type: "{SQL_TYPE}" # e.g. NVARCHAR(255) | BIT | DATETIME2 | INT
nullable: true # MUST be nullable or have DEFAULT for zero-downtime
default: null # provide DEFAULT if NOT NULL required
# ─────────────────────────────────────────────
# CACHE
# Cache TTL MUST be declared for every cached entity (B-10)
# Missing TTL = pipeline blocks deployment
# ─────────────────────────────────────────────
cache: # OPTIONAL — omit if no caching changes
"{service-name}":
- entity: "{EntityName}"
store: megacache # megacache is the standard cache layer
ttl: 300s # REQUIRED — no indefinite caching of data
key: "{cache-key-pattern}" # e.g. recipient:{recipientId}
invalidate_on: "{event_name}" # OPTIONAL — event that invalidates this cache entry
# ─────────────────────────────────────────────
# FEATURE FLAGS
# Epic-specific flag declarations — names, owners, and flag-off behavior per platform.
# CCM (backend/Android) and Firebase RemoteConfig (iOS) are the two registries.
# Org mandate (B-01/B-02/B-03/I-10): every new feature must ship behind a flag.
# Declare the flag NAME and behavior here — the flag registration step is in implementation.
# ─────────────────────────────────────────────
feature_flags: # REQUIRED if any new feature is introduced
ccm: # OPTIONAL — CCM flags for backend and Android
- name: "{ccm.flag.name}" # e.g.
service: "{service-name}" # which backend service reads this flag
default: false # false = flag-off (safe default for new features)
flag_off_behavior: > # REQUIRED — what happens when flag is false
"{describe observable behavior: e.g. endpoint returns 404, UI hides entry point}"
rollout_strategy: "0 → 10 → 50 → 100" # percentage rollout plan
owner: "{team-name}" # team responsible for flag lifecycle
cleanup_jira: null # OPTIONAL — Jira story to remove flag after full rollout
firebase: # OPTIONAL — Firebase RemoteConfig flags for iOS
- name: "{firebase_flag_name}" # e.g.
default: false
flag_off_behavior: >
"{describe observable behavior: e.g. feature entry point hidden from nav}"
owner: "{team-name}"
# ─────────────────────────────────────────────
# EVENTS (Kafka)
# Epic-specific Kafka topic declarations.
# Declare topic, schema, and producer/consumer per service.
# Schema versioning: use Avro or JSON Schema — declare format here.
# ─────────────────────────────────────────────
events: # OPTIONAL — omit if no Kafka events in this epic
- topic: "{topic-name}" # e.g. recipient.validated.v1
schema_format: avro # avro | json-schema
schema: | # inline schema — must match what workers implement
{
"type": "record",
"name": "{EventName}",
"fields": [
{"name": "epicKey", "type": "string"},
{"name": "timestamp", "type": "long", "logicalType": "timestamp-millis"}
]
}
producer:
service: "{service-name}" # which service emits this event
trigger: "{what causes emission}" # e.g. "POST /v1/recipients/validate succeeds"
consumers:
- service: "{service-name}" # which service(s) consume this event
action: "{what the consumer does}" # e.g. "invalidates recipient cache entry"
retention: 7d # OPTIONAL — default platform retention if non-standard
# ─────────────────────────────────────────────
# NAVIGATION
# Declares new screens, flows, and routing changes per platform.
# iOS: coordinator / deeplink registry entries
# Android: nav graph destinations and deeplinks
# Web: route definitions and lazy-loaded modules
# ─────────────────────────────────────────────
navigation: # OPTIONAL — omit if no new screens or nav changes
ios: # OPTIONAL
new_screens:
- name: "{ScreenName}View" # SwiftUI view name
coordinator: "{CoordinatorName}" # owning coordinator (I-15)
entry_points: # how the screen is reached
- "{previous screen or deeplink}"
exit_points: # where the screen navigates to on completion/cancel
- destination: "{screen or dismiss}"
trigger: "{user action}"
deeplinks: # OPTIONAL — new deeplinks registered in this epic
- scheme: "app://w/{path}" # full deeplink URI pattern (I-17)
destination: "{ScreenName}View"
params: # query param names the deeplink accepts
- "{paramName}"
android: # OPTIONAL
new_destinations:
- name: "{FragmentName}" # nav graph destination name
nav_graph: "{graph-name}" # which nav_graph XML file owns this destination
entry_points:
- "{action or deeplink}"
exit_points:
- destination: "{fragment or popBackStack}"
trigger: "{user action}"
deeplinks:
- uri_pattern: "app://w/{path}" # Android deeplink URI pattern
destination: "{FragmentName}"
params:
- "{paramName}"
web: # OPTIONAL
new_routes:
- path: "/w/{route}" # React Router path
component: "{ComponentName}"
lazy: true # true = lazy-loaded module (W-11)
guards: # route guards required
- "AuthGuard"
module_federation: # OPTIONAL — if this epic adds a new federated module
- module_name: "{module}"
exposes: "{component}"
# ─────────────────────────────────────────────
# ANALYTICS
# Epic-specific analytics event declarations.
# Every new user-facing action that requires measurement must be declared here.
# Workers implement the event emission; evaluators verify events fire.
# ─────────────────────────────────────────────
analytics: # OPTIONAL — omit if no new analytics events
ios: # OPTIONAL
events:
- name: "{EventName}" # e.g. RecipientValidationSuccess
trigger: "{user action or system event that fires this}"
properties:
- name: "{propertyName}"
type: string # string | int | bool
required: true
screen: "{ScreenName}" # screen from which event fires
android: # OPTIONAL
events:
- name: "{EventName}"
trigger: "{trigger description}"
properties:
- name: "{propertyName}"
type: string
required: true
backend: # OPTIONAL — server-side events / audit log entries
events:
- name: "{event_name}" # e.g. validation_attempted
trigger: "{endpoint or service event}"
properties:
- name: "{propertyName}"
type: string
# ─────────────────────────────────────────────
# SECURITY
# Epic-specific security declarations.
# Only values that vary per epic — org-level rules enforced by platform-invariants.md.
# ─────────────────────────────────────────────
security: # REQUIRED if epic handles financial data, PII, or PCI
pii_fields: # OPTIONAL — list field names in THIS epic that contain PII
- field: "{fieldName}" # e.g.
model: "{ModelName}" # which data model
annotation: "@SensitiveData" # always @SensitiveData — implementation reminder
pci_in_scope: false # REQUIRED — true if this epic touches card numbers/CVV/expiry
# true → no logging of raw values, PCI DSS controls apply
cnbv_audit_required: false # REQUIRED — true if this epic initiates transactions
# true → audit_fields below must be declared
audit_fields: # REQUIRED if cnbv_audit_required: true
- "{fieldName}" # fields that must appear in the audit trail
# e.g.
auth_scope: # OPTIONAL — OAuth scopes or JWT claims required
required_claims:
- "{claim-name}" # e.g.
new_scopes: # OPTIONAL — new scopes introduced by this epic
- name: "{scope-name}"
description: "{what this scope grants}"
# ─────────────────────────────────────────────
# ERROR HANDLING (epic-specific)
# Offline and partial-failure behaviors that vary per feature.
# Org-level retry/timeout mandates (B-21) are in platform-invariants.md.
# ─────────────────────────────────────────────
error_handling: # OPTIONAL — omit if no special error handling needed
offline_behavior: # OPTIONAL — how this feature behaves when device is offline
ios: "{describe: e.g. cached recipients shown, send disabled, offline banner shown}"
android: "{describe}"
web: "{describe}"
partial_success: # OPTIONAL — pending scenario
strategy: "{idempotent-retry | saga | compensation}"
description: >
"{Describe the specific partial-failure scenario this epic must handle
and what the system does when debit succeeds but credit fails}"
# ─────────────────────────────────────────────
# ROLLBACK
# Compensation strategy for THIS epic if a feature must be rolled back post-deploy.
# Financial flow epics MUST declare a rollback strategy.
# ─────────────────────────────────────────────
rollback: # REQUIRED if epic involves financial transactions or DB writes
strategy: "{flag-off | saga | 2pc | compensation | db-migration-down}"
# flag-off — turn CCM/Firebase flag to false; no data to roll back
# saga — compensating transaction reverses prior steps
# 2pc — two-phase commit (use only if saga is insufficient)
# compensation — manual or automated journal entry to reverse
# db-migration-down — reversible Flyway migration V{N}__down.sql exists
flag_name: null # OPTIONAL — which feature flag disables this feature
saga_steps: # REQUIRED if strategy is saga or compensation
- step: "{action}"
compensation: "{reversal action}"
# ─────────────────────────────────────────────
# LOCALISATION
# New string keys introduced by this epic.
# Key names only — copy text comes from PRD; workers pull it from there.
# ─────────────────────────────────────────────
localisation: # OPTIONAL — omit if no new user-visible strings
new_keys:
- key: "{string.key.name}" # e.g. recipient.validation.error.invalid_clabe
context: "{what this string is used for — helps translators}"
platforms: # which platforms use this key
- ios
- android
- web
# Copy text is NOT defined here — sourced from PRD by workers.
# Workers must not invent copy; they must extract it from prd.md.
# ─────────────────────────────────────────────
# NEW DEPENDENCIES
# Declared here so the orchestrator validates them before worker dispatch (I-06, B-18)
# iOS: new SPM packages → must be added to Package.swift + Package.resolved committed
# Android: new Gradle dependencies → must be in build.gradle.kts
# Backend: new Maven dependencies → must be in pom.xml (prefer banking-bom versions)
# ─────────────────────────────────────────────
new_dependencies: # REQUIRED — declare empty lists if none
ios: [] # e.g. - name: SomePackage, url: https://...
android: [] # e.g. - "com.example:library:1.0.0"
backend: [] # e.g. - groupId/artifactId (version from bom preferred)
# ─────────────────────────────────────────────
# CONSTRAINTS
# Architectural mandates specific to THIS epic.
# Org-level mandates are already in platform-invariants.md and AGENTS.md —
# do NOT repeat them here. Only add epic-specific constraints.
# ─────────────────────────────────────────────
constraints: # OPTIONAL — add only epic-specific rules
- "Contract is additive-only. No breaking changes to existing endpoints."
- "All new endpoints must be gated by CCM flag: {flag-name} (B-01)"
- "Error codes must be exhaustive — no generic 500s returned to mobile clients"
- "Megacache TTL declared for every cached entity (B-10)"
# Add any epic-specific constraints the adversary agent flagged as critical
# ─────────────────────────────────────────────
# ORCHESTRATOR NOTES
# Internal notes written by orchestrator during generation.
# Not shown to workers. Used for audit trail and amendment tracking.
# ─────────────────────────────────────────────
orchestrator_notes: # OPTIONAL — populated automatically
design_rationale: "" # why this design was chosen over alternatives
adversary_findings_addressed: [] # findings from adversary agent, resolved in this contract
open_decisions: [] # items requiring human judgment flagged during generation
contract_amendments: 0 # incremented each time contract is amended post-freeze
revision_cycles: 0 # number of times team requested changes before approval
# ─────────────────────────────────────────────
# HOLDOUT SCENARIOS (pipeline metadata only)
# Scenarios are NOT stored here — they live in
# This section is metadata only.
# ─────────────────────────────────────────────
holdout_scenarios(Acceptance Scenario):
owner: PM # PM authors scenarios in PRD; pipeline extracts them
location:
count: 0 # populated by orchestrator after extraction
# Workers NEVER read this section or the scenarios directory.
# Evaluators read scenarios directly from the scenarios/ directory.
The Wall of Isolation and Quality
The Input PRD has another holy section called Acceptance Scenarios which we will discuss now. These are Product Manager Written User Test Scenarios in Given-When-Then format from User’s perspective. These are the definitions of DONE. These tests do not contain Unit Tests, Integration Tests, etc which can be easily be gamed by Worker(Developer) Agents.
In classic machine learning, the Golden Rule of Data Splitting is:
Never let your test data leak into your training phase. Data leakage occurs when info from the test set accidentally influences the model’s training, leading to overly optimistic and falsely inflated performance metrics.
Similarly, The Worker(Developer) Agents should never see User Test Scenarios while implementing. The evaluator(Tester) Agents should never see Implementation Details. Workers and Evaluator should never share Context and should work in isolation.
<button data-code="
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
<!-- ACCEPTANCE:SCENARIOS:START -->
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
<!-- ACCEPTANCE:SCENARIOS:END -->
<!-- ACCEPTANCE:SCENARIOS:START -->
## Acceptance Scenarios
### AS-01: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-02: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P0
Given: {initial state}
When: {action}
Then: {expected outcome}
### AS-03: {Scenario Title}
Platform: {iOS | Android | Backend:{service-name} | All}
Priority: P1
Given: {initial state}
When: {action}
Then: {expected outcome}
<!-- ACCEPTANCE:SCENARIOS:END -->
Scenario Gate Checks
The Orchestrator extracts the PM written Scenarios. These Scenarios first go through Scenario Gate. The scenario gate is a 7-check automated quality validator that validates each scenarios against specificity, Error Coverage, Forward Traceability, Reverse Traceability, Testability, Error Exhaustiveness, Platform Formats, etc.
Scenario Expansion Agent
This agent tries to surface missing scenarios to PM, edge cases PM might not have thought of. PM can choose to accept/defer/skip. This leads to more matured Scenarios. Finalized Scenarios are used as input to evaluators.
Introducing Workers(Developer Agents)
After HLD contract is approved by Human, Orchestrator creates JIRA stories(one story per repo touched via JIRA MCP). JIRA IDs will be used for branch naming. Orchestrator splits the HLD contract into relevant LLD(lld.yml) slices per story/repo using deterministic python code, builds the dependency order of development to be done, then spawns parallel Worker Agents obeying the dependency order, and injects the relevant slice of LLDs for them to work in their isolated work-trees.
The number of Development workers that will be spawned is decided by the dependency order of work at hand(implicit from HLD Contract).
Let’s understand how a worker Agent works across a repo given an LLD. It could be iOS, Android, Backend, web, etc.
The worker Agent works in phases:
- LLD Injection and Team’s Shared Memory Recall: The LLD slice relevant to the story is passed as a context to worker. Also relevant team knowledge base per platform is fetched.
- Question Derivation: The worker generates clarifying questions(Questions.md) based on given LLD and presents it to user to answer and clarify. The worker would like to literally grill the user with questions to understand LLDs so Agent and Human are aligned.
- Perform Research Phase: Now worker spawns research Agents as already discussed earlier to get relevant codebase files, APIs, existing patterns, etc and writes to a research.md file.
- Design Direction Phase: In this phase worker tries to understand “Where are we going ?” to get a directional commitment. It analyses research.md file tries to understand whats the design direction. Here Worker & Orchestrator go through multiple iterations until Design.md is finalized.
5. Structure Outline Phase: In this phase worker tries to understand “How do we get there? What order? How to validate?”. Worker comes up with a structure based on existing codebase like:
Defines layers: Data → Domain → Presentation. It creates a structure.md file.
-
Detailed Plan Phase: In this phase workers create a detailed plan(blueprint) with File:line level — exact class names, method signatures, tests and save it as plan.md file.
-
Implementation Phase: In this phase workers implement plan.md file sequentially(layer by layer) respecting code dependency order
Data layer → Domain layer → Presentation layer.
For Each layer: write code → compile → lint → unit tests, then move to next layer following dependency order.
8. AC verification Phase: We also add a critic layer during implementation phase to check drift between actual code change vs plan.md. Also it creates ac-verification.md file with pass/fail status. If all ac do not PASS we loop back to Implement Phase.
9. Build & Runtime Verification Phase: In this phase we have headless integration with IDEs(XCode, AndroidStudio, Intellij, VSCode) for full compile/build/lint/UT checks. If failures found we loop back to implement phase. Once .app/ .apk / Service local host endpoint is created. It is shared to Evaluators to evaluation against PM written ACs in PRD.
10. Lessons Capture: We add determinstic harness to capture lessons learnt and post it to Shared team memory for next pipeline run.
Parallel Development across Frontend(Mobile/Web) and Backend
How do we set the environment for Parallel backend and frontend Development ?
-
The new/modified API endpoints might not be available to consume for mobile Dev Workers for frontend Development to complete.
-
Backend Dev Worker may have many dependent systems to validate against(other Services, dB, Cache, Queues, Auth, etc) for backend development to complete.
Introducing Prism
It is an open-source, command-line HTTP mock server and proxy tool created by Stoplight. It reads your API specification files (such as OpenAPI v2/v3) and automatically generates a live, local mock server that mimics how your real API will behave once it is built.
Before mobile worker is spawned we set up the mock server using Prism for new/modified endpoints consumed by App(iOS/Android) and inject into mobile worker’s environment. This way mobile worker can validate its work after implementing. This also helps during behavioural(User Scenario) testing of the .app / .apk during evaluation phase.
How will backend Worker validate its work implemented in a service ? It could have a long list of dependent systems to validate against. Use Mock Services for dependencies ? That helps structurally, how do we test the behaviour ?
Introducing Digital Twin Universe(DTU)
Everyone might have watched Stranger Things. !! The core premise of a digital twin is to create a living, breathing virtual replica of a physical asset. We want to create a breathing replica of entire backend system including vendors. But Why ? and How ?
First Lets see how DTU compares with Stranger Things:
Components of DTU
- FastAPI Server: It is a fastAPI server that contains all the endpoints(routes) there exists in the backend.
- State Management: We use Redis and Kafka for state management sync/async.
- Local Support: This helps us to inject DTU ports in the Agent’s local environment during its dev/eval workflows.
- Fidelity Pipeline: This pipeline helps us keep DTU high fidelity with Production. It is a behaviour sync mechanism between local DTU and Production backend system.
Fidelity Pipeline
we build a sync engine to keep our DTU high fidelity. So Agents get high quality test harness to verify its work against.
- Production Logs(Open Observe/ Datadog): We try to capture/extract signals from logs like request, response bodies, error shapes, latency, call graph, consumer ids, outbound vendor urls, traces, etc for last 30 days.
- Anonimyze, Dedupe, compute, classify: We strip all PII data, deduplicate and normalize endpoint paths, compute endpoint volumes, error rates, latency p50/p99 and classify as: new endpoint / existing / drifted / deprecated. We create a signal catalog based on this.
- Drift Detection: Before each run of the pipeline we run a sync_script to detect drift between DTU routes and catalog captured earlier. Drift could be related to endpoint change, shape drift, volume surge, deprecations, error rates, latency drift. We create a drift Report.
- Twin Patch Agent: For each service we run twin patch agents to patch the drift occured since last 30 days.
- Validation: After all patches applied we run the DTU and perform syntax, behavioural sanity and smoke tests. Also we perform coverage regression so number of paths covered in new DTU is greater than old DTU before sync.
- Commit & Publish with HIL: Now we commit and publish new DTU after human review for pipeline to consume.
Great, Now what do we do with DTU server built ? We inject it to evaluator Agents’ environment.
Introducing Evaluators(API/App)
Evaluators take the User scenarios already created(discussed earlier) and runs on the API endpoints and .app/.apk file and computes a satisfaction score. For Every failing user Scenario eval report is sent back to worker. We exit the loop after 3 iteration of Worker — Evaluator loop.
We have two types of evaluators:
- API Evaluator: It takes an endpoint, injects DTUs for existing dependent systems and perform scenario evaluations and comes up with a satisfaction score. DTUs help us double down in testing the behaviour of code against near production system currently running.
- Mobile Evaluator: Given test Credentials it installs and crawls the app file(headless simulator/emulator) using accessability ids/visual texts/screenshots. We use prism mocks for modified endpoint dependencies. For more details you can check Mobile App Testing Like a Human using Gen AI
PR Reviews at Scale
Of course not every line of code can be reviewed at scale. But do we need to review every line of code after we have evaluated the frontend/Backend Code against real user Scenarios(Using Mobile App Testing) and Real production system constraints**(using DTUs). We want to reserve human bandwidth for valuable tasks:**
- We dont want humans to review PRs w.r.t: Style, lint, Obvious bugs, Spec Drift, Missing tests, Repeated Patterns.
- We want humans to review PRs w.r.t: Security Sensitive Code, Product Sense and Taste, Trust Boundaries, Risk Tolerance and legal Reviews.
So we build a PR Agent to handle case 1. We integrated commentary Agent that gives Audio/Visual commentary on PR diff highlighting reviewer focus areas, blast radius of change, live Q&A and posts comments on PR. This helps to focus valuable human bandwidth on specific areas of Agent generated PRs at scale.
The Economics of Building this entire Pipeline
- After consuming millions of tokens to build this pipeline over a year, I figured it is cheaper than everyone in the team doing vibe coding trying to inject Team’s context every hour on their machines as shown above!!
- There is a cost to building this pipeline but cost to maintain flattens at scale. Controlling cost boils down to optimising just one pipeline across org/teams.!!
- I can have another post on cost reduction. Mostly, I have used Advisor Architecture for this pipeline as shown below:
Accuracy of the Pipeline
The accuracy of the pipeline is directly proportional to number of deterministic checkpoints and state machine we have. Consider adding deterministic eval harness or Agents will game the pipeline. Also consider building against Context Bloat, Context Drift, Progressive Disclosure optimisations, structured Input/Output and never use LLMs at control flows. There were many other constructs I have tried to improve the accuracy/repeatability of the pipeline that would require another post.
Thanks for Reading till the end. It has taken me around an year to build this pipeline. For understanding every step in great detail, I will share the github link in the comment section soon. !! Any Queries on building similar pipeline for your team ? Ping me on LinkedIn. Regards !!

