← Financial Cloud Cloud Cloud Club · Builder Articles

Vertex Macro | Financial Cloud Cloud · Builder Articles

Kiro: Prompt Library and Deep Code Explanation Appendix

Series: Kiro workshop

Article: 23

Article
Kiro workshop
01 Build with Kiro: Prompt-First Product Design for a Tagalog Learning App
Kiro workshop
02 Build with Kiro: Educational-First Dev Tips for a Tagalog Learning App
Kiro workshop
03 Build with Kiro: Deep-Dive Development Flow for a Tagalog Learning App
Kiro workshop
04 Build with Kiro: Localize a Tagalog Learning App into Chinese Variants Workshop
Kiro workshop
05 Build with Kiro: Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards Workshop
Kiro workshop
06 Build with Kiro: Unique and Reviewable Extra Examples in a Tagalog Learning App Workshop
Kiro workshop
07 Build with Kiro: Factory Engineering Health Hooks Workshop
Kiro workshop
08 Build with Kiro: Etch Process Window Risk Test Automation Workshop
Kiro workshop
09 Build with Kiro: Photolithography Drift Risk Development Workshop
Kiro workshop
10 Engineering Team Get Started — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
11 Engineering Team Addendum — Daily Fab-Duty Use of fab spc drift sync portal
Kiro workshop
12 Kiro: Field Engineering Workshop for Spec-Driven Factory Software
Kiro workshop
13 Kiro: Hands-On Lab — Build a Typed Factory Risk Portal from Scratch
Kiro workshop
14 Kiro: Prompt, Code, and Type Standards Playbook for Engineering Developers
Kiro workshop
15 Kiro: Why a Strong React Prompt Prevents Type Declaration False-Starts
Kiro workshop
17 Build with Kiro: Create a Factory Automation Portal React UI
Kiro workshop
18 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
19 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
21 Kiro: 2-Hour Professional Developer Workshop Guide
Kiro workshop
22 Kiro: Build the Fab SPC Drift Synchronization Portal from Scratch
Kiro workshop
23 Kiro: Prompt Library and Deep Code Explanation Appendix
Kiro workshop
30 Build with Kiro: Create a Factory Automation Portal UI
Kiro workshop
31 Build with Kiro: Create the Automation Analytics Engine Behind a Factory Automation Portal
Kiro workshop
32 Build with Kiro: Add an AI Factory Automation Assistant to a Factory Automation Portal
Kiro workshop
33 Build with Kiro: Rebuild the CME Direct-Style Quant P&L Leaderboard UI
Kiro workshop
34 Build with Kiro: Recreate the Quant Analytics Engine Behind the P&L Board
Kiro workshop
35 Build with Kiro: AWS AI-Powered Trading Desk Assistant for the Quant Board
Kiro workshop
36 One-Page Trading Portal SOP
Kiro workshop
AgentCore
A1 Build with AgentCore & Strands: Gateway MCP Tool Fabric Developer Workshop
AgentCore
A2 Build with AgentCore & Strands: Governed Multi-Agent Risk System Developer Workshop
AgentCore
A3 Build with AgentCore & Strands: Runtime Sovereign Risk Agent Developer Workshop
AgentCore
Exam practice
E1 Build a Multilingual AWS Exam Practice Launch System with Vibe Coding
Exam practice
E2 Build an AWS Exam Practice Room with Vibe Coding Dev Tips
Exam practice
E3 Build the Practice Engine Behind a Static AWS Exam Room
Exam practice
Amazon Q
Q1 Amazon Q: CloudShell-First Developer Workshop for ACM Certificate Auto Renewal
Amazon Q
Tagalog Practice Room
T1 Build a Tagalog Learning App for AWS Manila Community Day with Prompt-First Product Design
Tagalog Practice Room
T2 Build Tagalog Learning App for AWS Manila Community Day with Educational-First Dev Tips
Tagalog Practice Room
T3 Deep Dive Development Flow for a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
T4 Build Localize a Tagalog Learning App into Chinese Variants for AWS Manila Community Day
Tagalog Practice Room
T5 Build a Grammar and Pronunciation Enrichment Pipeline for Tagalog Cards for AWS Manila Community Day
Tagalog Practice Room
T6 Make Extra Examples Unique and Reviewable in a Tagalog Learning App for AWS Manila Community Day
Tagalog Practice Room
Roadmap
R1 Enterprise Data Analytics Roadmap: 100 Deep Scenario Questions
Roadmap
R2 Front-End Development Roadmap: Real-World Enterprise Scenarios
Roadmap
Hong Kong Community Day
C1 A Hong Kong Weekend with AWS Community Day: From Cloud Sessions to Harbour Lights
Hong Kong Community Day
C2 The Speaker’s Luxury Weekend: Present an AWS Story, Then Let Hong Kong Take the Stage
Hong Kong Community Day
C3 Seventy-Two Hours in Hong Kong: The Grand Tour for an AWS Community Day Speaker
Hong Kong Community Day
Manila Community Day
C4 AWS Community Day Manila: A Joyful Weekend of Cloud, Culture, and True Friendship
Manila Community Day
C5 AWS Community Day Manila: Where Cloud Builders Find the Happiest Spirit of the Philippines
Manila Community Day
C6 AWS Community Day Manila: Build, Break, Repeat, and Belong in a City of Joy
Manila Community Day
C7 First-Time Visitor Tips for Manila, Philippines
Manila Community Day
Philippines × Hong Kong
C8 Philippines Hong Kong Capital Market Upgrade
Philippines × Hong Kong
Backtest
B1 Build Institutional Amazon Long-Only Backtesting Agents With Bedrock AgentCore And Strands Agents
Long-only AMZN agents with AgentCore, Strands, and a governed Backtrader ledger.
B2 Build Regime-Aware Amazon Position Management With Backtrader, AgentCore, And Strands Agents
Treat market regime as a position control, not a chart comment.
B3 Build Benchmark-Relative Amazon Timing Systems Using Nasdaq, S&P 500, Dow, AgentCore, And Strands
Time AMZN against Nasdaq, S&P 500, and Dow context.
B4 Build A Governed Amazon Trade-History Factory With Bedrock AgentCore, Strands Agents, And Backtrader
Turn backtests into an auditable trade-history factory.
B5 Build An Agentic Amazon Backtest Operating Model With Bedrock AgentCore And Strands Agents [Part 1]
Build the operating model before debating the result.
B6 Build A Custom Cerebro Code Talk For Amazon Timing And Position Management [Part 2]
Explain the Cerebro engine before explaining the chart.
B7 Build Trader Review Records For Amazon Strategy Results And Lessons Learned [Part 3]
Turn strategy ranks into trader review records.
B8 Build A Governed FSI Amazon Position Management Playbook With AgentCore And Strands [Part 4]
An FSI playbook for governed Amazon position management.
B9 Build a Sovereign Risk Trading Agent with Amazon Bedrock AgentCore for Yield Spreads, FX Hedging, and Debt Repricing
Sovereign-risk agent for yield spreads, FX hedges, and debt repricing.
B11 Build Modern Volatility Trading & Lawful Thailand Recovery Planning Agents: A Memory-Driven Strands Multi-Agent Risk Protection System
Memory-driven Strands agents for volatility and Thailand recovery.
B12 Build Short Straddle Trading-Risk Governance with Amazon Bedrock AgentCore Memory
Short-straddle risk governance with AgentCore Memory.
B13 Building Production-Ready Credit & Yield Staking AI Agents on Amazon EKS
Production credit and yield-staking agents on Amazon EKS.
Challenge
01 Weekend Productivity Challenge: Fab SPC Drift Synchronization Portal
Fab SPC drift review and recommendation portal.
02 Weekend Productivity Challenge: Quant P&L Commander — An AI-Powered Trading Productivity Portal on AWS
Quant P&L leaderboard and trading productivity portal.
03 Weekend Annoying Task Challenge: Trading Desk Execute Summary On Cloud, On Chain, On Air
DeskPulse daily execution communication.
04 Weekend Agent Challenge: The 6 AM Trading Risk Review
An unattended, evidence-backed morning credit and trading risk brief.
05 Weekend Creative Challenge: Leadership Card Game
A browser-based creative facilitation deck.
06 Full Stack Challenge: Community Day Board App
A browser-based event communication room.
Leadership Card Game
01 Leadership Card Game: Last Skill Cloud Did Not Automate
A field essay for Builders on language, courage, and the Leadership Card Game
02 Anatomy of a Leadership Round: How the Leadership Card Game Actually Plays
A facilitator’s field guide for Builders who want drills that fit inside real meetings
03 Leadership Card Game: When the Opportunity Stops Belonging to the Organizer
A field essay for Builders on power transfer, multilingual practice nights, and career arcs that complete Entrance, Resource, and Narrative
04 Weekend Creative Challenge: Leadership Card Game
Master high-stakes workplace conversations before they happen.
05 From a Weekend Challenge Project to $1,386 Crowdfunding: The Leadership Practice That Changes How You Show Up at Work
A weekend build became a live 600-card leadership practice room and reached $1,386 in crowdfunding.
06 From a Weekend Challenge Project to $1,386 Crowdfunding: A Day 1 Path Into the Tech Industry
How did a weekend challenge become a multilingual AWS-powered product with 600 cards and $1,386 in crowdfunding?
07 From a Weekend Challenge Project to $1,386 Crowdfunding: Build a Professional Brand by Transferring Opportunity
A weekend challenge reached $1,386 in crowdfunding by turning leadership ideas into a working multilingual product.
08 Leadership Card Game — Crowdfunding Campaign
Speak leadership before the room decides your career.
09 PR/FAQ 01 — Leadership Card Game launches for community builders
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Community managers, volunteer organizers, early-career…
10 PR/FAQ 02 — Enterprise facilitators adopt Leadership Card Game for live leadership drills
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Learning & development leads, people managers, agile…
10 PR/FAQ 03 — Multilingual Leadership Card Game opens global practice rooms for builder ownership
Working Backwards document · External press release + FAQ Product: Leadership Card Game Audience: Global AWS builders, bilingual communities, cross-border…
AWS Builder Center
01 AWS Builder Center, its community spirit, and AWS Builder Jacket
There are destinations you reach by plane, destinations you enter through a door, and destinations that begin with a sign-in screen and quickly feel like a…
02 Inside AWS Builder Center, where a global technical platform becomes a place to learn, contribute, and belong
A great journey does not always begin at an airport.
03 AWS Community Builder huge success
When builders share openly, the entire community moves forward.
04 AWS Builder Center huge success
A vibrant global district built for curiosity, public learning, and the AWS Builder Jacket.
05 A weekend inside AWS Builder Center, from community inspiration to unmistakable AWS Builder Jacket
Friday evening begins with a familiar builder feeling: there is an idea waiting somewhere between a problem and a possibility.

