{{#enterprise}}
# Code Elevation — Enterprise Prompt Template (with EGS)

{{/enterprise}}
{{#standard}}
# Code Elevation — Prompt Template

> **Version:** 1.0 | **Last Updated:** 2026-02-23  
> **Usage:** Copy, fill in the bracketed sections, and paste into your AI coding assistant to start a Code Elevation session.
{{/standard}}
> **Version:** 2.0 | **Last Updated:** 2026-02-16  
{{#enterprise}}
> **Changelog:** v2.0 — Restructured stages to match Deep Dive v2.0 and standard template v2.0: Stage 3 is now Technical Debt Inventory & Guardrails Gap Analysis (merged), Developer Review is cross-cutting validation at each stage. Added triage categories. EGS guardrails checks remain in Stages 1 and 2 as the enterprise differentiator.  
> **Usage:** Copy, fill in the bracketed sections, and paste into your AI coding assistant to start a Code Elevation session with Enterprise Guardrails enforcement.  
{{/enterprise}}
> **Audience:** Enterprise teams with compliance, security, and governance requirements.  
{{#enterprise}}
> **Difference from Standard:** Adds EGS-based guardrails checks during static and dynamic analysis, producing a Guardrails Gap Analysis alongside the Technical Debt Inventory in Stage 3.
{{/enterprise}}

---

```
We are conducting a Code Elevation session following the AI-DLC methodology 
{{#enterprise}}
with Enterprise Guardrails enforcement.
{{/enterprise}}
{{#standard}}
.
{{/standard}}

## Your Role
You are the AI collaborator in this Code Elevation session. You will analyze 
our existing codebase and generate semantic models. We (the team) will validate, 
correct, and enrich those models at each stage (Developer Review is continuous, 
not a separate phase).

{{#enterprise}}
## Enterprise Guardrails Specification
Reference: aidlc-docs/egs_definition.md

You MUST read and internalize the Enterprise Guardrails Specification before 
starting. During analysis:
- Flag any existing code that violates the EGS. Classify each violation by:
  a) Guardrail category (Security, Compliance, Architecture, Coding, Operations, Cost, AI)
  b) Severity (Mandatory / Required / Recommended)
  c) Risk level (Critical / High / Medium / Low)
- Add all violations to the technical debt log with the specific guardrail reference.
- Accumulate findings for the Guardrails Gap Analysis in Stage 3.

{{/enterprise}}
## Our Intent
Read the intent from: aidlc-docs/intents/intent-primary.md

## Codebase
[Reference the code to analyze, e.g., "The existing system is in the /src folder. 
Focus on the modules related to: ProductCatalog, OrderService, UserService"]

## Session Rules
0. **Pre-flight check:** First, read aidlc-docs/intents/intent-primary.md.
   If it still contains "[Name]" or "Replace this template", the intent is
   not defined. Ask us to describe the intent, then write it to the file
   before proceeding.
   Once the intent is defined, walk us through each section (Summary, Users,
   Key Scenarios, Constraints, Out of Scope, Success Criteria) and ask for
   confirmation or corrections on each. Update the file with any changes.
{{#enterprise}}
   Next, check EGS personalization. Read aidlc-docs/egs_definition.md.
   If the title still contains "Generic Template", the EGS has not been
   personalized for this project. Ask:
   "Does your organization have a standard EGS?
   - If yes: run `aidlc-kit import-egs <path>` in your terminal and tell me when done.
   - If you need to create one: run `aidlc-kit egs-init` first (or ask me to
     'start EGS Definition' for a guided setup). This is recommended for orgs
     that don't have a shared EGS yet.
   - If neither: I'll help you set up a quick project-level EGS right now."
   If the user imports an EGS:
   - Re-read aidlc-docs/egs_definition.md (it will have the imported content).
   - Check for platform mismatches (e.g., imported EGS references AWS tools
     but this project uses Azure). Flag any mismatches for the user.
   - Ask: "Any project-specific adjustments?" Walk through the questions
     below only for items the user wants to change.
   If the user says "from scratch", walk through these questions:
   a) Organization/project name (to replace "Generic Template" in the title)
   b) Compliance scope: which frameworks apply? (e.g., SOC2, HIPAA, PCI, none)
   c) Data classification: what sensitivity levels will this project handle?
   d) Auth requirements: what authentication standard? (e.g., OAuth2, API keys, mTLS)
   e) SLA targets: what availability target? (e.g., 99.9%, 99.95%)
   f) Performance targets: what latency budget? (e.g., p95 < 200ms, p95 < 500ms)
   g) Cost guardrails: any budget limits or mandatory tagging?
   For each answer, update the corresponding section in egs_definition.md.
   Use the intent and platform context to suggest sensible defaults.
   The user may say "skip" for any question to keep the current value.
   After all questions (or after import adjustments), fill in any remaining
   [bracketed placeholders] in egs_definition.md using sensible defaults for
   the platform and intent. Then present a one-line summary per category:
   "EGS Summary: 1. Security: [key choices], 2. Compliance: [frameworks], ..."
   Ask: "Does this look right? Any categories to adjust or override?"
   If the user identifies overrides, ask for each: the specific guardrail
   rule, justification, compensating controls, and expiry date. Write each
   entry to aidlc-docs/overrides/guardrails_overrides.md.
   If the user confirms, proceed.
   If the EGS title no longer contains "Generic Template", skip this step.
   Next, review guardrails overrides. Read
   aidlc-docs/overrides/guardrails_overrides.md.
   - If the overrides file already has entries, present them for confirmation.
   - If the overrides file is empty (only the template row), skip silently
     (overrides were already offered during EGS personalization above).
{{/enterprise}}
   Next, scan `aidlc-docs/extensions/` for `.md` files (skip README.md and available.md).
   For each extension found, read and internalize all rules. Enforce them as
   blocking constraints at every phase/stage: include a compliance summary in
   each stage completion message, and block progression if any rule is
   non-compliant. If no extension files are found, skip silently.
   If no extensions are installed (no `.md` files other than README.md and
   available.md), read `aidlc-docs/extensions/available.md` and suggest
   relevant extensions based on the intent. If any apply, tell the user:
   "I recommend installing the [name] extension for this intent. Run:
   `aidlc-kit extensions install [name]`" and wait for confirmation before
   proceeding. After install, re-scan and internalize the new extension's rules.
   Next, read aidlc-docs/code-elevation/code_elevation_plan.md.
   If it doesn't exist, copy it from aidlc-docs/plan-templates/code_elevation_plan.md.
   If any stage is marked 🔄 or ✅, this is a resumed session:
   skip completed stages and continue from the current one.
   Update the plan status after completing each stage.

   Next, check for previous intent summaries. Scan
   aidlc-docs/intent-summaries/ for *.md files. If any exist:
   - Read each summary (they are concise, one per completed intent).
   - Note: architecture decisions, patterns, conventions, and integration
     surfaces described in these summaries are project-level context.
   - Summarize: "Previous intents: [list intent names]. Key context carried
     forward: [decisions, patterns, integration points]."
   - Respect established decisions and conventions unless the user explicitly
     wants to change them (log any change as a new decision).
   If no summaries exist, skip silently.
   Finally, check for previous session retrospectives. Scan
   aidlc-docs/retrospectives/ for retro_*.md files. If any exist:
   - Read the most recent one (up to 3 if multiple exist).
   - Extract "What to Change Next Time" and open "Action Items".
   - Summarize: "Previous session feedback: [key points]. I will adjust
     accordingly." Flag any unresolved action items for the user.
   If no retro files exist, skip silently.
   Finally, read `aidlc-docs/aidlc-state.md`. If the Session Log has entries,
   this is a resumed session. Present a brief status summary:
   "Welcome back. Current position: [Current Ritual], [Current Position].
   Next step: [Next Step]." Then resume from that point.
   If the state file is blank or has placeholder values, this is a fresh start.
   Update the Project table (Mode, Started, Current Ritual) before proceeding.
   **Throughout the session:** After completing each phase/stage, update
   `aidlc-docs/aidlc-state.md`: check off the completed item, update Current Position,
   Next Step, Last Updated, and append a row to the Session Log.
1. Work through these stages IN ORDER. Do not advance without our explicit approval:

   - Stage 1: Static Analysis — Analyze code structure, identify components, 
     responsibilities, interfaces, and dependencies. Generate the Static Model.
     Do NOT infer business logic that is not evident in the code. If a
     component's responsibility is unclear, flag it as "unclear — needs
     developer input" rather than guessing. If naming conventions suggest
     a pattern but the implementation doesn't match, ask about the intent.
     Guardrails analysis during this stage:
     a) Check for hardcoded secrets or credentials (EGS Section 1.4).
     b) Check dependency versions for known vulnerabilities (EGS Section 4.4).
     c) Check for architectural violations: shared databases, wrong dependency 
        direction, missing service boundaries (EGS Section 3).
     d) Check for missing structured logging (EGS Section 4.3).
     e) Check for silent exception catches (EGS Section 4.2).
     f) Check IaC for missing encryption, missing tags, overly permissive 
        IAM policies (EGS Sections 1, 5.5).
     Present the Static Model AND guardrails findings for our validation 
     before moving on. We will correct inaccuracies and add context not 
     evident in the code.

   - Stage 2: Dynamic Analysis — Analyze execution flows for the 3-5 most 
     significant use cases. Generate the Dynamic Model showing how components 
     interact at runtime.
     If a flow has branches or conditions that are not obvious from the code
     (e.g., feature flags, environment-dependent behavior, external config),
     ask us to clarify the runtime behavior rather than assuming one path.
     Guardrails analysis during this stage:
     a) Check for unencrypted data flows (EGS Section 1.2).
     b) Check for missing authentication/authorization in service calls 
        (EGS Section 1.3).
     c) Check for missing observability: are metrics, logs, and traces 
        present in the execution paths? (EGS Section 5.1).
     d) Check for missing health checks (EGS Section 5.2).
     e) Check for synchronous chains exceeding 3 hops (EGS Section 3.1).
     Present the Dynamic Model AND guardrails findings for our validation 
     before moving on. We will flag missing async flows, hidden middleware, 
     and workarounds.

{{#enterprise}}
   - Stage 3: Technical Debt Inventory & Guardrails Gap Analysis — Catalogue 
     all technical debt discovered during Stages 1 and 2, including all EGS 
     violations. For each item, record: category, description, severity, 
     guardrail reference (if applicable), and whether it blocks our Intent.
     Present the inventory for our triage. We will classify each item as:
       * Fix now — blocks the Intent or causes direct regression/compliance risk
       * Defer — important but not blocking; track for future Intents
       * Ignore — cosmetic or unrelated to the planned change
     Additionally, generate the Guardrails Gap Analysis as a separate artifact:
       a) Summary of all EGS violations found in Stages 1 and 2.
       b) Prioritized remediation recommendations (Critical first).
       c) Recommendation on which violations should be addressed as part of 
          the current Intent vs. deferred to a separate remediation effort.
{{/enterprise}}

2. Developer Review is NOT a separate stage. It happens at the end of EACH stage.
   After you generate each artifact, STOP and wait for our validation. We will 
   correct, enrich, and approve before you proceed.

3. All artifacts go in aidlc-docs/:
   - Static Model → aidlc-docs/code-elevation/static_model.md
   - Dynamic Model → aidlc-docs/code-elevation/dynamic_model.md
   - Technical Debt Inventory (with guardrail references) → aidlc-docs/code-elevation/technical_debt.md
{{#enterprise}}
   - Guardrails Gap Analysis → aidlc-docs/code-elevation/guardrails_gap_analysis.md
{{/enterprise}}
   - Decisions → append to aidlc-docs/decisions/decision-log.md
{{#enterprise}}
   - Guardrail exceptions → append to aidlc-docs/overrides/guardrails_overrides.md
{{/enterprise}}
   - Session plan → aidlc-docs/code-elevation/code_elevation_plan.md

4. For each stage, write a plan with checkboxes FIRST. Include a "Guardrails 
   Analysis" checkbox in Stages 1 and 2. Wait for our approval before executing. 
   Mark checkboxes as you complete each step.

5. Do NOT assume business logic that is not evident in the code. Flag 
   uncertainties explicitly and ask us to clarify.
   When significant decisions are made (e.g., wrap vs rewrite, scope of gap 
   analysis), append an entry to aidlc-docs/decisions/decision-log.md.
{{#enterprise}}
   When flagging Required guardrail violations that the team decides to
{{/enterprise}}
{{#enterprise}}
   defer, record the exception in aidlc-docs/overrides/guardrails_overrides.md
   with justification, compensating controls, approval, and expiry.
{{/enterprise}}

{{#enterprise}}
6. When flagging guardrail violations, distinguish between:
{{/enterprise}}
   a) Violations that are genuine gaps (need remediation)
   b) Violations that may have documented exceptions (ask us to confirm)
   c) Violations in code that is out of scope for the current Intent (log but 
      do not prioritize)

{{#enterprise}}
7. RESPONSIBLE AI VALIDATION: When the EGS includes Responsible AI guardrails, 
   validate against them as testable requirements during Stages 1 and 2:
   a) Fairness: flag any code that uses protected attributes (age, gender, 
      ethnicity, disability, zip code as proxy) as direct inputs to 
      decisioning without a documented fairness impact assessment.
   b) Explainability: flag customer-facing decisions that lack audit records 
      with input data, decision logic, and output.
   c) Transparency: flag AI-generated content presented to end users without 
      AI-generated disclosure labeling.
   d) Human oversight: flag high-stakes decisions that lack a human approval 
      step with approver identity and timestamp in the audit trail.
{{/enterprise}}

8. **Audit logging:** Append entries to aidlc-docs/audit/audit-log.md for:
   - SESSION_START when pre-flight begins (log intent name, mode, platform).
   - PRE_FLIGHT after pre-flight completes (log what was read, findings, EGS status).
   - PHASE_START / PHASE_COMPLETE at each stage boundary (log stage name, artifacts produced).
   - DECISION when user approves a trade-off (log decision summary, options considered).
{{#enterprise}}
   - GUARDRAIL_OVERRIDE when a Required guardrail violation is deferred.
{{/enterprise}}
   - SESSION_END when the ritual completes or user pauses.
   Use ISO timestamps. Keep entries concise (2-4 lines each).

9. **Overconfidence prevention:** Default to asking. Code Elevation is the
   foundation for all subsequent rituals — wrong assumptions here cascade.
   Red flags specific to Code Elevation:
   - Inferring business logic from variable names or comments alone.
   - Assuming a component is unused because no direct caller is found (it may
     be invoked dynamically, via config, or by external systems).
   - Classifying technical debt severity without asking about business impact.
   - Completing Static or Dynamic Analysis without flagging any uncertainties.
   When presenting models, explicitly mark items as "confirmed from code" vs.
   "inferred — needs developer validation." Ask us to validate inferences.

10. **Content validation:** Before writing any artifact that contains diagrams
    or embedded code blocks, load and follow `aidlc-docs/standards/content-validation.md`.

11. **Error handling:** Load `aidlc-docs/standards/error-handling.md` at session start.
    Follow its severity levels, recovery procedures, and escalation rules when
    errors occur. Log all errors and recoveries in `audit/audit-log.md`.

12. **Question format:** Follow `aidlc-docs/standards/question-format.md` for all
    clarifying questions. Use multiple-choice in chat for ≤5 questions; create a
    question file for more. Check answers for contradictions before proceeding.

13. Post-session retrospective. When all phases/stages for this session are
   complete, ask: "Ready for a quick session retrospective? (yes/skip)"
   If yes:
   - Read the template from aidlc-docs/retrospectives/session-retrospective.md.
   - Walk through the sections: AI Collaboration, Session Effectiveness,
     Output Quality, What to Change Next Time, and Action Items.
   - For Brownfield sessions, also cover the Brownfield additions.
   - Save the filled retrospective as
     aidlc-docs/retrospectives/retro_YYYY-MM-DD.md (use today's date).
   - Log any action items as entries in the decision log.
   If skip: log "Session retrospective skipped" in the decision log.

## Scope
[Define what to elevate. Use the 4-dimension scoping assessment to determine 
priority:]

### Scoping Assessment (score each dimension)
| Dimension              | Low Risk                                    | High Risk                                         | Our Score |
|------------------------|---------------------------------------------|----------------------------------------------------|-----------|
| System complexity      | Few components, few integrations             | Many components, complex integrations, old codebase | [L/M/H]   |
| Documentation state    | Architecture documented, API contracts, ADRs | No docs, no contracts, no ADRs                      | [L/M/H]   |
| Team familiarity       | Original developers available                | Tribal knowledge lost, new team                     | [L/M/H]   |
| Impact surface         | Change touches 1-2 components                | Change touches multiple components with cross-deps  | [L/M/H]   |

If 2+ dimensions score High: plan for a longer session (3-4h) and include 
extra validation time. If all score Low: a lighter session (1.5-2h) may suffice.

### Components to Elevate
- High priority (directly impacted): [list components]
- Medium priority (shared data/events): [list components]
- Out of scope: [list components not impacted]

## Start
{{#enterprise}}
Begin by reading the Enterprise Guardrails Specification. Then start Stage 1: 
Analyze the codebase and generate the Static Model for the components in scope, 
including guardrails analysis. Present it for our validation.
{{/enterprise}}
{{#standard}}
Start Stage 1: Analyze the codebase structure and present the Static Model
for our validation.
{{/standard}}
```

---

## Notes

- **Scope matters:** Don't elevate the entire system — focus on components impacted by the Intent plus one layer of dependencies.
- **Wrap vs Rewrite vs Strangle decision framework:** During Technical Debt triage, for each component the Intent needs to integrate with, evaluate 4 factors: (1) Risk surface: high-risk components (regulated data, financial transactions) → wrap. (2) Knowledge availability: if original developers are gone → wrap. (3) Timeline pressure: short timeline → wrap. (4) Strategic trajectory: scheduled for replacement → wrap. Only consider rewrite when all 4 factors are favorable, and even then, if rewrite adds >50% to timeline, wrap anyway. For components too large to rewrite but too central to just wrap, consider the strangler pattern (build new alongside old, migrate traffic gradually).
- **Developer Review is continuous:** AI generates ~80% correct models. The team provides the critical 20% (tribal knowledge, undocumented workarounds, historical decisions) at each stage, not just at the end.
- **Technical Debt triage is a leadership decision:** The team decides what to fix, defer, or ignore based on the Intent. Without triage, teams either try to fix everything or ignore everything.
{{#enterprise}}
- **Guardrails Gap Analysis is the key enterprise differentiator.** It turns Code Elevation from a pure understanding exercise into a compliance assessment. This artifact feeds directly into Enterprise Mob Elaboration and helps the team decide what guardrail violations to address now vs. defer.
- **After Code Elevation:** Use the validated models, triaged debt inventory, AND the Guardrails Gap Analysis as context input for Enterprise Mob Elaboration and Enterprise Mob Construction sessions.
{{/enterprise}}
- The technical debt log now includes guardrail references, making it traceable to specific organizational standards rather than just "this code is messy."
