極點宏觀|Financial Cloud Cloud · 建構文章
與 Kiro 一同建構:打造工廠自動化入口網站背後的自動化分析引擎
僅供工程教學工作坊使用。此為軟體架構演練,而非正式發佈之製程建議。
摘要: 本獨立工作坊旨在教導開發者如何使用 Kiro、TypeScript、純製程視窗函式、SVG 圖表產生器、測試以及受控的即時模擬,重新建構最新工廠自動化入口網站(Factory Automation Portal)的 JavaScript 分析與互動邏輯。開發者將實作製程變動量(deltas)、漂移(drift)、訊號波動度(signal volatility)、效率比(efficiency ratio)、P05 變動量、最佳變動量、最差變動量、視窗率(window rate)、排序、搜尋過濾、走勢圖路徑(sparkline paths)、製程視窗指標曲線、漂移水位線(drift waterlines)、直方圖、狀態圖磚圖表、頁籤互動狀態保留,以及具備完整原型覆蓋率與審查任務的更新迴圈安全性。
工作坊目的
這場 2 小時的工作坊將焦點放在工廠自動化入口網站展示背後的分析與互動引擎。本工作坊不側重於 UI 樣式,而是將原型的 JavaScript 行為萃取至可測試的 TypeScript 模組中。開發者將學習如何使用 Kiro 來設計確定性的製程視窗函式、測試邊緣情況、解釋指標含意、保留狀態圖磚與排行榜的行為,並將即時更新模擬明確限制在展示行為內。
學習目標與原始的分析引擎工作坊架構一致:捕捉每個 JavaScript 輔助函式、為簡短的原型函式定義專業的領域名稱、撰寫確定性測試,並保護圖表幾何形狀免於發生退化(regressions)。所有內容皆已全面更新至最新的入口網站展示。
展示涵蓋範圍地圖
本工作坊涵蓋以下入口網站實作細節:
● runtimeCards 陣列:包含六個執行期工作台項目:同步執行期(Synchronous Runtime)、串流執行期(Streaming Runtime)、大型負載執行期(Large Payload Runtime)、承載資料驗證(Payload Validation)、冒煙測試(Smoke Tests)、工作階段清理(Session Cleanup)。
● tools 陣列:包含四個工具:throughput_throughput、metrology_drift_widening、process_window_drift 和 tool_to_tool_mismatch。
● specialists 陣列:包含四個受治理的代理:throughput、metrology、overlay 和 etch-process。
● runbook 陣列:包含從 0-10 到 115-120 的八個時間軸步驟。
● 製程視窗資料列陣列 P:包含 8 個自動化工作站(cells)、製程模式、指標 %、變動量 %、穩定度、PF、WR、偏態(Skew)、最大漂移以及索引序列。
● 狀態圖磚陣列 M:包含 Runtime、Tools、Policy 和 Eval 等通道(lanes)、變動值、整備狀態以及微型序列。
● 格式化輔助函式:sg(正負號數值)、cl(語意類別)和 id(詳細資料面板 ID)。
● 計算輔助函式:ret、dd、avg、sd 和 perc,對應至專業的 TypeScript 函式。
● SVG 輔助函式:path、spark、gridlines、eqChart、ddChart 和 hist。
● 詳細資料面板建構器 panel:包含衍生的高階指標與 architecture 自動化筆記。
● data 中的搜尋與排序行為。
● render 中的資料列轉譯與開啟面板狀態保留。
● tog 中的分析切換行為。
● markets 中的狀態圖磚轉譯。
● clock 中的即時 HKT 時鐘。
● 5 秒受控的製程視窗模擬更新迴圈。
目標開發者
● 欲將儀表板數學公式轉換為經測試模組的 TypeScript 開發者。
● 學習如何為自動化入口網站設計確定性計算模式的開發者。
● 需要產生可重現圖表路徑的前端工程師。
● 學習如何利用 Kiro 審查數學公式、邊緣情況、模擬行為及互動式儀表板一致性的平台工程師。
兩小時議程
| 時間 | 模組 | 開發者產出 |
|---|---|---|
| 0:00-0:10 | 擷取需求 | 來自入口網站 HTML 展示的分析功能清單 |
| 0:10-0:25 | Kiro 引導規範 | 指標正負號、單位、測試及模擬規則 |
| 0:25-0:45 | 指標引擎 | 變動量、漂移、波動度、百分位數、效率比 |
| 0:45-1:05 | 聚合引擎 | 搜尋、排序、面板狀態保留、狀態統計 |
| 1:05-1:25 | SVG 圖表引擎 | 走勢圖、指標曲線、漂移水位線、直方圖路徑 |
| 1:25-1:45 | 即時模擬 | 受控的更新迴圈與狀態安全性 |
| 1:45-1:55 | 測試 | 單元測試、測試基礎資料(fixture)與屬性導向測試 |
| 1:55-2:00 | Kiro 審查 | 邊緣情況與生產環境強化待辦事項 |
系統架構
src/domain/
├─ types.ts # AutomationCell, StatusTile, RuntimeCard, ToolCard, SpecialistCard, RunbookStep, Metrics, SortKey
├─ fixtures.ts # 從入口網站展示複製的 P, M, runtimeCards, tools, specialists, runbook
├─ formatting.ts # 帶正負號的百分比、語意類別、慢速命名 ID (slug ID)
├─ calculations.ts # 變動量、漂移、波動度、百分位數、自動化指標
├─ portalAnalytics.ts # 搜尋、排序、統計、資料列模型、面板模型
├─ charts.ts # SVG 路徑與圖表模型函式
├─ simulator.ts # 確定性更新迴圈輔助函式
├─ chartAudit.ts # 供審查的圖表元資料
└─ __tests__/
├─ calculations.test.ts
├─ portalAnalytics.test.ts
├─ charts.test.ts
├─ simulator.test.ts
├─ fixtures.test.ts
└─ chartAudit.test.ts
自動化指標定義與審查用途
| 指標 | 展示公式或解讀方式 | 工程審查用途 |
|---|---|---|
| 視窗指標 (Window Index) | (最後一個指標 / 第一個指標 - 1) * 100。 |
量測所顯示製程視窗樣本中的累積變動。 |
| 每日變動量 (Daily Delta) | (今日指標 / 昨日指標 - 1) * 100。 |
顯示短期變動並驅動直方圖條條。 |
| 訊號波動度 (Signal Volatility) | 每日變動量的標準差乘以 sqrt(252)。 |
比較各自動化工作站之間的訊號強度。 |
| 漂移 (Drift) | (當前指標 / 執行峰值 - 1) * 100。 |
偵測工作站低於其局部高水位線的程度。 |
| 最大漂移 (Max Drift) | 該序列中的最小漂移值。 | 用作製程視窗審查的壓力指標。 |
| 效率比 (Efficiency Ratio) | 視窗指標除以最大漂移的絕對值。 | 在展示中比較指標變動與漂移壓力。 |
| P05 變動量 (P05 Delta) | 簡化展示中每日變動量的第五百分位數。 | 突顯下尾部變動以供審查討論。 |
| 最佳變動量 (Best Delta) | 最大每日變動量。 | 識別單一週期內最大的向上移動。 |
| 最差變動量 (Worst Delta) | 最小每日變動量。 | 識別單一週期內最大的向下移動。 |
| 視窗率 (Window Rate) | 正向每日變動量除以總變動量次數。 | 量測一致性,而非因果品質。 |
| 製程因子 (Process Factor) | 來自自動化工作站資料的展示資料列品質指標,顯示為 PF。 | 支援入口網站中的資料列比較,但不代表自動化操作。 |
| 穩定度 (Stability) | 展示資料列品質分數,顯示為 Stability。 | 支援跨展示工作站的排名與比較。 |
| 偏態 (Skew) | 展示資料列的不對稱性指標。 | 標記審查人員可透過圖表元資料檢查的不對稱性。 |
步驟 1 — 為製程視窗計算加入 Kiro 引導規範
建立 .kiro/steering/process-math.md:
# 製程數學引導規範
- 將所有顯示的變動量(deltas)和指標變動視為百分點,而非小數。
- 漂移值必須為零或負數。
- 在此展示中,P05 變動量為每日變動量的第五百分位數。
- 訊號波動度使用 sqrt(252) 年化計算,以呼應原型設計的計算風格。
- 保持所有計算函式為純函式且無副作用。
- 請勿杜撰實際設備資料或製程發佈聲明。
- 展示模擬必須明確標記為模擬行為。
- 除非工作坊明確要求建立合成固定裝置(fixtures),否則請保留原始入口網站的值與序列。
建立 .kiro/steering/testing.md:
# 測試引導規範
每個製程視窗公式都需要確定性的單元測試。
使用屬性導向測試(property-style tests)來驗證不變量,例如漂移量 <= 0。
測試空陣列、單點陣列、平坦指標、全漲指標、全跌指標、無效指標以及極端漂移。
在模擬測試中使用注入的隨機值。
驗證來自入口網站展示的所有八個自動化單元序列和四個狀態圖磚序列。
給 Kiro 的提示詞範例
Create a spec for extracting the latest factory automation portal JavaScript into TypeScript analytics modules. Include process-window formula definitions, sort and search behavior, SVG path generation, live simulation behavior, fixture parity, status-tile analytics, tests, edge cases, and production-hardening tasks.
商業邏輯: 引導規範在程式碼產生之前先定義了指標的含意。開發者需要一致的單位和正負號慣例,以避免產生誤導性的排名。
程式邏輯: Kiro 使用引導規則來產生純函式與測試,而不是將計算邏輯嵌入 UI 轉譯過程中。
預期結果: Kiro 為自動化分析引擎產出需求/設計/任務流程。
系統設計原理解析:
● 製程數學引導規範是強制性的,因為原型包含諸如 ret、dd 和 perc 等簡短的輔助名稱;生產環境開發者需要明確的定義。
● 測試引導規範與數學規範分離,因為測試覆蓋率是一項工程政策,而非數學公式。
● 禁止杜撰實際資料的規則,能確保工作坊的真實性。模擬資料僅能在明確標記為展示行為時使用。
步驟 2 — 定義型別
建立 src/domain/types.ts:
export type SortKey = 'indexPct' | 'deltaPct' | 'stability' | 'processFactor' | 'windowRatePct' | 'maxDriftPct';
export type RuntimeCard = {
title: string;
body: string;
tags: string[];
};
export type ToolCard = {
name: string;
desc: string;
signals: string[];
};
export type SpecialistCard = {
name: string;
focus: string;
tools: string;
};
export type RunbookStep = [string, string, string];
export type AutomationCell = {
name: string;
strategy: string;
indexPct: number;
deltaPct: number;
stability: number;
processFactor: number;
windowRatePct: number;
skew: number;
maxDriftPct: number;
series: number[];
};
export type AutomationMetrics = {
windowIndexPct: number;
signalVolPct: number;
efficiencyRatio: number;
p05DeltaPct: number;
bestDeltaPct: number;
worstDeltaPct: number;
windowRatePct: number;
maxDriftPct: number;
};
export type StatusTile = {
key: 'RUNTIME' | 'GATEWAY' | 'POLICY' | 'EVAL';
move: string;
state: 'READY' | 'WATCH';
up: boolean;
series: number[];
};
商業邏輯: 型別文件化了哪些數值是原始輸入,哪些是衍生的分析結果。它們也保留了 Runtime、Tools、Governed 和 Runbook 面板所需的非資料列入口網站資料。
程式邏輯: SortKey 模擬了展示中的排序按鈕。AutomationCell 對應製程視窗的資料列物件,而 AutomationMetrics 則對應詳細資料面板中的區塊。
預期結果: TypeScript 在開發期間能捕捉到無效的排序鍵值、缺失的固定裝置欄位或不完整的入口網站面板資料。
系統設計原理解析:
● 明確的型別取代了隱式的 JavaScript 物件形狀。
● 排序鍵值使用領域名稱,而非 UI 標籤(如 INDEX、PF 或 DRIFT),這使程式碼更容易理解,同時在展示層保留原有的標籤。
● 衍生指標與自動化工作站輸入分離,因為諸如 P05 變動量和效率比等數值是由序列計算而得,而非手動維護。
步驟 3 — 完整複製入口網站固定裝置
建立 src/domain/fixtures.ts:
import type { AutomationCell, RuntimeCard, RunbookStep, SpecialistCard, StatusTile, ToolCard } from './types';
export const runtimeCards: RuntimeCard[] = [
{ title: 'Synchronous Runtime', body: 'runtime entrypoint in app.py validates prompt, injects request and session context, runs an AI assistant backed by Amazon Bedrock, and returns structured engineering analysis.', tags: ['app.py', 'FactoryAutomationApp', 'boto3 invoke'] },
{ title: 'Streaming Runtime', body: 'Async entrypoint yields incremental chunks from agent.stream_async so portals and chat interfaces can render analysis progressively.', tags: ['app_streaming.py', 'async', 'partial output'] },
{ title: 'Large Payload Runtime', body: 'Base64 Excel and image fields are decoded into typed document and image content payloads for combined factory engineering analysis.', tags: ['xlsx', 'png', 'base64'] },
{ title: 'Payload Validation', body: 'Local validators check required prompt field, optional metadata, and unknown top-level fields before runtime invocation.', tags: ['JSON Schema', 'fail fast', 'client contract'] },
{ title: 'Smoke Tests', body: 'Deterministic tests validate payload contract and Python calculation tools without model calls, credentials, or latency.', tags: ['pytest', 'deterministic', 'local'] },
{ title: 'Session Cleanup', body: 'Runtime sessions are treated as managed resources and stopped explicitly after workflow completion.', tags: ['session ID', 'cleanup', 'operations'] },
];
export const tools: ToolCard[] = [
{ name: 'throughput_throughput', desc: 'Assess WIP queue stress, tool availability pressure, wafer throughput, and hot-lot preference.', signals: ['queue depth', 'tool availability', 'wafer throughput', 'hot-lot preference'] },
{ name: 'metrology_drift_widening', desc: 'Assess inline and lot-level drift widening, CD-SEM pressure, yield-loss watch, and measurement capacity.', signals: ['inline drift', 'lot drift', 'CD-SEM index', 'yield-loss watch'] },
{ name: 'process_window_drift', desc: 'Assess process capability, overlay error, recipe divergence, lot flow, and process-window drift.', signals: ['overlay error', 'process capability', 'recipe divergence', 'lot flow'] },
{ name: 'tool_to_tool_mismatch', desc: 'Assess overlay mismatch, backlog pressure, baseline offsets, and control context.', signals: ['overlay mismatch', 'baseline offsets', 'control context', 'tool matching'] },
];
export const specialists: SpecialistCard[] = [
{ name: 'throughput', focus: 'throughput stability, WIP queue stress, hot-lot preference, and tool capacity depth', tools: 'bpu_change, throughput_buffer' },
{ name: 'metrology', focus: 'CD-SEM drift widening, yield-loss pressure, defect-risk drift, and measurement capacity', tools: 'bpu_change' },
{ name: 'overlay', focus: 'tool-to-tool mismatch, lot flow, overlay drift, baseline offsets, and control context', tools: 'control_amount' },
{ name: 'etch-process', focus: 'overlay error, process capability, recipe divergence, controller reaction, and process-window drift', tools: 'bpu_change' },
];
export const runbook: RunbookStep[] = [
['0-10', 'Environment and architecture check', 'Confirm AWS identity, region, Python environment, project resources, and role boundaries.'],
['10-25', 'Prompt and schema contracts', 'Create runtime system prompt, orchestrator prompt, canonical tool schema, and payload contract.'],
['25-45', 'Local agent and tooling build', 'Implement AI assistance tools, local runtime logic, local FastAPI tool server server, and discovery client.'],
['45-65', 'Validation, policy, and smoke tests', 'Run payload validators, deterministic tool smoke tests, policy tests, and tool schema linting.'],
['65-85', 'Managed deployment', 'Launch runtime, package Lambda target, create AWS tool gateway, and register tooling target.'],
['85-105', 'Invocation and debugging', 'Invoke runtime with boto3, run Tools semantic search, direct tools/call, and tools/list debugging.'],
['105-115', 'Governed orchestration', 'Run specialists, bounded memory, response policy checks, and structured observability events.'],
['115-120', 'Evaluation and handoff', 'Run safe and blocked evaluation fixtures, capture session ID, cleanup, and backlog follow-up tasks.'],
];
export const automationCells: AutomationCell[] = [
{ name: 'Sofia Garcia', strategy: 'Etch Endpoint Depth Multi-Step Recipe Control', indexPct: 18.4, deltaPct: 0.42, stability: 0.73, processFactor: 1.8, windowRatePct: 58, skew: 0.44, maxDriftPct: 18, series: [100,101,100.7,102.2,104,103.2,105.7,106.1,108,109.8,111,112.4,114.9,116.2,118.4] },
{ name: 'Lucia Fernandez', strategy: 'Photolithography Overlay Drift Detection', indexPct: 16.9, deltaPct: 0.88, stability: 0.91, processFactor: 1.7, windowRatePct: 61, skew: 0.31, maxDriftPct: 22, series: [100,102.1,101.5,103.8,102.9,106.4,108.2,107.5,110.8,112.2,111.6,114.1,115.2,116,116.9] },
{ name: 'Carmen Lopez', strategy: 'Chamber Matching RF Power Pressure Stability', indexPct: 14.2, deltaPct: -0.31, stability: 0.68, processFactor: 1.6, windowRatePct: 56, skew: 0.22, maxDriftPct: 25, series: [100,99.4,101.7,103.2,104.8,103.7,106.8,108.9,110.4,109.2,112.6,113.8,115.1,114.8,114.2] },
{ name: 'Elena Martin', strategy: 'Factory Line Yield Trend Automation', indexPct: 11.8, deltaPct: 0.17, stability: 0.62, processFactor: 1.5, windowRatePct: 54, skew: 0.18, maxDriftPct: 17, series: [100,100.8,101.1,102.5,103.2,104,103.8,105.4,106.2,107,108.9,109.3,110.2,111.1,111.8] },
{ name: 'Marta Sanchez', strategy: 'Recipe Parameter Relative Stability', indexPct: 9.6, deltaPct: 0.09, stability: 0.57, processFactor: 1.4, windowRatePct: 53, skew: 0.09, maxDriftPct: 15, series: [100,100.2,99.9,101,101.8,102.5,102.2,103.6,104.1,105.4,106,106.8,108.2,109,109.6] },
{ name: 'Paula Romero', strategy: 'Metrology Feature Ensemble Scoring', indexPct: 7.1, deltaPct: -0.12, stability: 0.49, processFactor: 1.3, windowRatePct: 52, skew: -0.04, maxDriftPct: 14, series: [100,100.5,101.2,100.8,102.1,102.7,103.4,104.2,103.8,105,105.4,106.2,106.8,107.3,107.1] },
{ name: 'Ana Torres', strategy: 'Endpoint Signal Breakout Alarm System', indexPct: 5.4, deltaPct: 0.28, stability: 0.42, processFactor: 1.2, windowRatePct: 51, skew: 0.12, maxDriftPct: 19, series: [100,99.1,100.4,101.6,100.8,102.2,101.5,103.4,102.8,104.2,103.8,104.7,105.1,105.2,105.4] },
{ name: 'Laura Navarro', strategy: 'Multi-Tool Mean Reversion Control', indexPct: 3.8, deltaPct: -0.06, stability: 0.35, processFactor: 1.1, windowRatePct: 49, skew: -0.11, maxDriftPct: 16, series: [100,100.4,99.8,100.9,101.4,100.6,101.8,102.2,101.7,102.8,103.1,102.9,103.6,103.9,103.8] },
];
export const statusTiles: StatusTile[] = [
{ key: 'RUNTIME', move: '+0.38%', state: 'READY', up: true, series: [20,21,20,22,23,23,24,25,24,26] },
{ key: 'GATEWAY', move: '-0.22%', state: 'WATCH', up: false, series: [30,29,31,28,27,26,25,24,23,22] },
{ key: 'POLICY', move: '+0.62%', state: 'READY', up: true, series: [18,18.5,19,18.7,20,21,20.5,22,23,23.5] },
{ key: 'EVAL', move: '+2.18%', state: 'READY', up: true, series: [20,22,21,24,26,25,29,28,32,34] },
];
商業邏輯: 固定裝置保留了入口網站作為單一事實來源。開發者應能證明每個可見的資料列、圖磚、卡片和執行手冊步驟都得到了呈現。
程式邏輯: 此檔案映射了原始的 JavaScript 陣列,並為 React、測試、分析模組和文件提供一個具備型別定義的匯入路徑。
預期結果: 固定裝置測試可以斷言數量:6 個執行期卡片、4 個工具、4 個專家、8 個執行手冊步驟、8 個自動化單元和 4 個狀態圖磚。
步驟 4 — 實作計算邏輯
建立 src/domain/calculations.ts:
import type { AutomationMetrics } from './types';
export function deltasPct(series: number[]): number[] {
if (series.length < 2) return [];
return series.slice(1).map((value, index) => ((value / series[index]) - 1) * 100);
}
export function driftPct(series: number[]): number[] {
if (!series.length) return [];
let peak = series[0];
return series.map(value => {
peak = Math.max(peak, value);
return peak === 0 ? 0 : ((value / peak) - 1) * 100;
});
}
export function average(values: number[]): number {
return values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;
}
export function standardDeviation(values: number[]): number {
const m = average(values);
return values.length ? Math.sqrt(average(values.map(v => (v - m) ** 2))) : 0;
}
export function percentile(values: number[], p: number): number {
if (!values.length) return 0;
const sorted = [...values].sort((a, b) => a - b);
const index = Math.min(sorted.length - 1, Math.max(0, Math.floor((p / 100) * sorted.length)));
return sorted[index];
}
export function automationMetrics(series: number[]): AutomationMetrics {
const deltas = deltasPct(series);
const drift = driftPct(series);
const windowIndexPct = series.length >= 2 ? ((series.at(-1)! / series[0]) - 1) * 100 : 0;
const maxDriftPct = drift.length ? Math.min(...drift) : 0;
return {
windowIndexPct,
signalVolPct: standardDeviation(deltas) * Math.sqrt(252),
efficiencyRatio: maxDriftPct === 0 ? 0 : windowIndexPct / Math.abs(maxDriftPct),
p05DeltaPct: percentile(deltas, 5),
bestDeltaPct: deltas.length ? Math.max(...deltas) : 0,
worstDeltaPct: deltas.length ? Math.min(...deltas) : 0,
windowRatePct: deltas.length ? deltas.filter(x => x > 0).length / deltas.length * 100 : 0,
maxDriftPct,
};
}
商業邏輯: 這些函式使用專業名稱和安全的空陣列處理行為,重新實現分析面板的邏輯。
程式邏輯: 此段程式碼將原型的輔助工具轉換為可組合的函式。automationMetrics 聚合了詳細資料面板中顯示的特定區塊數值。
預期結果: 傳入 Sofia 的指標序列會傳回約 18.4% 的視窗指標、負值最大漂移以及面板所需的進階分析數值。
系統設計原理解析:
● 純函式使分析引擎可供 UI、API、測試或批次作業使用。
● automationMetrics 集中管理面板計算,使 React 詳細資料面板不需重複撰寫公式。
● 百分位數方法故意呼應了簡化的展示邏輯。生產環境系統在將下尾部摘要用於營運決策前,需要更健全的資料治理。
步驟 5 — 實作排序、過濾、摘要統計與面板模型
建立 src/domain/portalAnalytics.ts:
import type { AutomationCell, SortKey, StatusTile } from './types';
import { automationMetrics } from './calculations';
export function signed(value: number, digits = 1, suffix = ''): string {
return `${value >= 0 ? '+' : ''}${value.toFixed(digits)}${suffix}`;
}
export function semanticClass(value: number): 'pos' | 'neg' {
return value >= 0 ? 'pos' : 'neg';
}
export function slugId(value: string): string {
return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
}
export function searchAndSort(cells: AutomationCell[], query: string, sortKey: SortKey): AutomationCell[] {
const q = query.trim().toLowerCase();
return cells
.filter(cell => !q || cell.name.toLowerCase().includes(q) || cell.strategy.toLowerCase().includes(q))
.sort((a, b) => sortKey === 'maxDriftPct' ? a.maxDriftPct - b.maxDriftPct : b[sortKey] - a[sortKey]);
}
export function portalLeaderboardStats(cells: AutomationCell[]) {
return {
cellCount: cells.length,
bestStability: Math.max(...cells.map(cell => cell.stability)),
avgWindowRatePct: cells.reduce((sum, cell) => sum + cell.windowRatePct, 0) / cells.length,
bestIndexPct: Math.max(...cells.map(cell => cell.indexPct)),
};
}
export function statusTileSummary(tiles: StatusTile[]) {
return {
tileCount: tiles.length,
readyCount: tiles.filter(tile => tile.state === 'READY').length,
watchCount: tiles.filter(tile => tile.state === 'WATCH').length,
};
}
export function analysisPanelModel(cell: AutomationCell) {
return {
id: slugId(cell.name),
owner: cell.name,
strategy: cell.strategy,
metrics: automationMetrics(cell.series),
automationNote: `Automation path: runtime validates payload and session context; Tools discovers or calls domain tools; Lambda returns structured evidence; specialists synthesize throughput, metrology, overlay, and etch-process findings; policy checks confirm boundary terms; telemetry is emitted with request ID and trace ID. Domain context: ${cell.strategy}.`,
};
}
商業邏輯: 使用者可以依據指標、變動量、穩定度、製程因子、視窗率或漂移進行排名,並依據擁有者或製程模式進行搜尋。
程式邏輯: 此函式重現了展示的 data、panel、architecture 和狀態摘要行為。最大漂移採用升序排序,因為在原始邏輯中,較低的漂移壓力代表較佳的狀態。
預期結果: 依指標排序時 Sofia 會排在第一位。搜尋 overlay 會傳回 Lucia Fernandez。搜尋 metrology 會傳回 Paula Romero。搜尋 tool 會傳回 Laura Navarro。
系統設計原理解析:
● 排序邏輯自轉譯流程中分離,如此一來,測試便能在不依賴 UI 的情況下驗證排名行為。
● 搜尋同時比對擁有者與策略,因為入口網站允許使用者透過製程模式來探索資料列。
● 最大漂移排序屬於特例處理,因為壓力指標的方向性通常與正向指標相反。
步驟 6 — 實作 SVG 路徑輔助函式
建立 src/domain/charts.ts:
import { deltasPct, driftPct } from './calculations';
export function svgPath(values: number[], width: number, height: number, padding = 18): string {
if (!values.length) return '';
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
const innerWidth = width - padding * 2;
const innerHeight = height - padding * 2;
return values.map((value, index) => {
const x = padding + index * innerWidth / Math.max(1, values.length - 1);
const y = padding + innerHeight - ((value - min) / range) * innerHeight;
return `${index ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`;
}).join(' ');
}
export function histogramBars(deltas: number[], width: number, height: number, padding = 18) {
const maxAbs = Math.max(...deltas.map(Math.abs), 1);
const barWidth = (width - padding * 2) / Math.max(1, deltas.length);
const mid = height / 2;
return deltas.map((value, index) => {
const barHeight = Math.abs(value) / maxAbs * (height / 2 - padding);
return {
x: padding + index * barWidth + 1,
y: value >= 0 ? mid - barHeight : mid,
width: Math.max(2, barWidth - 2),
height: barHeight,
positive: value >= 0,
};
});
}
export function sparklineModel(values: number[]) {
return { viewBox: '0 0 120 32', path: svgPath(values, 120, 32, 2) };
}
export function indexChartModel(series: number[]) {
return {
viewBox: '0 0 680 190',
path: svgPath(series, 680, 190, 20),
label: `Index ${series[0]?.toFixed(1) ?? '0.0'} to ${series.at(-1)?.toFixed(1) ?? '0.0'}`,
};
}
export function driftChartModel(series: number[]) {
const drift = driftPct(series);
return {
viewBox: '0 0 680 120',
drift,
maxDriftPct: drift.length ? Math.min(...drift) : 0,
};
}
export function deltaHistogramModel(series: number[]) {
const deltas = deltasPct(series);
return {
viewBox: '0 0 680 120',
deltas,
bars: histogramBars(deltas, 680, 120, 18),
};
}
商業邏輯: 比起單純的數字,圖表能幫助開發者更快理解趨勢、漂移壓力以及每日製程變動量的分佈。
程式邏輯: svgPath 呼應了原型路徑產生器。histogramBars 將變動量轉換為正向/負向長條條的矩形幾何圖形。圖表模型函式將資料準備流程與 React/SVG 轉譯流程解耦。
預期結果: 同一個指標序列可以生成走勢圖、製程視窗指標圖、漂移模型和每日變動量直方圖模型。
系統設計原理解析:
● 圖表幾何形狀在純函式中計算,因此可以在不依賴瀏覽器渲染的情況下進行測試。
● 路徑函式將數值正規化到檢視區(view box)。這使得同一個輔助函式既能支援微型走勢圖,也能支援大型圖表。
● 直方圖條條帶有正向旗標(positive flag),因此 UI 可以直接套用綠色或紅色樣式,不需重新計算正負號邏輯。
步驟 7 — 實作受控的即時模擬
建立 src/domain/simulator.ts:
import type { AutomationCell } from './types';
export function nextTick(cells: AutomationCell[], random = Math.random): AutomationCell[] {
return cells.map(cell => {
const bump = (random() - 0.48) * 0.18;
const nextDeltaPct = Number((cell.deltaPct + bump).toFixed(2));
const nextIndexPct = Number((cell.indexPct + bump * 0.25).toFixed(2));
return {
...cell,
deltaPct: nextDeltaPct,
indexPct: nextIndexPct,
series: [...cell.series.slice(1), 100 + nextIndexPct],
};
});
}
商業邏輯: 展示看板每五秒更新一次,以模擬即時的自動化看板。開發者必須將其明確標記為模擬資料,而非實際設備資料。
程式邏輯: 此函式呼應了更新迴圈,但使隨機性可被注入,以利進行確定性測試。
預期結果: 每個週期(tick)會調整變動量、微幅調整指標、移動系列視窗,並附加一個新的合成指標點。
系統設計原理解析:
● 注入隨機性是因為測試需要確定性的行為。
● 該序列透過捨棄最舊的數據點來使用滾動視窗。這保留了圖表長度並避免了無限制的記憶體增長。
● 該函式傳回新物件而非變更原始陣列,符合 React 狀態管理預期。
步驟 8 — 加入測試
建立 src/domain/__tests__/calculations.test.ts:
import { describe, expect, it } from 'vitest';
import { automationMetrics, driftPct, deltasPct } from '../calculations';
describe('process-window calculations', () => {
it('calculates deltas from indexed series', () => {
expect(deltasPct([100, 110, 99]).map(x => Number(x.toFixed(2)))).toEqual([10, -10]);
});
it('drift is never positive', () => {
expect(driftPct([100, 120, 90, 130]).every(x => x <= 0)).toBe(true);
});
it('creates automation panel metrics', () => {
const metrics = automationMetrics([100, 105, 99.75]);
expect(Number(metrics.windowIndexPct.toFixed(2))).toBe(-0.25);
expect(Number(metrics.maxDriftPct.toFixed(2))).toBe(-5.00);
});
});
建立 src/domain/__tests__/fixtures.test.ts:
import { describe, expect, it } from 'vitest';
import { automationCells, runtimeCards, runbook, specialists, statusTiles, tools } from '../fixtures';
describe('portal fixtures', () => {
it('preserves portal fixture counts', () => {
expect(runtimeCards).toHaveLength(6);
expect(tools).toHaveLength(4);
expect(specialists).toHaveLength(4);
expect(runbook).toHaveLength(8);
expect(automationCells).toHaveLength(8);
expect(statusTiles).toHaveLength(4);
});
it('preserves required tool names', () => {
expect(tools.map(tool => tool.name)).toEqual([
'throughput_throughput',
'metrology_drift_widening',
'process_window_drift',
'tool_to_tool_mismatch',
]);
});
});
建立 src/domain/__tests__/portalAnalytics.test.ts :
import { describe, expect, it } from 'vitest';
import { automationCells } from '../fixtures';
import { searchAndSort, signed, slugId } from '../portalAnalytics';
describe('portal analytics', () => {
it('formats signed values', () => {
expect(signed(0.42, 2, '%')).toBe('+0.42%');
expect(signed(-0.31, 2, '%')).toBe('-0.31%');
});
it('creates stable detail ids', () => {
expect(slugId('Sofia Garcia')).toBe('sofia-garcia');
});
it('sorts by index descending', () => {
expect(searchAndSort(automationCells, '', 'indexPct')[0].name).toBe('Sofia Garcia');
});
it('searches by process pattern', () => {
expect(searchAndSort(automationCells, 'photolithography', 'indexPct').map(cell => cell.name)).toEqual(['Lucia Fernandez']);
expect(searchAndSort(automationCells, 'metrology', 'indexPct').map(cell => cell.name)).toEqual(['Paula Romero']);
});
});
給 Kiro 的提示詞範例
Review the automation analytics modules and tests. Add test cases for every automation-cell series, every status tile series, sort behavior for Index and Max Drift, search by each process-pattern keyword, SVG path boundaries, histogram positive/negative bars, and deterministic simulation with injected random values.
商業邏輯: 測試可保護驅動工程解讀的計算公式,並證明 TypeScript 移植版仍與入口網站展示相符。
程式邏輯: 單元測試驗證了已知的數值範例,並可擴展至涵蓋所有的自動化工作站與狀態圖磚。
預期結果: 執行 npx vitest run 通過,且 Kiro 提出了額外的覆蓋範圍建議。
系統設計原理解析:
● 已知值測試能快速捕獲公式退化。
● 要求 Kiro 加入自動化工作站專屬的迴歸測試,使資料或公式的變更不會非預期地改變顯示的分析結果。
● 圖表測試著重於幾何圖形邊界,因為視覺化圖表測試成本高昂,且對於此工作坊而言並非必要。
最終實驗室挑戰
詢問 Kiro:
Generate a complete analytics gap report comparing the TypeScript modules against the latest portal JavaScript functions and data structures: runtimeCards, tools, specialists, runbook, P, M, renderStatic, tab click handling, sg, cl, id, ret, dd, avg, sd, perc, path, spark, gridlines, eqChart, ddChart, hist, architecture, panel, data, render, tog, markets, clock, and the five-second update loop. Identify what is implemented, what is intentionally moved to React, and what still needs tests.
完成檢查清單
● [ ] 已為 Runtime 卡片、工具、專家、執行手冊步驟、自動化工作站和狀態圖磚定義型別。
● [ ] 已實作變動量、漂移、訊號波動度、百分位數、效率比、P05 變動量、最佳/最差變動量以及視窗率。
● [ ] 搜尋與排序重現展示行為。
● [ ] SVG 路徑與直方圖幾何圖形為純函式。
● [ ] 圖表模型輔助工具涵蓋走勢圖、指標圖、漂移圖和變動量直方圖。
● [ ] 即時模擬在測試中被明確標記且具備確定性。
● [ ] Kiro 已審查數學邊緣情況。
● [ ] 測試涵蓋固定裝置、計算、排序、圖表和模擬。
附錄 — 用於分析測試的完整自動化工作站與狀態圖磚涵蓋範圍
使用此檢查清單以確保分析引擎涵蓋完整的入口網站展示,而非僅僅是範例資料列:
● Sofia Garcia — 蝕刻終點深度多步驟配方控制(Etch Endpoint Depth Multi-Step Recipe Control):指標 +18.4%、變動量 +0.42%、穩定度 0.73、製程因子 1.8、視窗率 58%、偏態 +0.44、最大漂移 18。
● Lucia Fernandez — 黃光微影疊對漂移偵測(Photolithography Overlay Drift Detection):指標 +16.9%、變動量 +0.88%、穩定度 0.91、製程因子 1.7、視窗率 61%、偏態 +0.31、最大漂移 22。
● Carmen Lopez — 反應腔匹配射頻功率壓力穩定度(Chamber Matching RF Power Pressure Stability):指標 +14.2%、變動量 -0.31%、穩定度 0.68、製程因子 1.6、視窗率 56%、偏態 +0.22、最大漂移 25。
● Elena Martin — 工廠產線良率趨勢自動化(Factory Line Yield Trend Automation):指標 +11.8%、變動量 +0.17%、穩定度 0.62、製程因子 1.5、視窗率 54%、偏態 +0.18、最大漂移 17。
● Marta Sanchez — 配方參數相對穩定度(Recipe Parameter Relative Stability):指標 +9.6%、變動量 +0.09%、穩定度 0.57、製程因子 1.4、視窗率 53%、偏態 +0.09、最大漂移 15。
● Paula Romero — 量測特徵集成評分(Metrology Feature Ensemble Scoring):指標 +7.1%、變動量 -0.12%、穩定度 0.49、製程因子 1.3、視窗率 52%、偏態 -0.04、最大漂移 14。
● Ana Torres — 終點訊號異常告警系統(Endpoint Signal Breakout Alarm System):指標 +5.4%、變動量 +0.28%、穩定度 0.42、製程因子 1.2、視窗率 51%、偏態 +0.12、最大漂移 19。
● Laura Navarro — 多工具均值回歸控制(Multi-Tool Mean Reversion Control):指標 +3.8%、變動量 -0.06%、穩定度 0.35、製程因子 1.1、視窗率 49%、偏態 -0.11、最大漂移 16。
狀態圖磚迴歸測試個案:
● RUNTIME:+0.38%, READY, 序列 [20,21,20,22,23,23,24,25,24,26]。
● GATEWAY:-0.22%, WATCH, 序列 [30,29,31,28,27,26,25,24,23,22]。
● POLICY:+0.62%, READY, 序列 [18,18.5,19,18.7,20,21,20.5,22,23,23.5]。
● EVAL:+2.18%, READY, 序列 [20,22,21,24,26,25,29,28,32,34]。
用於完整涵蓋範圍的 Kiro 提示詞:
Generate a regression test suite that loads all six runtime cards, four tools, four specialists, eight runbook steps, eight automation-cell rows, and four status tiles. Validate summary stats, sort order for every sort key, search by each process-pattern keyword, SVG paths for each series, and automation panel metrics for every row.
針對進階開發者的額外動手操練實驗室 — HTML 圖形分析
這些實驗室藉由分析展示網站的 SVG 圖表圖形,擴展了自動化分析工作坊。它們遵循與原始量化分析工作坊相同的架構,但每個概念都針對工廠自動化入口網站進行了更新。
進階圖形分析目標
在本節結束時,進階開發者將能夠:
● 解釋 HTML 如何將製程視窗序列轉換為 SVG 路徑、區域、線條、標籤和長條條。
● 透過確定性測試驗證圖表幾何形狀。
● 將視覺編碼邏輯與製程視窗計算分離。
● 建立圖表審查元資料,幫助審查人員理解圖形含意。
● 偵測因縮放比例、內邊距、樣本過短或邊緣情況資料所導致的誤導性圖表輸出。
來自入口網站 HTML 檔案的圖表圖形清單
入口網站 HTML 使用多個 JavaScript 函式來產生 SVG 圖形:
● path(a,w,h,p) 將序列正規化為 SVG 的 M 和 L 指令。
● spark(a) 轉譯緊湊的資料列與狀態圖磚走勢圖。
● gridlines(w,h,p) 建立水平網格線和底部軸線。
● eqChart(a) 轉譯帶有填滿區域和起迄標籤的製程視窗指標路徑。
● ddChart(a) 將漂移轉譯為零軸下方的紅色水位線形狀。
● hist(a) 圍繞中線轉譯每日製程變動量長條條,並使用獨立的正向和負向類別。
進階實驗室 1 — 圖表幾何形狀契約測試
目標: 建立測試以證明 SVG 幾何圖形保持在圖表邊界內,並安全地處理平坦、過短和高波動的序列。
建立 src/domain/__tests__/chartGeometry.test.ts:
import { describe, expect, it } from 'vitest';
import { histogramBars, svgPath } from '../charts';
function extractNumbers(path: string): number[] {
return path.match(/-?\d+(\.\d+)?/g)?.map(Number) ?? [];
}
describe('SVG chart geometry contracts', () => {
it('keeps path coordinates inside the viewbox padding boundaries', () => {
const d = svgPath([100, 102, 101, 104], 120, 32, 2);
const numbers = extractNumbers(d);
const xs = numbers.filter((_, index) => index % 2 === 0);
const ys = numbers.filter((_, index) => index % 2 === 1);
expect(Math.min(...xs)).toBeGreaterThanOrEqual(2);
expect(Math.max(...xs)).toBeLessThanOrEqual(118);
expect(Math.min(...ys)).toBeGreaterThanOrEqual(2);
expect(Math.max(...ys)).toBeLessThanOrEqual(30);
});
it('renders flat series without division-by-zero geometry failures', () => {
const d = svgPath([100, 100, 100], 120, 32, 2);
expect(d).toContain('M');
expect(d).toContain('L');
expect(d).not.toContain('NaN');
expect(d).not.toContain('Infinity');
});
it('creates positive and negative histogram bars around a midline', () => {
const bars = histogramBars([1, -2, 0.5], 680, 120, 18);
expect(bars.some(bar => bar.positive)).toBe(true);
expect(bars.some(bar => !bar.positive)).toBe(true);
});
});
Kiro 提示詞:
Generate chart geometry tests for the portal HTML path, sparkline, Process Window Index Path, Drift Waterline, and Daily Process Delta Distribution behavior. Verify coordinate bounds, no NaN or Infinity, flat series behavior, short series behavior, positive/negative histogram flags, and drawing consistency across all automation-cell and status-tile series.
預期結果: 開發者可以重構圖表程式碼,而不會意外產生損壞的 SVG。
進階實驗室 2 — SVG 視覺編碼文件化
目標: 文件化製程視窗概念與圖形標記之間的關係,使圖表行為可被審查。
建立 docs/svg-visual-encoding.md:
# 工廠自動化入口網站 SVG 視覺編碼說明
## 走勢圖 (Sparkline)
- 資料輸入:自動化單元指標序列或狀態圖磚微型序列。
- 標記類型:單一綠色線條。
- 目的:精簡的趨勢預覽。
- 風險:未顯示 Y 軸刻度,因此不應視為精確量測。
## 製程視窗指標路徑 (Process Window Index Path)
- 資料輸入:索引化的製程視窗序列。
- 標記類型:綠色線條加上半透明填滿區域。
- 目的:視覺化累積指標路徑。
- 標籤:第一個指標值與最後一個指標值。
## 漂移水位線 (Drift Waterline)
- 資料輸入:衍生自指標序列的漂移百分比序列。
- 標記類型:紅色線條與零軸下方的紅色填滿區域。
- 目的:顯示峰值到谷底的漂移壓力與復原情況。
## 每日製程變動量分佈 (Daily Process Delta Distribution)
- 資料輸入:每日製程變動量序列。
- 標記類型:圍繞水平中線的垂直長條條。
- 正向編碼:中線之上的綠色長條。
- 負向編碼:中線之下的紅色長條。
Kiro 提示詞:
Create visual encoding documentation for the portal charts. Explain sparkline, Process Window Index Path, Drift Waterline, and Daily Process Delta Distribution using data input, SVG mark type, color encoding, scale limitations, automation-boundary notes, and reviewer cautions.
預期結果: 圖表圖形對開發者、設計師和審查人員而言變得清晰易懂。
進階實驗室 3 — 圖表審查元資料產生器
目標: 為每個圖表產生元資料,以便審查人員可以檢查縮放比例、極值、範圍、正負長條計數和標籤文字。
建立 src/domain/chartAudit.ts:
import { deltasPct, driftPct } from './calculations';
export type SeriesAudit = {
pointCount: number;
min: number;
max: number;
range: number;
first: number;
last: number;
};
export type ChartAudit = {
index: SeriesAudit;
drift: SeriesAudit;
deltas: SeriesAudit & {
positiveCount: number;
negativeCount: number;
zeroCount: number;
};
};
function auditSeries(values: number[]): SeriesAudit {
if (!values.length) {
return { pointCount: 0, min: 0, max: 0, range: 0, first: 0, last: 0 };
}
const min = Math.min(...values);
const max = Math.max(...values);
return {
pointCount: values.length,
min,
max,
range: max - min,
first: values[0],
last: values.at(-1)!,
};
}
export function auditChartSeries(indexSeries: number[]): ChartAudit {
const drift = driftPct(indexSeries);
const deltas = deltasPct(indexSeries);
const deltasAudit = auditSeries(deltas);
return {
index: auditSeries(indexSeries),
drift: auditSeries(drift),
deltas: {
...deltasAudit,
positiveCount: deltas.filter(value => value > 0).length,
negativeCount: deltas.filter(value => value < 0).length,
zeroCount: deltas.filter(value => value === 0).length,
},
};
}
Kiro 提示詞:
Add chart-audit metadata for every process-window index series and every status-tile mini-series. Include point count, min, max, range, first/last values, drift range, delta range, and positive/negative/zero delta counts. Add tests for all eight automation-cell series and four status-tile series.
預期結果: 分析審查人員無需開啟瀏覽器即可檢查圖表輸入與縮放風險。
進階實驗室 4 — 具誤導性的圖表邊緣情況實驗室
目標: 教導開發者識別圖表雖然在技術上正確,但視覺上可能產生誤導的邊緣情況。
建立 docs/misleading-chart-edge-cases.md:
# 工廠自動化入口網站 具誤導性的圖表邊緣情況
## 平坦序列
平坦的指標序列會產生一條直線,但如果忽略標籤,視覺範圍的回退機制可能會使微小的變動看起來比實際更大。
## 單點序列
單個數據點無法呈現趨勢。圖表應轉譯安全的預留位置,或顯示資料不足的訊息。
## 極端離群值
單一巨大跳躍可能會壓縮所有其他變化,使正常的訊號變動看起來像是隱形了。
## 過短的變動量視窗
14 點的變動量直方圖具有教學意義,但不足以得出穩健的分佈結論。
## 缺失刻度標籤
走勢圖對於快速形狀識別非常實用,但不應被用作精確的製程證據。
## 自動化邊界
任何圖表皆不應被解讀為設備指令、製程發佈決策或旁路訊號。
Kiro 提示詞:
Create a misleading-graphic edge-case guide for the portal chart functions. Cover flat series, one-point series, extreme outliers, short delta windows, missing y-axis scale, histogram interpretation limits, and automation-boundary cautions.
進階實驗室 5 — 圖表渲染驗收標準
目標: 在進行生產環境重構驗收之前,定義圖表圖形的驗收標準。
建立 docs/chart-rendering-acceptance-criteria.md:
# 工廠自動化入口網站 圖表渲染驗收標準
## 製程視窗指標路徑 (Process Window Index Path)
- 使用與 HTML 原型相同的正規化座標邏輯。
- 包含可見的線條與填滿區域。
- 標註第一個和最後一個指標值。
- 不得轉譯出 NaN 或 Infinity。
## 漂移水位線 (Drift Waterline)
- 漂移值在轉譯前必須為零或負數。
- 零軸必須清晰可見。
- 紅色區域隨著漂移加深而向下擴展。
- 最大漂移標籤與計算出的最小漂移相符。
## 每日製程變動量分佈 (Daily Process Delta Distribution)
- 正向長條出現在中線上方。
- 負向長條出現在中線下方。
- 零值長條不會導致視覺錯誤。
- 長條寬度在所有支援的圖表尺寸下皆保持可見。
## 走勢圖 (Sparkline)
- 緊湊的圖表不包含未受支援的刻度宣告。
- 為所有自動化工作站與狀態圖磚微型序列保留趨勢形狀。
Kiro 提示詞:
Generate chart rendering acceptance criteria for React/SVG refactoring. Include Process Window Index Path, Drift Waterline, Daily Process Delta Distribution, and Sparkline checks. Tie every visual assertion to a deterministic test where possible.
進階最終挑戰 — SVG 圖表精確度審查
詢問 Kiro:
Perform an SVG chart fidelity review against the latest portal HTML file. Compare path normalization, padding, index-area closure, grid lines, drift zero axis, histogram midline, positive/negative bar placement, labels, status-tile sparklines, and edge-case behavior. Produce a prioritized remediation backlog.
進階圖形分析完成檢查清單
● [ ] 圖表幾何形狀測試已驗證邊界與無效數值保護。
● [ ] 視覺編碼文件已解釋每個入口網站 SVG 圖表類型。
● [ ] 圖表審查元資料已摘要指標、漂移與變動量序列。
● [ ] 已文件化具誤導性的圖表邊緣情況。
● [ ] 轉譯驗收標準為圖表重構提供了保護。
● [ ] 自動化邊界警示在圖表文件中保持可見。