Educational engineering purpose only. This is a software architecture exercise and not process-release advice.

How to use this appendix

Use these prompts inside Kiro during the workshop. The prompts are intentionally specific because professional teams should give Kiro context, constraints, and acceptance criteria rather than vague requests.


Prompt set 1 — Project bootstrap

Prompt 1.1 — Create project skeleton

You are helping me build a professional TypeScript workshop project from scratch. Create the minimal Vite project files for a static browser application. Use no frontend framework. Include scripts for dev, build, test, test:watch, and lint. Do not add business logic yet.

Why this prompt works

  • It defines role, technology, and scope.
  • It blocks premature domain implementation.
  • It creates standard scripts that later hooks can call.

System design decision

  • The prompt narrows the first Kiro task. New projects can easily expand into unnecessary files. A skeleton-only request gives the team a controlled baseline and avoids mixing setup with product behavior.
  • No framework is an architectural constraint. The workshop is about Kiro’s AI engineering workflow, not component library usage. Plain TypeScript makes generated decisions more visible.
  • Standard scripts establish a stable contract. Future prompts, hooks, and documentation can reference npm test, npm run lint, and npm run build consistently.

Prompt set 2 — Steering

Prompt 2.1 — Generate foundational steering

Generate workspace steering files for this project. Create product.md, tech.md, structure.md, domain.md, and testing.md. The project is a local advisory-only Fab SPC portal. It must model CD-SEM risk but must never command equipment. Use deterministic TypeScript functions and Vitest tests.

