# AS0558844 Synthesis Architect — Forward Engineering Prompt

## Role

You are the Synthesis Architect responsible for forward-engineering the AS0558844 Excel/VBA regulatory risk-reporting EUC into a functional full-stack application.

The result must preserve the business behavior, operational workflow, screen meaning, validation rules, formulas, traceability, and visible spreadsheet structure evidenced by the supplied Knowledge Graph, the live Neo4j database, and the sanitised source workbook.

Do not generate CardDemo, payment-card, COBOL, CICS, BMS, or generic banking functionality.

## Execution Configuration

- `TARGET_LANGUAGE`: Python (backend), TypeScript + React (frontend)
- `TARGET_FRAMEWORK`: FastAPI (backend), React (frontend)
- `ARCH_STYLE`: Layered Architecture
- `EXECUTION_MODE`: SPA (frontend), REST API (backend)
- `DB_STRATEGY`: In memory
- `INFORMATION_PROCESSING_STRATEGY`: Realtime
- `INTERACTIVE_PHASE_GATES`: false

## Execution Paths

Use this directory as the execution root:

`hsbc/forward-eng/asset_kg_builder_cli/`

Use this consolidated Knowledge Graph:

`out/asset_kg_graph.json`

Generate the complete application under:

`code/`

Use this workbook for source-screen and calculation parity validation:

`../../Sanitised_HSBC_EUCs/AS0558844.xlsm`

The graph was built from the current Assets 1–7 stored under:

`assets/`

Do not use existing files under `code/` as source evidence. Regenerate the implementation from the authoritative graph and workbook evidence.

## Authoritative Evidence Contract

Use the following evidence order:

1. The live Neo4j graph and the consolidated `out/asset_kg_graph.json` are authoritative for technical lineage, VBA procedures, formulas, entry points, flows, business rules, logical data elements, epics, tests, and synthetic fixtures.
2. `AS0558844.xlsm` is authoritative for visible workbook surfaces, worksheet names, labels, table structure, reporting periods, presentation conventions, field groupings, and operator workflow.
3. Assets 1–7 provide the normalized contracts from which the consolidated graph was generated.
4. When evidence conflicts, preserve both facts in traceability and explain the chosen modern behavior. Never silently invent or discard fields.

Known source limitation: formula lineage is partial because extraction reached both the 10,000 range-reference-node limit and the 100,000 formula-dependency-link limit. Do not claim complete formula lineage.

## Knowledge Graph Reading Contract

The consolidated graph has:

- `nodes`: graph nodes.
- `links`: graph relationships.

Each node contains:

- numeric `id`
- `labels`
- label-specific `properties`

Each link contains:

- numeric `source`
- numeric `target`
- relationship `type`
- relationship `properties`

Build an index by `node.id` and traverse `links`. Do not treat nodes as an unrelated flat list.

Parse JSON-encoded properties before reasoning. Important properties include:

- `traceability`
- `data_contract`
- `outcome`
- `error_and_exception_semantics`
- `flow_refs`
- `data_refs`
- `implementation_footprint`
- `acceptance_criteria`
- `inputs`
- `expected_results`
- `targets`
- `payload`

Prioritize:

- `BusinessFunctionTier3`
- `LogicalDataElement`
- `PhysicalDataElement`
- `EntryPoint`
- `Flow`
- `FlowStep`
- `BusinessRule`
- `Epic`
- `AcceptanceCriteria`
- `PseudocodeBlock`
- `TestCase`
- `Dataset`
- `Entity`
- `EntityField`
- `LogicalElementSampleEntry`
- `DataElementCatalogEntry`
- `TechnicalNode`
- `Paragraph`

Preserve relationships such as:

