Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

Add lifecycle diagram renderer

tt-a1i693e7ab72092
diff --git a/CHANGELOG.md b/CHANGELOG.md
index affb263d..3dc339f8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,9 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
- **Data-flow diagram mode.** Added a renderer-backed data-flow diagram type for analytics pipelines, ETL/ELT, PII isolation, governance boundaries, data lineage, warehouse sync, and downstream consumers.
- **Data-flow JSON Schema.** Added `archify/schemas/dataflow.schema.json` to document and validate the data-flow IR shape.
- **Data-flow example.** Added a rendered product analytics data-flow example at `examples/dataflow-product-analytics.html`, plus a README preview screenshot.
+- **Lifecycle diagram mode.** Added a renderer-backed lifecycle/state-machine diagram type for object lifecycles, wait states, retries, cancellation, timeout, terminal states, and recovery paths.
+- **Lifecycle JSON Schema.** Added `archify/schemas/lifecycle.schema.json` to document and validate the lifecycle IR shape.
+- **Lifecycle example.** Added a rendered agent-run lifecycle example at `examples/lifecycle-agent-run.html`, plus a README preview screenshot.
### Changed
- **Template responsive polish.** The shared HTML template now handles narrow viewports better: the toolbar no longer overlaps the title, diagrams can scale down to the available width, and cards stack cleanly on mobile.
diff --git a/README.md b/README.md
index 65fb30d7..b2f21e78 100644
--- a/README.md
+++ b/README.md
@@ -2,12 +2,12 @@
# Archify
-**聊两句就画出好看的架构图、技术流程图、调用时序图和数据流图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**
+**聊两句就画出好看的架构图、技术流程图、调用时序图、数据流图和生命周期图。深色 / 浅色一键切。导出 4× 清晰 PNG / JPEG / WebP / SVG,或直接复制到剪贴板。**
Archify 是一个 [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude):你用大白话描述自己的系统或流程,它就把你的描述变成一张做工精细的技术图 —— 一个单文件 HTML,在浏览器里打开就能切主题、复制到剪贴板、导出成各种图片格式。
- **不需要会画图** —— 把组件和连接关系说给 Claude 就行
-- **支持 workflow / sequence / data flow** —— 技术流程、审批链、工具调用、CI/CD、请求调用链、数据管线、PII 边界都可以画
+- **支持 workflow / sequence / data flow / lifecycle** —— 技术流程、审批链、工具调用、CI/CD、请求调用链、数据管线、PII 边界、状态机都可以画
- **内置主题切换** —— 深色 / 浅色一键切,浏览器记住偏好
- **一键复制到剪贴板** —— 直接贴到 Slack、飞书、微信、Notion、GitHub issue
- **导出图片超清晰** —— PNG / JPEG / WebP 全部由浏览器在 4× 源分辨率下**原生光栅化**(不是位图放大,没有糊),或导出 SVG 做真矢量
@@ -38,7 +38,7 @@ Export 菜单 —— 复制到剪贴板 + 四种格式下载:
## 图表类型
-Archify 现在有四种主要输出:
+Archify 现在有五种主要输出:
| 类型 | 适合画什么 | 怎么用 |
|---|---|---|
@@ -46,6 +46,7 @@ Archify 现在有四种主要输出:
| **Workflow** | 请求生命周期、审批流程、工具调用、CI/CD、运维 runbook、事故响应 | 说明参与方、步骤顺序、关键分支 |
| **Sequence** | API 调用链、请求生命周期、缓存回源、鉴权、异步 trace、服务交互 | 说明谁调用谁、先后顺序、返回路径 |
| **Data Flow** | 数据管线、ETL/ELT、埋点、PII 隔离、仓库同步、数据血缘、下游消费 | 说明数据来源、处理阶段、存储位置、敏感边界和消费方 |
+| **Lifecycle** | 状态机、订单/任务/部署/Agent run 生命周期、等待态、重试、取消、超时、终态 | 说明对象有哪些状态、哪些事件触发转移、哪些状态是终态 |
Workflow 不是通用流程图的替代品,它更偏“技术沟通图”:有泳道、有语义颜色、有主路径和异步/审批/观测路径。比如:
@@ -79,6 +80,19 @@ Warehouse 存分析表,Feature Store 做每日特征,Dashboard 和 ML Model
![Data Flow 示例](examples/images/archify-dataflow.png)
+Lifecycle 用来解释“对象状态怎么变”,比如:
+
+```
+用 archify 画一个 lifecycle diagram:
+Agent Run 从 Queued 进入 Planning,再进入 Executing 和 Reviewing。需要人工确认时进入
+Needs Approval,缺少输入时进入 Blocked;工具失败可以 Failed 后重试,用户取消进入 Cancelled,
+超时进入 Expired,成功则进入 Completed。
+```
+
+示例:[`examples/lifecycle-agent-run.html`](examples/lifecycle-agent-run.html)。
+
+![Lifecycle 示例](examples/images/archify-lifecycle.png)
+
## 版本演进
Archify 基于 [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0(只有深色主题的 HTML 输出)fork 重写。**2.0** 把模板重构成 CSS 变量驱动的可主题化系统,加入客户端导出流水线。**2.1** 加入剪贴板复制 + 键盘导航。**2.2** 加入打印样式 + 本地字体回退。**2.3** 修了一个存在已久的位图升采样 bug,所有光栅导出改为 4× 原生渲染(同时移除了 v2.1 引入的 1×/2×/4× 选择器 —— 那个选择器只是在诱导用户选出更糊的图)。**2.4** SVG 导出升级成双主题自持版 —— 同一个 `.svg` 文件贴在 GitHub README 里,读者切深浅色图会自己跟着切。
@@ -238,6 +252,17 @@ unzip archify.zip -d ./.claude/skills/
- Dashboards 和 ML Model 消费下游数据
```
+**状态机 / 生命周期:**
+```
+用 archify 画一个 lifecycle diagram:
+- 任务从 Queued 开始
+- Planning 生成计划
+- Executing 调用工具
+- Reviewing 做质量检查
+- Needs Approval 和 Blocked 是等待态
+- Failed 可重试,Cancelled / Expired / Completed 是终态
+```
+
## 语义配色
| 类型 | 颜色 | 用途 |
diff --git a/README_EN.md b/README_EN.md
index a7aa3be6..943c8e28 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -2,12 +2,12 @@
# Archify
-**Generate beautiful architecture, technical workflow, sequence, and data-flow diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**
+**Generate beautiful architecture, technical workflow, sequence, data-flow, and lifecycle diagrams in chat. Switch dark / light. Copy to clipboard or export crisp 4× PNG / JPEG / WebP / SVG.**
Archify is a [Claude Skill](https://support.claude.com/en/articles/12512180-using-skills-in-claude) that turns a plain-English description of your system or process into a polished, self-contained technical diagram — a single HTML file you can open, toggle themes on, copy to the clipboard, and export at maximum resolution.
- **No design skills needed** — describe your architecture in English, get a diagram
-- **Workflow, sequence, and data-flow diagrams too** — technical flows, approvals, tool calls, CI/CD, runbooks, request call chains, data pipelines, and PII boundaries can be drawn
+- **Workflow, sequence, data-flow, and lifecycle diagrams too** — technical flows, approvals, tool calls, CI/CD, runbooks, request call chains, data pipelines, PII boundaries, and state machines can be drawn
- **Built-in theme toggle** — one click between dark and light, persists across sessions
- **Copy PNG to clipboard** — one click, paste straight into Slack / Notion / GitHub
- **Ultra-crisp image export** — PNG / JPEG / WebP rendered natively at 4× source resolution (no upsampling blur), or SVG for true vector
@@ -37,7 +37,7 @@ Live example: [`examples/web-app.html`](examples/web-app.html) — open in a bro
## Diagram types
-Archify now has four primary outputs:
+Archify now has five primary outputs:
| Type | Good for | How to ask |
|---|---|---|
@@ -45,6 +45,7 @@ Archify now has four primary outputs:
| **Workflow** | Request lifecycles, approval flows, tool calls, CI/CD, runbooks, incident response | Describe participants, step order, and key branches |
| **Sequence** | API call chains, request lifecycles, cache fallback, auth checks, async trace, service interactions | Describe who calls whom, in what order, and what returns |
| **Data Flow** | Data pipelines, ETL/ELT, analytics events, PII isolation, warehouse sync, lineage, downstream consumers | Describe sources, processing stages, storage, sensitivity boundaries, and consumers |
+| **Lifecycle** | State machines, order/task/deployment/agent-run lifecycles, wait states, retries, cancellation, timeout, terminal states | Describe states, transition events, retry paths, and terminal outcomes |
Workflow is not trying to replace every general-purpose flowchart. It is a technical communication diagram: swimlanes, semantic colors, a clear happy path, and secondary async / approval / trace paths.
@@ -78,6 +79,18 @@ Open the example here: [`examples/dataflow-product-analytics.html`](examples/dat
![Data Flow example](examples/images/archify-dataflow.png)
+Lifecycle diagrams explain how an object changes state:
+
+```text
+Use archify to draw a lifecycle diagram:
+Agent Run starts at Queued, moves through Planning, Executing, and Reviewing. It can pause at Needs Approval,
+wait at Blocked, retry after Failed, end at Cancelled or Expired, or finish at Completed.
+```
+
+Open the example here: [`examples/lifecycle-agent-run.html`](examples/lifecycle-agent-run.html).
+
+![Lifecycle example](examples/images/archify-lifecycle.png)
+
## What's new
Archify is based on [Cocoon-AI/architecture-diagram-generator](https://github.com/Cocoon-AI/architecture-diagram-generator) v1.0 (dark-only, HTML output). **2.0** rewrote the template around a themeable CSS-variable system and added a client-side export pipeline. **2.1** added copy-to-clipboard + keyboard nav. **2.2** added a print stylesheet + local-font fallback. **2.3** fixed a long-standing upsampling bug and made every raster export genuinely sharp at 4× source resolution (the 1× / 2× / 4× selector introduced in 2.1 was removed at the same time — it only encouraged picking a soft-looking scale). **2.4** upgraded the SVG export to a dual-theme self-contained file — drop the same `.svg` into a GitHub README and it follows the reader's dark/light preference automatically.
@@ -236,6 +249,17 @@ Use archify to draw a data flow:
- Dashboards and ML Model consume downstream data
```
+**State machine / lifecycle:**
+```
+Use archify to draw a lifecycle diagram:
+- A task starts at Queued
+- Planning builds the plan
+- Executing calls tools
+- Reviewing checks quality
+- Needs Approval and Blocked are wait states
+- Failed can retry, while Cancelled / Expired / Completed are terminal states
+```
+
## Color palette
| Component Type | Color | Use for |
diff --git a/ROADMAP.md b/ROADMAP.md
index 223c0116..596f09a6 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -117,6 +117,12 @@ Data-flow diagrams became the third typed renderer pilot. They use `diagram_type
Like workflow and sequence, data-flow is not a generic graph layout engine. The renderer provides stable stage/row placement and validation checks, while Claude still decides which data assets matter, where sensitive boundaries should appear, which paths are primary, and which batch or restricted joins should stay visually secondary.
+### Lifecycle renderer pilot (2026-04-24)
+
+Lifecycle diagrams became the fourth typed renderer pilot. They use `diagram_type: "lifecycle"` JSON with lanes, states, semantic state types, routed transitions, transition labels, and summary cards. The goal is to explain state machines for agent runs, tasks, orders, deployments, subscriptions, incident tickets, retries, wait states, cancellation, timeout, and terminal outcomes.
+
+Like the other typed renderers, lifecycle is deliberately constrained rather than fully automatic. The renderer gives stable lane/column placement and validation checks, while Claude still decides which states are worth showing, which transitions should be labeled, and how to separate happy path, waits, and exception recovery.
+
---
## Not planned
diff --git a/archify.zip b/archify.zip
index f282eff5..4d110e67 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index b4ac235a..b7370c83 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -1,6 +1,6 @@
---
name: archify
-description: Create professional architecture, workflow, sequence, and data-flow diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, technical workflows, approval flows, runbooks, CI/CD flows, process diagrams, API call sequences, request lifecycles, interaction diagrams, data pipelines, analytics flows, ETL/ELT maps, PII boundaries, or governance/data lineage diagrams.
+description: Create professional architecture, workflow, sequence, data-flow, and lifecycle/state diagrams as standalone HTML files with SVG graphics, a built-in dark/light theme toggle, and one-click export to PNG / JPEG / WebP / SVG. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, technical workflows, approval flows, runbooks, CI/CD flows, process diagrams, API call sequences, request lifecycles, interaction diagrams, data pipelines, analytics flows, ETL/ELT maps, PII boundaries, governance/data lineage diagrams, state machines, lifecycle diagrams, status transitions, or terminal/retry paths.
license: MIT
metadata:
version: "2.4"
@@ -20,7 +20,7 @@ Every diagram this skill produces ships with:
## Diagram Types
-Archify supports four technical diagram modes:
+Archify supports five technical diagram modes:
| Type | Use for | Output path |
|------|---------|-------------|
@@ -28,6 +28,7 @@ Archify supports four technical diagram modes:
| `workflow` | Technical flows, request lifecycles, approval gates, tool calls, runbooks, CI/CD paths, incident response, and process ownership | Prefer `renderers/workflow/render-workflow.mjs` with a workflow JSON file |
| `sequence` | API calls, request lifecycles, service interactions, cache fallback paths, async trace/logging, and return paths over time | Prefer `renderers/sequence/render-sequence.mjs` with a sequence JSON file |
| `dataflow` | Data pipelines, ETL/ELT, analytics flows, PII isolation, governance boundaries, lineage, warehouse sync, and downstream consumers | Prefer `renderers/dataflow/render-dataflow.mjs` with a data-flow JSON file |
+| `lifecycle` | State machines, object lifecycles, run/order/deployment status transitions, wait states, retries, terminal states, and recovery paths | Prefer `renderers/lifecycle/render-lifecycle.mjs` with a lifecycle JSON file |
When the user says "architecture", "system diagram", "cloud diagram", or asks to understand a codebase structure, use the `architecture` mode unless the requested output is clearly process-oriented.
@@ -37,6 +38,8 @@ When the user says "sequence", "interaction", "call sequence", "request lifecycl
When the user says "data flow", "pipeline", "ETL", "ELT", "lineage", "analytics", "warehouse", "PII", "consent", "governance", or asks where data comes from, how it is transformed, and who consumes it, use the `dataflow` mode.
+When the user says "state", "status", "lifecycle", "state machine", "terminal", "retry", "cancel", "timeout", "order lifecycle", "deployment lifecycle", "agent run lifecycle", or asks how an object changes state over time, use the `lifecycle` mode.
+
### Workflow Mode
Workflow diagrams use a compact JSON IR:
@@ -161,6 +164,47 @@ The renderer:
Use data-flow diagrams when the important thing is data lineage and governance. Keep labels asset-like: "clickstream", "identity map", "normalized facts", "feature vectors", "restricted join". Put sensitivity in `classification`: "PII touch", "encrypted PII", "approved only", "non-PII", "read-only".
+### Lifecycle Mode
+
+Lifecycle diagrams use a compact JSON IR:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "lifecycle",
+ "meta": {
+ "title": "Agent Run Lifecycle",
+ "subtitle": "State machine for planning, execution, waits, retries, and terminal outcomes",
+ "output": "agent-run.html",
+ "viewBox": [980, 720]
+ },
+ "lanes": [
+ { "id": "main", "label": "Main lifecycle" },
+ { "id": "waiting", "label": "Wait states" },
+ { "id": "exceptions", "label": "Exceptions + recovery" }
+ ],
+ "states": [],
+ "transitions": [],
+ "cards": []
+}
+```
+
+If you have filesystem/tool access, create a lifecycle JSON file and render it with:
+
+```bash
+node archify/renderers/lifecycle/render-lifecycle.mjs lifecycle.json lifecycle.html
+```
+
+The renderer:
+
+- Places states by lane + column
+- Uses lanes to separate the happy path, wait states, and exception/recovery paths
+- Uses semantic state types: `start`, `active`, `waiting`, `decision`, `success`, `failure`, and `neutral`
+- Uses transition variants: `emphasis` for the primary lifecycle, `security` for failure/cancel/timeout/policy paths, and `dashed` for retry/resume paths
+- Fails fast when states overlap, leave their lane, reference unknown lanes, use unknown transition endpoints, or push the legend outside the viewBox
+
+Use lifecycle diagrams when the important thing is state, not step-by-step work. Keep transition labels event-like: "start", "plan ready", "needs approval", "retry", "timeout", "cancel". Put terminal states on the right or in the bottom lane so endings are visually unambiguous.
+
## The Cardinal Rule: Use CSS Classes, Not Inline Colors
The theme toggle works by switching CSS custom properties. If you hardcode `fill="rgba(...)"` or `stroke="#22d3ee"` on SVG elements, those values will NOT update when the theme changes. Always prefer the class-based system.
diff --git a/archify/examples/agent-run.lifecycle.json b/archify/examples/agent-run.lifecycle.json
new file mode 100644
index 00000000..6b299212
--- /dev/null
+++ b/archify/examples/agent-run.lifecycle.json
@@ -0,0 +1,70 @@
+{
+ "schema_version": 1,
+ "diagram_type": "lifecycle",
+ "meta": {
+ "title": "Agent Run Lifecycle",
+ "subtitle": "State machine for planning, tool execution, human approval, retries, and terminal outcomes",
+ "output": "examples/lifecycle-agent-run.html",
+ "viewBox": [980, 720]
+ },
+ "lanes": [
+ { "id": "main", "label": "Main lifecycle" },
+ { "id": "waiting", "label": "Wait states" },
+ { "id": "exceptions", "label": "Exceptions + recovery" }
+ ],
+ "states": [
+ { "id": "queued", "type": "start", "label": "Queued", "sublabel": "request accepted", "lane": "main", "col": 0, "tag": "entry" },
+ { "id": "planning", "type": "active", "label": "Planning", "sublabel": "build task graph", "lane": "main", "col": 1, "tag": "model" },
+ { "id": "executing", "type": "active", "label": "Executing", "sublabel": "tool calls", "lane": "main", "col": 2, "tag": "work" },
+ { "id": "reviewing", "type": "decision", "label": "Reviewing", "sublabel": "quality gate", "lane": "main", "col": 3, "tag": "check" },
+ { "id": "completed", "type": "success", "label": "Completed", "sublabel": "final response", "lane": "main", "col": 5, "tag": "terminal" },
+ { "id": "approval", "type": "waiting", "label": "Needs Approval", "sublabel": "human gate", "lane": "waiting", "col": 3, "tag": "pause" },
+ { "id": "blocked", "type": "waiting", "label": "Blocked", "sublabel": "missing input", "lane": "waiting", "col": 4, "tag": "wait" },
+ { "id": "failed", "type": "failure", "label": "Failed", "sublabel": "recoverable error", "lane": "exceptions", "col": 2, "tag": "retryable" },
+ { "id": "cancelled", "type": "failure", "label": "Cancelled", "sublabel": "user stopped", "lane": "exceptions", "col": 4, "tag": "terminal" },
+ { "id": "expired", "type": "failure", "label": "Expired", "sublabel": "timeout", "lane": "exceptions", "col": 5, "tag": "terminal" }
+ ],
+ "transitions": [
+ { "from": "queued", "to": "planning", "label": "start", "variant": "emphasis", "route": "straight" },
+ { "from": "planning", "to": "executing", "label": "plan ready", "variant": "emphasis", "route": "straight" },
+ { "from": "executing", "to": "reviewing", "label": "tool results", "variant": "emphasis", "route": "straight" },
+ { "from": "reviewing", "to": "completed", "label": "passes", "note": "terminal", "variant": "emphasis", "route": "straight", "labelAt": [624, 104] },
+ { "from": "executing", "to": "approval", "label": "needs approval", "note": "policy gate", "variant": "security", "fromSide": "bottom", "toSide": "top", "via": [[396, 194], [546, 194]], "labelAt": [478, 182] },
+ { "from": "approval", "to": "executing", "variant": "dashed", "fromSide": "top", "toSide": "bottom", "via": [[546, 216], [396, 216]] },
+ { "from": "reviewing", "to": "blocked", "label": "needs input", "variant": "default", "route": "drop", "labelAt": [618, 190] },
+ { "from": "blocked", "to": "planning", "label": "user reply", "variant": "dashed", "fromSide": "left", "toSide": "bottom", "route": "bottom-channel", "channelY": 350, "labelAt": [472, 350] },
+ { "from": "executing", "to": "failed", "label": "tool error", "variant": "security", "fromSide": "bottom", "toSide": "top", "route": "straight", "labelAt": [426, 392] },
+ { "from": "failed", "to": "planning", "label": "retry", "note": "bounded", "variant": "dashed", "fromSide": "left", "toSide": "bottom", "route": "left-channel", "channelX": 188, "labelAt": [188, 446] },
+ { "from": "blocked", "to": "expired", "label": "timeout", "variant": "security", "fromSide": "right", "toSide": "top", "route": "right-channel", "channelX": 906, "labelAt": [906, 362] },
+ { "from": "approval", "to": "cancelled", "label": "cancel", "variant": "security", "fromSide": "bottom", "toSide": "top", "route": "drop", "labelAt": [620, 362] }
+ ],
+ "cards": [
+ {
+ "dot": "emerald",
+ "title": "Main Path",
+ "items": [
+ "Main states are Queued, Planning, Executing, Reviewing, and Completed",
+ "The hot path stays in one lane and reads left to right",
+ "Completed is the only success terminal state"
+ ]
+ },
+ {
+ "dot": "amber",
+ "title": "Human + Input Gates",
+ "items": [
+ "Approval pauses execution without ending the run",
+ "Blocked waits for missing user input",
+ "Wait states can resume back into planning or execution"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Terminal + Recovery",
+ "items": [
+ "Failed is recoverable while retry budget remains",
+ "Cancelled and Expired are terminal failure states",
+ "Error transitions are separated from the happy path"
+ ]
+ }
+ ]
+}
diff --git a/archify/renderers/lifecycle/README.md b/archify/renderers/lifecycle/README.md
new file mode 100644
index 00000000..162d5fb9
--- /dev/null
+++ b/archify/renderers/lifecycle/README.md
@@ -0,0 +1,56 @@
+# Lifecycle Renderer
+
+Render `diagram_type: "lifecycle"` JSON files into the standard Archify HTML
+template.
+
+```bash
+node archify/renderers/lifecycle/render-lifecycle.mjs input.lifecycle.json output.html
+```
+
+If `output.html` is omitted, the renderer uses `meta.output` from the JSON file
+or falls back to `lifecycle.html` in the current working directory.
+
+## Input
+
+Lifecycle JSON files must set:
+
+```json
+{
+ "schema_version": 1,
+ "diagram_type": "lifecycle",
+ "meta": {
+ "title": "Agent Run Lifecycle",
+ "subtitle": "State machine for planning, execution, waits, retries, and terminal outcomes",
+ "viewBox": [980, 720]
+ },
+ "lanes": [],
+ "states": [],
+ "transitions": [],
+ "cards": []
+}
+```
+
+The schema lives at:
+
+```text
+archify/schemas/lifecycle.schema.json
+```
+
+## Design Rules
+
+- Use lanes for lifecycle layers: main path, wait states, exception/recovery
+ paths, terminal states.
+- Place states with lane IDs and column indexes.
+- Keep the happy path left-to-right in one lane when possible.
+- Use `success` for terminal success, `failure` for failure/terminal error,
+ `waiting` for pauses, and `decision` for gates.
+- Use `emphasis` for the main transition path.
+- Use `security` for cancellation, timeout, failure, policy, and blocked paths.
+- Use `dashed` for retry, resume, async, or non-primary transitions.
+- Keep transition labels short: `start`, `plan ready`, `needs approval`,
+ `retry`, `timeout`, `cancel`.
+
+The renderer fails when it can detect layout problems, including duplicate state
+IDs, unknown lanes, unknown transition endpoints, states outside their lanes,
+overlapping states, unreadably short transitions, or a legend outside the
+viewBox.
diff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjs
new file mode 100644
index 00000000..22fb82c9
--- /dev/null
+++ b/archify/renderers/lifecycle/render-lifecycle.mjs
@@ -0,0 +1,404 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(__dirname, '../..');
+const inputPath = path.resolve(process.argv[2] || path.join(skillRoot, 'examples/agent-run.lifecycle.json'));
+const lifecycle = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
+
+const templatePath = path.join(skillRoot, 'assets/template.html');
+const template = fs.readFileSync(templatePath, 'utf8');
+const outPath = path.resolve(process.cwd(), process.argv[3] || lifecycle.meta.output || 'lifecycle.html');
+
+const viewBox = lifecycle.meta.viewBox || [980, 720];
+const layout = {
+ laneX: 34,
+ laneY: 48,
+ laneW: 912,
+ laneGap: 22,
+ laneTitleH: 30,
+ laneH: 150,
+ colXs: [96, 246, 396, 546, 696, 846],
+ nodeW: 112,
+ nodeH: 58
+};
+
+const typeClass = {
+ start: 'c-frontend',
+ active: 'c-backend',
+ waiting: 'c-cloud',
+ decision: 'c-security',
+ success: 'c-database',
+ failure: 'c-security',
+ neutral: 'c-external',
+ external: 'c-external'
+};
+
+const textClass = {
+ start: 't-frontend',
+ active: 't-backend',
+ waiting: 't-cloud',
+ decision: 't-security',
+ success: 't-database',
+ failure: 't-security',
+ neutral: 't-muted',
+ external: 't-muted'
+};
+
+const arrowClass = {
+ default: ['a-default', 'arrowhead'],
+ emphasis: ['a-emphasis', 'arrowhead-emphasis'],
+ security: ['a-security', 'arrowhead-security'],
+ dashed: ['a-dashed', 'arrowhead-dashed']
+};
+
+function esc(value) {
+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;'
+ }[c]));
+}
+
+const laneIndex = new Map((lifecycle.lanes || []).map((lane, index) => [lane.id, index]));
+
+function laneTop(id) {
+ return layout.laneY + laneIndex.get(id) * (layout.laneH + layout.laneGap);
+}
+
+function lastLaneBottom() {
+ return layout.laneY + lifecycle.lanes.length * layout.laneH + (lifecycle.lanes.length - 1) * layout.laneGap;
+}
+
+function legendY() {
+ return lastLaneBottom() + 44;
+}
+
+function measureState(state) {
+ const width = state.width || layout.nodeW;
+ const height = state.height || layout.nodeH;
+ const cx = layout.colXs[state.col];
+ const contentH = layout.laneH - layout.laneTitleH;
+ const y = laneTop(state.lane) + layout.laneTitleH + (contentH - height) / 2 + (state.yOffset || 0);
+ return {
+ ...state,
+ width,
+ height,
+ x: cx - width / 2,
+ y,
+ cx,
+ cy: y + height / 2
+ };
+}
+
+const states = new Map((lifecycle.states || []).map((state) => [state.id, measureState(state)]));
+
+function rectsOverlap(a, b, gap = 0) {
+ return !(
+ a.x + a.width + gap <= b.x ||
+ b.x + b.width + gap <= a.x ||
+ a.y + a.height + gap <= b.y ||
+ b.y + b.height + gap <= a.y
+ );
+}
+
+function validateLifecycle() {
+ const problems = [];
+ if (lifecycle.schema_version !== 1) problems.push('Lifecycle files must set "schema_version": 1.');
+ if (lifecycle.diagram_type !== 'lifecycle') problems.push('Lifecycle files must set "diagram_type": "lifecycle".');
+ if (!lifecycle.meta?.title) problems.push('Lifecycle files must include meta.title.');
+ if (!Array.isArray(lifecycle.lanes) || lifecycle.lanes.length < 1) problems.push('Lifecycle diagrams need at least one lane.');
+ if (!Array.isArray(lifecycle.states) || lifecycle.states.length < 2) problems.push('Lifecycle diagrams need at least two states.');
+ if (!Array.isArray(lifecycle.transitions)) problems.push('Lifecycle diagrams must include a transitions array.');
+ if (states.size !== (lifecycle.states || []).length) problems.push('State ids must be unique.');
+
+ const laneIds = new Set((lifecycle.lanes || []).map((lane) => lane.id));
+ if (laneIds.size !== (lifecycle.lanes || []).length) problems.push('Lane ids must be unique.');
+
+ for (const state of states.values()) {
+ if (!laneIds.has(state.lane)) {
+ problems.push(`State "${state.id}" uses unknown lane "${state.lane}".`);
+ continue;
+ }
+ if (typeof state.col !== 'number' || state.col < 0 || state.col >= layout.colXs.length) {
+ problems.push(`State "${state.id}" uses invalid column ${state.col}.`);
+ }
+ const top = laneTop(state.lane);
+ const contentTop = top + layout.laneTitleH;
+ if (state.x < layout.laneX || state.x + state.width > layout.laneX + layout.laneW) {
+ problems.push(`State "${state.id}" exceeds the horizontal bounds of lane "${state.lane}".`);
+ }
+ if (state.y < contentTop || state.y + state.height > top + layout.laneH) {
+ problems.push(`State "${state.id}" collides with the title or boundary of lane "${state.lane}".`);
+ }
+ }
+
+ const byLane = new Map();
+ for (const state of states.values()) {
+ byLane.set(state.lane, [...(byLane.get(state.lane) || []), state]);
+ }
+ for (const [lane, laneStates] of byLane) {
+ for (let i = 0; i < laneStates.length; i += 1) {
+ for (let j = i + 1; j < laneStates.length; j += 1) {
+ if (rectsOverlap(laneStates[i], laneStates[j], 10)) {
+ problems.push(`States "${laneStates[i].id}" and "${laneStates[j].id}" are too close in lane "${lane}".`);
+ }
+ }
+ }
+ }
+
+ for (const transition of lifecycle.transitions || []) {
+ if (!states.has(transition.from)) problems.push(`Transition "${transition.label || transition.from}" references unknown source "${transition.from}".`);
+ if (!states.has(transition.to)) problems.push(`Transition "${transition.label || transition.to}" references unknown target "${transition.to}".`);
+ if (states.has(transition.from) && states.has(transition.to)) {
+ const routed = pathFor(transition);
+ const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
+ const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
+ if (distance < 32) problems.push(`Transition "${transition.label || `${transition.from}->${transition.to}`}" is too short.`);
+ }
+ }
+
+ if (legendY() + 18 > viewBox[1]) problems.push(`Legend exceeds viewBox height ${viewBox[1]}.`);
+
+ if (problems.length) {
+ throw new Error(`Lifecycle layout validation failed:\n- ${problems.join('\n- ')}`);
+ }
+}
+
+function anchor(state, side) {
+ switch (side || 'auto') {
+ case 'left': return [state.x, state.cy];
+ case 'right': return [state.x + state.width, state.cy];
+ case 'top': return [state.cx, state.y];
+ case 'bottom': return [state.cx, state.y + state.height];
+ default:
+ return [state.x + state.width, state.cy];
+ }
+}
+
+function defaultFromSide(from, to) {
+ if (to.cx < from.cx) return 'left';
+ if (to.cx > from.cx) return 'right';
+ if (to.cy > from.cy) return 'bottom';
+ return 'top';
+}
+
+function defaultToSide(from, to) {
+ if (to.cx < from.cx) return 'right';
+ if (to.cx > from.cx) return 'left';
+ if (to.cy > from.cy) return 'top';
+ return 'bottom';
+}
+
+function gapYBetween(fromLane, toLane, bias = 0.5) {
+ const a = laneTop(fromLane) + layout.laneH;
+ const b = laneTop(toLane);
+ return a + (b - a) * bias;
+}
+
+function routeVia(transition, from, to, start, end) {
+ if (transition.via) return transition.via;
+ switch (transition.route || 'auto') {
+ case 'straight':
+ return [];
+ case 'drop': {
+ const y = gapYBetween(from.lane, to.lane, transition.bias || 0.5);
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'raise': {
+ const y = gapYBetween(to.lane, from.lane, transition.bias || 0.5);
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'bottom-channel': {
+ const y = transition.channelY || Math.max(from.y + from.height, to.y + to.height) + 34;
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'top-channel': {
+ const y = transition.channelY || Math.min(from.y, to.y) - 28;
+ return [[start[0], y], [end[0], y]];
+ }
+ case 'right-channel': {
+ const x = transition.channelX || Math.max(from.x + from.width, to.x + to.width) + 36;
+ return [[x, start[1]], [x, end[1]]];
+ }
+ case 'left-channel': {
+ const x = transition.channelX || Math.min(from.x, to.x) - 36;
+ return [[x, start[1]], [x, end[1]]];
+ }
+ case 'auto':
+ default: {
+ if (from.lane === to.lane) return [];
+ const y = gapYBetween(from.lane, to.lane, transition.bias || 0.5);
+ return [[start[0], y], [end[0], y]];
+ }
+ }
+}
+
+function pathFor(transition) {
+ const from = states.get(transition.from);
+ const to = states.get(transition.to);
+ const start = anchor(from, transition.fromSide || defaultFromSide(from, to));
+ const end = anchor(to, transition.toSide || defaultToSide(from, to));
+ const points = [start, ...routeVia(transition, from, to, start, end), end];
+ return {
+ d: points.map(([x, y], index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' '),
+ points
+ };
+}
+
+function labelPoint(transition, points) {
+ if (transition.labelAt) return transition.labelAt;
+ if (points.length === 2) {
+ return [
+ (points[0][0] + points[1][0]) / 2 + (transition.labelDx || 0),
+ points[0][1] - 10 + (transition.labelDy || 0)
+ ];
+ }
+ const segmentIndex = Math.min(points.length - 2, Math.max(0, transition.labelSegment ?? 1));
+ const a = points[segmentIndex];
+ const b = points[segmentIndex + 1];
+ return [(a[0] + b[0]) / 2 + (transition.labelDx || 0), (a[1] + b[1]) / 2 - 10 + (transition.labelDy || 0)];
+}
+
+function renderDefinitions() {
+ return ` <!-- Definitions -->
+ <defs>
+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-default" />
+ </marker>
+ <marker id="arrowhead-emphasis" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-emphasis" />
+ </marker>
+ <marker id="arrowhead-security" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-security" />
+ </marker>
+ <marker id="arrowhead-dashed" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-dashed" />
+ </marker>
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
+ <path d="M 40 0 L 0 0 0 40" class="c-grid" stroke-width="0.5"/>
+ </pattern>
+ </defs>`;
+}
+
+function renderLane(lane, index) {
+ const y = layout.laneY + index * (layout.laneH + layout.laneGap);
+ return ` <rect x="${layout.laneX}" y="${y}" width="${layout.laneW}" height="${layout.laneH}" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="${layout.laneX + 14}" y="${y + 22}" class="t-dim" font-size="10" font-weight="600">${String(index + 1).padStart(2, '0')} / ${esc(lane.label)}</text>`;
+}
+
+function renderState(state) {
+ const fill = typeClass[state.type] || typeClass.neutral;
+ const accent = textClass[state.type] || 't-muted';
+ const tag = state.tag
+ ? `\n <text x="${state.cx}" y="${state.y + state.height - 11}" class="${accent}" font-size="7" text-anchor="middle">${esc(state.tag)}</text>`
+ : '';
+ return ` <rect x="${state.x}" y="${state.y}" width="${state.width}" height="${state.height}" rx="6" class="c-mask"/>
+ <rect x="${state.x}" y="${state.y}" width="${state.width}" height="${state.height}" rx="6" class="${fill}" stroke-width="1.5"/>
+ <text x="${state.cx}" y="${state.y + 21}" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">${esc(state.label)}</text>
+ <text x="${state.cx}" y="${state.y + 37}" class="t-muted" font-size="7" text-anchor="middle">${esc(state.sublabel || '')}</text>${tag}`;
+}
+
+function transitionAccent(transition) {
+ return transition.variant === 'security'
+ ? 't-security'
+ : transition.variant === 'emphasis'
+ ? 't-backend'
+ : transition.variant === 'dashed'
+ ? 't-messagebus'
+ : 't-muted';
+}
+
+function renderTransitionPath(transition) {
+ const [cls, marker] = arrowClass[transition.variant || 'default'] || arrowClass.default;
+ const routed = pathFor(transition);
+ const strokeWidth = transition.width || (transition.variant === 'emphasis' ? 1.8 : 1.4);
+ return ` <path d="${routed.d}" class="${cls}" stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
+}
+
+function renderTransitionLabel(transition) {
+ if (!transition.label) return '';
+ const routed = pathFor(transition);
+ const [lx, ly] = labelPoint(transition, routed.points);
+ const longestLine = Math.max(transition.label.length, (transition.note || '').length);
+ const labelW = Math.max(32, longestLine * 4.9 + 12);
+ const labelH = transition.note ? 27 : 16;
+ const note = transition.note
+ ? `\n <text x="${lx}" y="${ly + 11}" class="t-dim" font-size="7" text-anchor="middle">${esc(transition.note)}</text>`
+ : '';
+ return ` <rect x="${lx - labelW / 2}" y="${ly - 11}" width="${labelW}" height="${labelH}" rx="4" class="c-mask"/>
+ <text x="${lx}" y="${ly}" class="${transitionAccent(transition)}" font-size="8" text-anchor="middle">${esc(transition.label)}</text>${note}`;
+}
+
+function renderLegend() {
+ const y = legendY();
+ return ` <text x="220" y="${y - 20}" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <rect x="220" y="${y - 8}" width="14" height="9" rx="2" class="c-backend" stroke-width="1"/>
+ <text x="240" y="${y}" class="t-muted" font-size="7">active state</text>
+ <rect x="325" y="${y - 8}" width="14" height="9" rx="2" class="c-cloud" stroke-width="1"/>
+ <text x="345" y="${y}" class="t-muted" font-size="7">waiting</text>
+ <rect x="415" y="${y - 8}" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>
+ <text x="435" y="${y}" class="t-muted" font-size="7">terminal success</text>
+ <rect x="560" y="${y - 8}" width="14" height="9" rx="2" class="c-security" stroke-width="1"/>
+ <text x="580" y="${y}" class="t-muted" font-size="7">failure / gate</text>
+ <path d="M 690 ${y} L 724 ${y}" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="733" y="${y + 3}" class="t-muted" font-size="7">retry / async</text>`;
+}
+
+function renderSvg() {
+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}">
+${renderDefinitions()}
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Lifecycle lanes -->
+${lifecycle.lanes.map(renderLane).join('\n\n')}
+
+ <!-- Transition paths -->
+${(lifecycle.transitions || []).map(renderTransitionPath).join('\n')}
+
+ <!-- States -->
+${[...states.values()].map(renderState).join('\n\n')}
+
+ <!-- Transition labels -->
+${(lifecycle.transitions || []).map(renderTransitionLabel).join('\n')}
+
+ <!-- Legend -->
+${renderLegend()}
+ </svg>`;
+}
+
+function renderCards() {
+ const cards = lifecycle.cards || [];
+ return ` <!-- Info Cards -->
+ <div class="cards">
+${cards.map((card) => ` <div class="card">
+ <div class="card-header">
+ <div class="card-dot ${esc(card.dot)}"></div>
+ <h3>${esc(card.title)}</h3>
+ </div>
+ <ul>
+${card.items.map((item) => ` <li>&bull; ${esc(item)}</li>`).join('\n')}
+ </ul>
+ </div>`).join('\n\n')}
+ </div>`;
+}
+
+function applyTemplate(svg, cards) {
+ return template
+ .replace('<title>[PROJECT NAME] Architecture Diagram</title>', `<title>${esc(lifecycle.meta.title)} Diagram</title>`)
+ .replace('<h1>[PROJECT NAME] Architecture</h1>', `<h1>${esc(lifecycle.meta.title)}</h1>`)
+ .replace('<p class="subtitle">[Subtitle description]</p>', `<p class="subtitle">${esc(lifecycle.meta.subtitle || '')}</p>`)
+ .replace(/ <svg viewBox="0 0 1000 680">[\s\S]*? <\/svg>/, svg)
+ .replace(/ <!-- Info Cards -->[\s\S]*? <!-- Footer -->/, `${cards}\n\n <!-- Footer -->`)
+ .replace('[Project Name] &bull; [Additional metadata]', 'Lifecycle diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export');
+}
+
+validateLifecycle();
+fs.mkdirSync(path.dirname(outPath), { recursive: true });
+fs.writeFileSync(outPath, applyTemplate(renderSvg(), renderCards()));
+console.log(outPath);
diff --git a/archify/schemas/lifecycle.schema.json b/archify/schemas/lifecycle.schema.json
new file mode 100644
index 00000000..f280682a
--- /dev/null
+++ b/archify/schemas/lifecycle.schema.json
@@ -0,0 +1,151 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/tt-a1i/archify/schemas/lifecycle.schema.json",
+ "title": "Archify Lifecycle Diagram",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["schema_version", "diagram_type", "meta", "lanes", "states", "transitions"],
+ "properties": {
+ "schema_version": {
+ "const": 1
+ },
+ "diagram_type": {
+ "const": "lifecycle"
+ },
+ "meta": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["title"],
+ "properties": {
+ "title": { "type": "string", "minLength": 1 },
+ "subtitle": { "type": "string" },
+ "output": { "type": "string" },
+ "viewBox": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number", "minimum": 420 },
+ { "type": "number", "minimum": 360 }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ }
+ }
+ },
+ "lanes": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 4,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "label"],
+ "properties": {
+ "id": { "$ref": "#/$defs/id" },
+ "label": { "type": "string", "minLength": 1 }
+ }
+ }
+ },
+ "states": {
+ "type": "array",
+ "minItems": 2,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id", "type", "label", "lane", "col"],
+ "properties": {
+ "id": { "$ref": "#/$defs/id" },
+ "type": {
+ "enum": ["start", "active", "waiting", "decision", "success", "failure", "neutral", "external"]
+ },
+ "label": { "type": "string", "minLength": 1 },
+ "sublabel": { "type": "string" },
+ "tag": { "type": "string" },
+ "lane": { "$ref": "#/$defs/id" },
+ "col": { "type": "integer", "minimum": 0 },
+ "width": { "type": "number", "minimum": 48 },
+ "height": { "type": "number", "minimum": 36 },
+ "yOffset": { "type": "number" }
+ }
+ }
+ },
+ "transitions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["from", "to"],
+ "properties": {
+ "from": { "$ref": "#/$defs/id" },
+ "to": { "$ref": "#/$defs/id" },
+ "label": { "type": "string" },
+ "note": { "type": "string" },
+ "variant": {
+ "enum": ["default", "emphasis", "security", "dashed"]
+ },
+ "route": {
+ "enum": ["auto", "straight", "drop", "raise", "bottom-channel", "top-channel", "right-channel", "left-channel"]
+ },
+ "fromSide": {
+ "enum": ["left", "right", "top", "bottom"]
+ },
+ "toSide": {
+ "enum": ["left", "right", "top", "bottom"]
+ },
+ "channelX": { "type": "number" },
+ "channelY": { "type": "number" },
+ "bias": { "type": "number", "minimum": 0, "maximum": 1 },
+ "labelAt": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number" },
+ { "type": "number" }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ },
+ "labelDx": { "type": "number" },
+ "labelDy": { "type": "number" },
+ "labelSegment": { "type": "integer", "minimum": 0 },
+ "via": {
+ "type": "array",
+ "items": {
+ "type": "array",
+ "prefixItems": [
+ { "type": "number" },
+ { "type": "number" }
+ ],
+ "items": false,
+ "minItems": 2,
+ "maxItems": 2
+ }
+ },
+ "width": { "type": "number", "minimum": 0.5 }
+ }
+ }
+ },
+ "cards": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["dot", "title", "items"],
+ "properties": {
+ "dot": { "enum": ["cyan", "emerald", "violet", "amber", "rose", "orange", "slate"] },
+ "title": { "type": "string", "minLength": 1 },
+ "items": {
+ "type": "array",
+ "items": { "type": "string" }
+ }
+ }
+ }
+ }
+ },
+ "$defs": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-zA-Z][a-zA-Z0-9_-]*$"
+ }
+ }
+}
diff --git a/examples/images/archify-lifecycle.png b/examples/images/archify-lifecycle.png
new file mode 100644
index 00000000..e67d03df
Binary files /dev/null and b/examples/images/archify-lifecycle.png differ
diff --git a/examples/lifecycle-agent-run.html b/examples/lifecycle-agent-run.html
new file mode 100644
index 00000000..5f5745ac
--- /dev/null
+++ b/examples/lifecycle-agent-run.html
@@ -0,0 +1,1104 @@
+<!DOCTYPE html>
+<html lang="en" data-theme="dark">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Agent Run Lifecycle Diagram</title>
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
+ <style>
+ /* ==========================================================
+ THEME VARIABLES — switch by toggling [data-theme] on <html>
+ ========================================================== */
+ :root,
+ [data-theme="dark"] {
+ --bg: #020617;
+ --grid: #1e293b;
+ --text: #ffffff;
+ --text-muted: #94a3b8;
+ --text-dim: #475569;
+
+ --panel: rgba(15, 23, 42, 0.5);
+ --panel-border: #1e293b;
+ --lane-fill: rgba(15, 23, 42, 0.22);
+ --lane-stroke: #334155;
+
+ --arrow: #64748b;
+ --arrow-emphasis: #34d399;
+
+ /* Opaque mask color used behind semi-transparent component fills
+ so the arrows drawn underneath are properly hidden. */
+ --mask: #0f172a;
+
+ --frontend-fill: rgba(8, 51, 68, 0.4);
+ --frontend-stroke: #22d3ee;
+ --backend-fill: rgba(6, 78, 59, 0.4);
+ --backend-stroke: #34d399;
+ --database-fill: rgba(76, 29, 149, 0.4);
+ --database-stroke: #a78bfa;
+ --cloud-fill: rgba(120, 53, 15, 0.3);
+ --cloud-stroke: #fbbf24;
+ --security-fill: rgba(136, 19, 55, 0.4);
+ --security-stroke: #fb7185;
+ --messagebus-fill: rgba(251, 146, 60, 0.3);
+ --messagebus-stroke:#fb923c;
+ --external-fill: rgba(30, 41, 59, 0.5);
+ --external-stroke: #94a3b8;
+
+ --toolbar-bg: rgba(15, 23, 42, 0.8);
+ --toolbar-border: #334155;
+ --toolbar-text: #e2e8f0;
+ --toolbar-hover: rgba(15, 23, 42, 0.95);
+ --toolbar-menu-bg: #0f172a;
+ }
+
+ [data-theme="light"] {
+ --bg: #f8fafc;
+ --grid: #e2e8f0;
+ --text: #0f172a;
+ --text-muted: #64748b;
+ --text-dim: #94a3b8;
+
+ --panel: #ffffff;
+ --panel-border: #e2e8f0;
+ --lane-fill: rgba(248, 250, 252, 0.65);
+ --lane-stroke: #cbd5e1;
+
+ --arrow: #94a3b8;
+ --arrow-emphasis: #059669;
+
+ --mask: #ffffff;
+
+ --frontend-fill: rgba(34, 211, 238, 0.15);
+ --frontend-stroke: #0891b2;
+ --backend-fill: rgba(52, 211, 153, 0.18);
+ --backend-stroke: #059669;
+ --database-fill: rgba(167, 139, 250, 0.2);
+ --database-stroke: #7c3aed;
+ --cloud-fill: rgba(251, 191, 36, 0.18);
+ --cloud-stroke: #d97706;
+ --security-fill: rgba(251, 113, 133, 0.15);
+ --security-stroke: #e11d48;
+ --messagebus-fill: rgba(251, 146, 60, 0.15);
+ --messagebus-stroke:#ea580c;
+ --external-fill: rgba(148, 163, 184, 0.18);
+ --external-stroke: #64748b;
+
+ --toolbar-bg: rgba(255, 255, 255, 0.92);
+ --toolbar-border: #cbd5e1;
+ --toolbar-text: #334155;
+ --toolbar-hover: #ffffff;
+ --toolbar-menu-bg: #ffffff;
+ }
+
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+
+ body {
+ font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace;
+ background: var(--bg);
+ min-height: 100vh;
+ padding: 2rem;
+ color: var(--text);
+ transition: background 0.2s ease, color 0.2s ease;
+ }
+
+ .container { max-width: 1200px; margin: 0 auto; }
+
+ .header { margin-bottom: 2rem; }
+
+ .header-row {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin-bottom: 0.5rem;
+ }
+
+ .pulse-dot {
+ width: 12px;
+ height: 12px;
+ background: var(--frontend-stroke);
+ border-radius: 50%;
+ animation: pulse 2s infinite;
+ }
+
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+
+ h1 {
+ font-size: 1.5rem;
+ font-weight: 700;
+ letter-spacing: -0.025em;
+ }
+
+ .subtitle {
+ color: var(--text-muted);
+ font-size: 0.875rem;
+ margin-left: 1.75rem;
+ }
+
+ .diagram-container {
+ background: var(--panel);
+ border-radius: 1rem;
+ border: 1px solid var(--panel-border);
+ padding: 1.5rem;
+ overflow-x: auto;
+ }
+
+ svg {
+ width: 100%;
+ min-width: min(900px, 100%);
+ display: block;
+ }
+
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 1rem;
+ margin-top: 2rem;
+ }
+
+ .card {
+ background: var(--panel);
+ border-radius: 0.75rem;
+ border: 1px solid var(--panel-border);
+ padding: 1.25rem;
+ }
+
+ .card-header {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin-bottom: 0.75rem;
+ }
+
+ .card-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ }
+
+ .card-dot.cyan { background: var(--frontend-stroke); }
+ .card-dot.emerald { background: var(--backend-stroke); }
+ .card-dot.violet { background: var(--database-stroke); }
+ .card-dot.amber { background: var(--cloud-stroke); }
+ .card-dot.rose { background: var(--security-stroke); }
+ .card-dot.orange { background: var(--messagebus-stroke); }
+ .card-dot.slate { background: var(--external-stroke); }
+
+ .card h3 { font-size: 0.875rem; font-weight: 600; color: var(--text); }
+
+ .card ul {
+ list-style: none;
+ color: var(--text-muted);
+ font-size: 0.75rem;
+ }
+
+ .card li { margin-bottom: 0.375rem; }
+
+ .footer {
+ text-align: center;
+ margin-top: 1.5rem;
+ color: var(--text-dim);
+ font-size: 0.75rem;
+ }
+
+ /* ==========================================================
+ Print stylesheet — hide interactive controls, force light,
+ drop the grid so the diagram doesn't waste ink, use landscape
+ so wide diagrams fit, pack summary cards into 2 columns to
+ avoid an orphan card on a trailing page.
+ ========================================================== */
+ @page { size: landscape; margin: 1.5cm; }
+
+ @media print {
+ :root, [data-theme="dark"], [data-theme="light"] {
+ --bg: #ffffff;
+ --grid: transparent;
+ --panel: #ffffff;
+ --panel-border: #e2e8f0;
+ --text: #0f172a;
+ --text-muted: #475569;
+ --text-dim: #94a3b8;
+ --mask: #ffffff;
+ }
+ body { background: #ffffff !important; padding: 0; }
+ .container { max-width: none; }
+ .toolbar, .archify-toast { display: none !important; }
+ .diagram-container, .card { box-shadow: none; border-color: #e2e8f0; }
+ .cards { grid-template-columns: 1fr 1fr; }
+ /* Ensure elements break sensibly across pages */
+ .card { break-inside: avoid; page-break-inside: avoid; }
+ .diagram-container { break-inside: avoid; page-break-inside: avoid; }
+ h1, .subtitle { color: #0f172a; }
+ }
+
+ /* ==========================================================
+ TOOLBAR (theme toggle + export menu)
+ ========================================================== */
+ .toolbar {
+ position: fixed;
+ top: 1rem;
+ right: 1rem;
+ display: flex;
+ gap: 0.5rem;
+ z-index: 100;
+ }
+ .toolbar button {
+ background: var(--toolbar-bg);
+ color: var(--toolbar-text);
+ border: 1px solid var(--toolbar-border);
+ padding: 0.5rem 0.875rem;
+ border-radius: 0.5rem;
+ font-family: inherit;
+ font-size: 0.75rem;
+ font-weight: 500;
+ cursor: pointer;
+ backdrop-filter: blur(8px);
+ transition: background 0.15s, border-color 0.15s;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ }
+ .toolbar button:hover {
+ background: var(--toolbar-hover);
+ border-color: var(--arrow);
+ }
+ .toolbar button:focus-visible {
+ outline: 2px solid var(--frontend-stroke);
+ outline-offset: 2px;
+ }
+ .toolbar .export-wrap { position: relative; }
+ .toolbar .export-menu {
+ position: absolute;
+ top: calc(100% + 0.375rem);
+ right: 0;
+ background: var(--toolbar-menu-bg);
+ border: 1px solid var(--toolbar-border);
+ border-radius: 0.5rem;
+ padding: 0.375rem;
+ min-width: 160px;
+ display: none;
+ flex-direction: column;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);
+ }
+ .toolbar .export-menu.open { display: flex; }
+ .toolbar .export-menu button {
+ background: transparent;
+ border: 0;
+ justify-content: space-between;
+ width: 100%;
+ text-align: left;
+ padding: 0.5rem 0.75rem;
+ }
+ .toolbar .export-menu button:hover {
+ background: var(--toolbar-hover);
+ }
+ .toolbar .export-menu .hint {
+ color: var(--text-dim);
+ font-size: 0.625rem;
+ }
+ .toolbar .export-menu hr {
+ border: 0;
+ border-top: 1px solid var(--toolbar-border);
+ margin: 0.25rem 0.375rem;
+ opacity: 0.5;
+ }
+
+ /* Toast — brief feedback for actions like "copied" */
+ .archify-toast {
+ position: fixed;
+ top: 1rem;
+ left: 50%;
+ transform: translateX(-50%) translateY(-8px);
+ background: var(--toolbar-menu-bg);
+ color: var(--text);
+ border: 1px solid var(--toolbar-border);
+ padding: 0.5rem 1rem;
+ border-radius: 0.5rem;
+ font-family: inherit;
+ font-size: 0.75rem;
+ opacity: 0;
+ transition: opacity 0.2s, transform 0.2s;
+ z-index: 200;
+ pointer-events: none;
+ box-shadow: 0 4px 20px rgba(0,0,0,0.25);
+ }
+ .archify-toast.show {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0);
+ }
+
+ @media (max-width: 720px) {
+ body { padding: 1rem; }
+ .toolbar {
+ position: static;
+ justify-content: flex-end;
+ margin-bottom: 1rem;
+ }
+ .header { margin-bottom: 1.25rem; }
+ .header-row {
+ gap: 0.75rem;
+ align-items: flex-start;
+ }
+ h1 {
+ font-size: 1.25rem;
+ line-height: 1.25;
+ }
+ .subtitle {
+ margin-left: 0;
+ font-size: 0.8125rem;
+ line-height: 1.55;
+ }
+ .diagram-container {
+ padding: 0.75rem;
+ border-radius: 0.75rem;
+ }
+ .cards {
+ grid-template-columns: 1fr;
+ margin-top: 1rem;
+ }
+ }
+
+ /* ==========================================================
+ SVG SEMANTIC CLASSES — use these instead of inline fill/stroke
+ ========================================================== */
+ .c-grid { stroke: var(--grid); fill: none; }
+ .c-mask { fill: var(--mask); stroke: none; }
+
+ .c-frontend { fill: var(--frontend-fill); stroke: var(--frontend-stroke); }
+ .c-backend { fill: var(--backend-fill); stroke: var(--backend-stroke); }
+ .c-database { fill: var(--database-fill); stroke: var(--database-stroke); }
+ .c-cloud { fill: var(--cloud-fill); stroke: var(--cloud-stroke); }
+ .c-security { fill: var(--security-fill); stroke: var(--security-stroke); }
+ .c-messagebus { fill: var(--messagebus-fill); stroke: var(--messagebus-stroke); }
+ .c-external { fill: var(--external-fill); stroke: var(--external-stroke); }
+
+ /* Text helpers */
+ .t-primary { fill: var(--text); }
+ .t-muted { fill: var(--text-muted); }
+ .t-dim { fill: var(--text-dim); }
+ .t-frontend { fill: var(--frontend-stroke); }
+ .t-backend { fill: var(--backend-stroke); }
+ .t-database { fill: var(--database-stroke); }
+ .t-cloud { fill: var(--cloud-stroke); }
+ .t-security { fill: var(--security-stroke); }
+ .t-messagebus { fill: var(--messagebus-stroke); }
+ .t-external { fill: var(--external-stroke); }
+
+ /* Arrows */
+ .a-default { stroke: var(--arrow); fill: none; }
+ .a-emphasis { stroke: var(--arrow-emphasis); fill: none; }
+ .a-security { stroke: var(--security-stroke); fill: none; stroke-dasharray: 5,5; }
+ .a-dashed { stroke: var(--database-stroke); fill: none; stroke-dasharray: 4,4; }
+
+ /* Arrowhead markers reference these */
+ .m-default { fill: var(--arrow); }
+ .m-emphasis { fill: var(--arrow-emphasis); }
+ .m-security { fill: var(--security-stroke); }
+ .m-dashed { fill: var(--database-stroke); }
+
+ /* Dashed boundary variants */
+ .c-security-group { fill: transparent; stroke: var(--security-stroke); stroke-dasharray: 4,4; }
+ .c-region { fill: rgba(251, 191, 36, 0.05); stroke: var(--cloud-stroke); stroke-dasharray: 8,4; }
+ .c-lane { fill: var(--lane-fill); stroke: var(--lane-stroke); stroke-dasharray: 6,6; }
+ </style>
+</head>
+<body>
+ <!-- Toolbar: theme toggle + export menu (present on every generated diagram)
+ Keyboard: T toggles theme, E opens export menu (when no input focused) -->
+ <div class="toolbar" role="toolbar" aria-label="Diagram actions">
+ <button id="btn-theme" type="button"
+ title="Toggle theme (T)"
+ aria-label="Toggle color theme"
+ aria-pressed="false">
+ <span id="theme-icon" aria-hidden="true">&#9790;</span>
+ <span id="theme-label">Dark</span>
+ </button>
+ <div class="export-wrap">
+ <button id="btn-export" type="button"
+ title="Export diagram (E)"
+ aria-label="Export diagram"
+ aria-haspopup="menu"
+ aria-expanded="false"
+ aria-controls="export-menu">
+ Export <span aria-hidden="true">&#9662;</span>
+ </button>
+ <div class="export-menu" id="export-menu" role="menu" aria-label="Export">
+ <button data-action="copy" type="button" role="menuitem" tabindex="-1">Copy to clipboard <span class="hint">PNG</span></button>
+ <hr role="separator" aria-hidden="true">
+ <button data-format="png" type="button" role="menuitem" tabindex="-1">Download PNG</button>
+ <button data-format="jpeg" type="button" role="menuitem" tabindex="-1">Download JPEG</button>
+ <button data-format="webp" type="button" role="menuitem" tabindex="-1">Download WebP</button>
+ <hr role="separator" aria-hidden="true">
+ <button data-format="svg" type="button" role="menuitem" tabindex="-1">Download SVG <span class="hint">vector</span></button>
+ </div>
+ </div>
+ </div>
+
+ <div class="container">
+ <!-- Header -->
+ <div class="header">
+ <div class="header-row">
+ <div class="pulse-dot"></div>
+ <h1>Agent Run Lifecycle</h1>
+ </div>
+ <p class="subtitle">State machine for planning, tool execution, human approval, retries, and terminal outcomes</p>
+ </div>
+
+ <!-- Main Diagram -->
+ <div class="diagram-container">
+ <svg viewBox="0 0 980 720">
+ <!-- Definitions -->
+ <defs>
+ <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-default" />
+ </marker>
+ <marker id="arrowhead-emphasis" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-emphasis" />
+ </marker>
+ <marker id="arrowhead-security" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-security" />
+ </marker>
+ <marker id="arrowhead-dashed" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
+ <polygon points="0 0, 10 3.5, 0 7" class="m-dashed" />
+ </marker>
+ <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
+ <path d="M 40 0 L 0 0 0 40" class="c-grid" stroke-width="0.5"/>
+ </pattern>
+ </defs>
+
+ <!-- Background Grid -->
+ <rect width="100%" height="100%" fill="url(#grid)" />
+
+ <!-- Lifecycle lanes -->
+ <rect x="34" y="48" width="912" height="150" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="48" y="70" class="t-dim" font-size="10" font-weight="600">01 / Main lifecycle</text>
+
+ <rect x="34" y="220" width="912" height="150" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="48" y="242" class="t-dim" font-size="10" font-weight="600">02 / Wait states</text>
+
+ <rect x="34" y="392" width="912" height="150" rx="10" class="c-lane" stroke-width="1"/>
+ <text x="48" y="414" class="t-dim" font-size="10" font-weight="600">03 / Exceptions + recovery</text>
+
+ <!-- Transition paths -->
+ <path d="M 152 138 L 190 138" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 302 138 L 340 138" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 452 138 L 490 138" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 602 138 L 790 138" class="a-emphasis" stroke-width="1.8" marker-end="url(#arrowhead-emphasis)"/>
+ <path d="M 396 167 L 396 194 L 546 194 L 546 281" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <path d="M 546 281 L 546 216 L 396 216 L 396 167" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <path d="M 602 138 L 602 209 L 640 209 L 640 310" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
+ <path d="M 640 310 L 640 350 L 246 350 L 246 167" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <path d="M 396 167 L 396 453" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <path d="M 340 482 L 188 482 L 188 167 L 246 167" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <path d="M 752 310 L 906 310 L 906 453 L 846 453" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+ <path d="M 546 339 L 546 381 L 696 381 L 696 453" class="a-security" stroke-width="1.4" marker-end="url(#arrowhead-security)"/>
+
+ <!-- States -->
+ <rect x="40" y="109" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="40" y="109" width="112" height="58" rx="6" class="c-frontend" stroke-width="1.5"/>
+ <text x="96" y="130" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Queued</text>
+ <text x="96" y="146" class="t-muted" font-size="7" text-anchor="middle">request accepted</text>
+ <text x="96" y="156" class="t-frontend" font-size="7" text-anchor="middle">entry</text>
+
+ <rect x="190" y="109" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="190" y="109" width="112" height="58" rx="6" class="c-backend" stroke-width="1.5"/>
+ <text x="246" y="130" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Planning</text>
+ <text x="246" y="146" class="t-muted" font-size="7" text-anchor="middle">build task graph</text>
+ <text x="246" y="156" class="t-backend" font-size="7" text-anchor="middle">model</text>
+
+ <rect x="340" y="109" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="340" y="109" width="112" height="58" rx="6" class="c-backend" stroke-width="1.5"/>
+ <text x="396" y="130" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Executing</text>
+ <text x="396" y="146" class="t-muted" font-size="7" text-anchor="middle">tool calls</text>
+ <text x="396" y="156" class="t-backend" font-size="7" text-anchor="middle">work</text>
+
+ <rect x="490" y="109" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="490" y="109" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="546" y="130" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Reviewing</text>
+ <text x="546" y="146" class="t-muted" font-size="7" text-anchor="middle">quality gate</text>
+ <text x="546" y="156" class="t-security" font-size="7" text-anchor="middle">check</text>
+
+ <rect x="790" y="109" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="790" y="109" width="112" height="58" rx="6" class="c-database" stroke-width="1.5"/>
+ <text x="846" y="130" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Completed</text>
+ <text x="846" y="146" class="t-muted" font-size="7" text-anchor="middle">final response</text>
+ <text x="846" y="156" class="t-database" font-size="7" text-anchor="middle">terminal</text>
+
+ <rect x="490" y="281" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="490" y="281" width="112" height="58" rx="6" class="c-cloud" stroke-width="1.5"/>
+ <text x="546" y="302" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Needs Approval</text>
+ <text x="546" y="318" class="t-muted" font-size="7" text-anchor="middle">human gate</text>
+ <text x="546" y="328" class="t-cloud" font-size="7" text-anchor="middle">pause</text>
+
+ <rect x="640" y="281" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="640" y="281" width="112" height="58" rx="6" class="c-cloud" stroke-width="1.5"/>
+ <text x="696" y="302" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Blocked</text>
+ <text x="696" y="318" class="t-muted" font-size="7" text-anchor="middle">missing input</text>
+ <text x="696" y="328" class="t-cloud" font-size="7" text-anchor="middle">wait</text>
+
+ <rect x="340" y="453" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="340" y="453" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="396" y="474" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Failed</text>
+ <text x="396" y="490" class="t-muted" font-size="7" text-anchor="middle">recoverable error</text>
+ <text x="396" y="500" class="t-security" font-size="7" text-anchor="middle">retryable</text>
+
+ <rect x="640" y="453" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="640" y="453" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="696" y="474" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Cancelled</text>
+ <text x="696" y="490" class="t-muted" font-size="7" text-anchor="middle">user stopped</text>
+ <text x="696" y="500" class="t-security" font-size="7" text-anchor="middle">terminal</text>
+
+ <rect x="790" y="453" width="112" height="58" rx="6" class="c-mask"/>
+ <rect x="790" y="453" width="112" height="58" rx="6" class="c-security" stroke-width="1.5"/>
+ <text x="846" y="474" class="t-primary" font-size="10" font-weight="600" text-anchor="middle">Expired</text>
+ <text x="846" y="490" class="t-muted" font-size="7" text-anchor="middle">timeout</text>
+ <text x="846" y="500" class="t-security" font-size="7" text-anchor="middle">terminal</text>
+
+ <!-- Transition labels -->
+ <rect x="152.75" y="117" width="36.5" height="16" rx="4" class="c-mask"/>
+ <text x="171" y="128" class="t-backend" font-size="8" text-anchor="middle">start</text>
+ <rect x="290.5" y="117" width="61" height="16" rx="4" class="c-mask"/>
+ <text x="321" y="128" class="t-backend" font-size="8" text-anchor="middle">plan ready</text>
+ <rect x="435.6" y="117" width="70.80000000000001" height="16" rx="4" class="c-mask"/>
+ <text x="471" y="128" class="t-backend" font-size="8" text-anchor="middle">tool results</text>
+ <rect x="598.4" y="93" width="51.2" height="27" rx="4" class="c-mask"/>
+ <text x="624" y="104" class="t-backend" font-size="8" text-anchor="middle">passes</text>
+ <text x="624" y="115" class="t-dim" font-size="7" text-anchor="middle">terminal</text>
+ <rect x="437.7" y="171" width="80.60000000000001" height="27" rx="4" class="c-mask"/>
+ <text x="478" y="182" class="t-security" font-size="8" text-anchor="middle">needs approval</text>
+ <text x="478" y="193" class="t-dim" font-size="7" text-anchor="middle">policy gate</text>
+
+ <rect x="585.05" y="179" width="65.9" height="16" rx="4" class="c-mask"/>
+ <text x="618" y="190" class="t-muted" font-size="8" text-anchor="middle">needs input</text>
+ <rect x="441.5" y="339" width="61" height="16" rx="4" class="c-mask"/>
+ <text x="472" y="350" class="t-messagebus" font-size="8" text-anchor="middle">user reply</text>
+ <rect x="395.5" y="381" width="61" height="16" rx="4" class="c-mask"/>
+ <text x="426" y="392" class="t-security" font-size="8" text-anchor="middle">tool error</text>
+ <rect x="164.85" y="435" width="46.300000000000004" height="27" rx="4" class="c-mask"/>
+ <text x="188" y="446" class="t-messagebus" font-size="8" text-anchor="middle">retry</text>
+ <text x="188" y="457" class="t-dim" font-size="7" text-anchor="middle">bounded</text>
+ <rect x="882.85" y="351" width="46.300000000000004" height="16" rx="4" class="c-mask"/>
+ <text x="906" y="362" class="t-security" font-size="8" text-anchor="middle">timeout</text>
+ <rect x="599.3" y="351" width="41.400000000000006" height="16" rx="4" class="c-mask"/>
+ <text x="620" y="362" class="t-security" font-size="8" text-anchor="middle">cancel</text>
+
+ <!-- Legend -->
+ <text x="220" y="566" class="t-primary" font-size="10" font-weight="600">Legend</text>
+ <rect x="220" y="578" width="14" height="9" rx="2" class="c-backend" stroke-width="1"/>
+ <text x="240" y="586" class="t-muted" font-size="7">active state</text>
+ <rect x="325" y="578" width="14" height="9" rx="2" class="c-cloud" stroke-width="1"/>
+ <text x="345" y="586" class="t-muted" font-size="7">waiting</text>
+ <rect x="415" y="578" width="14" height="9" rx="2" class="c-database" stroke-width="1"/>
+ <text x="435" y="586" class="t-muted" font-size="7">terminal success</text>
+ <rect x="560" y="578" width="14" height="9" rx="2" class="c-security" stroke-width="1"/>
+ <text x="580" y="586" class="t-muted" font-size="7">failure / gate</text>
+ <path d="M 690 586 L 724 586" class="a-dashed" stroke-width="1.4" marker-end="url(#arrowhead-dashed)"/>
+ <text x="733" y="589" class="t-muted" font-size="7">retry / async</text>
+ </svg>
+ </div>
+
+ <!-- Info Cards -->
+ <div class="cards">
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot emerald"></div>
+ <h3>Main Path</h3>
+ </div>
+ <ul>
+ <li>&bull; Main states are Queued, Planning, Executing, Reviewing, and Completed</li>
+ <li>&bull; The hot path stays in one lane and reads left to right</li>
+ <li>&bull; Completed is the only success terminal state</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot amber"></div>
+ <h3>Human + Input Gates</h3>
+ </div>
+ <ul>
+ <li>&bull; Approval pauses execution without ending the run</li>
+ <li>&bull; Blocked waits for missing user input</li>
+ <li>&bull; Wait states can resume back into planning or execution</li>
+ </ul>
+ </div>
+
+ <div class="card">
+ <div class="card-header">
+ <div class="card-dot rose"></div>
+ <h3>Terminal + Recovery</h3>
+ </div>
+ <ul>
+ <li>&bull; Failed is recoverable while retry budget remains</li>
+ <li>&bull; Cancelled and Expired are terminal failure states</li>
+ <li>&bull; Error transitions are separated from the happy path</li>
+ </ul>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <p class="footer">
+ Lifecycle diagram &bull; Built with Archify &bull; Press <kbd>T</kbd> for theme and <kbd>E</kbd> for export
+ </p>
+ </div>
+
+ <script>
+ /* ============================================================
+ Theme toggle — persists to localStorage, respects system pref
+ ============================================================ */
+ var Archify = {};
+
+ Archify.theme = (function () {
+ var STORAGE_KEY = 'archify-theme';
+ var html = document.documentElement;
+ var btn = document.getElementById('btn-theme');
+ var icon = document.getElementById('theme-icon');
+ var label = document.getElementById('theme-label');
+
+ function resolveInitial() {
+ // URL param wins (useful for deterministic screenshots / share links)
+ try {
+ var param = new URLSearchParams(window.location.search).get('theme');
+ if (param === 'light' || param === 'dark') return param;
+ } catch (_) {}
+ var saved = localStorage.getItem(STORAGE_KEY);
+ if (saved === 'light' || saved === 'dark') return saved;
+ return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
+ }
+
+ function apply(theme) {
+ html.setAttribute('data-theme', theme);
+ icon.textContent = theme === 'dark' ? '\u263E' : '\u263C';
+ label.textContent = theme === 'dark' ? 'Dark' : 'Light';
+ btn.setAttribute('aria-pressed', theme === 'light' ? 'true' : 'false');
+ }
+
+ function toggle() {
+ var next = html.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
+ apply(next);
+ localStorage.setItem(STORAGE_KEY, next);
+ }
+
+ apply(resolveInitial());
+ btn.addEventListener('click', toggle);
+
+ return { toggle: toggle };
+ })();
+
+ /* ============================================================
+ Export — PNG / JPEG / WebP / SVG (download) and Copy PNG (clipboard)
+
+ Raster exports are always rendered at 4x source resolution for
+ maximum sharpness. The trick: we set the serialized SVG's
+ `width`/`height` to viewBox * 4 so the browser rasterizes the
+ vectors at that resolution natively. drawImage then draws at
+ the image's natural size (no upscaling = no blur).
+
+ JPEG/WebP paint the current theme's background explicitly since
+ those formats have no alpha channel.
+ ============================================================ */
+ (function () {
+ var RASTER_SCALE = 4;
+
+ function diagramFilename() {
+ var title = (document.title || 'diagram').replace(/\s+Architecture(\s+Diagram)?$/i, '').trim();
+ return title.replace(/[^a-z0-9_\-]+/gi, '-')
+ .toLowerCase()
+ .replace(/^-+|-+$/g, '') || 'diagram';
+ }
+
+ function currentBg() {
+ return getComputedStyle(document.body).backgroundColor || '#ffffff';
+ }
+
+ /**
+ * Serialize the main SVG into a standalone document.
+ *
+ * Two modes:
+ * - Default (opts.autoTheme=false) — locks the serialized SVG to the
+ * viewer's current theme. Used by the raster pipeline
+ * (PNG/JPEG/WebP/clipboard) because canvas rasterization needs
+ * deterministic colors; a raster cannot react to
+ * prefers-color-scheme after encoding.
+ * - autoTheme=true — emits BOTH dark and light variable sets plus a
+ * `@media (prefers-color-scheme)` rule so the resulting SVG
+ * self-themes when embedded in GitHub READMEs or other hosts that
+ * expose a color scheme. Used for "Download SVG".
+ */
+ function serializeSvg(scale, opts) {
+ // scale: integer multiplier for intrinsic SVG pixel dimensions used by
+ // the raster path. Defaults to 1 (natural size) for SVG download.
+ scale = scale || 1;
+ opts = opts || {};
+ var autoTheme = opts.autoTheme === true;
+
+ var svg = document.querySelector('.diagram-container svg');
+ var clone = svg.cloneNode(true);
+
+ var vb = svg.viewBox.baseVal;
+ // Scale width/height so the browser rasterizes the vectors at target
+ // resolution directly. viewBox stays unchanged so coordinates don't
+ // shift. This is the key to sharp rasters — do NOT scale later via
+ // canvas upscaling.
+ clone.setAttribute('width', vb.width * scale);
+ clone.setAttribute('height', vb.height * scale);
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+
+ var hostStyle = Array.prototype.map.call(document.querySelectorAll('style'), function (s) {
+ return s.textContent;
+ }).join('\n');
+
+ var varNames = [
+ '--bg','--grid','--text','--text-muted','--text-dim',
+ '--arrow','--arrow-emphasis','--mask',
+ '--frontend-fill','--frontend-stroke',
+ '--backend-fill','--backend-stroke',
+ '--database-fill','--database-stroke',
+ '--cloud-fill','--cloud-stroke',
+ '--security-fill','--security-stroke',
+ '--messagebus-fill','--messagebus-stroke',
+ '--external-fill','--external-stroke'
+ ];
+
+ // Resolve the full variable set for a given data-theme via an
+ // off-DOM probe, independent of what the viewer is currently set to.
+ function resolveVars(themeAttr) {
+ var probe = document.createElement('div');
+ probe.setAttribute('data-theme', themeAttr);
+ probe.style.cssText = 'position:absolute;width:0;height:0;visibility:hidden;';
+ document.body.appendChild(probe);
+ try {
+ var c = getComputedStyle(probe);
+ return varNames.map(function (n) {
+ return n + ': ' + c.getPropertyValue(n).trim() + ';';
+ }).join(' ');
+ } finally {
+ document.body.removeChild(probe);
+ }
+ }
+
+ // Prepend a local()-only @font-face block for each weight so that the
+ // sandboxed image-rendering context used during PNG/JPEG/WebP export
+ // can find JetBrains Mono if the user has it installed locally, and
+ // falls through cleanly to the monospace stack otherwise. The usual
+ // Google-Fonts <link> in the host document is unreachable from the
+ // serialized SVG, so url()-sourced faces would just hang.
+ var fontFallback = [400, 500, 600, 700].map(function (w) {
+ return "@font-face { font-family: 'JetBrains Mono'; font-weight: " + w +
+ "; src: local('JetBrains Mono'), local('JetBrainsMono-Regular'); }";
+ }).join('\n');
+
+ var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');
+ var bgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ bgRect.setAttribute('width', '100%');
+ bgRect.setAttribute('height', '100%');
+
+ if (autoTheme) {
+ // Dual-theme SVG. Dark is the default (so hosts without
+ // prefers-color-scheme still render), light swaps in via media
+ // query, and svg[data-theme="..."] still lets downstream
+ // consumers force a specific theme.
+ var darkVars = resolveVars('dark');
+ var lightVars = resolveVars('light');
+
+ style.textContent =
+ fontFallback + "\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ hostStyle + "\n" +
+ ":root, svg { " + darkVars + " }\n" +
+ "@media (prefers-color-scheme: light) { :root, svg { " + lightVars + " } }\n" +
+ "svg[data-theme=\"light\"] { " + lightVars + " }\n" +
+ "svg[data-theme=\"dark\"] { " + darkVars + " }\n" +
+ "rect.c-bg-rect { fill: var(--bg); }\n";
+
+ // Don't lock the serialized SVG to the viewer's current theme.
+ clone.removeAttribute('data-theme');
+ // Background follows the CSS variable, not a fixed color, so it
+ // swaps with the media query.
+ bgRect.setAttribute('class', 'c-bg-rect');
+ } else {
+ // Raster path: lock to the viewer's current theme.
+ var theme = document.documentElement.getAttribute('data-theme') || 'dark';
+ var themeHost = document.querySelector('[data-theme="' + theme + '"]') || document.documentElement;
+ var computed = getComputedStyle(themeHost);
+ var vars = varNames.map(function (n) {
+ return n + ': ' + computed.getPropertyValue(n).trim() + ';';
+ }).join(' ');
+
+ // IMPORTANT: inject the resolved variables AFTER hostStyle,
+ // otherwise hostStyle's ":root, [data-theme=\"dark\"] { ... }" rule
+ // overrides our chosen theme via later-in-cascade equal-specificity.
+ // Keep this order.
+ style.textContent =
+ fontFallback + "\n" +
+ "svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; }\n" +
+ hostStyle + "\n" +
+ ":root, svg { " + vars + " }\n";
+
+ bgRect.setAttribute('fill', computed.getPropertyValue('--bg').trim() || '#ffffff');
+ }
+
+ clone.insertBefore(style, clone.firstChild);
+ clone.insertBefore(bgRect, style.nextSibling);
+
+ return {
+ svgString: new XMLSerializer().serializeToString(clone),
+ width: vb.width * scale,
+ height: vb.height * scale
+ };
+ }
+
+ function download(blob, filename) {
+ var url = URL.createObjectURL(blob);
+ var a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
+ }
+
+ // Conservative upper bound on total canvas pixels. Older Safari on iOS
+ // silently produces a blank canvas above ~16 Mpx; Chrome / Firefox /
+ // desktop Safari are far higher but start failing on memory-constrained
+ // devices. We pick the largest integer scale in {4,3,2,1} whose target
+ // pixel count fits under this cap.
+ var MAX_CANVAS_PIXELS = 16 * 1024 * 1024;
+
+ function pickSafeScale(vbW, vbH) {
+ for (var s = RASTER_SCALE; s >= 1; s--) {
+ if (vbW * s * vbH * s <= MAX_CANVAS_PIXELS) return s;
+ }
+ return 1;
+ }
+
+ function rasterize(format) {
+ // Serialize at a safe scale (RASTER_SCALE=4 by default, reduced if the
+ // resulting canvas would exceed MAX_CANVAS_PIXELS). The SVG itself is
+ // rasterized at target resolution natively; drawImage draws at natural
+ // size — no upsampling blur.
+ var svg = document.querySelector('.diagram-container svg');
+ var vb = svg.viewBox.baseVal;
+ var scale = pickSafeScale(vb.width, vb.height);
+ var data = serializeSvg(scale);
+ var svgBlob = new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' });
+ var svgUrl = URL.createObjectURL(svgBlob);
+
+ return new Promise(function (resolve, reject) {
+ var img = new Image();
+ img.onload = function () {
+ var canvas = document.createElement('canvas');
+ canvas.width = data.width;
+ canvas.height = data.height;
+ var ctx = canvas.getContext('2d');
+ if (format === 'jpeg') {
+ ctx.fillStyle = currentBg();
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }
+ // Draw at natural size — SVG was already rasterized at target res.
+ ctx.drawImage(img, 0, 0);
+ URL.revokeObjectURL(svgUrl);
+ var mime = format === 'jpeg' ? 'image/jpeg' :
+ format === 'webp' ? 'image/webp' : 'image/png';
+ var quality = format === 'png' ? undefined : 0.95;
+ canvas.toBlob(function (blob) {
+ if (!blob) reject(new Error('toBlob returned null for ' + format));
+ else resolve(blob);
+ }, mime, quality);
+ };
+ img.onerror = function (e) {
+ URL.revokeObjectURL(svgUrl);
+ reject(e);
+ };
+ img.src = svgUrl;
+ });
+ }
+
+ var menu = document.getElementById('export-menu');
+ var btn = document.getElementById('btn-export');
+ var items = function () {
+ return Array.prototype.slice.call(menu.querySelectorAll('button[role="menuitem"]'));
+ };
+
+ // ---- Clipboard support ----------------------------------------------
+ function canCopyImage() {
+ return typeof ClipboardItem !== 'undefined' &&
+ navigator.clipboard &&
+ typeof navigator.clipboard.write === 'function';
+ }
+
+ // ---- Raster format detection ----------------------------------------
+ // canvas.toBlob('image/webp') silently returns a PNG on browsers without
+ // WebP encoding (older Safari), so detect explicitly.
+ function supports(format) {
+ if (format === 'svg' || format === 'png') return true;
+ var mime = format === 'jpeg' ? 'image/jpeg' : 'image/webp';
+ try {
+ var c = document.createElement('canvas');
+ c.width = c.height = 2;
+ return c.toDataURL(mime).indexOf('data:' + mime) === 0;
+ } catch (_) { return false; }
+ }
+
+ // Gray out unsupported items.
+ items().forEach(function (it) {
+ if (it.dataset.format && !supports(it.dataset.format)) {
+ it.disabled = true;
+ it.title = 'Not supported by this browser';
+ it.style.opacity = '0.5';
+ }
+ if (it.dataset.action === 'copy' && !canCopyImage()) {
+ it.disabled = true;
+ it.title = 'Clipboard image write not supported by this browser';
+ it.style.opacity = '0.5';
+ }
+ });
+
+ // ---- Toast ----------------------------------------------------------
+ function toast(msg) {
+ var t = document.createElement('div');
+ t.className = 'archify-toast';
+ t.textContent = msg;
+ document.body.appendChild(t);
+ requestAnimationFrame(function () { t.classList.add('show'); });
+ setTimeout(function () {
+ t.classList.remove('show');
+ setTimeout(function () { t.remove(); }, 300);
+ }, 1500);
+ }
+
+ function open() {
+ menu.classList.add('open');
+ btn.setAttribute('aria-expanded', 'true');
+ var first = items().filter(function (i) { return !i.disabled; })[0];
+ if (first) first.focus();
+ }
+ function close(focusTrigger) {
+ menu.classList.remove('open');
+ btn.setAttribute('aria-expanded', 'false');
+ if (focusTrigger) btn.focus();
+ }
+ function isOpen() { return menu.classList.contains('open'); }
+
+ btn.addEventListener('click', function (e) {
+ e.stopPropagation();
+ if (isOpen()) close(false);
+ else open();
+ });
+ document.addEventListener('click', function (e) {
+ if (!menu.contains(e.target) && e.target !== btn) close(false);
+ });
+
+ // Keyboard navigation inside the menu.
+ // Menu items: Up/Down, Home/End.
+ // Esc closes + returns focus to trigger; Tab closes.
+ menu.addEventListener('keydown', function (e) {
+ if (e.key === 'Escape') { e.preventDefault(); close(true); return; }
+ if (e.key === 'Tab') { close(false); return; }
+
+ var available = items().filter(function (i) { return !i.disabled; });
+ var current = available.indexOf(document.activeElement);
+ switch (e.key) {
+ case 'ArrowDown':
+ e.preventDefault();
+ if (available.length) available[(current + 1 + available.length) % available.length].focus();
+ break;
+ case 'ArrowUp':
+ e.preventDefault();
+ if (available.length) available[(current - 1 + available.length) % available.length].focus();
+ break;
+ case 'Home':
+ e.preventDefault();
+ if (available[0]) available[0].focus();
+ break;
+ case 'End':
+ e.preventDefault();
+ if (available.length) available[available.length - 1].focus();
+ break;
+ }
+ });
+
+ function runExport(format) {
+ var base = diagramFilename();
+ close(false);
+ return (format === 'svg'
+ ? Promise.resolve(serializeSvg(1, { autoTheme: true })).then(function (d) {
+ download(new Blob([d.svgString], { type: 'image/svg+xml;charset=utf-8' }), base + '.svg');
+ })
+ : rasterize(format).then(function (blob) {
+ download(blob, base + '.' + format);
+ })
+ ).catch(function (err) {
+ console.error(err);
+ alert('Export failed: ' + (err && err.message ? err.message : format));
+ });
+ }
+
+ function runCopy() {
+ close(false);
+ if (!canCopyImage()) {
+ alert('Clipboard image write not supported in this browser.');
+ return;
+ }
+ return rasterize('png').then(function (blob) {
+ return navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ }).then(function () {
+ toast('Copied PNG to clipboard');
+ }).catch(function (err) {
+ console.error(err);
+ alert('Copy failed: ' + (err && err.message ? err.message : 'unknown'));
+ });
+ }
+
+ menu.addEventListener('click', function (e) {
+ var copyBtn = e.target.closest('button[data-action="copy"]');
+ if (copyBtn && !copyBtn.disabled) { runCopy(); return; }
+
+ var formatBtn = e.target.closest('button[data-format]');
+ if (formatBtn && !formatBtn.disabled) { runExport(formatBtn.dataset.format); }
+ });
+
+ Archify.exportMenu = { open: open, close: close, isOpen: isOpen, run: runExport };
+
+ // Auto-open on page load for demo/screenshot purposes: ?openExport=1
+ // Wait for fonts (so the menu doesn't flash before typography lands)
+ // and paint before opening. Fallback timeout for browsers without the
+ // Font Loading API.
+ try {
+ if (new URLSearchParams(window.location.search).get('openExport') === '1') {
+ var openWhenReady = function () {
+ requestAnimationFrame(function () { requestAnimationFrame(open); });
+ };
+ if (document.fonts && document.fonts.ready) {
+ document.fonts.ready.then(openWhenReady);
+ } else {
+ setTimeout(openWhenReady, 200);
+ }
+ }
+ } catch (_) {}
+ })();
+
+ /* ============================================================
+ Global keyboard shortcuts
+ T -> toggle theme
+ E -> open export menu
+ Ignored when focus is inside an input/textarea/contenteditable.
+ ============================================================ */
+ document.addEventListener('keydown', function (e) {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ var t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (e.key === 't' || e.key === 'T') {
+ e.preventDefault();
+ Archify.theme.toggle();
+ } else if (e.key === 'e' || e.key === 'E') {
+ e.preventDefault();
+ if (!Archify.exportMenu.isOpen()) Archify.exportMenu.open();
+ }
+ });
+ </script>
+</body>
+</html>