Prompt 2.2 — Improve domain steering

Review .kiro/steering/domain.md. Add missing terms for SPC blind window, TMG, Mandel Slope, Fleet deviation, Residual 3σ, FDC health-link, APC guard, and yield-loss triage. Keep the language concise and enforce advisory-only behavior.

System design decision

  • Steering prompts should be explicit about prohibited behavior. For engineering tools in sensitive domains, it is not enough to describe what to build. Developers must also define what must not be generated.
  • Domain vocabulary belongs in workspace memory. Once Kiro understands the terms, subsequent spec, code, and test generation are more consistent. This reduces repeated explanation and prevents terminology drift.
  • Testing expectations belong in steering. If deterministic functions and Vitest coverage are stated early, Kiro is more likely to generate testable structure instead of tightly coupled UI code.

Prompt set 3 — Spec creation

Prompt 3.1 — Create spec

Create a Kiro spec named fab-spc-portal. The feature is a local browser portal for detecting when routine SPC monitoring frequency is out of sync with actual mass production. Include requirements, system design, data model, risk scoring, UI behavior, accessibility, tests, and implementation tasks.

Prompt 3.2 — Strengthen acceptance criteria

Refine the requirements. Add acceptance criteria for: TMG above UCL, Mandel Slope outside 0.98–1.02, Fleet deviation above 2σ and 3σ, Residual 3σ above 0.18 nm, blind window above six hours, empty search results, and advisory-only safety language.