- `TRACES_EPIC`
- `TRACES_RULE`
- `TRACES_FLOW`
- `TRACES_ENTRY_POINT`
- `TRACES_DATA_ELEMENT`
- `AC_REF_RULE`
- `AC_REF_FLOW`
- `AC_REF_LOGICAL_ELEMENT`
- `HAS_TEST_CASE`
- `DERIVED_TEST_CASE`
- `TARGETS_PSEUDOCODE`
- `RULE_INPUT`
- `RULE_OUTPUT`
- `READS`
- `WRITES`
- `HAS_NODE`
- `NEXT`
- `MAPS_TO_LOGICAL_ELEMENT`
- `LOGICAL_TO_PHYSICAL`

## Required Business Scope

Implement all four graph epics:

1. `EPIC1` — Import and normalize risk source feeds.
2. `EPIC2` — Rebuild the monthly comparison schedule.
3. `EPIC3` — Refresh the previous-month baseline and variance analysis.
4. `EPIC4` — Control workbook mode, adjustments, protection, and template export.

Implement the graph business rules `BR1` through `BR8`, including negative and rejection paths.

Use the graph VBA procedures as technical traceability, including:

- `importncrrdata`
- `importlobtemplate`
- `importprarwapack`
- `importtm1`
- `importoriskdata`
- `importccrdata`
- `clo_adjustment`
- `rebuildpage`
- `previousmonthschedule`
- `rebuildvariance`
- `presentationmode`
- `workmode`
- `protectcells`
- `unprotect`
- `addadjust`
- `exporttemplate`

## Mandatory Workbook-to-Application Screen Mapping

The modern application must expose a visible, testable mapping from each workspace to the corresponding workbook surface.

At minimum, implement:

| Modern workspace | Workbook evidence | Required behavior |
|---|---|---|
| Overview | `Dashboard`, `Version Control` | Show the LOB Template context, workbook identity, current reporting period, version, refresh state, and navigation to operational workspaces. |
| Reporting Controls | `Worksheet Controls` | Edit reporting month/year and previous month/year; run rebuild, snapshot, mode, protection, adjustment, and export actions. |
| Source Data Hub | `Base`, `CCR Data`, `CLO Data`, `Market Risk Data`, `Operational Risk Data`, `PRA RWA Pack`, `TM1 Data`, `Controls BSM` | Show source-feed status, import actions, representative tabular records, selected-row details, and source-sheet traceability. |
| Monthly Comparison | `Sched 2.1- Monthly Comparat` | Display current/prior RWA, EAD, capital/excess-EL measures, business segment rows, calculated variances, schedule rebuild status, and evidence. |
| Previous Month | `Previous Month` | Show the preserved prior-period schedule snapshot and snapshot metadata. |
| Variance Analysis | `Variance Analysis` | Display reference-code-level current/prior measures, absolute and percentage variances, missing-reference status, comments, row selection, and evidence. |
| Reconciliation Controls | `Controls` | Display current/prior reconciliation blocks, source-vs-schedule checks, RWA/EAD control totals, exceptions, and pass/fail status. |
| Adjustments and Export | VBA user forms and `exporttemplate` | Create an auditable manual adjustment, validate required inputs, and produce an export job/result without pretending to write back to the source workbook. |

The UI must state the source worksheet for every workspace. Include a context-sensitive Evidence panel that shows:

- workbook worksheet
- workbook cell/range or named evidence when known
- epic
- acceptance criteria
- entry point and flow
- business rules
- VBA procedures
- logical data elements
- modern API endpoint and service method
- verification method

## Screen Field Inventory and Parity Matrix

Before coding, create `docs/screen-parity.json` and `docs/screen-parity.md`.

For every implemented field or action, record:

- modern workspace
- source worksheet
- source range/cell/label
- legacy/VBA procedure when applicable
- logical data element
- modern field name
- component type
- role: input, output, readonly, computed, lookup, comment, confirmation, or action
- API mapping
- graph evidence
- implemented status
- test identifier
- omission reason when not implemented

Every row marked `implemented: true` must have:

1. A visible React control, readonly value, table column, detail value, or action.
2. A stable `data-testid`.
3. A backend DTO or an explicit `UI_ONLY` classification.
4. A parity test.

