[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HX8MH6JCXR37BKQ3RRKDQP":3,"skill-same:01M6HX8MH6JCXR37BKQ3RRKDQP":82},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":54,"commitSha":55,"skillDirectory":56,"forksCount":57,"repositoryHtmlUrl":58,"repositoryHomepageUrl":6,"ownerHtmlUrl":59,"ownerBlogUrl":60,"ownerDescription":6,"updatedAt":61,"install":62,"resources":75},"01M6HX8MH6JCXR37BKQ3RRKDQP","full-stack-panel-authoring",null,"Single cohesive workflow for creating complete dashboard panel features in vanilla TypeScript — covers project-structure exploration, server dispatch pattern detection and wiring (Express or manual http.createServer), Panel base class component authoring with CircuitBreaker resilience and localStorage persistence, panel registration in index.ts, and safe file writing (including emoji workarounds).","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Ffull-stack-panel-authoring\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000036","内容创作者","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"full stack","full stack panel authoring","panel","authoring","full","stack","resilience","server","component","exploration","writing","structure","pattern","project","dashboard","express","workflow","typescript","features","safe","2026-11-10 10:12:30",false,"---\nname: full-stack-panel-authoring\ndescription: Single cohesive workflow for creating complete dashboard panel features in vanilla TypeScript — covers project-structure exploration, server dispatch pattern detection and wiring (Express or manual http.createServer), Panel base class component authoring with CircuitBreaker resilience and localStorage persistence, panel registration in index.ts, and safe file writing (including emoji workarounds).\n---\n\n# Unified Full-Stack Panel Authoring\n\nOne guide for the complete workflow: backend route → service → server wiring → Panel component with resilience → registration. Eliminates the need to consult separate skills for what is always a single cohesive task.\n\n---\n\n## When to Use\n\n- Adding a new panel type to a vanilla-TypeScript dashboard\n- Creating a feature that spans all layers: server route, service, component, registration\n- Ensuring pattern-consistency across the stack\n- Projects using a manual `http.createServer` dispatch loop **or** Express\n\n---\n\n## Quick Reference — File Checklist\n\n| # | File | Action |\n|---|------|--------|\n| 1 | `server\u002Froutes\u002F{feature}-route.ts` | Create |\n| 2 | `src\u002Fservices\u002F{feature}.ts` | Create |\n| 3 | `src\u002Fcomponents\u002F{Feature}Panel.ts` | Create |\n| 4 | `src\u002Fcomponents\u002Findex.ts` | Update — add export |\n| 5 | `server\u002Findex.ts` | Update — import + dispatch case |\n| 6 | `src\u002Futils\u002Fcircuit-breaker.ts` | Create if absent |\n| 7 | `src\u002Futils\u002Fsparkline.ts` | Create if absent |\n\n---\n\n## Step 1 — Explore Project Structure\n\nRun these commands before writing a single line of code. Reading existing patterns prevents style drift and reveals the exact dispatch mechanism.\n\n```bash\n# Locate server entry point (critical for wiring)\nfind . -name \"index.ts\" -o -name \"index.js\" -o -name \"server.ts\" -o -name \"server.js\" \\\n  | grep -v node_modules | head -10\n\n# Find existing route handlers to use as pattern files\nfind server\u002Froutes -name \"*.ts\" -o -name \"*.js\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find existing service files\nfind src\u002Fservices -name \"*.ts\" -o -name \"*.js\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find existing Panel components\nfind src\u002Fcomponents -name \"*Panel.ts\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find the Panel base class\nfind src -name \"Panel.ts\" 2>\u002Fdev\u002Fnull | head -5\n\n# Find component registration index\nfind src\u002Fcomponents -name \"index.ts\" 2>\u002Fdev\u002Fnull | head -3\n\n# Check for CircuitBreaker utility\nfind src\u002Futils -name \"circuit-breaker.ts\" 2>\u002Fdev\u002Fnull\n\n# Check framework (should NOT find React in vanilla TS projects)\ngrep -s '\"react\"' package.json | head -3\n```\n\n**Read 1-2 examples from each layer before generating any code:**\n\n```bash\ncat server\u002Froutes\u002F\u003Cexisting>-route.ts\ncat src\u002Fservices\u002F\u003Cexisting>.ts\ncat src\u002Fcomponents\u002F\u003Cexisting>Panel.ts\ncat src\u002Fcomponents\u002Findex.ts\ncat server\u002Findex.ts          # most important: reveals dispatch pattern\n```\n\n---\n\n## Step 2 — Detect Server Dispatch Pattern\n\nRead `server\u002Findex.ts` (or `server\u002Findex.js`, `src\u002Fserver.ts`) and classify:\n\n```bash\n# Express signals\ngrep -n \"express\\|app\\.use\\|router\\.\" server\u002Findex.ts 2>\u002Fdev\u002Fnull\n\n# Manual http.createServer signals\ngrep -n \"createServer\\|switch.*url\\|switch.*pathname\\|req\\.url\\|case '\u002F\" server\u002Findex.ts 2>\u002Fdev\u002Fnull\n```\n\n| Pattern in file | Wiring method (Step 5) |\n|----------------|------------------------|\n| `app.use('\u002Fapi\u002Fx', xRouter)` | **5A - Express** |\n| `switch(pathname) { case '\u002Fapi\u002Fx':` | **5B - Manual switch\u002Fcase** |\n| `if (url.startsWith('\u002Fapi\u002Fx'))` | **5C - Manual if\u002Felse chain** |\n| `const handlers = { '\u002Fapi\u002Fx': fn }` | **5D - Handler map** |\n\nNOTE: Misidentifying the dispatch pattern is the most common cause of silent 404s.\nIf unsure, read the full server entry point before proceeding.\n\n---\n\n## Step 3 — Create the Server Route Handler\n\nUse the **manual dispatch** template for `http.createServer` projects (most common in this codebase). Use the Express template only when Express is confirmed.\n\n### Manual dispatch (TypeScript) — preferred template\n\n```typescript\n\u002F\u002F server\u002Froutes\u002F{feature}-route.ts\nimport { IncomingMessage, ServerResponse } from 'http';\nimport { fetch{Feature}Data } from '..\u002F..\u002Fsrc\u002Fservices\u002F{feature}';\n\nexport async function handle{Feature}Request(\n  req: IncomingMessage,\n  res: ServerResponse,\n  action?: string\n): Promise\u003Cvoid> {\n  try {\n    const data = await fetch{Feature}Data(action);\n    res.writeHead(200, { 'Content-Type': 'application\u002Fjson' });\n    res.end(JSON.stringify({ success: true, data }));\n  } catch (err) {\n    res.writeHead(500, { 'Content-Type': 'application\u002Fjson' });\n    res.end(JSON.stringify({\n      success: false,\n      error: err instanceof Error ? err.message : String(err)\n    }));\n  }\n}\n```\n\n### Express template (only when confirmed)\n\n```typescript\n\u002F\u002F server\u002Froutes\u002F{feature}-route.ts\nimport { Router } from 'express';\nimport { fetch{Feature}Data } from '..\u002F..\u002Fsrc\u002Fservices\u002F{feature}';\n\nconst router = Router();\n\nrouter.get('\u002F', async (req, res) => {\n  try {\n    const data = await fetch{Feature}Data(req.query.action as string | undefined);\n    res.json({ success: true, data });\n  } catch (err) {\n    res.status(500).json({ success: false, error: (err as Error).message });\n  }\n});\n\nexport default router;\n```\n\n---\n\n## Step 4 — Create the Service Layer\n\nThe service owns data fetching and transformation. The CircuitBreaker (Step 6) wraps the service call at the **component** level — keep the service itself simple.\n\n```typescript\n\u002F\u002F src\u002Fservices\u002F{feature}.ts\n\nexport interface {Feature}Item {\n  id: string;\n  \u002F\u002F define your data shape matching the API response\n}\n\n\u002F**\n * Fetch {feature} data from the server API.\n * @param action  Optional sub-action \u002F filter parameter.\n *\u002F\nexport async function fetch{Feature}Data(action?: string): Promise\u003C{Feature}Item[]> {\n  const url = `\u002Fapi\u002Fpanels\u002F{feature}${action ? `?action=${encodeURIComponent(action)}` : ''}`;\n  const res = await fetch(url, {\n    headers: { Authorization: `Bearer ${localStorage.getItem('token') ?? ''}` }\n  });\n  if (!res.ok) throw new Error(`HTTP ${res.status}`);\n  const { data } = await res.json() as { data: {Feature}Item[] };\n  return data;\n}\n```\n\n---\n\n## Step 5 — Wire the Route Handler into the Server\n\n**This step is the most frequently missed and causes features to silently return 404.**\n\nAfter creating the route file, open `server\u002Findex.ts` and add **both** an import and a dispatch entry.\n\n### 5A - Express\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport {feature}Router from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F Add alongside other app.use() calls:\napp.use('\u002Fapi\u002Fpanels\u002F{feature}', {feature}Router);\n```\n\n### 5B - Manual switch\u002Fcase (most common pattern)\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt showing the additions\n\n\u002F\u002F 1. Add import near the top with other route imports\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F 2. Inside the switch \u002F if-else dispatch block, add a new case\n\u002F\u002F Find the block that looks like:\n\u002F\u002F   switch (pathname) {\n\u002F\u002F     case '\u002Fapi\u002Fpanels\u002Fhealth': ...\n\u002F\u002F     case '\u002Fapi\u002Fpanels\u002Femail':  ...\n\u002F\u002F Add:\n    case '\u002Fapi\u002Fpanels\u002F{feature}':\n      await handle{Feature}Request(req, res, action);\n      break;\n```\n\n### 5C - Manual if\u002Felse chain\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F Add a new else-if branch:\n} else if (url.startsWith('\u002Fapi\u002Fpanels\u002F{feature}')) {\n  await handle{Feature}Request(req, res, action);\n}\n```\n\n### 5D - Handler map\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\nconst handlers: Record\u003Cstring, HandlerFn> = {\n  \u002F\u002F ... existing entries ...\n  '\u002Fapi\u002Fpanels\u002F{feature}': handle{Feature}Request,\n};\n```\n\n**Verification:** After wiring, start the server and `curl \u002Fapi\u002Fpanels\u002F{feature}` — you should receive JSON, not a 404.\n\n---\n\n## Step 6 — Create the Panel Component\n\n### Architecture overview\n\n```\nPanel (base class)\n+-- element: HTMLElement (.panel)\n    +-- header (.panel-header)\n    |   +-- headerLeft (.panel-header-left)\n    |   |   +-- title (.panel-title)\n    |   +-- countEl (.panel-count)  [optional]\n    +-- content (.panel-content)\n```\n\n### Resilience layers\n\n| Layer | When to use |\n|---|---|\n| `isFetching` guard | Always -- prevents duplicate concurrent requests |\n| `fetchWithRetry()` | When you own the raw fetch and want per-request retry |\n| `CircuitBreaker.execute()` | When a service may fail repeatedly; serves stale cache during cooldown |\n| `saveState()` \u002F `loadState()` | When collapsed\u002Fsize state should survive page reloads |\n\n### Complete Panel component template\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002F{Feature}Panel.ts\nimport { Panel } from '.\u002FPanel';\nimport { createCircuitBreaker } from '..\u002Futils\u002Fcircuit-breaker';\nimport { fetch{Feature}Data, {Feature}Item } from '..\u002Fservices\u002F{feature}';\n\n\u002F\u002F Module-level breaker -- persists cache and failure state between re-renders\nconst breaker = createCircuitBreaker\u003C{Feature}Item[]>({\n  name: '{Feature}',\n  cacheTtlMs: 60_000,      \u002F\u002F serve cache for 1 min\n  cooldownMs: 5 * 60_000,  \u002F\u002F open circuit for 5 min after maxFailures\n  maxFailures: 2,\n});\n\nexport class {Feature}Panel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: '{feature}', title: '{Feature Display Name}', showCount: true });\n    this.loadState();                                  \u002F\u002F restore collapsed\u002Fsize\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      \u002F\u002F One-liner: wraps existing service call with caching + circuit-break\n      const items = await breaker.execute(() => fetch{Feature}Data(), []);\n      this.setCount(items.length);\n      this.render(items);\n    } catch (err) {\n      this.showError(\n        err instanceof Error ? err.message : 'Failed to load',\n        () => {\n          this.retryAttempts = 0;\n          this.retryDelay = 1000;\n          this.fetchData();\n        }\n      );\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(items: {Feature}Item[]): void {\n    if (items.length === 0) {\n      this.setContent('\u003Cdiv class=\"panel-empty\">No items found.\u003C\u002Fdiv>');\n      return;\n    }\n\n    const container = document.createElement('div');\n    container.className = '{feature}-panel';\n\n    for (const item of items) {\n      const row = document.createElement('div');\n      row.className = '{feature}-panel__row';\n      \u002F\u002F Build DOM from item fields -- no JSX, no innerHTML with untrusted data:\n      const label = document.createElement('span');\n      label.className = '{feature}-panel__label';\n      label.textContent = item.id;          \u002F\u002F replace with real fields\n      row.appendChild(label);\n      container.appendChild(row);\n    }\n\n    this.content.innerHTML = '';\n    this.content.appendChild(container);\n    this.saveState();\n  }\n\n  destroy(): void {\n    if (this.refreshTimer !== null) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n**Key rules for vanilla TS panels (no React):**\n- Extend `Panel` base class; use `setContent()` \u002F `showError()` \u002F `setCount()` \u002F `showLoading()` instead of React state.\n- Build DOM via `document.createElement` -- not JSX, not `innerHTML` with untrusted strings.\n- Lifecycle: `constructor` -> `fetchData()` -> `render()` -> `destroy()`. No `useEffect`.\n- File extension is `.ts`, not `.jsx`\u002F`.tsx`.\n\n---\n\n## Step 7 — Register the Component in index.ts\n\nExport the new panel from the components barrel file so the dashboard can discover it.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002Findex.ts  -- add alongside existing exports\nexport { {Feature}Panel } from '.\u002F{Feature}Panel';\n```\n\nThen instantiate and mount in the dashboard bootstrap (follow the existing pattern):\n\n```typescript\n\u002F\u002F src\u002Findex.ts or src\u002Fdashboard.ts  -- excerpt\nimport { {Feature}Panel } from '.\u002Fcomponents';\n\nconst {feature}Panel = new {Feature}Panel();\ndocument.getElementById('{feature}-slot')?.appendChild({feature}Panel.getElement());\n```\n\n---\n\n## Step 8 — Add Utility Files (if absent)\n\nOnly create these if `find src\u002Futils -name \"circuit-breaker.ts\"` returns nothing.\n\n### `src\u002Futils\u002Fcircuit-breaker.ts`\n\n```typescript\ninterface CircuitState { failures: number; cooldownUntil: number; }\ninterface CacheEntry\u003CT> { data: T; timestamp: number; }\n\nexport interface CircuitBreakerOptions {\n  name: string;\n  maxFailures?: number;  \u002F\u002F default 2\n  cooldownMs?: number;   \u002F\u002F default 5 min\n  cacheTtlMs?: number;   \u002F\u002F default 10 min\n}\n\nexport class CircuitBreaker\u003CT> {\n  private state: CircuitState = { failures: 0, cooldownUntil: 0 };\n  private cache: CacheEntry\u003CT> | null = null;\n  private readonly name: string;\n  private readonly maxFailures: number;\n  private readonly cooldownMs: number;\n  private readonly cacheTtlMs: number;\n\n  constructor(options: CircuitBreakerOptions) {\n    this.name        = options.name;\n    this.maxFailures = options.maxFailures ?? 2;\n    this.cooldownMs  = options.cooldownMs  ?? 5 * 60 * 1000;\n    this.cacheTtlMs  = options.cacheTtlMs  ?? 10 * 60 * 1000;\n  }\n\n  isOnCooldown(): boolean {\n    if (Date.now() \u003C this.state.cooldownUntil) return true;\n    if (this.state.cooldownUntil > 0) this.state = { failures: 0, cooldownUntil: 0 };\n    return false;\n  }\n\n  getCached(): T | null {\n    if (this.cache && Date.now() - this.cache.timestamp \u003C this.cacheTtlMs) return this.cache.data;\n    return null;\n  }\n\n  recordSuccess(data: T): void {\n    this.state = { failures: 0, cooldownUntil: 0 };\n    this.cache = { data, timestamp: Date.now() };\n  }\n\n  recordFailure(): void {\n    this.state.failures++;\n    if (this.state.failures >= this.maxFailures) {\n      this.state.cooldownUntil = Date.now() + this.cooldownMs;\n      console.warn(`[${this.name}] Circuit open -- cooldown ${this.cooldownMs \u002F 1000}s`);\n    }\n  }\n\n  async execute\u003CR extends T>(fn: () => Promise\u003CR>, defaultValue: R): Promise\u003CR> {\n    if (this.isOnCooldown()) return (this.getCached() as R) ?? defaultValue;\n    const cached = this.getCached();\n    if (cached !== null) return cached as R;\n    try {\n      const result = await fn();\n      this.recordSuccess(result);\n      return result;\n    } catch (e) {\n      console.error(`[${this.name}] Request failed:`, e);\n      this.recordFailure();\n      return defaultValue;\n    }\n  }\n}\n\nexport function createCircuitBreaker\u003CT>(options: CircuitBreakerOptions): CircuitBreaker\u003CT> {\n  return new CircuitBreaker\u003CT>(options);\n}\n```\n\n### `src\u002Futils\u002Fsparkline.ts` (optional — for numeric trend data)\n\n```typescript\n\u002F**\n * Returns an inline SVG sparkline string, or '' if data is too short.\n * Embed directly in HTML template strings.\n *\u002F\nexport function miniSparkline(\n  data: number[] | undefined,\n  change: number | null,\n  w = 50,\n  h = 16\n): string {\n  if (!data || data.length \u003C 2) return '';\n  const min   = Math.min(...data);\n  const max   = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">` +\n    `\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" ` +\n    `stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Step 9 — Panel Base Class (if absent)\n\nOnly create `src\u002Fcomponents\u002FPanel.ts` if no existing base class is found.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FPanel.ts\nexport interface PanelOptions {\n  id: string;\n  title: string;\n  showCount?: boolean;\n  className?: string;\n}\n\nexport class Panel {\n  protected element: HTMLElement;\n  protected content: HTMLElement;\n  protected header: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected panelId: string;\n  private _fetching = false;\n\n  \u002F\u002F Retry state (used by fetchWithRetry)\n  protected retryAttempts = 0;\n  protected retryDelay = 1000;\n  private maxRetries = 3;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n    this.element = document.createElement('div');\n    this.element.className = `panel ${options.className ?? ''}`;\n    this.element.dataset.panel = options.id;\n\n    this.header = document.createElement('div');\n    this.header.className = 'panel-header';\n\n    const headerLeft = document.createElement('div');\n    headerLeft.className = 'panel-header-left';\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-spinner\">\u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  public showError(message = 'Failed to load', onRetry?: () => void): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void { this.content.innerHTML = html; }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n  public destroy(): void { this.element.remove(); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const response = await fetch(url);\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        return await response.json();\n      } catch (error) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${(error as Error).message}`);\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  public saveState(): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify({\n      isExpanded: !this.element.classList.contains('collapsed'),\n      width: this.element.style.width,\n      height: this.element.style.height,\n    }));\n  }\n\n  public loadState(): void {\n    const raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return;\n    const { isExpanded, width, height } = JSON.parse(raw) as {\n      isExpanded: boolean; width: string; height: string;\n    };\n    if (!isExpanded) this.element.classList.add('collapsed');\n    if (width)  this.element.style.width  = width;\n    if (height) this.element.style.height = height;\n  }\n}\n```\n\n---\n\n## Step 10 — Safe File Writing\n\n**Known tool issue:** `write_file` (and some shell tools) fail silently or with \"unknown error\" when file content contains multi-byte Unicode characters such as emoji (e.g., document, chart, checkmark emoji).\n\n### Rules for safe content\n\n1. **Never use emoji in generated source code.** Replace with plain-text equivalents:\n   - Document emoji -> `[doc]` or `(file)`\n   - Chart emoji -> `[chart]`\n   - Checkmark emoji -> `[ok]` or `(done)`\n   - Warning emoji -> `[warn]` or `WARNING:`\n\n2. **Use ASCII substitutes in comments** instead of Unicode box-drawing characters.\n\n3. **Test-write suspect content** to a throwaway file first if unsure:\n   ```bash\n   echo \"test content\" > \u002Ftmp\u002Fwrite_test.txt && cat \u002Ftmp\u002Fwrite_test.txt\n   ```\n\n4. **Recovery pattern** -- if a write_file call fails:\n   - Strip all non-ASCII characters from the content.\n   - Retry the write.\n   - If still failing, split the file into smaller chunks and concatenate with `cat`.\n\n---\n\n## Validation Checklist\n\nBefore considering the feature complete, verify each layer:\n\n```\nServer route\n  [ ] File created at server\u002Froutes\u002F{feature}-route.ts\n  [ ] Exports handle{Feature}Request function\n  [ ] Returns { success: true, data } on success\n  [ ] Returns { success: false, error } on failure with correct HTTP status\n\nService\n  [ ] File created at src\u002Fservices\u002F{feature}.ts\n  [ ] Exports fetch{Feature}Data function\n  [ ] Throws on non-ok HTTP status (so CircuitBreaker can record failures)\n\nServer wiring\n  [ ] Import added to server\u002Findex.ts\n  [ ] Dispatch case\u002Froute added (matching the detected pattern)\n  [ ] curl \u002Fapi\u002Fpanels\u002F{feature} returns JSON (not 404)\n\nPanel component\n  [ ] Extends Panel base class\n  [ ] Uses isFetching guard\n  [ ] CircuitBreaker wraps the service call\n  [ ] showError() called with retry callback on failure\n  [ ] destroy() clears interval and calls super.destroy()\n\nRegistration\n  [ ] Export added to src\u002Fcomponents\u002Findex.ts\n  [ ] Panel instantiated and mounted in dashboard bootstrap\n\nFile safety\n  [ ] No emoji in any generated source file\n  [ ] All write_file calls succeeded (check file size > 0)\n```\n\n---\n\n## Common Mistakes\n\n| Mistake | Symptom | Fix |\n|---------|---------|-----|\n| Skipping Step 5 (server wiring) | Feature returns 404 | Add import + dispatch entry to server\u002Findex.ts |\n| Wrong dispatch pattern | 404 or runtime error | Re-read server\u002Findex.ts; use grep from Step 2 |\n| Emoji in source files | write_file silent failure | Replace all emoji with ASCII equivalents |\n| React template in vanilla TS project | Compile errors | Confirm no React in package.json; use Panel base class template |\n| Creating Panel.ts when one exists | Overwrites base class | Check with `find src -name \"Panel.ts\"` first |\n| Not calling `super.destroy()` | Memory leak | Always chain super.destroy() in subclass destroy() |\n| CircuitBreaker declared inside class | Cache lost between fetches | Declare `const breaker = ...` at module level outside the class |\n","# Unified Full-Stack Panel Authoring\n\nOne guide for the complete workflow: backend route → service → server wiring → Panel component with resilience → registration. Eliminates the need to consult separate skills for what is always a single cohesive task.\n\n---\n\n## When to Use\n\n- Adding a new panel type to a vanilla-TypeScript dashboard\n- Creating a feature that spans all layers: server route, service, component, registration\n- Ensuring pattern-consistency across the stack\n- Projects using a manual `http.createServer` dispatch loop **or** Express\n\n---\n\n## Quick Reference — File Checklist\n\n| # | File | Action |\n|---|------|--------|\n| 1 | `server\u002Froutes\u002F{feature}-route.ts` | Create |\n| 2 | `src\u002Fservices\u002F{feature}.ts` | Create |\n| 3 | `src\u002Fcomponents\u002F{Feature}Panel.ts` | Create |\n| 4 | `src\u002Fcomponents\u002Findex.ts` | Update — add export |\n| 5 | `server\u002Findex.ts` | Update — import + dispatch case |\n| 6 | `src\u002Futils\u002Fcircuit-breaker.ts` | Create if absent |\n| 7 | `src\u002Futils\u002Fsparkline.ts` | Create if absent |\n\n---\n\n## Step 1 — Explore Project Structure\n\nRun these commands before writing a single line of code. Reading existing patterns prevents style drift and reveals the exact dispatch mechanism.\n\n```bash\n# Locate server entry point (critical for wiring)\nfind . -name \"index.ts\" -o -name \"index.js\" -o -name \"server.ts\" -o -name \"server.js\" \\\n  | grep -v node_modules | head -10\n\n# Find existing route handlers to use as pattern files\nfind server\u002Froutes -name \"*.ts\" -o -name \"*.js\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find existing service files\nfind src\u002Fservices -name \"*.ts\" -o -name \"*.js\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find existing Panel components\nfind src\u002Fcomponents -name \"*Panel.ts\" 2>\u002Fdev\u002Fnull | head -10\n\n# Find the Panel base class\nfind src -name \"Panel.ts\" 2>\u002Fdev\u002Fnull | head -5\n\n# Find component registration index\nfind src\u002Fcomponents -name \"index.ts\" 2>\u002Fdev\u002Fnull | head -3\n\n# Check for CircuitBreaker utility\nfind src\u002Futils -name \"circuit-breaker.ts\" 2>\u002Fdev\u002Fnull\n\n# Check framework (should NOT find React in vanilla TS projects)\ngrep -s '\"react\"' package.json | head -3\n```\n\n**Read 1-2 examples from each layer before generating any code:**\n\n```bash\ncat server\u002Froutes\u002F\u003Cexisting>-route.ts\ncat src\u002Fservices\u002F\u003Cexisting>.ts\ncat src\u002Fcomponents\u002F\u003Cexisting>Panel.ts\ncat src\u002Fcomponents\u002Findex.ts\ncat server\u002Findex.ts          # most important: reveals dispatch pattern\n```\n\n---\n\n## Step 2 — Detect Server Dispatch Pattern\n\nRead `server\u002Findex.ts` (or `server\u002Findex.js`, `src\u002Fserver.ts`) and classify:\n\n```bash\n# Express signals\ngrep -n \"express\\|app\\.use\\|router\\.\" server\u002Findex.ts 2>\u002Fdev\u002Fnull\n\n# Manual http.createServer signals\ngrep -n \"createServer\\|switch.*url\\|switch.*pathname\\|req\\.url\\|case '\u002F\" server\u002Findex.ts 2>\u002Fdev\u002Fnull\n```\n\n| Pattern in file | Wiring method (Step 5) |\n|----------------|------------------------|\n| `app.use('\u002Fapi\u002Fx', xRouter)` | **5A - Express** |\n| `switch(pathname) { case '\u002Fapi\u002Fx':` | **5B - Manual switch\u002Fcase** |\n| `if (url.startsWith('\u002Fapi\u002Fx'))` | **5C - Manual if\u002Felse chain** |\n| `const handlers = { '\u002Fapi\u002Fx': fn }` | **5D - Handler map** |\n\nNOTE: Misidentifying the dispatch pattern is the most common cause of silent 404s.\nIf unsure, read the full server entry point before proceeding.\n\n---\n\n## Step 3 — Create the Server Route Handler\n\nUse the **manual dispatch** template for `http.createServer` projects (most common in this codebase). Use the Express template only when Express is confirmed.\n\n### Manual dispatch (TypeScript) — preferred template\n\n```typescript\n\u002F\u002F server\u002Froutes\u002F{feature}-route.ts\nimport { IncomingMessage, ServerResponse } from 'http';\nimport { fetch{Feature}Data } from '..\u002F..\u002Fsrc\u002Fservices\u002F{feature}';\n\nexport async function handle{Feature}Request(\n  req: IncomingMessage,\n  res: ServerResponse,\n  action?: string\n): Promise\u003Cvoid> {\n  try {\n    const data = await fetch{Feature}Data(action);\n    res.writeHead(200, { 'Content-Type': 'application\u002Fjson' });\n    res.end(JSON.stringify({ success: true, data }));\n  } catch (err) {\n    res.writeHead(500, { 'Content-Type': 'application\u002Fjson' });\n    res.end(JSON.stringify({\n      success: false,\n      error: err instanceof Error ? err.message : String(err)\n    }));\n  }\n}\n```\n\n### Express template (only when confirmed)\n\n```typescript\n\u002F\u002F server\u002Froutes\u002F{feature}-route.ts\nimport { Router } from 'express';\nimport { fetch{Feature}Data } from '..\u002F..\u002Fsrc\u002Fservices\u002F{feature}';\n\nconst router = Router();\n\nrouter.get('\u002F', async (req, res) => {\n  try {\n    const data = await fetch{Feature}Data(req.query.action as string | undefined);\n    res.json({ success: true, data });\n  } catch (err) {\n    res.status(500).json({ success: false, error: (err as Error).message });\n  }\n});\n\nexport default router;\n```\n\n---\n\n## Step 4 — Create the Service Layer\n\nThe service owns data fetching and transformation. The CircuitBreaker (Step 6) wraps the service call at the **component** level — keep the service itself simple.\n\n```typescript\n\u002F\u002F src\u002Fservices\u002F{feature}.ts\n\nexport interface {Feature}Item {\n  id: string;\n  \u002F\u002F define your data shape matching the API response\n}\n\n\u002F**\n * Fetch {feature} data from the server API.\n * @param action  Optional sub-action \u002F filter parameter.\n *\u002F\nexport async function fetch{Feature}Data(action?: string): Promise\u003C{Feature}Item[]> {\n  const url = `\u002Fapi\u002Fpanels\u002F{feature}${action ? `?action=${encodeURIComponent(action)}` : ''}`;\n  const res = await fetch(url, {\n    headers: { Authorization: `Bearer ${localStorage.getItem('token') ?? ''}` }\n  });\n  if (!res.ok) throw new Error(`HTTP ${res.status}`);\n  const { data } = await res.json() as { data: {Feature}Item[] };\n  return data;\n}\n```\n\n---\n\n## Step 5 — Wire the Route Handler into the Server\n\n**This step is the most frequently missed and causes features to silently return 404.**\n\nAfter creating the route file, open `server\u002Findex.ts` and add **both** an import and a dispatch entry.\n\n### 5A - Express\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport {feature}Router from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F Add alongside other app.use() calls:\napp.use('\u002Fapi\u002Fpanels\u002F{feature}', {feature}Router);\n```\n\n### 5B - Manual switch\u002Fcase (most common pattern)\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt showing the additions\n\n\u002F\u002F 1. Add import near the top with other route imports\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F 2. Inside the switch \u002F if-else dispatch block, add a new case\n\u002F\u002F Find the block that looks like:\n\u002F\u002F   switch (pathname) {\n\u002F\u002F     case '\u002Fapi\u002Fpanels\u002Fhealth': ...\n\u002F\u002F     case '\u002Fapi\u002Fpanels\u002Femail':  ...\n\u002F\u002F Add:\n    case '\u002Fapi\u002Fpanels\u002F{feature}':\n      await handle{Feature}Request(req, res, action);\n      break;\n```\n\n### 5C - Manual if\u002Felse chain\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\n\u002F\u002F Add a new else-if branch:\n} else if (url.startsWith('\u002Fapi\u002Fpanels\u002F{feature}')) {\n  await handle{Feature}Request(req, res, action);\n}\n```\n\n### 5D - Handler map\n\n```typescript\n\u002F\u002F server\u002Findex.ts  -- excerpt\nimport { handle{Feature}Request } from '.\u002Froutes\u002F{feature}-route';\n\nconst handlers: Record\u003Cstring, HandlerFn> = {\n  \u002F\u002F ... existing entries ...\n  '\u002Fapi\u002Fpanels\u002F{feature}': handle{Feature}Request,\n};\n```\n\n**Verification:** After wiring, start the server and `curl \u002Fapi\u002Fpanels\u002F{feature}` — you should receive JSON, not a 404.\n\n---\n\n## Step 6 — Create the Panel Component\n\n### Architecture overview\n\n```\nPanel (base class)\n+-- element: HTMLElement (.panel)\n    +-- header (.panel-header)\n    |   +-- headerLeft (.panel-header-left)\n    |   |   +-- title (.panel-title)\n    |   +-- countEl (.panel-count)  [optional]\n    +-- content (.panel-content)\n```\n\n### Resilience layers\n\n| Layer | When to use |\n|---|---|\n| `isFetching` guard | Always -- prevents duplicate concurrent requests |\n| `fetchWithRetry()` | When you own the raw fetch and want per-request retry |\n| `CircuitBreaker.execute()` | When a service may fail repeatedly; serves stale cache during cooldown |\n| `saveState()` \u002F `loadState()` | When collapsed\u002Fsize state should survive page reloads |\n\n### Complete Panel component template\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002F{Feature}Panel.ts\nimport { Panel } from '.\u002FPanel';\nimport { createCircuitBreaker } from '..\u002Futils\u002Fcircuit-breaker';\nimport { fetch{Feature}Data, {Feature}Item } from '..\u002Fservices\u002F{feature}';\n\n\u002F\u002F Module-level breaker -- persists cache and failure state between re-renders\nconst breaker = createCircuitBreaker\u003C{Feature}Item[]>({\n  name: '{Feature}',\n  cacheTtlMs: 60_000,      \u002F\u002F serve cache for 1 min\n  cooldownMs: 5 * 60_000,  \u002F\u002F open circuit for 5 min after maxFailures\n  maxFailures: 2,\n});\n\nexport class {Feature}Panel extends Panel {\n  private refreshTimer: ReturnType\u003Ctypeof setInterval> | null = null;\n\n  constructor() {\n    super({ id: '{feature}', title: '{Feature Display Name}', showCount: true });\n    this.loadState();                                  \u002F\u002F restore collapsed\u002Fsize\n    this.fetchData();\n    this.refreshTimer = setInterval(() => this.fetchData(), 60_000);\n  }\n\n  private async fetchData(): Promise\u003Cvoid> {\n    if (this.isFetching) return;\n    this.setFetching(true);\n    try {\n      \u002F\u002F One-liner: wraps existing service call with caching + circuit-break\n      const items = await breaker.execute(() => fetch{Feature}Data(), []);\n      this.setCount(items.length);\n      this.render(items);\n    } catch (err) {\n      this.showError(\n        err instanceof Error ? err.message : 'Failed to load',\n        () => {\n          this.retryAttempts = 0;\n          this.retryDelay = 1000;\n          this.fetchData();\n        }\n      );\n    } finally {\n      this.setFetching(false);\n    }\n  }\n\n  private render(items: {Feature}Item[]): void {\n    if (items.length === 0) {\n      this.setContent('\u003Cdiv class=\"panel-empty\">No items found.\u003C\u002Fdiv>');\n      return;\n    }\n\n    const container = document.createElement('div');\n    container.className = '{feature}-panel';\n\n    for (const item of items) {\n      const row = document.createElement('div');\n      row.className = '{feature}-panel__row';\n      \u002F\u002F Build DOM from item fields -- no JSX, no innerHTML with untrusted data:\n      const label = document.createElement('span');\n      label.className = '{feature}-panel__label';\n      label.textContent = item.id;          \u002F\u002F replace with real fields\n      row.appendChild(label);\n      container.appendChild(row);\n    }\n\n    this.content.innerHTML = '';\n    this.content.appendChild(container);\n    this.saveState();\n  }\n\n  destroy(): void {\n    if (this.refreshTimer !== null) clearInterval(this.refreshTimer);\n    super.destroy();\n  }\n}\n```\n\n**Key rules for vanilla TS panels (no React):**\n- Extend `Panel` base class; use `setContent()` \u002F `showError()` \u002F `setCount()` \u002F `showLoading()` instead of React state.\n- Build DOM via `document.createElement` -- not JSX, not `innerHTML` with untrusted strings.\n- Lifecycle: `constructor` -> `fetchData()` -> `render()` -> `destroy()`. No `useEffect`.\n- File extension is `.ts`, not `.jsx`\u002F`.tsx`.\n\n---\n\n## Step 7 — Register the Component in index.ts\n\nExport the new panel from the components barrel file so the dashboard can discover it.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002Findex.ts  -- add alongside existing exports\nexport { {Feature}Panel } from '.\u002F{Feature}Panel';\n```\n\nThen instantiate and mount in the dashboard bootstrap (follow the existing pattern):\n\n```typescript\n\u002F\u002F src\u002Findex.ts or src\u002Fdashboard.ts  -- excerpt\nimport { {Feature}Panel } from '.\u002Fcomponents';\n\nconst {feature}Panel = new {Feature}Panel();\ndocument.getElementById('{feature}-slot')?.appendChild({feature}Panel.getElement());\n```\n\n---\n\n## Step 8 — Add Utility Files (if absent)\n\nOnly create these if `find src\u002Futils -name \"circuit-breaker.ts\"` returns nothing.\n\n### `src\u002Futils\u002Fcircuit-breaker.ts`\n\n```typescript\ninterface CircuitState { failures: number; cooldownUntil: number; }\ninterface CacheEntry\u003CT> { data: T; timestamp: number; }\n\nexport interface CircuitBreakerOptions {\n  name: string;\n  maxFailures?: number;  \u002F\u002F default 2\n  cooldownMs?: number;   \u002F\u002F default 5 min\n  cacheTtlMs?: number;   \u002F\u002F default 10 min\n}\n\nexport class CircuitBreaker\u003CT> {\n  private state: CircuitState = { failures: 0, cooldownUntil: 0 };\n  private cache: CacheEntry\u003CT> | null = null;\n  private readonly name: string;\n  private readonly maxFailures: number;\n  private readonly cooldownMs: number;\n  private readonly cacheTtlMs: number;\n\n  constructor(options: CircuitBreakerOptions) {\n    this.name        = options.name;\n    this.maxFailures = options.maxFailures ?? 2;\n    this.cooldownMs  = options.cooldownMs  ?? 5 * 60 * 1000;\n    this.cacheTtlMs  = options.cacheTtlMs  ?? 10 * 60 * 1000;\n  }\n\n  isOnCooldown(): boolean {\n    if (Date.now() \u003C this.state.cooldownUntil) return true;\n    if (this.state.cooldownUntil > 0) this.state = { failures: 0, cooldownUntil: 0 };\n    return false;\n  }\n\n  getCached(): T | null {\n    if (this.cache && Date.now() - this.cache.timestamp \u003C this.cacheTtlMs) return this.cache.data;\n    return null;\n  }\n\n  recordSuccess(data: T): void {\n    this.state = { failures: 0, cooldownUntil: 0 };\n    this.cache = { data, timestamp: Date.now() };\n  }\n\n  recordFailure(): void {\n    this.state.failures++;\n    if (this.state.failures >= this.maxFailures) {\n      this.state.cooldownUntil = Date.now() + this.cooldownMs;\n      console.warn(`[${this.name}] Circuit open -- cooldown ${this.cooldownMs \u002F 1000}s`);\n    }\n  }\n\n  async execute\u003CR extends T>(fn: () => Promise\u003CR>, defaultValue: R): Promise\u003CR> {\n    if (this.isOnCooldown()) return (this.getCached() as R) ?? defaultValue;\n    const cached = this.getCached();\n    if (cached !== null) return cached as R;\n    try {\n      const result = await fn();\n      this.recordSuccess(result);\n      return result;\n    } catch (e) {\n      console.error(`[${this.name}] Request failed:`, e);\n      this.recordFailure();\n      return defaultValue;\n    }\n  }\n}\n\nexport function createCircuitBreaker\u003CT>(options: CircuitBreakerOptions): CircuitBreaker\u003CT> {\n  return new CircuitBreaker\u003CT>(options);\n}\n```\n\n### `src\u002Futils\u002Fsparkline.ts` (optional — for numeric trend data)\n\n```typescript\n\u002F**\n * Returns an inline SVG sparkline string, or '' if data is too short.\n * Embed directly in HTML template strings.\n *\u002F\nexport function miniSparkline(\n  data: number[] | undefined,\n  change: number | null,\n  w = 50,\n  h = 16\n): string {\n  if (!data || data.length \u003C 2) return '';\n  const min   = Math.min(...data);\n  const max   = Math.max(...data);\n  const range = max - min || 1;\n  const color = change != null && change >= 0 ? 'var(--green)' : 'var(--red)';\n  const points = data.map((v, i) => {\n    const x = (i \u002F (data.length - 1)) * w;\n    const y = h - ((v - min) \u002F range) * (h - 2) - 1;\n    return `${x.toFixed(1)},${y.toFixed(1)}`;\n  }).join(' ');\n  return `\u003Csvg width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">` +\n    `\u003Cpolyline points=\"${points}\" fill=\"none\" stroke=\"${color}\" ` +\n    `stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"\u002F>\u003C\u002Fsvg>`;\n}\n```\n\n---\n\n## Step 9 — Panel Base Class (if absent)\n\nOnly create `src\u002Fcomponents\u002FPanel.ts` if no existing base class is found.\n\n```typescript\n\u002F\u002F src\u002Fcomponents\u002FPanel.ts\nexport interface PanelOptions {\n  id: string;\n  title: string;\n  showCount?: boolean;\n  className?: string;\n}\n\nexport class Panel {\n  protected element: HTMLElement;\n  protected content: HTMLElement;\n  protected header: HTMLElement;\n  protected countEl: HTMLElement | null = null;\n  protected panelId: string;\n  private _fetching = false;\n\n  \u002F\u002F Retry state (used by fetchWithRetry)\n  protected retryAttempts = 0;\n  protected retryDelay = 1000;\n  private maxRetries = 3;\n\n  constructor(options: PanelOptions) {\n    this.panelId = options.id;\n    this.element = document.createElement('div');\n    this.element.className = `panel ${options.className ?? ''}`;\n    this.element.dataset.panel = options.id;\n\n    this.header = document.createElement('div');\n    this.header.className = 'panel-header';\n\n    const headerLeft = document.createElement('div');\n    headerLeft.className = 'panel-header-left';\n    const title = document.createElement('span');\n    title.className = 'panel-title';\n    title.textContent = options.title;\n    headerLeft.appendChild(title);\n    this.header.appendChild(headerLeft);\n\n    if (options.showCount) {\n      this.countEl = document.createElement('span');\n      this.countEl.className = 'panel-count';\n      this.countEl.textContent = '0';\n      this.header.appendChild(this.countEl);\n    }\n\n    this.content = document.createElement('div');\n    this.content.className = 'panel-content';\n    this.content.id = `${options.id}Content`;\n\n    this.element.appendChild(this.header);\n    this.element.appendChild(this.content);\n    this.showLoading();\n  }\n\n  public getElement(): HTMLElement { return this.element; }\n\n  public showLoading(message = 'Loading...'): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-loading\">\n        \u003Cdiv class=\"panel-loading-spinner\">\u003C\u002Fdiv>\n        \u003Cdiv class=\"panel-loading-text\">${message}\u003C\u002Fdiv>\n      \u003C\u002Fdiv>`;\n  }\n\n  public showError(message = 'Failed to load', onRetry?: () => void): void {\n    this.content.innerHTML = `\n      \u003Cdiv class=\"panel-error-state\">\n        \u003Cdiv class=\"panel-error-msg\">${message}\u003C\u002Fdiv>\n        ${onRetry ? '\u003Cbutton class=\"panel-retry-btn\" data-panel-retry>Retry\u003C\u002Fbutton>' : ''}\n      \u003C\u002Fdiv>`;\n    if (onRetry) {\n      this.content.querySelector('[data-panel-retry]')?.addEventListener('click', onRetry);\n    }\n  }\n\n  public setContent(html: string): void { this.content.innerHTML = html; }\n\n  public setCount(count: number): void {\n    if (this.countEl) this.countEl.textContent = count.toString();\n  }\n\n  public show(): void { this.element.classList.remove('hidden'); }\n  public hide(): void { this.element.classList.add('hidden'); }\n  public destroy(): void { this.element.remove(); }\n\n  protected setFetching(v: boolean): void { this._fetching = v; }\n  protected get isFetching(): boolean { return this._fetching; }\n\n  protected async fetchWithRetry(url: string): Promise\u003Cunknown> {\n    while (this.retryAttempts \u003C this.maxRetries) {\n      try {\n        const response = await fetch(url);\n        if (!response.ok) throw new Error(`HTTP ${response.status}`);\n        return await response.json();\n      } catch (error) {\n        this.retryAttempts++;\n        if (this.retryAttempts >= this.maxRetries) {\n          throw new Error(`Failed after ${this.maxRetries} attempts: ${(error as Error).message}`);\n        }\n        await new Promise(resolve => setTimeout(resolve, this.retryDelay));\n        this.retryDelay *= 2;\n      }\n    }\n  }\n\n  public saveState(): void {\n    localStorage.setItem(`panelState_${this.panelId}`, JSON.stringify({\n      isExpanded: !this.element.classList.contains('collapsed'),\n      width: this.element.style.width,\n      height: this.element.style.height,\n    }));\n  }\n\n  public loadState(): void {\n    const raw = localStorage.getItem(`panelState_${this.panelId}`);\n    if (!raw) return;\n    const { isExpanded, width, height } = JSON.parse(raw) as {\n      isExpanded: boolean; width: string; height: string;\n    };\n    if (!isExpanded) this.element.classList.add('collapsed');\n    if (width)  this.element.style.width  = width;\n    if (height) this.element.style.height = height;\n  }\n}\n```\n\n---\n\n## Step 10 — Safe File Writing\n\n**Known tool issue:** `write_file` (and some shell tools) fail silently or with \"unknown error\" when file content contains multi-byte Unicode characters such as emoji (e.g., document, chart, checkmark emoji).\n\n### Rules for safe content\n\n1. **Never use emoji in generated source code.** Replace with plain-text equivalents:\n   - Document emoji -> `[doc]` or `(file)`\n   - Chart emoji -> `[chart]`\n   - Checkmark emoji -> `[ok]` or `(done)`\n   - Warning emoji -> `[warn]` or `WARNING:`\n\n2. **Use ASCII substitutes in comments** instead of Unicode box-drawing characters.\n\n3. **Test-write suspect content** to a throwaway file first if unsure:\n   ```bash\n   echo \"test content\" > \u002Ftmp\u002Fwrite_test.txt && cat \u002Ftmp\u002Fwrite_test.txt\n   ```\n\n4. **Recovery pattern** -- if a write_file call fails:\n   - Strip all non-ASCII characters from the content.\n   - Retry the write.\n   - If still failing, split the file into smaller chunks and concatenate with `cat`.\n\n---\n\n## Validation Checklist\n\nBefore considering the feature complete, verify each layer:\n\n```\nServer route\n  [ ] File created at server\u002Froutes\u002F{feature}-route.ts\n  [ ] Exports handle{Feature}Request function\n  [ ] Returns { success: true, data } on success\n  [ ] Returns { success: false, error } on failure with correct HTTP status\n\nService\n  [ ] File created at src\u002Fservices\u002F{feature}.ts\n  [ ] Exports fetch{Feature}Data function\n  [ ] Throws on non-ok HTTP status (so CircuitBreaker can record failures)\n\nServer wiring\n  [ ] Import added to server\u002Findex.ts\n  [ ] Dispatch case\u002Froute added (matching the detected pattern)\n  [ ] curl \u002Fapi\u002Fpanels\u002F{feature} returns JSON (not 404)\n\nPanel component\n  [ ] Extends Panel base class\n  [ ] Uses isFetching guard\n  [ ] CircuitBreaker wraps the service call\n  [ ] showError() called with retry callback on failure\n  [ ] destroy() clears interval and calls super.destroy()\n\nRegistration\n  [ ] Export added to src\u002Fcomponents\u002Findex.ts\n  [ ] Panel instantiated and mounted in dashboard bootstrap\n\nFile safety\n  [ ] No emoji in any generated source file\n  [ ] All write_file calls succeeded (check file size > 0)\n```\n\n---\n\n## Common Mistakes\n\n| Mistake | Symptom | Fix |\n|---------|---------|-----|\n| Skipping Step 5 (server wiring) | Feature returns 404 | Add import + dispatch entry to server\u002Findex.ts |\n| Wrong dispatch pattern | 404 or runtime error | Re-read server\u002Findex.ts; use grep from Step 2 |\n| Emoji in source files | write_file silent failure | Replace all emoji with ASCII equivalents |\n| React template in vanilla TS project | Compile errors | Confirm no React in package.json; use Panel base class template |\n| Creating Panel.ts when one exists | Overwrites base class | Check with `find src -name \"Panel.ts\"` first |\n| Not calling `super.destroy()` | Memory leak | Always chain super.destroy() in subclass destroy() |\n| CircuitBreaker declared inside class | Cache lost between fetches | Declare `const breaker = ...` at module level outside the class |\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Ffull-stack-panel-authoring",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":74},[64,67,70],{"tool":65,"command":66},"npx","npx skills add HKUDS\u002FAgentPilot --skill full-stack-panel-authoring",{"tool":68,"command":69},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill full-stack-panel-authoring",{"tool":71,"command":72},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill full-stack-panel-authoring","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Ffull-stack-panel-authoring\u002FSKILL.md",true,[76],{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},".skill_id","OTHER","其他",61,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fexamples\u002Fmy-daily-monitor\u002Fskills\u002Ffull-stack-panel-authoring\u002F.skill_id",[83,103,122,145,168,190],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":49},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[85,90,91,92,93,94,95,96,97,98,99,100,101,102],"prepare","requests","with","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":49},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[105,110,111,112,113,114,115,116,117,118,119,120,121],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":131,"publishedAt":49},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[128],{"categoryNo":129,"categoryName":130,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[132,133,134,113,135,136,137,138,139,140,141,142,143,144],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":152,"publishedAt":49},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[151],{"categoryNo":129,"categoryName":130,"taxonomyType":21,"taxonomyTypeDesc":22},[153,154,155,113,156,157,158,159,160,134,112,97,161,162,34,163,164,165,166,167],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","for","share","tasks","automation","MCP",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":49},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[175,176,177,178,179,180,181,182,183,184,46,185,186,187,163,188,189],"write special chars ts check","write","check","type","files","filters","only","template","file","python","output","Existing","type-checking","errors","script",{"skillNo":191,"name":192,"nameZh":6,"description":193,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":196,"publishedAt":49},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[197,198,176,92,163,189,199,200,201,202,203,182,183,204,205,184],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]