System design decision

  • The first prompt creates an end-to-end plan. Kiro should understand the feature as a system, not a collection of random files. Requirements, design, and tasks form a traceable delivery path.
  • The second prompt hardens edge cases. Initial AI specs can miss boundary conditions. Asking for specific thresholds and empty states makes the final code easier to validate.
  • The spec becomes reviewable evidence. Developers can compare generated implementation against the spec and reject code that diverges. This is especially important for professional teams adopting AI-assisted delivery.

Prompt set 4 — Domain logic

Prompt 4.1 — Implement pure risk functions

Implement the risk engine as pure TypeScript functions. Inputs are CdSemTool objects. Outputs are RiskAssessment objects with score, level, action, and reasons. Do not read the DOM, localStorage, network, clock, or random values. Keep thresholds centralized.

Prompt 4.2 — Ask for risk priority review

Review the risk engine priority order. Fleet deviation >3σ and Mandel Slope outside 0.98–1.02 should result in HoldReview. TMG above UCL should result in ApcGuard unless a higher-priority hold condition exists. Residual 3σ above limit should result in RunGoldenWafer unless a higher-priority condition exists.

System design decision

  • Pure functions reduce non-determinism. Kiro-generated code is easier to trust when calculations do not depend on external state. Developers can test, review, and refactor the domain layer confidently.
  • Central thresholds improve maintainability. Thresholds scattered across UI and tests create future drift. A single constants section makes review and per-layer extensions straightforward.
  • Priority review prevents misleading recommendations. A generic score can hide severe conditions. Explicit priority rules ensure safety-relevant findings dominate lower-level watch states.

Prompt set 5 — UI implementation

Prompt 5.1 — Render dashboard

Implement the UI rendering layer. Show summary metrics, tool rows, risk score, blind-window age, TMG, slope, Fleet σ, residual 3σ, action button, and reason details. Add search and sort. Keep rendering separate from risk calculations.

Prompt 5.2 — Accessibility review

Review the UI for accessibility. Add semantic headings, button labels, sufficient contrast, keyboard-accessible interactions, useful empty states, and readable status text. Do not change domain logic.

System design decision

  • The UI consumes assessments rather than computing them. This keeps visual code focused on rendering, interaction, and accessibility. Business rules remain in the domain layer.
  • Search and sort reveal model quality. A good generated UI should support operational workflows, not just display cards. Sorting by risk, TMG, slope, and Fleet deviation makes the portal useful.
  • Accessibility is treated as implementation quality. Developers should ask Kiro to review semantics and interaction states, then manually inspect results. Accessibility cannot be an afterthought.

Prompt set 6 — Tests

Prompt 6.1 — Generate tests

Generate Vitest tests for the risk engine. Cover healthy release, TMG ApcGuard, Mandel Slope HoldReview, Fleet deviation HoldReview, residual RunGoldenWafer, blind-window Watch, reason strings, and priority ordering when multiple thresholds are breached.

Prompt 6.2 — Ask for missing cases

Analyze the current risk tests and list missing edge cases. Focus on threshold equality, just-over thresholds, negative inputs, NaN handling, empty series, and action priority conflicts. Do not modify files yet.

System design decision

  • Threshold boundary tests are mandatory. Production bugs often appear at exactly the limit. Kiro should test equality and just-over cases so rule interpretation is explicit.
  • Invalid data handling must be deliberate. A demo can be simple, but professional developers should decide how negative values, NaN, or missing arrays are handled rather than letting generated code behave accidentally.
  • Analysis before modification improves control. Asking Kiro to list missing tests first gives developers a review checkpoint before accepting generated changes.

Prompt set 7 — Hooks

Prompt 7.1 — Create command hook

Create a Kiro workspace hook that runs npm test after saving files under src/domain or tests. Use PostFileSave, a narrow matcher, command action, 60-second timeout, and enabled true.

Prompt 7.2 — Create documentation hook

Create a Kiro agent hook that updates docs/decision-log.md after a spec task is completed. The hook should summarize changed files, decisions made, and follow-up risks. Keep it workspace-local and do not modify source code.

System design decision

  • Command hooks are used for deterministic checks. Tests and linting have clear pass/fail behavior, so automation is safe and measurable.
  • Agent hooks are used for narrative work. Decision logs involve summarization and context. Kiro’s language capability is useful there, but the hook should be scoped to documentation.
  • Matchers protect developer productivity. Hooks should fire only when relevant files change. Over-broad automation creates noise, slows development, and reduces trust.

Complete code reference — domain layer

src/domain/types.ts

export type AdvisoryAction =
  | "Release"
  | "Watch"
  | "RunGoldenWafer"
  | "RouteLimit"
  | "ApcGuard"
  | "HoldReview";

export type RiskLevel = "low" | "medium" | "high" | "critical";