Silent omissions are forbidden.

## Target Architecture

Generate:

```text
code/
  README.md
  backend/
    pyproject.toml
    app/
      main.py
      api/
      domain/
      repositories/
      services/
      schemas/
      data/
      traceability/
    tests/
  frontend/
    package.json
    vite.config.ts
    tsconfig.json
    src/
      components/
      features/
      services/
      types/
      App.tsx
      main.tsx
      styles.css
    tests/
  docs/
    architecture.md
    screen-parity.json
    screen-parity.md
    traceability-matrix.md
    validation.md
```

### Backend Responsibilities

The FastAPI backend must own:

- Pydantic request/response contracts.
- Pure domain calculations and business rules.
- In-memory repositories and deterministic seed fixtures.
- Import workflow simulation.
- Current/prior schedule data.
- Variance calculations.
- Reconciliation checks.
- Adjustment audit records.
- Export job metadata.
- Traceability and screen-inventory endpoints.
- CORS configuration for the React development server.

Required endpoint groups:

- `/api/health`
- `/api/workbook`
- `/api/controls`
- `/api/sources`
- `/api/imports`
- `/api/schedule`
- `/api/previous-month`
- `/api/variance`
- `/api/reconciliation`
- `/api/adjustments`
- `/api/exports`
- `/api/traceability`
- `/api/screen-parity`

### Frontend Responsibilities

The React SPA must:

- Use a dense operational dashboard layout.
- Use restrained workbook-derived visual cues: red report headers, blue table headers, pale orange variance/current-prior emphasis, neutral enterprise navigation.
- Avoid marketing layouts, hero sections, gradients, and decorative illustrations.
- Render the first usable workspace immediately.
- Provide keyboard-accessible navigation and selectable table rows.
- Highlight selected rows and load their complete details.
- Show loading, success, validation, and error states.
- Keep the Evidence panel context-sensitive.
- Use the FastAPI REST API for operational data and actions.

## Functional Requirements

- Reporting-period changes must update the in-memory application context.
- Import cancellation or missing source name must produce a visible rejection.
- Imported sources must update their in-memory status and audit timestamp.
- CLO classification must distinguish `CLO` and `Non CLO`.
- Schedule rebuild must calculate current/prior variance values deterministically.
- Missing reference codes must return a visible `Ref Code not found` status.
- Previous-month snapshot must preserve the current baseline in the in-memory repository.
- Reconciliation must expose differences and an explicit pass/fail result.
- Mode/protection actions must update visible UI state.
- Adjustments must be auditable and require a reason.
- Export must create deterministic export metadata and must not claim that the original `.xlsm` was modified.

## Testing and Validation

Generate and run:

### Backend

- unit tests for `BR1`–`BR8`
- API tests for all endpoint groups
- negative-path tests
- deterministic calculation tests
- traceability and parity-contract tests

### Frontend

- component tests
- screen-inventory rendering tests
- representative row-selection tests for every table-backed workspace
- API integration mocks where appropriate
- production TypeScript build

### End-to-End

Run the backend and frontend, then validate with a real browser:

- application loads
- health and workbook context load
- each required workspace is reachable
- source worksheet is visible
- table rows can be selected
- period controls can be updated
- an import can succeed and reject invalid input
- schedule rebuild completes
- previous-month snapshot completes
- variance rows display
- reconciliation status displays
- adjustment validation works
- export job completes
- Evidence panel changes with the workspace

Capture the workbook-to-application mapping in the parity documents and in automated checks.

## Required Completion Standard

The task is complete only when:

- backend tests pass
- frontend tests pass
- frontend production build passes
- end-to-end browser smoke testing passes
- all required workspaces have workbook evidence
- screen parity and traceability documents are present
- no CardDemo or COBOL assumptions remain
- the application is runnable from the documented commands
- known graph extraction limits are disclosed

Generate the files directly under `code/`. Do not return placeholder pseudocode or a narrative-only answer.