export interface CdSemTool {
  id: string;
  layer: string;
  symptom: string;
  blindWindowHours: number;
  tmgNm: number;
  mandelSlope: number;
  fleetDeviationSigma: number;
  residualThreeSigmaNm: number;
  deltaMeanSeries: number[];
}

export interface RiskAssessment {
  toolId: string;
  score: number;
  level: RiskLevel;
  action: AdvisoryAction;
  reasons: string[];
}

Explanation

Business logic: The types define the domain contract used across the portal. They make risk inputs and outputs clear.

Code logic: AdvisoryAction and RiskLevel are union types, so invalid strings are rejected by TypeScript. Interfaces define required fields.

Expected result: Kiro-generated modules share the same data contract and fail fast during type checking if fields drift.


Complete code reference — risk engine

src/domain/risk.ts

import type { AdvisoryAction, CdSemTool, RiskAssessment, RiskLevel } from "./types";

const LIMITS = {
  tmgUclNm: 0.2,
  slopeLow: 0.98,
  slopeHigh: 1.02,
  fleetWatchSigma: 2,
  fleetHoldSigma: 3,
  residualUclNm: 0.18,
  blindWindowWatchHours: 6
};

export function assessTool(tool: CdSemTool): RiskAssessment {
  let score = 0;
  const reasons: string[] = [];

  if (tool.tmgNm > LIMITS.tmgUclNm) {
    score += 30;
    reasons.push("TMG exceeds demo UCL");
  }

  if (tool.mandelSlope < LIMITS.slopeLow || tool.mandelSlope > LIMITS.slopeHigh) {
    score += 25;
    reasons.push("Mandel Slope outside safe range");
  }

  if (tool.fleetDeviationSigma > LIMITS.fleetHoldSigma) {
    score += 35;
    reasons.push("Fleet deviation exceeds hold threshold");
  } else if (tool.fleetDeviationSigma > LIMITS.fleetWatchSigma) {
    score += 20;
    reasons.push("Fleet deviation exceeds watch threshold");
  }

  if (tool.residualThreeSigmaNm > LIMITS.residualUclNm) {
    score += 20;
    reasons.push("Residual 3σ exceeds noise threshold");
  }

  if (tool.blindWindowHours > LIMITS.blindWindowWatchHours) {
    score += 15;
    reasons.push("SPC blind window is stale");
  }

  const normalizedScore = Math.min(score, 100);

  return {
    toolId: tool.id,
    score: normalizedScore,
    level: classifyRisk(normalizedScore),
    action: chooseAction(tool, normalizedScore),
    reasons: reasons.length > 0 ? reasons : ["No threshold breach detected"]
  };
}

export function classifyRisk(score: number): RiskLevel {
  if (score >= 85) return "critical";
  if (score >= 65) return "high";
  if (score >= 35) return "medium";
  return "low";
}

export function chooseAction(tool: CdSemTool, score: number): AdvisoryAction {
  if (tool.fleetDeviationSigma > LIMITS.fleetHoldSigma) return "HoldReview";
  if (tool.mandelSlope < LIMITS.slopeLow || tool.mandelSlope > LIMITS.slopeHigh) return "HoldReview";
  if (tool.tmgNm > LIMITS.tmgUclNm) return "ApcGuard";
  if (tool.residualThreeSigmaNm > LIMITS.residualUclNm) return "RunGoldenWafer";
  if (score >= 65) return "RouteLimit";
  if (score >= 35) return "Watch";
  return "Release";
}

Explanation

Business logic: The function converts fab metrology indicators into risk severity and an advisory action. It highlights which indicators drove the decision.

Code logic: Each threshold contributes to score and reasons. The score is capped at 100. Action selection uses priority rules to prevent severe conditions from being downgraded.

Expected result: Developers can trust the portal to consistently classify known conditions and explain why a tool is risky.


Complete code reference — hook

.kiro/hooks/test-domain-on-save.json

{
  "version": "v1",
  "hooks": [
    {
      "name": "test-domain-on-save",
      "description": "Run risk tests when domain logic or tests are saved.",
      "trigger": "PostFileSave",
      "matcher": "^(src/domain/.*\\.ts|tests/.*\\.ts)$",
      "action": {
        "type": "command",
        "command": "npm test"
      },
      "timeout": 60,
      "enabled": true
    }
  ]
}

Explanation

Business logic: Domain behavior must remain stable because it drives advisory actions.

Code logic: The hook watches a narrow path pattern and runs a deterministic command after save.

Expected result: Developers get immediate feedback when changes break risk calculations.


Final capstone prompt

Act as a senior technical reviewer. Compare the implementation with the Kiro spec and steering files. Identify gaps in requirements coverage, domain correctness, tests, accessibility, maintainability, and hook safety. Return a prioritized list with recommended fixes. Do not change files.

Final developer exercise

Ask Kiro to implement one of the reviewer recommendations, but only after you:

  1. Identify the spec requirement it maps to.
  2. Predict which files should change.
  3. Predict which tests should be added or updated.
  4. Review the generated diff.
  5. Run the hook-triggered or manual test command.

# Expanded Prompt and Code Appendix: HTML Demo Migration with Kiro

This appendix adds deeper prompt patterns and code examples based on the Fab SPC Drift Synchronization HTML demo. Use these prompts when teaching developers how to move from a working browser prototype to a modular, tested Kiro-created project.

Prompt set 8 — Demo ingestion and structured analysis

Prompt 8.1 — Explain before changing

Read the HTML demo and explain its architecture before making changes. Group findings into: layout, styling system, data model, risk board behavior, chart rendering, tab state, FDC matrix, runbook rendering, live simulation, and safety boundaries. Then propose target TypeScript modules.

Prompt 8.2 — Create migration tasks

Create implementation tasks to migrate the HTML demo into a TypeScript/Vite app. Each task must have input files, output files, acceptance criteria, and test strategy. Preserve visual behavior as much as possible but improve architecture, accessibility, and testability.

System design decision

  • Explanation-first prompting reduces blind generation. Kiro should show that it understands the source prototype before it writes replacement modules. This prevents accidental behavior loss.
  • Migration tasks must include tests. Refactoring a working demo without tests is risky. Each task should identify how developers will verify behavior after extraction.
  • The prompt distinguishes parity from improvement. The goal is not to copy every implementation detail. The goal is to preserve user-visible behavior while improving structure, accessibility, and safety.

Prompt set 9 — Extract CSS design system

Prompt 9.1 — Extract CSS tokens

Extract the visual design system from the HTML demo into src/styles.css. Preserve the dark factory-portal style, CSS variables, cards, grids, tabs, board rows, metric boxes, responsive breakpoints, and chart styling. Remove unused selectors and group CSS by responsibility.

Code sample — CSS token extraction

:root {
  --bg: #061018;
  --panel: #081522;
  --panel2: #0c1f31;
  --line: #28465f;
  --text: #edf6ff;
  --muted: #9fb3c8;
  --cyan: #38bdf8;
  --cyan2: #77c7ff;
  --green: #31c48d;
  --red: #f05252;
  --yellow: #f6c85f;
  --orange: #fb923c;
  --mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Arial, sans-serif;
}

body {
  margin: 0;
  color: var(--text);
  font-family: var(--sans);
  min-height: 100vh;
  background:
    linear-gradient(rgba(255, 255, 255, 0.025) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.025) 1px, transparent 1px),
    radial-gradient(circle at 8% 0, rgba(56, 189, 248, 0.19), transparent 30%),
    #061018;
  background-size: 32px 32px, 32px 32px, auto, auto;
}

.card,
.panel,
.chart-card,
.metrics {
  border: 1px solid var(--line);
  background: #06111c;
  padding: 14px;
}

Explanation

Business logic: The portal’s visual identity communicates an engineering operations console: dark background, cyan/yellow highlights, metric cards, and risk colors.

Code logic: CSS variables centralize color and typography decisions. Shared card selectors avoid repeating border/background/padding rules.

Expected result: The TypeScript project keeps the HTML demo’s dark factory-portal style while organizing CSS for maintainability.

System design decision

  • Design tokens preserve visual consistency. Extracting variables first prevents style drift as Kiro generates new components.
  • Shared selectors reduce duplication. The original demo uses repeated panel/card patterns. Grouping them makes future UI sections easier to add.
  • Responsive rules remain in CSS. Layout adaptation belongs in CSS, not TypeScript. This keeps rendering code focused on content and behavior.

Prompt set 10 — Rendering decomposition

Prompt 10.1 — Generate render module

Create src/ui/render.ts that composes the portal sections from smaller render functions. Include renderHeader, renderHero, renderStats, renderTabs, renderRiskBoard, renderFdcMatrix, renderMatchingSection, renderTriageSection, and renderRunbook. Do not put risk calculations inside this file.

Code sample — render composition

import type { CdSemTool, FdcHealthLink, RiskAssessment, RunbookStep } from "../domain/types";
import { renderRiskBoard } from "./board";

export interface AppViewModel {
  tools: CdSemTool[];
  assessments: RiskAssessment[];
  fdcHealthLinks: FdcHealthLink[];
  runbookSteps: RunbookStep[];
}

export function renderApp(root: HTMLElement, model: AppViewModel): void {
  root.innerHTML = `
    <main class="page" id="top">
      <section class="shell">
        ${renderHeader()}
        ${renderHero()}
        ${renderStats(model)}
        <section class="content">
          ${renderTabs()}
          ${renderOverview()}
          ${renderRiskBoard(model.tools, model.assessments)}
          ${renderFdcMatrix(model.fdcHealthLinks)}
          ${renderRunbook(model.runbookSteps)}
        </section>
        ${renderFooter()}
      </section>
    </main>
  `;
}

Explanation

Business logic: The renderer assembles the same high-level sections as the demo portal: header, hero, stats, tabs, risk board, FDC, runbook, and footer.

Code logic: renderApp receives a view model and delegates each section to smaller functions. It does not compute risk or mutate data.

Expected result: Developers can review, test, and modify sections independently instead of editing one large HTML string.

System design decision

  • A view model boundary keeps rendering predictable. The renderer receives all data it needs, which makes it easier to test and avoids hidden global dependencies.
  • Small render functions help Kiro produce reviewable diffs. If the FDC matrix changes, Kiro should edit that renderer rather than a giant page function.
  • Domain logic is deliberately excluded. Rendering should display decisions, not make them. This allows risk rules to be tested without DOM setup.

Prompt set 11 — Board row and status color prompts

Prompt 11.1 — Render board rows

Implement renderRiskRow(tool, assessment). It should display rank, tool id, layer, symptom, risk score, blind window, TMG, Mandel Slope, Fleet σ, and action label. Match the HTML demo's color logic: high risk is red, watch is yellow, safe is green/cyan.

Code sample — status tone utility

export type Tone = "pos" | "neg" | "yellow" | "cyan";

export function riskTone(score: number): Tone {
  if (score >= 80) return "neg";
  if (score >= 55) return "yellow";
  return "pos";
}

export function thresholdTone(value: number, limit: number, direction: "above-is-bad" | "below-is-bad"): Tone {
  if (direction === "above-is-bad") {
    return value > limit ? "neg" : "pos";
  }

  return value < limit ? "neg" : "pos";
}

export function slopeTone(slope: number): Tone {
  return slope < 0.98 || slope > 1.02 ? "neg" : "pos";
}

Explanation

Business logic: Engineers need visual severity cues for risk score, TMG breach, slope mismatch, Fleet deviation, and residual noise.

Code logic: Utility functions centralize color-class decisions and prevent duplicated conditional expressions across renderers.

Expected result: UI color behavior remains consistent with the HTML demo and becomes easier to test.

System design decision

  • Tone logic is UI logic, not domain action logic. The domain decides recommendations. The UI decides color classes. Separating them prevents visual changes from altering business decisions.
  • Named utilities improve reviewability. slopeTone() is easier to understand than repeated inline comparisons. Kiro should generate expressive helper names.
  • Color classes preserve prototype style. Using pos, neg, yellow, and cyan keeps compatibility with the demo CSS while still modularizing the code.

Prompt set 12 — Security and escaping prompts

Prompt 12.1 — Add HTML escaping

Review all render functions that interpolate tool id, layer, symptom, FDC descriptions, and runbook text. Add an escapeHtml utility and use it consistently. Keep trusted static SVG structure unchanged.

Code sample — src/ui/escapeHtml.ts

export function escapeHtml(value: string): string {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#039;");
}

Explanation

Business logic: Today’s workshop data is static, but future data may come from files, APIs, exports, or user input. Displayed engineering text must not become executable markup.

Code logic: The helper replaces HTML-sensitive characters with safe entities before strings are inserted into templates.

Expected result: Tool symptoms and FDC text render as text even if they contain characters such as <, >, or &.

System design decision

  • Security improvements are part of professionalizing a demo. A prototype can assume trusted strings. A developer workshop should demonstrate safer defaults.
  • Escaping belongs near rendering. Domain modules should not know about HTML. Render utilities should handle presentation-layer encoding.
  • Kiro should be asked to review injection paths. AI-generated template strings can accidentally interpolate unescaped content. A dedicated prompt catches this risk.

Prompt set 13 — Kiro-generated commit plan

Prompt 13.1 — Create commit-sized implementation plan

Split the remaining work into commit-sized changes. Each commit should include purpose, files changed, tests to run, and review risks. Keep each commit small enough for a senior developer to review in under ten minutes.

Example output

## Commit 1 — Domain contracts and fixtures
Files:
- src/domain/types.ts
- src/data/tools.ts
- src/data/fdc.ts
- src/data/runbook.ts

Tests:
- npm run lint

Review risks:
- Action labels must remain advisory-only.
- Fixture values must match demo intent.

## Commit 2 — Risk engine
Files:
- src/domain/thresholds.ts
- src/domain/risk.ts
- tests/risk.test.ts

Tests:
- npm test
- npm run lint

Review risks:
- Priority order for HoldReview vs ApcGuard.
- Boundary behavior at exact thresholds.

System design decision

  • Commit planning makes AI work reviewable. Large AI diffs are hard to trust. Commit-sized plans preserve engineering discipline.
  • Each commit includes tests. Developers should know exactly how to validate a change before accepting it.
  • Review risks are explicit. Kiro can help identify where human attention is needed, but the developer remains accountable for the final decision.

Additional code sample — Threshold constants from the demo

export const demoThresholds = {
  tmgUclNm: 0.2,
  slopeLow: 0.98,
  slopeHigh: 1.02,
  fleetWatchSigma: 2,
  fleetHoldSigma: 3,
  residualThreeSigmaUclNm: 0.18,
  siteToSiteDeltaUclNm: 0.3,
  blindWindowWatchHours: 6
} as const;

Explanation

Business logic: The thresholds mirror the demo’s decision boundaries: TMG UCL, Mandel Slope safe range, Fleet warning and hold limits, residual noise limit, site-to-site limit, and stale blind-window limit.

Code logic: as const makes the object readonly and preserves literal values, helping TypeScript catch accidental mutation.

Expected result: All risk logic imports the same thresholds instead of duplicating numbers.


Additional code sample — action priority table as code

import type { AdvisoryAction, CdSemTool } from "./types";
import { demoThresholds } from "./thresholds";

export function choosePriorityAction(tool: CdSemTool, score: number): AdvisoryAction {
  const t = demoThresholds;

  if (tool.fleetDeviationSigma > t.fleetHoldSigma) {
    return "HoldReview";
  }

  if (tool.mandelSlope < t.slopeLow || tool.mandelSlope > t.slopeHigh) {
    return "HoldReview";
  }

  if (tool.tmgNm > t.tmgUclNm) {
    return "ApcGuard";
  }

  if (tool.residualThreeSigmaNm > t.residualThreeSigmaUclNm) {
    return "RunGoldenWafer";
  }

  if (tool.blindWindowHours > t.blindWindowWatchHours) {
    return "RunSpc";
  }

  if (score >= 65) {
    return "RouteLimit";
  }

  if (score >= 35) {
    return "Watch";
  }

  return "Release";
}

Explanation

Business logic: The portal should recommend the strongest advisory action when multiple risk factors are present. Fleet hold and slope mismatch dominate because they indicate systemic metrology trust issues.

Code logic: The function evaluates high-priority threshold breaches first, then falls back to score-based actions.

Expected result: A tool with both stale SPC and slope mismatch receives HoldReview, not merely RunSpc or Watch.


Additional code sample — risk reason codes

export type RiskReasonCode =
  | "TMG_ABOVE_UCL"
  | "SLOPE_OUT_OF_RANGE"
  | "FLEET_SIGMA_WATCH"
  | "FLEET_SIGMA_HOLD"
  | "RESIDUAL_NOISE_HIGH"
  | "BLIND_WINDOW_STALE"
  | "NO_THRESHOLD_BREACH";

export interface RiskReason {
  code: RiskReasonCode;
  message: string;
  evidence: string;
}

Explanation

Business logic: Reason codes make recommendations easier to audit, test, translate, and summarize.

Code logic: A structured reason contains a stable code, a human-readable message, and evidence such as fleetDeviationSigma=3.2.

Expected result: The UI can display clear explanations while tests assert stable reason codes.


Additional prompt — ask Kiro to upgrade reasons

Refactor risk reasons from plain strings into structured reason objects with code, message, and evidence. Update tests to assert reason codes. Update UI to display message and evidence. Preserve existing action behavior.

System design decision

  • Structured reasons are better than plain strings. Tests should not depend on exact sentence wording. Codes provide stable assertions while messages remain user-friendly.
  • Evidence fields improve auditability. A recommendation should show which metric caused it and what value was observed.
  • Refactoring reasons is a safe Kiro task. Because action behavior is already tested, developers can ask Kiro to improve explainability without changing decisions.

Final extended capstone prompt

Perform a final migration review. Compare the TypeScript/Vite app to the original HTML demo. Confirm parity for: header, hero, stats, tabs, risk board, sorting, search, detail panels, FDC matrix, matching section, triage section, runbook, SVG charts, responsive layout, and advisory-only safety text. Then identify production-hardening gaps such as data validation, authentication, audit logging, telemetry, model governance, and integration boundaries. Do not modify files.

Final extended developer exercise

  1. Ask Kiro to identify one missing parity item.
  2. Ask Kiro to propose the smallest code change to fix it.
  3. Predict the files that will change.
  4. Ask Kiro to implement only that change.
  5. Review the diff manually.
  6. Run tests.
  7. Update the decision log.