diff --git a/.agents/skills/skill-creator/LICENSE.txt b/.agents/skills/skill-creator/LICENSE.txt index 7a4a3ea..4f881c5 100644 --- a/.agents/skills/skill-creator/LICENSE.txt +++ b/.agents/skills/skill-creator/LICENSE.txt @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2026 Anthropic, PBC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/.agents/skills/skill-creator/SKILL.md b/.agents/skills/skill-creator/SKILL.md index 942bfe8..65b3a40 100644 --- a/.agents/skills/skill-creator/SKILL.md +++ b/.agents/skills/skill-creator/SKILL.md @@ -1,6 +1,6 @@ --- name: skill-creator -description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, update or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. +description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. --- # Skill Creator @@ -391,7 +391,7 @@ Use the model ID from your system prompt (the one powering the current session) While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like. -This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude with extended thinking to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting. +This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting. ### How skill triggering works @@ -435,6 +435,11 @@ In Claude.ai, the core workflow is the same (draft → test → review → impro **Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file. +**Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case: +- **Preserve the original name.** Note the skill's directory name and `name` frontmatter field -- use them unchanged. E.g., if the installed skill is `research-helper`, output `research-helper.skill` (not `research-helper-v2`). +- **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to `/tmp/skill-name/`, edit there, and package from the copy. +- **If packaging manually, stage in `/tmp/` first**, then copy to the output directory -- direct writes may fail due to permissions. + --- ## Cowork-Specific Instructions @@ -447,6 +452,7 @@ If you're in Cowork, the main things to know are: - Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first). - Packaging works — `package_skill.py` just needs Python and a filesystem. - Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape. +- **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. Follow the update guidance in the claude.ai section above. --- diff --git a/.agents/skills/skill-creator/scripts/__init__.py b/.agents/skills/skill-creator/scripts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/.agents/skills/skill-creator/scripts/improve_description.py b/.agents/skills/skill-creator/scripts/improve_description.py index a270777..06bcec7 100644 --- a/.agents/skills/skill-creator/scripts/improve_description.py +++ b/.agents/skills/skill-creator/scripts/improve_description.py @@ -2,22 +2,52 @@ """Improve a skill description based on eval results. Takes eval results (from run_eval.py) and generates an improved description -using Claude with extended thinking. +by calling `claude -p` as a subprocess (same auth pattern as run_eval.py — +uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed). """ import argparse import json +import os import re +import subprocess import sys from pathlib import Path -import anthropic - from scripts.utils import parse_skill_md +def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str: + """Run `claude -p` with the prompt on stdin and return the text response. + + Prompt goes over stdin (not argv) because it embeds the full SKILL.md + body and can easily exceed comfortable argv length. + """ + cmd = ["claude", "-p", "--output-format", "text"] + if model: + cmd.extend(["--model", model]) + + # Remove CLAUDECODE env var to allow nesting claude -p inside a + # Claude Code session. The guard is for interactive terminal conflicts; + # programmatic subprocess usage is safe. Same pattern as run_eval.py. + env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} + + result = subprocess.run( + cmd, + input=prompt, + capture_output=True, + text=True, + env=env, + timeout=timeout, + ) + if result.returncode != 0: + raise RuntimeError( + f"claude -p exited {result.returncode}\nstderr: {result.stderr}" + ) + return result.stdout + + def improve_description( - client: anthropic.Anthropic, skill_name: str, skill_content: str, current_description: str, @@ -99,7 +129,7 @@ Based on the failures, write a new and improved description that is more likely 1. Avoid overfitting 2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description. -Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. +Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it. Here are some tips that we've found to work well in writing these descriptions: - The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does" @@ -111,70 +141,41 @@ I'd encourage you to be creative and mix up the style in different iterations si Please respond with only the new description text in tags, nothing else.""" - response = client.messages.create( - model=model, - max_tokens=16000, - thinking={ - "type": "enabled", - "budget_tokens": 10000, - }, - messages=[{"role": "user", "content": prompt}], - ) + text = _call_claude(prompt, model) - # Extract thinking and text from response - thinking_text = "" - text = "" - for block in response.content: - if block.type == "thinking": - thinking_text = block.thinking - elif block.type == "text": - text = block.text - - # Parse out the tags match = re.search(r"(.*?)", text, re.DOTALL) description = match.group(1).strip().strip('"') if match else text.strip().strip('"') - # Log the transcript transcript: dict = { "iteration": iteration, "prompt": prompt, - "thinking": thinking_text, "response": text, "parsed_description": description, "char_count": len(description), "over_limit": len(description) > 1024, } - # If over 1024 chars, ask the model to shorten it + # Safety net: the prompt already states the 1024-char hard limit, but if + # the model blew past it anyway, make one fresh single-turn call that + # quotes the too-long version and asks for a shorter rewrite. (The old + # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we + # inline the prior output into the new prompt instead.) if len(description) > 1024: - shorten_prompt = f"Your description is {len(description)} characters, which exceeds the hard 1024 character limit. Please rewrite it to be under 1024 characters while preserving the most important trigger words and intent coverage. Respond with only the new description in tags." - shorten_response = client.messages.create( - model=model, - max_tokens=16000, - thinking={ - "type": "enabled", - "budget_tokens": 10000, - }, - messages=[ - {"role": "user", "content": prompt}, - {"role": "assistant", "content": text}, - {"role": "user", "content": shorten_prompt}, - ], + shorten_prompt = ( + f"{prompt}\n\n" + f"---\n\n" + f"A previous attempt produced this description, which at " + f"{len(description)} characters is over the 1024-character hard limit:\n\n" + f'"{description}"\n\n' + f"Rewrite it to be under 1024 characters while keeping the most " + f"important trigger words and intent coverage. Respond with only " + f"the new description in tags." ) - - shorten_thinking = "" - shorten_text = "" - for block in shorten_response.content: - if block.type == "thinking": - shorten_thinking = block.thinking - elif block.type == "text": - shorten_text = block.text - + shorten_text = _call_claude(shorten_prompt, model) match = re.search(r"(.*?)", shorten_text, re.DOTALL) shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"') transcript["rewrite_prompt"] = shorten_prompt - transcript["rewrite_thinking"] = shorten_thinking transcript["rewrite_response"] = shorten_text transcript["rewrite_description"] = shortened transcript["rewrite_char_count"] = len(shortened) @@ -216,9 +217,7 @@ def main(): print(f"Current: {current_description}", file=sys.stderr) print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr) - client = anthropic.Anthropic() new_description = improve_description( - client=client, skill_name=name, skill_content=content, current_description=current_description, diff --git a/.agents/skills/skill-creator/scripts/run_loop.py b/.agents/skills/skill-creator/scripts/run_loop.py index 36f9b4e..30a263d 100644 --- a/.agents/skills/skill-creator/scripts/run_loop.py +++ b/.agents/skills/skill-creator/scripts/run_loop.py @@ -15,8 +15,6 @@ import time import webbrowser from pathlib import Path -import anthropic - from scripts.generate_report import generate_html from scripts.improve_description import improve_description from scripts.run_eval import find_project_root, run_eval @@ -75,7 +73,6 @@ def run_loop( train_set = eval_set test_set = [] - client = anthropic.Anthropic() history = [] exit_reason = "unknown" @@ -200,7 +197,6 @@ def run_loop( for h in history ] new_description = improve_description( - client=client, skill_name=name, skill_content=content, current_description=current_description, diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/SKILL.md b/.agents/skills/wdd-vue3-ts-vuetify3/SKILL.md new file mode 100644 index 0000000..a90cf74 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/SKILL.md @@ -0,0 +1,258 @@ +--- +name: wdd-vue3-ts-vuetify3 +description: >- + Vue 3 + TypeScript + Vuetify 3 全栈前端开发指导 Skill。强制 Composition API + + + + + + +``` + +### 3.2 TypeScript 核心约束 + +- 所有函数必须声明返回类型(含 `void`) +- 使用 `interface` 定义对象形状,`type` 定义联合/工具类型 +- Props 使用 `defineProps()`,Emits 使用 `defineEmits()` +- 可变默认值使用工厂函数:`withDefaults(defineProps

(), { items: () => [] })` +- 禁止 `any`、`@ts-ignore`、`@ts-nocheck` + +详细规范 → [typescript-strict](references/typescript-strict.md) + +### 3.3 响应式默认值策略 + +| 场景 | 使用 | 原因 | +|------|------|------| +| 原始值 | `ref` | 简单高效 | +| 对象 / 数组 | `ref` | 深层追踪 | +| 第三方实例 | `shallowRef` | 避免代理破坏 | +| 只读派生 | `computed` | 缓存 + 依赖追踪 | +| 从 getter/props 创建 ref | `toRef` | 保持响应式链接 | + +### 3.4 组件拆分触发条件 + +当满足以下**任一条件**时必须拆分: + +- 承担 2+ 个独立职责 +- 包含 3+ 个独立 UI 区域 +- 模板超 100 行或 script 超 150 行 +- UI 模式在多处重复出现 + +CRUD 功能标准拆分:FilterBar + Table + Form + Detail + `useFeatureData.ts` + +详细规范 → [component-architecture](references/component-architecture.md) + +### 3.5 数据流 + +``` +Props (父 → 子) ─── 只读传递 +Events (子 → 父) ── emit 通知 +v-model ──────────── 仅用于表单控件双向绑定 +provide/inject ───── 仅用于深层嵌套上下文(主题、布局) +Pinia Store ──────── 跨组件共享的全局状态 +``` + +## §4 Vuetify 3 使用规范 + +### 4.1 组件选择 + +编码前先查决策表,按问题匹配组件,不要按关键词猜测。 +优先使用 Vuetify 组件,禁止在有对应组件时使用原生 HTML。 + +完整决策表 → [vuetify3-components](references/vuetify3-components.md) + +### 4.2 主题配置 + +- 必须同时提供 light 和 dark 主题 +- 所有颜色通过 `createVuetify` 的 `theme.themes` 定义 +- CSS 中使用 `rgb(var(--v-theme-))`,禁止硬编码颜色 +- 主题切换使用 `useTheme()` composable + +详细模板 → [vuetify3-theme](references/vuetify3-theme.md) + +### 4.3 响应式布局 + +- 使用 `v-container` + `v-row` + `v-col` 栅格系统 +- 编程式断点使用 `useDisplay()` composable +- 移动优先:从 `cols` 开始,逐步增加 `sm` / `md` / `lg` +- 所有页面必须在 xs 断点下可用 + +详细模式 → [vuetify3-responsive](references/vuetify3-responsive.md) + +### 4.4 容器化设计 + +- 所有内容区域必须有明确容器边界,使用 `min-height` 防御塌陷 +- 内容禁止被折断:`break-inside: avoid` +- 超出预设高度时使用 `overflow-y: auto` + `scrollbar-gutter: stable` +- 固定区域使用 `flex-shrink: 0`,滚动区域使用 `flex-grow: 1` + `min-height: 0` + +详细模式 → [container-defense](references/container-defense.md) + +## §5 统一请求层 + +前端类型必须与后端 `common-runtime.md` 的 Response 结构对齐: + +```typescript +interface ApiResponse { + code: number // 0 = 成功,1xxx = 通用错误,2xxx = 业务错误 + message: string + data: T + timestamp: string + request_id: string +} +``` + +所有 API 调用通过统一请求器(axios 实例 + 拦截器),禁止直接 import axios。 + +详细实现 → [api-layer](references/api-layer.md) + +## §6 Composable 设计模式 + +- 命名 `useXxx`,必须在 setup 同步上下文中调用 +- 返回具名对象(非数组),便于按需解构 +- 适配性输入:只读用 `MaybeRefOrGetter`,可写用 `MaybeRef` +- 生命周期钩子自动清理资源 + +详细模式 → [composables-patterns](references/composables-patterns.md) + +## §7 组件架构与复用 + +三层架构: + +| 层 | 职责 | 命名 | +|----|------|------| +| Base | 通用 UI 封装(与业务无关) | `BaseXxx.vue` | +| Feature | 业务功能组件 | `{Domain}Xxx.vue` | +| Page | 路由视图,布局编排 | `{Domain}XxxView.vue` | + +系统中重复出现的 UI 模式必须提取为 Base 组件。 + +详细架构 → [component-architecture](references/component-architecture.md) + +## §8 状态管理 + +- 全局共享状态 → Pinia Store(Setup Store 语法) +- 组件内部状态 → `ref` / `reactive` +- URL 可恢复状态 → Vue Router query/params +- Store 解构用 `storeToRefs()`,方法直接解构 +- Setup Store 必须 return 所有需要暴露的 ref 和方法 + +详细模式 → [pinia-state](references/pinia-state.md) + +## §9 路由管理 + +- 导航守卫使用返回值模式(禁止 `next()` 回调) +- 路由参数变化用 `watch(route.params)` 或 `:key="$route.fullPath"` +- 路由 Meta 使用 TypeScript 类型扩展 +- 异步守卫使用 `async` + `await` + +详细模式 → [router-patterns](references/router-patterns.md) + +## §10 页面美学 + +- 间距使用 Vuetify 4px 基数系统(`pa-4` 为标准内边距) +- 响应式间距:`pa-4 pa-md-6 pa-lg-8` +- 字体使用 Vuetify Typography 类(`text-h4` / `text-body-1` / `text-caption`) +- 颜色使用语义色(`primary` / `error` / `success`) +- 空状态和错误状态必须精心设计,禁止空白页面 +- 留白是设计元素,区块间距 `my-6` 或 `my-8` + +详细规范 → [design-aesthetics](references/design-aesthetics.md) + +## §11 调试与陷阱 + +遇到问题时先查调试索引表,覆盖以下分类: + +- 响应式陷阱(ref / reactive / watch / computed) +- 组件陷阱(Props / Emits / Slots / Lifecycle) +- TypeScript 陷阱(类型定义 / 模板 ref / defineProps) +- Vuetify 3 常见问题(样式 / 图标 / 主题 / 性能) +- 路由常见问题(参数变化 / 守卫 / 清理) + +详细索引 → [debug-guide](references/debug-guide.md) + +## §12 最终自检清单 + +每次提交代码前,逐项检查: + +- [ ] **UI 统一**:所有组件使用 Vuetify 3,无其他 UI 库引入 +- [ ] **明暗主题**:颜色通过主题系统定义,CSS 使用 `--v-theme-*` 变量 +- [ ] **响应式**:所有页面在 xs 断点下可用,使用 `useDisplay()` 判断 +- [ ] **容器化**:内容不折断,滚动条不影响布局,无高度塌陷 +- [ ] **组件复用**:重复 UI 模式已提取为 Base 组件 +- [ ] **TypeScript**:无 `any` / `@ts-ignore`,所有函数有返回类型 +- [ ] **Composition API**:所有组件使用 ` +``` + +## 全局错误通知 + +结合 Vuetify 的 `v-snackbar` 实现全局错误提示: + +```typescript +// src/composables/useNotification.ts +import { ref } from 'vue' + +interface Notification { + message: string + color: 'success' | 'error' | 'warning' | 'info' + timeout?: number +} + +const notification = ref(null) +const visible = ref(false) + +export function useNotification() { + function notify(options: Notification): void { + notification.value = { timeout: 3000, ...options } + visible.value = true + } + + function notifySuccess(message: string): void { + notify({ message, color: 'success' }) + } + + function notifyError(message: string): void { + notify({ message, color: 'error' }) + } + + return { notification, visible, notify, notifySuccess, notifyError } +} +``` + +## 反模式 + +### ❌ 直接使用 axios + +```typescript +// ❌ 禁止:绕过统一请求器 +import axios from 'axios' +const res = await axios.get('/api/users') +``` + +### ❌ 组件中处理 HTTP 细节 + +```typescript +// ❌ 禁止:组件中直接处理状态码 +if (response.status === 401) { ... } +``` + +### ❌ 忽略错误处理 + +```typescript +// ❌ 禁止:吞掉错误 +try { await fetchData() } catch { /* 空 catch */ } +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/component-architecture.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/component-architecture.md new file mode 100644 index 0000000..0998676 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/component-architecture.md @@ -0,0 +1,259 @@ +# 组件分层架构与复用 + +## 核心原则 + +- 组件按职责分为三层:Base → Feature → Page +- 系统中重复出现的 UI 模式必须提取为可复用组件 +- 组件保持单一职责,当一个组件承担多个独立职责时必须拆分 +- 数据流方向:Props down / Events up,`v-model` 仅用于真正的双向绑定 + +## 三层组件架构 + +### Base 组件(基础层) + +与业务无关的通用 UI 组件,对 Vuetify 组件的二次封装。 + +``` +src/components/base/ +├── BaseCard.vue # 统一卡片样式(防御高度塌陷) +├── BaseDialog.vue # 统一对话框(响应式宽度 + 滚动) +├── BaseTable.vue # 统一数据表格(分页 + 加载状态) +├── BaseForm.vue # 统一表单容器(验证 + 提交) +├── BaseConfirmDialog.vue # 二次确认对话框 +├── BaseEmptyState.vue # 空状态占位 +└── BasePageHeader.vue # 页面标题 + 面包屑 + 操作栏 +``` + +示例 — BaseDialog: + +```vue + + + + +``` + +### Feature 组件(业务层) + +特定业务功能的组件,组合 Base 组件和业务逻辑。 + +``` +src/components/ +├── user/ +│ ├── UserList.vue # 用户列表 +│ ├── UserForm.vue # 用户表单(新建/编辑) +│ ├── UserDetail.vue # 用户详情卡片 +│ └── UserRoleBadge.vue # 角色标签 +├── device/ +│ ├── DeviceTable.vue # 设备数据表 +│ ├── DeviceStatusChip.vue # 状态芯片 +│ └── DeviceFilterBar.vue # 筛选栏 +``` + +### Page 组件(页面层) + +路由级视图组件,仅做布局编排和数据组装,不包含具体 UI 实现。 + +``` +src/views/ +├── user/ +│ ├── UserListView.vue # 用户列表页(组装 UserList + 筛选 + 分页) +│ └── UserDetailView.vue # 用户详情页 +├── device/ +│ └── DeviceManageView.vue # 设备管理页 +``` + +## 组件拆分触发条件 + +当满足以下**任一条件**时,必须拆分组件: + +| 条件 | 说明 | +|------|------| +| 多重职责 | 同时负责数据编排和多个 UI 区域 | +| 3+ 个独立 UI 区域 | 如表单 + 筛选 + 列表 + 分页同时出现 | +| 可复用 UI 模式 | 列表项、卡片、状态标签等在多处出现 | +| 模板超过 100 行 | 可读性下降的信号 | +| script 超过 150 行 | 逻辑应抽取为 Composable | + +### CRUD 功能标准拆分 + +``` +feature/ +├── FeatureListView.vue # Page 层:布局编排 +├── FeatureFilterBar.vue # 筛选条件 +├── FeatureTable.vue # 数据表格 +├── FeatureForm.vue # 新建/编辑表单 +├── FeatureDetail.vue # 详情展示 +└── composables/ + └── useFeatureData.ts # 数据加载/分页/搜索逻辑 +``` + +## 命名约定 + +| 类型 | 命名规则 | 示例 | +|------|---------|------| +| Base 组件 | `Base` + 功能名 | `BaseDialog.vue` | +| Feature 组件 | 业务域 + 功能名 | `UserForm.vue` | +| Page 组件 | 业务域 + `View` | `UserListView.vue` | +| Composable | `use` + 功能名 | `useUserData.ts` | +| 类型文件 | 业务域 + `.types.ts` | `user.types.ts` | +| API 文件 | 业务域 + `.ts` | `user.ts`(在 `src/api/` 下) | + +## 数据流规范 + +### Props down / Events up + +```vue + + + + + +``` + +### v-model 双向绑定 + +仅在组件本质上是表单控件(输入值的读写)时使用 `v-model`: + +```vue + + + + + +``` + +### provide / inject + +仅用于深层嵌套场景(如主题、布局上下文),不用于一般数据传递: + +```typescript +// 定义 injection key +import { type InjectionKey } from 'vue' + +interface LayoutContext { + sidebarCollapsed: Ref + toggleSidebar: () => void +} + +const LayoutContextKey: InjectionKey = Symbol('LayoutContext') +``` + +## 反模式 + +### ❌ 万能组件 + +```vue + + +``` + +### ❌ 跨层级直接通信 + +```typescript +// ❌ 禁止:子组件直接调用父组件方法 +const parent = getCurrentInstance()?.parent +parent?.exposed?.refresh() + +// ✅ 正确:通过 emit 通知 +emit('dataChanged') +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/composables-patterns.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/composables-patterns.md new file mode 100644 index 0000000..428e312 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/composables-patterns.md @@ -0,0 +1,231 @@ +# Composable 设计模式 + +## 核心原则 + +- Composable 是 Vue 3 中复用有状态逻辑的核心机制 +- 命名统一使用 `use` 前缀:`useXxx` +- 必须在 ` +``` + +### Vuetify 覆盖样式调试 + +```css +/* 使用 :deep() 穿透 scoped 样式 */ +.my-custom-table :deep(.v-data-table-header) { + background-color: rgb(var(--v-theme-surface-variant)); +} +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/design-aesthetics.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/design-aesthetics.md new file mode 100644 index 0000000..a860c38 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/design-aesthetics.md @@ -0,0 +1,215 @@ +# UI 美学与设计规范 + +## 核心原则 + +- 页面不是功能的堆砌,而是信息的有序传达 +- 留白是设计元素,不是浪费空间 +- 颜色、字体、间距的选择必须有意为之,不使用默认模板风格 +- 错误状态和空状态同样需要精心设计 + +## 间距与留白 + +### Vuetify 间距系统 + +Vuetify 使用 4px 基数的间距系统(`ma-1` = 4px, `ma-2` = 8px, ...): + +| 类名 | 尺寸 | 使用场景 | +|------|------|---------| +| `pa-1` / `ma-1` | 4px | 紧密关联的元素间距 | +| `pa-2` / `ma-2` | 8px | 组内元素间距 | +| `pa-3` / `ma-3` | 12px | 小节内间距 | +| `pa-4` / `ma-4` | 16px | 标准内容间距(推荐默认) | +| `pa-6` / `ma-6` | 24px | 区块间距 | +| `pa-8` / `ma-8` | 32px | 大区块间距 | +| `pa-12` / `ma-12` | 48px | 页面级留白 | + +### 留白原则 + +``` +页面外边距:pa-4(移动端)→ pa-6(平板)→ pa-8(桌面) +卡片内边距:pa-4(标准)→ pa-6(宽松) +卡片间距:ga-4(row gap) +表单字段间距:通过 v-row dense 控制 +标题与内容间距:mb-4(标题下方) +区块间距:my-6 或 my-8 +``` + +### 响应式间距 + +```vue + +``` + +## Typography 排版 + +### 字体层级 + +使用 Vuetify 内置的 Typography 类,保持一致: + +| 类名 | 用途 | +|------|------| +| `text-h3` / `text-h4` | 页面大标题 | +| `text-h5` / `text-h6` | 区块标题 | +| `text-subtitle-1` | 副标题 | +| `text-subtitle-2` | 小副标题 | +| `text-body-1` | 正文(默认) | +| `text-body-2` | 辅助说明 | +| `text-caption` | 标注、时间戳 | +| `text-overline` | 分类标签 | + +### 字体颜色层级 + +```vue + +主标题 + + +描述文字 + + +不可用 +``` + +## 色彩使用 + +### 语义色使用场景 + +| 颜色 | 场景 | +|------|------| +| `primary` | 主按钮、链接、选中状态、品牌标识 | +| `secondary` | 次要操作、辅助装饰 | +| `error` | 错误提示、删除操作、验证失败 | +| `warning` | 警告信息、需要注意的状态 | +| `success` | 成功操作、正常状态 | +| `info` | 一般性提示信息 | + +### 状态色复用 + +```vue + + + {{ statusText }} + + + +``` + +## 空状态设计 + +每个可能为空的列表/表格都必须设计空状态: + +```vue + +``` + +## 错误状态设计 + +错误提示应当具体、可操作,不使用模糊的"出错了": + +```vue + +``` + +## 文案写作规范 + +借鉴 frontend-design skill 的核心原则: + +| 原则 | 说明 | +|------|------| +| 用户视角命名 | "通知管理" 而非 "Webhook 配置" | +| 主动语态 | "保存更改" 而非 "提交" | +| 动词一致性 | 按钮说 "发布" → 提示说 "已发布" | +| 错误不道歉 | "用户名已被注册" 而非 "抱歉,出错了" | +| 空状态即邀请 | 引导用户下一步操作 | +| 简洁 | 标签只标注,示例只演示,不让文字身兼多职 | + +## 反模式 + +### ❌ 毫无留白的拥挤界面 + +```vue + + + 标题 + + 操作 + +``` + +### ❌ 颜色乱用 + +```vue + +删除 + + +删除 +``` + +### ❌ 模糊的错误提示 + +```vue + +操作失败 + + +用户名已被注册,请更换后重试 +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/pinia-state.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/pinia-state.md new file mode 100644 index 0000000..0dc7859 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/pinia-state.md @@ -0,0 +1,165 @@ +# Pinia 状态管理精要 + +## 核心原则 + +- 使用 Pinia 进行全局/跨组件的状态管理 +- 优先使用 Setup Store 语法(与 Composition API 一致) +- 组件内部的临时状态使用 `ref` / `reactive`,不上升到 Store +- Store 解构时使用 `storeToRefs()` 保持响应式 + +## Store 定义 + +### Setup Store(推荐) + +```typescript +// src/stores/useUserStore.ts +import { defineStore, storeToRefs } from 'pinia' +import { ref, computed } from 'vue' +import { getUserList, type UserInfo } from '@/api/user' +import type { PageData } from '@/utils/request' + +export const useUserStore = defineStore('user', () => { + // State + const users = ref([]) + const currentUser = ref(null) + const loading = ref(false) + const total = ref(0) + + // Getters + const userCount = computed(() => users.value.length) + const isLoggedIn = computed(() => currentUser.value !== null) + + // Actions + async function fetchUsers(page: number, pageSize: number): Promise { + loading.value = true + try { + const result: PageData = await getUserList({ + page, + page_size: pageSize, + }) + users.value = result.list + total.value = result.total + } finally { + loading.value = false + } + } + + function setCurrentUser(user: UserInfo | null): void { + currentUser.value = user + } + + function $reset(): void { + users.value = [] + currentUser.value = null + loading.value = false + total.value = 0 + } + + // Setup Store 必须返回所有需要暴露的状态和方法 + return { + users, + currentUser, + loading, + total, + userCount, + isLoggedIn, + fetchUsers, + setCurrentUser, + $reset, + } +}) +``` + +## 在组件中使用 + +### 正确的解构方式 + +```vue + +``` + +### ❌ 错误的解构方式 + +```typescript +// ❌ 禁止:直接解构丢失响应式 +const { users, loading } = useUserStore() // users 和 loading 不再响应式 +``` + +## Store 之间通信 + +```typescript +// src/stores/useAuthStore.ts +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' +import { useUserStore } from './useUserStore' + +export const useAuthStore = defineStore('auth', () => { + const token = ref(null) + + const isAuthenticated = computed(() => token.value !== null) + + function logout(): void { + token.value = null + localStorage.removeItem('access_token') + + // 通知其他 Store 重置 + const userStore = useUserStore() + userStore.$reset() + } + + return { token, isAuthenticated, logout } +}) +``` + +## 状态分类决策 + +| 状态类型 | 存放位置 | 示例 | +|---------|---------|------| +| 全局共享状态 | Pinia Store | 用户信息、权限、主题偏好 | +| 页面级共享状态 | Pinia Store 或 Composable | 列表筛选条件、分页状态 | +| 组件内部状态 | `ref` / `reactive` | 表单输入值、对话框开关 | +| URL 可恢复状态 | Vue Router query/params | 搜索关键词、页码、筛选条件 | +| 临时 UI 状态 | `ref` | loading、hover、展开/折叠 | + +## 反模式 + +### ❌ 所有状态都放 Store + +```typescript +// ❌ 禁止:对话框开关状态不属于全局状态 +export const useDialogStore = defineStore('dialog', () => { + const showCreateDialog = ref(false) // ← 应该放在组件内 +}) +``` + +### ❌ Store 中直接操作 DOM + +```typescript +// ❌ 禁止 +export const useAppStore = defineStore('app', () => { + function showAlert(msg: string): void { + window.alert(msg) // ← Store 不应有 DOM 副作用 + } +}) +``` + +### ❌ 忘记在 Setup Store 中返回状态 + +```typescript +// ❌ 错误:DevTools 看不到 internalState +export const useBadStore = defineStore('bad', () => { + const internalState = ref(0) // ← 未返回 + return { /* 忘记返回 internalState */ } +}) +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/router-patterns.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/router-patterns.md new file mode 100644 index 0000000..ef70b9d --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/router-patterns.md @@ -0,0 +1,216 @@ +# Vue Router 4 模式精要 + +## 核心原则 + +- 使用 Vue Router 4(配合 Vue 3) +- 路由配置使用 TypeScript 严格类型 +- 导航守卫使用返回值模式(弃用 `next()` 回调) +- 异步数据加载在守卫或组件 `onMounted` 中处理 + +## 路由配置 + +```typescript +// src/router/index.ts +import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router' + +const routes: RouteRecordRaw[] = [ + { + path: '/login', + name: 'Login', + component: () => import('@/views/auth/LoginView.vue'), + meta: { requiresAuth: false, title: '登录' }, + }, + { + path: '/', + component: () => import('@/layouts/MainLayout.vue'), + meta: { requiresAuth: true }, + children: [ + { + path: '', + name: 'Dashboard', + component: () => import('@/views/dashboard/DashboardView.vue'), + meta: { title: '仪表板' }, + }, + { + path: 'users', + name: 'UserList', + component: () => import('@/views/user/UserListView.vue'), + meta: { title: '用户管理' }, + }, + { + path: 'users/:id', + name: 'UserDetail', + component: () => import('@/views/user/UserDetailView.vue'), + meta: { title: '用户详情' }, + props: true, + }, + ], + }, + { + path: '/:pathMatch(.*)*', + name: 'NotFound', + component: () => import('@/views/error/NotFoundView.vue'), + meta: { title: '页面未找到' }, + }, +] + +const router = createRouter({ + history: createWebHistory(import.meta.env.BASE_URL), + routes, +}) + +export default router +``` + +## 路由 Meta 类型扩展 + +```typescript +// src/types/router.d.ts +import 'vue-router' + +declare module 'vue-router' { + interface RouteMeta { + /** 是否需要登录 */ + requiresAuth?: boolean + /** 页面标题 */ + title?: string + /** 所需权限 */ + permissions?: string[] + } +} +``` + +## 导航守卫 + +### 全局前置守卫 + +```typescript +// src/router/guards.ts +import type { Router } from 'vue-router' +import { useAuthStore } from '@/stores/useAuthStore' + +export function setupRouterGuards(router: Router): void { + router.beforeEach((to) => { + const authStore = useAuthStore() + + // 需要认证但未登录 → 跳登录页 + if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) { + return { name: 'Login', query: { redirect: to.fullPath } } + } + + // 已登录访问登录页 → 跳首页 + if (to.name === 'Login' && authStore.isAuthenticated) { + return { name: 'Dashboard' } + } + + // 设置页面标题 + if (to.meta.title) { + document.title = `${to.meta.title} - 应用名称` + } + + // 放行 + return true + }) +} +``` + +### ❌ 弃用的 next() 模式 + +```typescript +// ❌ 禁止:使用 next() 回调 +router.beforeEach((to, from, next) => { + if (authenticated) { + next() + } else { + next('/login') + } +}) + +// ✅ 正确:使用返回值 +router.beforeEach((to) => { + if (!authenticated) { + return { path: '/login' } + } + // 不返回或返回 true 表示放行 +}) +``` + +## 路由参数变化不触发生命周期 + +同一路由不同参数(如 `/users/1` → `/users/2`)不会触发组件重新挂载。 + +### 解法一:watch 路由参数 + +```vue + +``` + +### 解法二:使用 key 强制重新挂载 + +```vue + + +``` + +## 异步守卫模式 + +```typescript +router.beforeEach(async (to) => { + if (to.meta.permissions) { + const authStore = useAuthStore() + const hasPermission = await authStore.checkPermissions(to.meta.permissions) + if (!hasPermission) { + return { name: 'Forbidden' } + } + } +}) +``` + +## 导航后清理 + +```vue + +``` + +## 反模式 + +### ❌ 无限重定向循环 + +```typescript +// ❌ 禁止:每个路由都重定向到另一个需要守卫的路由 +router.beforeEach((to) => { + if (!auth) return { name: 'Login' } // Login 也需要 auth?→ 死循环 +}) + +// ✅ 正确:排除不需要认证的路由 +router.beforeEach((to) => { + if (to.meta.requiresAuth !== false && !auth) { + return { name: 'Login' } + } +}) +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/typescript-strict.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/typescript-strict.md new file mode 100644 index 0000000..58416c5 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/typescript-strict.md @@ -0,0 +1,246 @@ +# TypeScript 严格规范 + +## 核心原则 + +- 所有代码必须使用 TypeScript,禁止出现 `.js` / `.jsx` 文件 +- 禁止使用 `any` 类型,必须提供具体的类型定义 +- 所有函数必须声明返回类型(`void` 也要显式标注) +- 使用 `interface` 定义对象形状,使用 `type` 定义联合类型和工具类型 + +## tsconfig 严格模式 + +```json +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "strictPropertyInitialization": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": false, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true + } +} +``` + +## 类型定义规范 + +### interface vs type 选择 + +```typescript +// ✅ interface:用于对象形状定义(可扩展) +interface UserInfo { + id: number + username: string + email: string + role: UserRole + createdAt: string +} + +// ✅ type:用于联合类型、交叉类型、工具类型 +type UserRole = 'admin' | 'editor' | 'viewer' +type Nullable = T | null +type AsyncData = { + data: T | null + loading: boolean + error: string | null +} +``` + +### Props 类型定义 + +```vue + +``` + +### Emits 类型定义 + +```vue + +``` + +### Ref 类型 + +```typescript +import { ref, shallowRef, computed, type Ref } from 'vue' + +// ✅ 类型推断充分时不需要显式标注 +const count = ref(0) // Ref +const name = ref('') // Ref + +// ✅ 需要显式标注的场景 +const user = ref(null) // 初始值无法推断目标类型 +const items = ref([]) // 空数组无法推断元素类型 +const el = ref(null) // DOM ref + +// ✅ shallowRef 用于非 Vue 实例对象(如 ECharts、地图实例等) +const chartInstance = shallowRef(null) +``` + +### 响应式默认值策略 + +选择正确的响应式原语(借鉴 vuetify0 策略): + +| 场景 | 使用 | 原因 | +|------|------|------| +| 原始值(string / number / boolean) | `ref` | 自动 unwrap,简单高效 | +| 对象/数组(需要深层响应式) | `ref` | 深层响应式追踪 | +| 非 Vue 管理的外部对象实例 | `shallowRef` | 避免代理破坏第三方实例 | +| 只读派生值 | `computed` | 缓存 + 自动依赖追踪 | +| 派生 ref(传递给 watcher) | `toRef` | 从 getter/props 创建 ref | +| 读取响应式值的当前快照 | `toValue` | 在需要当前值时解包 | + +## 禁止模式 + +### ❌ 使用 any + +```typescript +// ❌ 禁止 +const data: any = response.data +function process(input: any): any { ... } + +// ✅ 正确:定义具体类型 +const data: ApiResponse = response.data +function process(input: ProcessInput): ProcessResult { ... } +``` + +### ❌ 使用 @ts-ignore / @ts-nocheck + +```typescript +// ❌ 禁止 +// @ts-ignore +someFunction(wrongType) + +// ✅ 正确:修复类型问题或使用类型守卫 +if (isUserInfo(data)) { + someFunction(data) +} +``` + +### ❌ 类型断言滥用 + +```typescript +// ❌ 禁止:无依据的类型断言 +const user = data as UserInfo + +// ✅ 正确:使用类型守卫 +function isUserInfo(data: unknown): data is UserInfo { + return ( + typeof data === 'object' && + data !== null && + 'id' in data && + 'username' in data + ) +} +``` + +## 常用类型工具 + +```typescript +// src/types/utils.ts + +/** 将类型 T 的所有属性变为可选 + null */ +type Nullable = { [K in keyof T]: T[K] | null } + +/** 从类型 T 中排除 null 和 undefined */ +type NonNullableFields = { [K in keyof T]: NonNullable } + +/** 分页请求参数 */ +interface PaginationParams { + page: number + pageSize: number +} + +/** 排序参数 */ +interface SortParams { + sortBy: string + sortOrder: 'asc' | 'desc' +} + +/** 列表查询参数 */ +type ListQueryParams = PaginationParams & Partial & { + search?: string +} + +/** 表单字段状态 */ +interface FieldState { + value: T + error: string | null + dirty: boolean + touched: boolean +} +``` + +## Vue 3 + TypeScript 特有规范 + +### template ref 类型 + +```vue + + + +``` + +### provide / inject 类型安全 + +```typescript +import { type InjectionKey, provide, inject } from 'vue' + +// 定义类型安全的 injection key +const UserContextKey: InjectionKey = Symbol('UserContext') + +// 提供 +provide(UserContextKey, userContext) + +// 注入(类型安全) +const userContext = inject(UserContextKey) +if (!userContext) { + throw new Error('UserContext not provided') +} +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-components.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-components.md new file mode 100644 index 0000000..4a14b97 --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-components.md @@ -0,0 +1,158 @@ +# Vuetify 3 组件使用规范 + +## 核心原则 + +- 所有 UI 必须使用 Vuetify 3 组件构建,禁止引入其他 UI 库(Element Plus、Ant Design Vue 等) +- 优先使用 Vuetify 内置组件,只有在 Vuetify 确实不提供时才考虑自定义实现 +- 组件 props 使用 kebab-case(`:item-value`),事件使用 `@update:model-value` 形式 + +## 组件选择决策表 + +编码前先查此表,按问题匹配组件,不要按关键词猜测。 + +### 布局与容器 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 页面整体布局 | `v-app` + `v-main` | 应用根容器,必须包裹所有内容 | +| 侧边导航栏 | `v-navigation-drawer` | 支持 `rail` 模式(收缩)和响应式断点 | +| 顶部应用栏 | `v-app-bar` | 支持 `density` 调节高度 | +| 底部导航(移动端) | `v-bottom-navigation` | 移动端底部 Tab 栏 | +| 栅格布局 | `v-container` + `v-row` + `v-col` | 12 列 Grid 系统 | +| 卡片容器 | `v-card` | 标准内容容器,支持 `variant` | +| 通用容器 | `v-sheet` | 轻量级容器,用于自定义布局 | +| 工具栏 | `v-toolbar` | 独立工具栏(非 app-bar) | +| 内容分隔线 | `v-divider` | 水平/垂直分隔 | +| 间距控制 | `v-spacer` | Flex 弹性占位 | + +### 数据展示 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 表格数据(带排序/分页) | `v-data-table` | 功能完整的数据表格 | +| 简单表格(无排序) | `v-table` | 原生表格包装 | +| 虚拟滚动长列表 | `v-virtual-scroll` | 大数据量渲染优化 | +| 列表展示 | `v-list` + `v-list-item` | 垂直列表,支持分组 | +| 芯片/标签 | `v-chip` | 状态标签、筛选标签 | +| 徽章/角标 | `v-badge` | 数字或状态角标 | +| 头像 | `v-avatar` | 用户头像或图标容器 | +| 进度指示 | `v-progress-linear` / `v-progress-circular` | 进度条 | +| 骨架屏 | `v-skeleton-loader` | 数据加载占位 | +| 时间线 | `v-timeline` | 时间序列展示 | +| 树形结构 | `v-treeview` | 层级数据展示 | + +### 表单与输入 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 表单容器(带验证) | `v-form` | 统一表单验证入口 | +| 文本输入 | `v-text-field` | 支持 `type`、`rules`、`variant` | +| 多行文本 | `v-textarea` | 多行输入 | +| 下拉选择 | `v-select` | 单选/多选下拉 | +| 搜索选择(自动补全) | `v-autocomplete` | 可搜索的下拉 | +| 组合输入(自由输入+选择) | `v-combobox` | 允许输入不在列表中的值 | +| 开关 | `v-switch` | 布尔值切换 | +| 复选框 | `v-checkbox` | 单个/多个复选 | +| 单选 | `v-radio-group` + `v-radio` | 互斥选择 | +| 滑块 | `v-slider` / `v-range-slider` | 数值范围选择 | +| 文件上传 | `v-file-input` | 文件选择 | +| 日期选择 | `v-date-input` + `v-date-picker` | 日期输入 | +| 颜色选择 | `v-color-picker` | 颜色输入 | + +### 反馈与交互 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 模态对话框 | `v-dialog` | 居中弹窗 | +| 底部弹出面板 | `v-bottom-sheet` | 移动端底部弹出 | +| 临时消息通知 | `v-snackbar` | 自动消失的提示 | +| 工具提示 | `v-tooltip` | 悬浮提示 | +| 弹出菜单 | `v-menu` | 下拉/右键菜单 | +| 确认操作 | `v-dialog` + 自定义确认内容 | 危险操作二次确认 | +| 全屏遮罩/加载 | `v-overlay` | 覆盖层 | +| 警告横幅 | `v-alert` | 页面级提示信息 | +| 横幅通知 | `v-banner` | 持续性通知 | + +### 导航 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 页面标签页 | `v-tabs` + `v-tab` + `v-tabs-window` | 标签页切换 | +| 面包屑 | `v-breadcrumbs` | 路径导航 | +| 分页器 | `v-pagination` | 页码导航 | +| 步骤条 | `v-stepper` | 多步骤向导 | +| 手风琴面板 | `v-expansion-panels` | 折叠/展开面板组 | + +### 按钮与操作 + +| 问题场景 | 使用组件 | 说明 | +|---------|---------|------| +| 标准按钮 | `v-btn` | 支持 `variant`、`color`、`size` | +| 图标按钮 | `v-btn` + `icon` prop | 仅图标的按钮 | +| 浮动操作按钮 | `v-btn` + `position="fixed"` | FAB 按钮 | +| 按钮组 | `v-btn-toggle` | 互斥/多选按钮组 | +| 图标 | `v-icon` | Material Design Icons | + +## 组件使用规范 + +### variant 选择策略 + +``` +v-btn / v-text-field / v-card 等支持 variant 的组件: +- elevated → 强调操作(主按钮、重要卡片) +- filled → 次要强调 +- tonal → 柔和强调(推荐默认) +- outlined → 边框风格 +- text → 无背景无边框 +- plain → 最低视觉权重 +``` + +### density 选择策略 + +``` +适用于 v-text-field / v-select / v-list 等: +- default → 标准间距 +- comfortable → 稍紧凑 +- compact → 紧凑模式(数据密集场景) +``` + +### 图标使用 + +统一使用 Material Design Icons(mdi): + +```vue + +新建 +``` + +禁止混用多种图标库。项目中应在 `vuetify.ts` 插件中统一配置图标集。 + +## 反模式 + +### ❌ 混用 UI 库 + +```vue + +提交 +... +``` + +### ❌ 原生 HTML 替代 Vuetify 组件 + +```vue + +...
+ + + +``` + +### ❌ 硬编码颜色值 + +```vue + + + + + +``` diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-responsive.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-responsive.md new file mode 100644 index 0000000..88c438e --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-responsive.md @@ -0,0 +1,207 @@ +# Vuetify 3 响应式设计 + +## 核心原则 + +- 使用 Vuetify 的 Grid 系统(`v-container` / `v-row` / `v-col`)构建响应式布局 +- 使用 `useDisplay()` composable 进行编程式断点判断 +- 移动优先:从小屏开始设计,逐步增强大屏体验 +- 禁止使用原生 CSS media query 替代 Vuetify 断点系统 + +## 断点定义 + +Vuetify 3 默认断点: + +| 断点名 | 范围 | 设备 | +|--------|------|------| +| `xs` | 0 – 599px | 小型手机 | +| `sm` | 600 – 959px | 大型手机 / 小型平板 | +| `md` | 960 – 1279px | 平板 / 小型笔电 | +| `lg` | 1280 – 1919px | 桌面显示器 | +| `xl` | 1920 – 2559px | 大型显示器 | +| `xxl` | 2560px+ | 超大屏 | + +## Grid 系统 + +### 基础布局 + +```vue + +``` + +### 响应式间距 + +```vue + + + +``` + +### 对齐控制 + +```vue + + 左侧内容 + 右侧内容 + +``` + +## 编程式断点判断 + +### useDisplay() composable + +```typescript +import { useDisplay } from 'vuetify' +import { computed } from 'vue' + +const { mobile, mdAndUp, lgAndUp, name, width } = useDisplay() + +// 常用判断 +const isMobile = computed(() => mobile.value) +const isTabletOrAbove = computed(() => mdAndUp.value) +const isDesktop = computed(() => lgAndUp.value) +``` + +### 响应式组件属性 + +```vue + + + +``` + +## 响应式典型模式 + +### 侧边栏模式 + +```vue + + + +``` + +### 列表/卡片切换 + +```vue + + + +``` + +### 响应式对话框 + +```vue + + + +``` + +## 反模式 + +### ❌ 原生 media query 替代 Vuetify 断点 + +```css +/* 禁止:使用原生 media query */ +@media (max-width: 960px) { + .sidebar { display: none; } +} +``` + +```vue + + +``` + +### ❌ 固定像素宽度 + +```vue + + + + + +``` + +### ❌ 忽略移动端适配 + +所有页面必须在 xs 断点(< 600px)下可用且内容可读。 diff --git a/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-theme.md b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-theme.md new file mode 100644 index 0000000..e2361cf --- /dev/null +++ b/.agents/skills/wdd-vue3-ts-vuetify3/references/vuetify3-theme.md @@ -0,0 +1,208 @@ +# Vuetify 3 明暗主题配置 + +## 核心原则 + +- 所有颜色必须通过 Vuetify 主题系统定义,禁止在组件中硬编码颜色值 +- 必须同时提供 light 和 dark 两套主题配色 +- 自定义颜色通过 `colors` 扩展,不覆盖 Vuetify 默认语义色(primary / secondary / error 等) +- CSS 中引用颜色使用 `rgb(var(--v-theme-))` 变量 + +## 主题配置模板 + +### vuetify 插件配置 + +```typescript +// src/plugins/vuetify.ts +import { createVuetify, type ThemeDefinition } from 'vuetify' +import 'vuetify/styles' + +const lightTheme: ThemeDefinition = { + dark: false, + colors: { + background: '#FAFAFA', + surface: '#FFFFFF', + 'surface-variant': '#F5F5F5', + primary: '#1867C0', + 'primary-darken-1': '#1459A3', + secondary: '#5CBBF6', + 'secondary-darken-1': '#4BA3D8', + error: '#B00020', + info: '#2196F3', + success: '#4CAF50', + warning: '#FB8C00', + // 自定义扩展色 + 'on-surface-muted': '#757575', + 'border-color': '#E0E0E0', + }, +} + +const darkTheme: ThemeDefinition = { + dark: true, + colors: { + background: '#121212', + surface: '#1E1E1E', + 'surface-variant': '#2C2C2C', + primary: '#2196F3', + 'primary-darken-1': '#1976D2', + secondary: '#54B4EB', + 'secondary-darken-1': '#4BA3D8', + error: '#CF6679', + info: '#2196F3', + success: '#4CAF50', + warning: '#FB8C00', + // 自定义扩展色 + 'on-surface-muted': '#9E9E9E', + 'border-color': '#424242', + }, +} + +export default createVuetify({ + theme: { + defaultTheme: 'light', + themes: { + light: lightTheme, + dark: darkTheme, + }, + }, +}) +``` + +## 主题切换 + +### 使用 useTheme() composable + +```typescript +// src/composables/useThemeToggle.ts +import { useTheme } from 'vuetify' +import { computed } from 'vue' + +export function useThemeToggle() { + const theme = useTheme() + + const isDark = computed(() => theme.global.current.value.dark) + + function toggleTheme(): void { + theme.global.name.value = isDark.value ? 'light' : 'dark' + } + + return { isDark, toggleTheme } +} +``` + +### 模板中使用 + +```vue + + + +``` + +## CSS 中引用主题色 + +### 使用 CSS 变量 + +```css +/* 正确:通过 Vuetify CSS 变量引用主题色 */ +.custom-border { + border: 1px solid rgb(var(--v-theme-border-color)); +} + +.muted-text { + color: rgb(var(--v-theme-on-surface-muted)); +} + +/* 带透明度 */ +.overlay-bg { + background-color: rgba(var(--v-theme-surface), 0.85); +} +``` + +### 禁止模式 + +```css +/* ❌ 禁止:硬编码颜色 */ +.custom-bg { background: #1976d2; } + +/* ❌ 禁止:不走主题系统的 CSS 变量 */ +.custom-bg { background: var(--my-custom-color); } + +/* ✅ 正确:走 Vuetify 主题 */ +.custom-bg { background-color: rgb(var(--v-theme-primary)); } +``` + +## 组件级主题色使用 + +```vue + + + 标题 + 描述文字 + + + +

内容
+``` + +## 主题感知的条件样式 + +```vue + + + +``` + +## 主题持久化 + +将用户主题偏好存储到 localStorage,并在应用初始化时恢复: + +```typescript +// src/composables/useThemeToggle.ts +import { useTheme } from 'vuetify' +import { computed, watch } from 'vue' + +const THEME_STORAGE_KEY = 'user-theme-preference' + +export function useThemeToggle() { + const theme = useTheme() + + const isDark = computed(() => theme.global.current.value.dark) + + function toggleTheme(): void { + theme.global.name.value = isDark.value ? 'light' : 'dark' + } + + // 持久化 + watch( + () => theme.global.name.value, + (themeName) => { + localStorage.setItem(THEME_STORAGE_KEY, themeName) + }, + ) + + return { isDark, toggleTheme } +} + +export function restoreThemePreference(): string { + return localStorage.getItem(THEME_STORAGE_KEY) ?? 'light' +} +``` diff --git a/.agents/skills/frontend-vue3-vuetify/SKILL.md b/1-AgentSkills/frontend-vue3-vuetify/SKILL.md similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/SKILL.md rename to 1-AgentSkills/frontend-vue3-vuetify/SKILL.md diff --git a/.agents/skills/frontend-vue3-vuetify/examples/api-module.ts b/1-AgentSkills/frontend-vue3-vuetify/examples/api-module.ts similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/examples/api-module.ts rename to 1-AgentSkills/frontend-vue3-vuetify/examples/api-module.ts diff --git a/.agents/skills/frontend-vue3-vuetify/examples/data-table-page.vue b/1-AgentSkills/frontend-vue3-vuetify/examples/data-table-page.vue similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/examples/data-table-page.vue rename to 1-AgentSkills/frontend-vue3-vuetify/examples/data-table-page.vue diff --git a/.agents/skills/frontend-vue3-vuetify/examples/page-layout.vue b/1-AgentSkills/frontend-vue3-vuetify/examples/page-layout.vue similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/examples/page-layout.vue rename to 1-AgentSkills/frontend-vue3-vuetify/examples/page-layout.vue diff --git a/.agents/skills/frontend-vue3-vuetify/reference/api-patterns.md b/1-AgentSkills/frontend-vue3-vuetify/reference/api-patterns.md similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/reference/api-patterns.md rename to 1-AgentSkills/frontend-vue3-vuetify/reference/api-patterns.md diff --git a/.agents/skills/frontend-vue3-vuetify/reference/layout-patterns.md b/1-AgentSkills/frontend-vue3-vuetify/reference/layout-patterns.md similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/reference/layout-patterns.md rename to 1-AgentSkills/frontend-vue3-vuetify/reference/layout-patterns.md diff --git a/.agents/skills/frontend-vue3-vuetify/reference/typescript-rules.md b/1-AgentSkills/frontend-vue3-vuetify/reference/typescript-rules.md similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/reference/typescript-rules.md rename to 1-AgentSkills/frontend-vue3-vuetify/reference/typescript-rules.md diff --git a/.agents/skills/frontend-vue3-vuetify/reference/ui-interaction.md b/1-AgentSkills/frontend-vue3-vuetify/reference/ui-interaction.md similarity index 100% rename from .agents/skills/frontend-vue3-vuetify/reference/ui-interaction.md rename to 1-AgentSkills/frontend-vue3-vuetify/reference/ui-interaction.md diff --git a/1-Golang项目/3-api-development-prompt.md b/1-Golang-Dev/3-api-development-prompt.md similarity index 100% rename from 1-Golang项目/3-api-development-prompt.md rename to 1-Golang-Dev/3-api-development-prompt.md diff --git a/1-Golang项目/3-go-writer-refresh.md b/1-Golang-Dev/3-go-writer-refresh.md similarity index 100% rename from 1-Golang项目/3-go-writer-refresh.md rename to 1-Golang-Dev/3-go-writer-refresh.md diff --git a/1-Golang项目/go-gin-gorm-style.md b/1-Golang-Dev/go-gin-gorm-style.md similarity index 100% rename from 1-Golang项目/go-gin-gorm-style.md rename to 1-Golang-Dev/go-gin-gorm-style.md diff --git a/1-Golang项目/模块调用关系.md b/1-Golang-Dev/模块调用关系.md similarity index 100% rename from 1-Golang项目/模块调用关系.md rename to 1-Golang-Dev/模块调用关系.md diff --git a/1-Vue3-Dev/.agents/skills/create-adaptable-composable/SKILL.md b/1-Vue3-Dev/.agents/skills/create-adaptable-composable/SKILL.md new file mode 100644 index 0000000..e86c9c9 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/create-adaptable-composable/SKILL.md @@ -0,0 +1,76 @@ +--- +name: create-adaptable-composable +description: Create a library-grade Vue composable that accepts maybe-reactive inputs (MaybeRef / MaybeRefOrGetter) so callers can pass a plain value, ref, or getter. Normalize inputs with toValue()/toRef() inside reactive effects (watch/watchEffect) to keep behavior predictable and reactive. Use this skill when user asks for creating adaptable or reusable composables. +license: MIT +metadata: + author: github.com/vuejs-ai + version: "17.0.0" +compatibility: Requires Vue 3 (or above) or Nuxt 3 (or above) project +--- + +# Create Adaptable Composable + +Adaptable composables are reusable functions that can accept both reactive and non-reactive inputs. This allows developers to use the composable in a variety of contexts without worrying about the reactivity of the inputs. + +Steps to design an adaptable composable in Vue.js: +1. Confirm the composable's purpose and API design and expected inputs/outputs. +2. Identify inputs params that should be reactive (MaybeRef / MaybeRefOrGetter). +3. Use `toValue()` or `toRef()` to normalize inputs inside reactive effects. +4. Implement the core logic of the composable using Vue's reactivity APIs. + +## Core Type Concepts + +### Type Utilities + +```ts +/** + * value or writable ref (value/ref/shallowRef/writable computed) + */ +export type MaybeRef = T | Ref | ShallowRef | WritableComputedRef; + +/** + * MaybeRef + ComputedRef + () => T + */ +export type MaybeRefOrGetter = MaybeRef | ComputedRef | (() => T); +``` + +### Policy and Rules + +- Read-only, computed-friendly input: use `MaybeRefOrGetter` +- Needs to be writable / two-way input: use `MaybeRef` +- Parameter might be a function value (callback/predicate/comparator): do not use `MaybeRefOrGetter`, or you may accidentally invoke it as a getter. +- DOM/Element targets: if you want computed/derived targets, use `MaybeRefOrGetter`. + +When `MaybeRefOrGetter` or `MaybeRef` is used: +- resolve reactive value using `toRef()` (e.g. watcher source) +- resolve non-reactive value using `toValue()` + +### Examples + +Adaptable `useDocumentTitle` Composable: read-only title parameter + +```ts +import { watch, toRef } from 'vue' +import type { MaybeRefOrGetter } from 'vue' + +export function useDocumentTitle(title: MaybeRefOrGetter) { + watch(toRef(title), (t) => { + document.title = t + }, { immediate: true }) +} +``` + +Adaptable `useCounter` Composable: two-way writable count parameter + +```ts +import { watch, toRef } from 'vue' +import type { MaybeRef } from 'vue' + +function useCounter(count: MaybeRef) { + const countRef = toRef(count) + function add() { + countRef.value++ + } + return { add } +} +``` diff --git a/1-Vue3-Dev/.agents/skills/frontend-design/LICENSE.txt b/1-Vue3-Dev/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/1-Vue3-Dev/.agents/skills/frontend-design/SKILL.md b/1-Vue3-Dev/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..decdff4 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/frontend-design/SKILL.md @@ -0,0 +1,55 @@ +--- +name: frontend-design +description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. +license: Complete terms in LICENSE.txt +--- + +# Frontend Design + +Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. This client has already rejected proposals that felt templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take one real aesthetic risk you can justify. + +## Ground it in the subject + +If the brief does not pin down what the product or subject is, pin it yourself before designing: name one concrete subject, its audience, and the page's single job, and state your choice. If there's any information in your memory about the human's preferences, context about what they're building, or designs you've made before – use that as a hint. The subject's own world, its materials, instruments, artifacts, and vernacular, is where distinctive choices come from. Build with the brief's real content and subject matter throughout. + +## Design principles + +For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world, in whatever form makes sense for it: a headline, an image, an animation, a live demo, an interactive moment. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the template answer, only use if that's truly the best option. + +Typography carries the personality of the page. Pair the display and body faces deliberately, not the same families you would reach for on any other project, and set a clear type scale with intentional weights, widths, and spacing. Make the type treatment itself a memorable part of the design, not a neutral delivery vehicle for the content. + +Structure is information. Structural devices, numbering, eyebrows, dividers, labels, should encode something true about the content, not decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence - like a real process or a typed timeline where order carries information the reader needs. Question if choices like numbered markers actually make sense before incorporating them. + +Leverage motion deliberately. Think about where and if animation can serve the subject: a page-load sequence, a scroll-triggered reveal, hover micro-interactions, ambient atmosphere. An orchestrated moment usually lands harder than scattered effects; choose what the direction calls for. However, sometimes less is more, and extra animation contributes to the feeling that the design is AI-generated. + +Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well. + +Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance. + +## Process: brainstorm, explore, plan, critique, build, critique again + +For calibration: AI-generated design right now clusters around three looks: (1) a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta accent; (2) a near-black background with a single bright acid-green or vermilion accent; (3) a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns. All three are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. Just like a human designer who's hired, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn. + +Work in two passes. First, brainstorm a short design plan based on the human's design brief: create a compact token system with color, type, layout, and signature. Color: describe the palette as 4–6 named hex values. Type: the typefaces for 2+ roles (a characterful display face that's used with restraint, a complementary body face, and a utility face for captions or data if needed). Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Signature: the single unique element this page will be remembered by that embodies the brief in an appropriate way. + +Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan exactly and deriving every color and type decision from it. + +When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and a element-based selector like .cta). This can happen often with paddings/margins between sections. + +Try to do a lot of this planning and iteration in your thinking, and only show ideas to the user when you have higher confidence it'll delight them. + +## Restraint and self-critique + +Spend your boldness in one place. Let the signature element be the one memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Not taking a risk can be a risk itself! Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected. Critique your own work as you build, taking screenshots if your environment supports it – a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creators have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes. + +## More on writing in design + +Words appear in a design for one reason: to make it easier to understand, and therefore easier to use. They are design material, not decoration. Bring the same intentionality to copy that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience. + +Write from the end user's side of the screen. Name things by what people control and recognize, never by how the system is built. A person manages notifications, not webhook config. Describe what something does in plain terms rather than selling it. Being specific is always better than being clever. + +Use active voice as default. A control should say exactly what happens when it's used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around. + +Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act. + +Keep the register conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each element do exactly one job. A label labels, an example demonstrates, and nothing quietly does double duty. diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/LICENSE.txt b/1-Vue3-Dev/.agents/skills/skill-creator/LICENSE.txt new file mode 100644 index 0000000..4f881c5 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Anthropic, PBC. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/SKILL.md b/1-Vue3-Dev/.agents/skills/skill-creator/SKILL.md new file mode 100644 index 0000000..65b3a40 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/SKILL.md @@ -0,0 +1,485 @@ +--- +name: skill-creator +description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. +--- + +# Skill Creator + +A skill for creating new skills and iteratively improving them. + +At a high level, the process of creating a skill goes like this: + +- Decide what you want the skill to do and roughly how it should do it +- Write a draft of the skill +- Create a few test prompts and run claude-with-access-to-the-skill on them +- Help the user evaluate the results both qualitatively and quantitatively + - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist) + - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics +- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks) +- Repeat until you're satisfied +- Expand the test set and try again at larger scale + +Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat. + +On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop. + +Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead. + +Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill. + +Cool? Cool. + +## Communicating with the user + +The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate. + +So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea: + +- "evaluation" and "benchmark" are borderline, but OK +- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them + +It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it. + +--- + +## Creating a skill + +### Capture Intent + +Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step. + +1. What should this skill enable Claude to do? +2. When should this skill trigger? (what user phrases/contexts) +3. What's the expected output format? +4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide. + +### Interview and Research + +Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out. + +Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user. + +### Write the SKILL.md + +Based on the user interview, fill in these components: + +- **name**: Skill identifier +- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'" +- **compatibility**: Required tools, dependencies (optional, rarely needed) +- **the rest of the skill :)** + +### Skill Writing Guide + +#### Anatomy of a Skill + +``` +skill-name/ +├── SKILL.md (required) +│ ├── YAML frontmatter (name, description required) +│ └── Markdown instructions +└── Bundled Resources (optional) + ├── scripts/ - Executable code for deterministic/repetitive tasks + ├── references/ - Docs loaded into context as needed + └── assets/ - Files used in output (templates, icons, fonts) +``` + +#### Progressive Disclosure + +Skills use a three-level loading system: +1. **Metadata** (name + description) - Always in context (~100 words) +2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal) +3. **Bundled resources** - As needed (unlimited, scripts can execute without loading) + +These word counts are approximate and you can feel free to go longer if needed. + +**Key patterns:** +- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up. +- Reference files clearly from SKILL.md with guidance on when to read them +- For large reference files (>300 lines), include a table of contents + +**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant: +``` +cloud-deploy/ +├── SKILL.md (workflow + selection) +└── references/ + ├── aws.md + ├── gcp.md + └── azure.md +``` +Claude reads only the relevant reference file. + +#### Principle of Lack of Surprise + +This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though. + +#### Writing Patterns + +Prefer using the imperative form in instructions. + +**Defining output formats** - You can do it like this: +```markdown +## Report structure +ALWAYS use this exact template: +# [Title] +## Executive summary +## Key findings +## Recommendations +``` + +**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little): +```markdown +## Commit message format +**Example 1:** +Input: Added user authentication with JWT tokens +Output: feat(auth): implement JWT-based authentication +``` + +### Writing Style + +Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it. + +### Test Cases + +After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them. + +Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress. + +```json +{ + "skill_name": "example-skill", + "evals": [ + { + "id": 1, + "prompt": "User's task prompt", + "expected_output": "Description of expected result", + "files": [] + } + ] +} +``` + +See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later). + +## Running and evaluating test cases + +This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill. + +Put results in `-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go. + +### Step 1: Spawn all runs (with-skill AND baseline) in the same turn + +For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time. + +**With-skill run:** + +``` +Execute this task: +- Skill path: +- Task: +- Input files: +- Save outputs to: /iteration-/eval-/with_skill/outputs/ +- Outputs to save: +``` + +**Baseline run** (same prompt, but the baseline depends on context): +- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`. +- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r /skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`. + +Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations. + +```json +{ + "eval_id": 0, + "eval_name": "descriptive-name-here", + "prompt": "The user's task prompt", + "assertions": [] +} +``` + +### Step 2: While runs are in progress, draft assertions + +Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check. + +Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment. + +Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark. + +### Step 3: As runs complete, capture timing data + +When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory: + +```json +{ + "total_tokens": 84852, + "duration_ms": 23332, + "total_duration_seconds": 23.3 +} +``` + +This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them. + +### Step 4: Grade, aggregate, and launch the viewer + +Once all runs are done: + +1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations. + +2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory: + ```bash + python -m scripts.aggregate_benchmark /iteration-N --skill-name + ``` + This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects. +Put each with_skill version before its baseline counterpart. + +3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs. + +4. **Launch the viewer** with both qualitative outputs and quantitative data: + ```bash + nohup python /eval-viewer/generate_review.py \ + /iteration-N \ + --skill-name "my-skill" \ + --benchmark /iteration-N/benchmark.json \ + > /dev/null 2>&1 & + VIEWER_PID=$! + ``` + For iteration 2+, also pass `--previous-workspace /iteration-`. + + **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static ` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up. + +Note: please use generate_review.py to create the viewer; there's no need to write custom HTML. + +5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know." + +### What the user sees in the viewer + +The "Outputs" tab shows one test case at a time: +- **Prompt**: the task that was given +- **Output**: the files the skill produced, rendered inline where possible +- **Previous Output** (iteration 2+): collapsed section showing last iteration's output +- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail +- **Feedback**: a textbox that auto-saves as they type +- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox + +The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations. + +Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`. + +### Step 5: Read the feedback + +When the user tells you they're done, read `feedback.json`: + +```json +{ + "reviews": [ + {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."}, + {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."}, + {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."} + ], + "status": "complete" +} +``` + +Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints. + +Kill the viewer server when you're done with it: + +```bash +kill $VIEWER_PID 2>/dev/null +``` + +--- + +## Improving the skill + +This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback. + +### How to think about improvements + +1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great. + +2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens. + +3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach. + +4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel. + +This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need. + +### The iteration loop + +After improving the skill: + +1. Apply your improvements to the skill +2. Rerun all test cases into a new `iteration-/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration. +3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration +4. Wait for the user to review and tell you they're done +5. Read the new feedback, improve again, repeat + +Keep going until: +- The user says they're happy +- The feedback is all empty (everything looks good) +- You're not making meaningful progress + +--- + +## Advanced: Blind comparison + +For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won. + +This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient. + +--- + +## Description Optimization + +The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy. + +### Step 1: Generate trigger eval queries + +Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON: + +```json +[ + {"query": "the user prompt", "should_trigger": true}, + {"query": "another prompt", "should_trigger": false} +] +``` + +The queries must be realistic and something a Claude Code or Claude.ai user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them). + +Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"` + +Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"` + +For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win. + +For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate. + +The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky. + +### Step 2: Review with user + +Present the eval set to the user for review using the HTML template: + +1. Read the template from `assets/eval_review.html` +2. Replace the placeholders: + - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment) + - `__SKILL_NAME_PLACEHOLDER__` → the skill's name + - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description +3. Write to a temp file (e.g., `/tmp/eval_review_.html`) and open it: `open /tmp/eval_review_.html` +4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set" +5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`) + +This step matters — bad eval queries lead to bad descriptions. + +### Step 3: Run the optimization loop + +Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically." + +Save the eval set to the workspace, then run in the background: + +```bash +python -m scripts.run_loop \ + --eval-set \ + --skill-path \ + --model \ + --max-iterations 5 \ + --verbose +``` + +Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences. + +While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like. + +This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting. + +### How skill triggering works + +Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches. + +This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality. + +### Step 4: Apply the result + +Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores. + +--- + +### Package and Present (only if `present_files` tool is available) + +Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user: + +```bash +python -m scripts.package_skill +``` + +After packaging, direct the user to the resulting `.skill` file path so they can install it. + +--- + +## Claude.ai-specific instructions + +In Claude.ai, the core workflow is the same (draft → test → review → improve → repeat), but because Claude.ai doesn't have subagents, some mechanics change. Here's what to adapt: + +**Running test cases**: No subagents means no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested. + +**Reviewing results**: If you can't open a browser (e.g., Claude.ai's VM has no display, or you're on a remote server), skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?" + +**Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user. + +**The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one. + +**Description optimization**: This section requires the `claude` CLI tool (specifically `claude -p`) which is only available in Claude Code. Skip it if you're on Claude.ai. + +**Blind comparison**: Requires subagents. Skip it. + +**Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. On Claude.ai, you can run it and the user can download the resulting `.skill` file. + +**Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case: +- **Preserve the original name.** Note the skill's directory name and `name` frontmatter field -- use them unchanged. E.g., if the installed skill is `research-helper`, output `research-helper.skill` (not `research-helper-v2`). +- **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to `/tmp/skill-name/`, edit there, and package from the copy. +- **If packaging manually, stage in `/tmp/` first**, then copy to the output directory -- direct writes may fail due to permissions. + +--- + +## Cowork-Specific Instructions + +If you're in Cowork, the main things to know are: + +- You have subagents, so the main workflow (spawn test cases in parallel, run baselines, grade, etc.) all works. (However, if you run into severe problems with timeouts, it's OK to run the test prompts in series rather than parallel.) +- You don't have a browser or display, so when generating the eval viewer, use `--static ` to write a standalone HTML file instead of starting a server. Then proffer a link that the user can click to open the HTML in their browser. +- For whatever reason, the Cowork setup seems to disincline Claude from generating the eval viewer after running the tests, so just to reiterate: whether you're in Cowork or in Claude Code, after running tests, you should always generate the eval viewer for the human to look at examples before revising the skill yourself and trying to make corrections, using `generate_review.py` (not writing your own boutique html code). Sorry in advance but I'm gonna go all caps here: GENERATE THE EVAL VIEWER *BEFORE* evaluating inputs yourself. You want to get them in front of the human ASAP! +- Feedback works differently: since there's no running server, the viewer's "Submit All Reviews" button will download `feedback.json` as a file. You can then read it from there (you may have to request access first). +- Packaging works — `package_skill.py` just needs Python and a filesystem. +- Description optimization (`run_loop.py` / `run_eval.py`) should work in Cowork just fine since it uses `claude -p` via subprocess, not a browser, but please save it until you've fully finished making the skill and the user agrees it's in good shape. +- **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. Follow the update guidance in the claude.ai section above. + +--- + +## Reference files + +The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent. + +- `agents/grader.md` — How to evaluate assertions against outputs +- `agents/comparator.md` — How to do blind A/B comparison between two outputs +- `agents/analyzer.md` — How to analyze why one version beat another + +The references/ directory has additional documentation: +- `references/schemas.md` — JSON structures for evals.json, grading.json, etc. + +--- + +Repeating one more time the core loop here for emphasis: + +- Figure out what the skill is about +- Draft or edit the skill +- Run claude-with-access-to-the-skill on test prompts +- With the user, evaluate the outputs: + - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them + - Run quantitative evals +- Repeat until you and the user are satisfied +- Package the final skill and return it to the user. + +Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens. + +Good luck! diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/agents/analyzer.md b/1-Vue3-Dev/.agents/skills/skill-creator/agents/analyzer.md new file mode 100644 index 0000000..14e41d6 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/agents/analyzer.md @@ -0,0 +1,274 @@ +# Post-hoc Analyzer Agent + +Analyze blind comparison results to understand WHY the winner won and generate improvement suggestions. + +## Role + +After the blind comparator determines a winner, the Post-hoc Analyzer "unblids" the results by examining the skills and transcripts. The goal is to extract actionable insights: what made the winner better, and how can the loser be improved? + +## Inputs + +You receive these parameters in your prompt: + +- **winner**: "A" or "B" (from blind comparison) +- **winner_skill_path**: Path to the skill that produced the winning output +- **winner_transcript_path**: Path to the execution transcript for the winner +- **loser_skill_path**: Path to the skill that produced the losing output +- **loser_transcript_path**: Path to the execution transcript for the loser +- **comparison_result_path**: Path to the blind comparator's output JSON +- **output_path**: Where to save the analysis results + +## Process + +### Step 1: Read Comparison Result + +1. Read the blind comparator's output at comparison_result_path +2. Note the winning side (A or B), the reasoning, and any scores +3. Understand what the comparator valued in the winning output + +### Step 2: Read Both Skills + +1. Read the winner skill's SKILL.md and key referenced files +2. Read the loser skill's SKILL.md and key referenced files +3. Identify structural differences: + - Instructions clarity and specificity + - Script/tool usage patterns + - Example coverage + - Edge case handling + +### Step 3: Read Both Transcripts + +1. Read the winner's transcript +2. Read the loser's transcript +3. Compare execution patterns: + - How closely did each follow their skill's instructions? + - What tools were used differently? + - Where did the loser diverge from optimal behavior? + - Did either encounter errors or make recovery attempts? + +### Step 4: Analyze Instruction Following + +For each transcript, evaluate: +- Did the agent follow the skill's explicit instructions? +- Did the agent use the skill's provided tools/scripts? +- Were there missed opportunities to leverage skill content? +- Did the agent add unnecessary steps not in the skill? + +Score instruction following 1-10 and note specific issues. + +### Step 5: Identify Winner Strengths + +Determine what made the winner better: +- Clearer instructions that led to better behavior? +- Better scripts/tools that produced better output? +- More comprehensive examples that guided edge cases? +- Better error handling guidance? + +Be specific. Quote from skills/transcripts where relevant. + +### Step 6: Identify Loser Weaknesses + +Determine what held the loser back: +- Ambiguous instructions that led to suboptimal choices? +- Missing tools/scripts that forced workarounds? +- Gaps in edge case coverage? +- Poor error handling that caused failures? + +### Step 7: Generate Improvement Suggestions + +Based on the analysis, produce actionable suggestions for improving the loser skill: +- Specific instruction changes to make +- Tools/scripts to add or modify +- Examples to include +- Edge cases to address + +Prioritize by impact. Focus on changes that would have changed the outcome. + +### Step 8: Write Analysis Results + +Save structured analysis to `{output_path}`. + +## Output Format + +Write a JSON file with this structure: + +```json +{ + "comparison_summary": { + "winner": "A", + "winner_skill": "path/to/winner/skill", + "loser_skill": "path/to/loser/skill", + "comparator_reasoning": "Brief summary of why comparator chose winner" + }, + "winner_strengths": [ + "Clear step-by-step instructions for handling multi-page documents", + "Included validation script that caught formatting errors", + "Explicit guidance on fallback behavior when OCR fails" + ], + "loser_weaknesses": [ + "Vague instruction 'process the document appropriately' led to inconsistent behavior", + "No script for validation, agent had to improvise and made errors", + "No guidance on OCR failure, agent gave up instead of trying alternatives" + ], + "instruction_following": { + "winner": { + "score": 9, + "issues": [ + "Minor: skipped optional logging step" + ] + }, + "loser": { + "score": 6, + "issues": [ + "Did not use the skill's formatting template", + "Invented own approach instead of following step 3", + "Missed the 'always validate output' instruction" + ] + } + }, + "improvement_suggestions": [ + { + "priority": "high", + "category": "instructions", + "suggestion": "Replace 'process the document appropriately' with explicit steps: 1) Extract text, 2) Identify sections, 3) Format per template", + "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior" + }, + { + "priority": "high", + "category": "tools", + "suggestion": "Add validate_output.py script similar to winner skill's validation approach", + "expected_impact": "Would catch formatting errors before final output" + }, + { + "priority": "medium", + "category": "error_handling", + "suggestion": "Add fallback instructions: 'If OCR fails, try: 1) different resolution, 2) image preprocessing, 3) manual extraction'", + "expected_impact": "Would prevent early failure on difficult documents" + } + ], + "transcript_insights": { + "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script -> Fixed 2 issues -> Produced output", + "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods -> No validation -> Output had errors" + } +} +``` + +## Guidelines + +- **Be specific**: Quote from skills and transcripts, don't just say "instructions were unclear" +- **Be actionable**: Suggestions should be concrete changes, not vague advice +- **Focus on skill improvements**: The goal is to improve the losing skill, not critique the agent +- **Prioritize by impact**: Which changes would most likely have changed the outcome? +- **Consider causation**: Did the skill weakness actually cause the worse output, or is it incidental? +- **Stay objective**: Analyze what happened, don't editorialize +- **Think about generalization**: Would this improvement help on other evals too? + +## Categories for Suggestions + +Use these categories to organize improvement suggestions: + +| Category | Description | +|----------|-------------| +| `instructions` | Changes to the skill's prose instructions | +| `tools` | Scripts, templates, or utilities to add/modify | +| `examples` | Example inputs/outputs to include | +| `error_handling` | Guidance for handling failures | +| `structure` | Reorganization of skill content | +| `references` | External docs or resources to add | + +## Priority Levels + +- **high**: Would likely change the outcome of this comparison +- **medium**: Would improve quality but may not change win/loss +- **low**: Nice to have, marginal improvement + +--- + +# Analyzing Benchmark Results + +When analyzing benchmark results, the analyzer's purpose is to **surface patterns and anomalies** across multiple runs, not suggest skill improvements. + +## Role + +Review all benchmark run results and generate freeform notes that help the user understand skill performance. Focus on patterns that wouldn't be visible from aggregate metrics alone. + +## Inputs + +You receive these parameters in your prompt: + +- **benchmark_data_path**: Path to the in-progress benchmark.json with all run results +- **skill_path**: Path to the skill being benchmarked +- **output_path**: Where to save the notes (as JSON array of strings) + +## Process + +### Step 1: Read Benchmark Data + +1. Read the benchmark.json containing all run results +2. Note the configurations tested (with_skill, without_skill) +3. Understand the run_summary aggregates already calculated + +### Step 2: Analyze Per-Assertion Patterns + +For each expectation across all runs: +- Does it **always pass** in both configurations? (may not differentiate skill value) +- Does it **always fail** in both configurations? (may be broken or beyond capability) +- Does it **always pass with skill but fail without**? (skill clearly adds value here) +- Does it **always fail with skill but pass without**? (skill may be hurting) +- Is it **highly variable**? (flaky expectation or non-deterministic behavior) + +### Step 3: Analyze Cross-Eval Patterns + +Look for patterns across evals: +- Are certain eval types consistently harder/easier? +- Do some evals show high variance while others are stable? +- Are there surprising results that contradict expectations? + +### Step 4: Analyze Metrics Patterns + +Look at time_seconds, tokens, tool_calls: +- Does the skill significantly increase execution time? +- Is there high variance in resource usage? +- Are there outlier runs that skew the aggregates? + +### Step 5: Generate Notes + +Write freeform observations as a list of strings. Each note should: +- State a specific observation +- Be grounded in the data (not speculation) +- Help the user understand something the aggregate metrics don't show + +Examples: +- "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value" +- "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure that may be flaky" +- "Without-skill runs consistently fail on table extraction expectations (0% pass rate)" +- "Skill adds 13s average execution time but improves pass rate by 50%" +- "Token usage is 80% higher with skill, primarily due to script output parsing" +- "All 3 without-skill runs for eval 1 produced empty output" + +### Step 6: Write Notes + +Save notes to `{output_path}` as a JSON array of strings: + +```json +[ + "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value", + "Eval 3 shows high variance (50% ± 40%) - run 2 had an unusual failure", + "Without-skill runs consistently fail on table extraction expectations", + "Skill adds 13s average execution time but improves pass rate by 50%" +] +``` + +## Guidelines + +**DO:** +- Report what you observe in the data +- Be specific about which evals, expectations, or runs you're referring to +- Note patterns that aggregate metrics would hide +- Provide context that helps interpret the numbers + +**DO NOT:** +- Suggest improvements to the skill (that's for the improvement step, not benchmarking) +- Make subjective quality judgments ("the output was good/bad") +- Speculate about causes without evidence +- Repeat information already in the run_summary aggregates diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/agents/comparator.md b/1-Vue3-Dev/.agents/skills/skill-creator/agents/comparator.md new file mode 100644 index 0000000..80e00eb --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/agents/comparator.md @@ -0,0 +1,202 @@ +# Blind Comparator Agent + +Compare two outputs WITHOUT knowing which skill produced them. + +## Role + +The Blind Comparator judges which output better accomplishes the eval task. You receive two outputs labeled A and B, but you do NOT know which skill produced which. This prevents bias toward a particular skill or approach. + +Your judgment is based purely on output quality and task completion. + +## Inputs + +You receive these parameters in your prompt: + +- **output_a_path**: Path to the first output file or directory +- **output_b_path**: Path to the second output file or directory +- **eval_prompt**: The original task/prompt that was executed +- **expectations**: List of expectations to check (optional - may be empty) + +## Process + +### Step 1: Read Both Outputs + +1. Examine output A (file or directory) +2. Examine output B (file or directory) +3. Note the type, structure, and content of each +4. If outputs are directories, examine all relevant files inside + +### Step 2: Understand the Task + +1. Read the eval_prompt carefully +2. Identify what the task requires: + - What should be produced? + - What qualities matter (accuracy, completeness, format)? + - What would distinguish a good output from a poor one? + +### Step 3: Generate Evaluation Rubric + +Based on the task, generate a rubric with two dimensions: + +**Content Rubric** (what the output contains): +| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) | +|-----------|----------|----------------|---------------| +| Correctness | Major errors | Minor errors | Fully correct | +| Completeness | Missing key elements | Mostly complete | All elements present | +| Accuracy | Significant inaccuracies | Minor inaccuracies | Accurate throughout | + +**Structure Rubric** (how the output is organized): +| Criterion | 1 (Poor) | 3 (Acceptable) | 5 (Excellent) | +|-----------|----------|----------------|---------------| +| Organization | Disorganized | Reasonably organized | Clear, logical structure | +| Formatting | Inconsistent/broken | Mostly consistent | Professional, polished | +| Usability | Difficult to use | Usable with effort | Easy to use | + +Adapt criteria to the specific task. For example: +- PDF form → "Field alignment", "Text readability", "Data placement" +- Document → "Section structure", "Heading hierarchy", "Paragraph flow" +- Data output → "Schema correctness", "Data types", "Completeness" + +### Step 4: Evaluate Each Output Against the Rubric + +For each output (A and B): + +1. **Score each criterion** on the rubric (1-5 scale) +2. **Calculate dimension totals**: Content score, Structure score +3. **Calculate overall score**: Average of dimension scores, scaled to 1-10 + +### Step 5: Check Assertions (if provided) + +If expectations are provided: + +1. Check each expectation against output A +2. Check each expectation against output B +3. Count pass rates for each output +4. Use expectation scores as secondary evidence (not the primary decision factor) + +### Step 6: Determine the Winner + +Compare A and B based on (in priority order): + +1. **Primary**: Overall rubric score (content + structure) +2. **Secondary**: Assertion pass rates (if applicable) +3. **Tiebreaker**: If truly equal, declare a TIE + +Be decisive - ties should be rare. One output is usually better, even if marginally. + +### Step 7: Write Comparison Results + +Save results to a JSON file at the path specified (or `comparison.json` if not specified). + +## Output Format + +Write a JSON file with this structure: + +```json +{ + "winner": "A", + "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.", + "rubric": { + "A": { + "content": { + "correctness": 5, + "completeness": 5, + "accuracy": 4 + }, + "structure": { + "organization": 4, + "formatting": 5, + "usability": 4 + }, + "content_score": 4.7, + "structure_score": 4.3, + "overall_score": 9.0 + }, + "B": { + "content": { + "correctness": 3, + "completeness": 2, + "accuracy": 3 + }, + "structure": { + "organization": 3, + "formatting": 2, + "usability": 3 + }, + "content_score": 2.7, + "structure_score": 2.7, + "overall_score": 5.4 + } + }, + "output_quality": { + "A": { + "score": 9, + "strengths": ["Complete solution", "Well-formatted", "All fields present"], + "weaknesses": ["Minor style inconsistency in header"] + }, + "B": { + "score": 5, + "strengths": ["Readable output", "Correct basic structure"], + "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"] + } + }, + "expectation_results": { + "A": { + "passed": 4, + "total": 5, + "pass_rate": 0.80, + "details": [ + {"text": "Output includes name", "passed": true}, + {"text": "Output includes date", "passed": true}, + {"text": "Format is PDF", "passed": true}, + {"text": "Contains signature", "passed": false}, + {"text": "Readable text", "passed": true} + ] + }, + "B": { + "passed": 3, + "total": 5, + "pass_rate": 0.60, + "details": [ + {"text": "Output includes name", "passed": true}, + {"text": "Output includes date", "passed": false}, + {"text": "Format is PDF", "passed": true}, + {"text": "Contains signature", "passed": false}, + {"text": "Readable text", "passed": true} + ] + } + } +} +``` + +If no expectations were provided, omit the `expectation_results` field entirely. + +## Field Descriptions + +- **winner**: "A", "B", or "TIE" +- **reasoning**: Clear explanation of why the winner was chosen (or why it's a tie) +- **rubric**: Structured rubric evaluation for each output + - **content**: Scores for content criteria (correctness, completeness, accuracy) + - **structure**: Scores for structure criteria (organization, formatting, usability) + - **content_score**: Average of content criteria (1-5) + - **structure_score**: Average of structure criteria (1-5) + - **overall_score**: Combined score scaled to 1-10 +- **output_quality**: Summary quality assessment + - **score**: 1-10 rating (should match rubric overall_score) + - **strengths**: List of positive aspects + - **weaknesses**: List of issues or shortcomings +- **expectation_results**: (Only if expectations provided) + - **passed**: Number of expectations that passed + - **total**: Total number of expectations + - **pass_rate**: Fraction passed (0.0 to 1.0) + - **details**: Individual expectation results + +## Guidelines + +- **Stay blind**: DO NOT try to infer which skill produced which output. Judge purely on output quality. +- **Be specific**: Cite specific examples when explaining strengths and weaknesses. +- **Be decisive**: Choose a winner unless outputs are genuinely equivalent. +- **Output quality first**: Assertion scores are secondary to overall task completion. +- **Be objective**: Don't favor outputs based on style preferences; focus on correctness and completeness. +- **Explain your reasoning**: The reasoning field should make it clear why you chose the winner. +- **Handle edge cases**: If both outputs fail, pick the one that fails less badly. If both are excellent, pick the one that's marginally better. diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/agents/grader.md b/1-Vue3-Dev/.agents/skills/skill-creator/agents/grader.md new file mode 100644 index 0000000..558ab05 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/agents/grader.md @@ -0,0 +1,223 @@ +# Grader Agent + +Evaluate expectations against an execution transcript and outputs. + +## Role + +The Grader reviews a transcript and output files, then determines whether each expectation passes or fails. Provide clear evidence for each judgment. + +You have two jobs: grade the outputs, and critique the evals themselves. A passing grade on a weak assertion is worse than useless — it creates false confidence. When you notice an assertion that's trivially satisfied, or an important outcome that no assertion checks, say so. + +## Inputs + +You receive these parameters in your prompt: + +- **expectations**: List of expectations to evaluate (strings) +- **transcript_path**: Path to the execution transcript (markdown file) +- **outputs_dir**: Directory containing output files from execution + +## Process + +### Step 1: Read the Transcript + +1. Read the transcript file completely +2. Note the eval prompt, execution steps, and final result +3. Identify any issues or errors documented + +### Step 2: Examine Output Files + +1. List files in outputs_dir +2. Read/examine each file relevant to the expectations. If outputs aren't plain text, use the inspection tools provided in your prompt — don't rely solely on what the transcript says the executor produced. +3. Note contents, structure, and quality + +### Step 3: Evaluate Each Assertion + +For each expectation: + +1. **Search for evidence** in the transcript and outputs +2. **Determine verdict**: + - **PASS**: Clear evidence the expectation is true AND the evidence reflects genuine task completion, not just surface-level compliance + - **FAIL**: No evidence, or evidence contradicts the expectation, or the evidence is superficial (e.g., correct filename but empty/wrong content) +3. **Cite the evidence**: Quote the specific text or describe what you found + +### Step 4: Extract and Verify Claims + +Beyond the predefined expectations, extract implicit claims from the outputs and verify them: + +1. **Extract claims** from the transcript and outputs: + - Factual statements ("The form has 12 fields") + - Process claims ("Used pypdf to fill the form") + - Quality claims ("All fields were filled correctly") + +2. **Verify each claim**: + - **Factual claims**: Can be checked against the outputs or external sources + - **Process claims**: Can be verified from the transcript + - **Quality claims**: Evaluate whether the claim is justified + +3. **Flag unverifiable claims**: Note claims that cannot be verified with available information + +This catches issues that predefined expectations might miss. + +### Step 5: Read User Notes + +If `{outputs_dir}/user_notes.md` exists: +1. Read it and note any uncertainties or issues flagged by the executor +2. Include relevant concerns in the grading output +3. These may reveal problems even when expectations pass + +### Step 6: Critique the Evals + +After grading, consider whether the evals themselves could be improved. Only surface suggestions when there's a clear gap. + +Good suggestions test meaningful outcomes — assertions that are hard to satisfy without actually doing the work correctly. Think about what makes an assertion *discriminating*: it passes when the skill genuinely succeeds and fails when it doesn't. + +Suggestions worth raising: +- An assertion that passed but would also pass for a clearly wrong output (e.g., checking filename existence but not file content) +- An important outcome you observed — good or bad — that no assertion covers at all +- An assertion that can't actually be verified from the available outputs + +Keep the bar high. The goal is to flag things the eval author would say "good catch" about, not to nitpick every assertion. + +### Step 7: Write Grading Results + +Save results to `{outputs_dir}/../grading.json` (sibling to outputs_dir). + +## Grading Criteria + +**PASS when**: +- The transcript or outputs clearly demonstrate the expectation is true +- Specific evidence can be cited +- The evidence reflects genuine substance, not just surface compliance (e.g., a file exists AND contains correct content, not just the right filename) + +**FAIL when**: +- No evidence found for the expectation +- Evidence contradicts the expectation +- The expectation cannot be verified from available information +- The evidence is superficial — the assertion is technically satisfied but the underlying task outcome is wrong or incomplete +- The output appears to meet the assertion by coincidence rather than by actually doing the work + +**When uncertain**: The burden of proof to pass is on the expectation. + +### Step 8: Read Executor Metrics and Timing + +1. If `{outputs_dir}/metrics.json` exists, read it and include in grading output +2. If `{outputs_dir}/../timing.json` exists, read it and include timing data + +## Output Format + +Write a JSON file with this structure: + +```json +{ + "expectations": [ + { + "text": "The output includes the name 'John Smith'", + "passed": true, + "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'" + }, + { + "text": "The spreadsheet has a SUM formula in cell B10", + "passed": false, + "evidence": "No spreadsheet was created. The output was a text file." + }, + { + "text": "The assistant used the skill's OCR script", + "passed": true, + "evidence": "Transcript Step 2 shows: 'Tool: Bash - python ocr_script.py image.png'" + } + ], + "summary": { + "passed": 2, + "failed": 1, + "total": 3, + "pass_rate": 0.67 + }, + "execution_metrics": { + "tool_calls": { + "Read": 5, + "Write": 2, + "Bash": 8 + }, + "total_tool_calls": 15, + "total_steps": 6, + "errors_encountered": 0, + "output_chars": 12450, + "transcript_chars": 3200 + }, + "timing": { + "executor_duration_seconds": 165.0, + "grader_duration_seconds": 26.0, + "total_duration_seconds": 191.0 + }, + "claims": [ + { + "claim": "The form has 12 fillable fields", + "type": "factual", + "verified": true, + "evidence": "Counted 12 fields in field_info.json" + }, + { + "claim": "All required fields were populated", + "type": "quality", + "verified": false, + "evidence": "Reference section was left blank despite data being available" + } + ], + "user_notes_summary": { + "uncertainties": ["Used 2023 data, may be stale"], + "needs_review": [], + "workarounds": ["Fell back to text overlay for non-fillable fields"] + }, + "eval_feedback": { + "suggestions": [ + { + "assertion": "The output includes the name 'John Smith'", + "reason": "A hallucinated document that mentions the name would also pass — consider checking it appears as the primary contact with matching phone and email from the input" + }, + { + "reason": "No assertion checks whether the extracted phone numbers match the input — I observed incorrect numbers in the output that went uncaught" + } + ], + "overall": "Assertions check presence but not correctness. Consider adding content verification." + } +} +``` + +## Field Descriptions + +- **expectations**: Array of graded expectations + - **text**: The original expectation text + - **passed**: Boolean - true if expectation passes + - **evidence**: Specific quote or description supporting the verdict +- **summary**: Aggregate statistics + - **passed**: Count of passed expectations + - **failed**: Count of failed expectations + - **total**: Total expectations evaluated + - **pass_rate**: Fraction passed (0.0 to 1.0) +- **execution_metrics**: Copied from executor's metrics.json (if available) + - **output_chars**: Total character count of output files (proxy for tokens) + - **transcript_chars**: Character count of transcript +- **timing**: Wall clock timing from timing.json (if available) + - **executor_duration_seconds**: Time spent in executor subagent + - **total_duration_seconds**: Total elapsed time for the run +- **claims**: Extracted and verified claims from the output + - **claim**: The statement being verified + - **type**: "factual", "process", or "quality" + - **verified**: Boolean - whether the claim holds + - **evidence**: Supporting or contradicting evidence +- **user_notes_summary**: Issues flagged by the executor + - **uncertainties**: Things the executor wasn't sure about + - **needs_review**: Items requiring human attention + - **workarounds**: Places where the skill didn't work as expected +- **eval_feedback**: Improvement suggestions for the evals (only when warranted) + - **suggestions**: List of concrete suggestions, each with a `reason` and optionally an `assertion` it relates to + - **overall**: Brief assessment — can be "No suggestions, evals look solid" if nothing to flag + +## Guidelines + +- **Be objective**: Base verdicts on evidence, not assumptions +- **Be specific**: Quote the exact text that supports your verdict +- **Be thorough**: Check both transcript and output files +- **Be consistent**: Apply the same standard to each expectation +- **Explain failures**: Make it clear why evidence was insufficient +- **No partial credit**: Each expectation is pass or fail, not partial diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/assets/eval_review.html b/1-Vue3-Dev/.agents/skills/skill-creator/assets/eval_review.html new file mode 100644 index 0000000..938ff32 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/assets/eval_review.html @@ -0,0 +1,146 @@ + + + + + + Eval Set Review - __SKILL_NAME_PLACEHOLDER__ + + + + + + +

Eval Set Review: __SKILL_NAME_PLACEHOLDER__

+

Current description: __SKILL_DESCRIPTION_PLACEHOLDER__

+ +
+ + +
+ + + + + + + + + + +
QueryShould TriggerActions
+ +

+ + + + diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/generate_review.py b/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/generate_review.py new file mode 100644 index 0000000..7fa5978 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/generate_review.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +"""Generate and serve a review page for eval results. + +Reads the workspace directory, discovers runs (directories with outputs/), +embeds all output data into a self-contained HTML page, and serves it via +a tiny HTTP server. Feedback auto-saves to feedback.json in the workspace. + +Usage: + python generate_review.py [--port PORT] [--skill-name NAME] + python generate_review.py --previous-feedback /path/to/old/feedback.json + +No dependencies beyond the Python stdlib are required. +""" + +import argparse +import base64 +import json +import mimetypes +import os +import re +import signal +import subprocess +import sys +import time +import webbrowser +from functools import partial +from http.server import HTTPServer, BaseHTTPRequestHandler +from pathlib import Path + +# Files to exclude from output listings +METADATA_FILES = {"transcript.md", "user_notes.md", "metrics.json"} + +# Extensions we render as inline text +TEXT_EXTENSIONS = { + ".txt", ".md", ".json", ".csv", ".py", ".js", ".ts", ".tsx", ".jsx", + ".yaml", ".yml", ".xml", ".html", ".css", ".sh", ".rb", ".go", ".rs", + ".java", ".c", ".cpp", ".h", ".hpp", ".sql", ".r", ".toml", +} + +# Extensions we render as inline images +IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"} + +# MIME type overrides for common types +MIME_OVERRIDES = { + ".svg": "image/svg+xml", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", +} + + +def get_mime_type(path: Path) -> str: + ext = path.suffix.lower() + if ext in MIME_OVERRIDES: + return MIME_OVERRIDES[ext] + mime, _ = mimetypes.guess_type(str(path)) + return mime or "application/octet-stream" + + +def find_runs(workspace: Path) -> list[dict]: + """Recursively find directories that contain an outputs/ subdirectory.""" + runs: list[dict] = [] + _find_runs_recursive(workspace, workspace, runs) + runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"])) + return runs + + +def _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None: + if not current.is_dir(): + return + + outputs_dir = current / "outputs" + if outputs_dir.is_dir(): + run = build_run(root, current) + if run: + runs.append(run) + return + + skip = {"node_modules", ".git", "__pycache__", "skill", "inputs"} + for child in sorted(current.iterdir()): + if child.is_dir() and child.name not in skip: + _find_runs_recursive(root, child, runs) + + +def build_run(root: Path, run_dir: Path) -> dict | None: + """Build a run dict with prompt, outputs, and grading data.""" + prompt = "" + eval_id = None + + # Try eval_metadata.json + for candidate in [run_dir / "eval_metadata.json", run_dir.parent / "eval_metadata.json"]: + if candidate.exists(): + try: + metadata = json.loads(candidate.read_text()) + prompt = metadata.get("prompt", "") + eval_id = metadata.get("eval_id") + except (json.JSONDecodeError, OSError): + pass + if prompt: + break + + # Fall back to transcript.md + if not prompt: + for candidate in [run_dir / "transcript.md", run_dir / "outputs" / "transcript.md"]: + if candidate.exists(): + try: + text = candidate.read_text() + match = re.search(r"## Eval Prompt\n\n([\s\S]*?)(?=\n##|$)", text) + if match: + prompt = match.group(1).strip() + except OSError: + pass + if prompt: + break + + if not prompt: + prompt = "(No prompt found)" + + run_id = str(run_dir.relative_to(root)).replace("/", "-").replace("\\", "-") + + # Collect output files + outputs_dir = run_dir / "outputs" + output_files: list[dict] = [] + if outputs_dir.is_dir(): + for f in sorted(outputs_dir.iterdir()): + if f.is_file() and f.name not in METADATA_FILES: + output_files.append(embed_file(f)) + + # Load grading if present + grading = None + for candidate in [run_dir / "grading.json", run_dir.parent / "grading.json"]: + if candidate.exists(): + try: + grading = json.loads(candidate.read_text()) + except (json.JSONDecodeError, OSError): + pass + if grading: + break + + return { + "id": run_id, + "prompt": prompt, + "eval_id": eval_id, + "outputs": output_files, + "grading": grading, + } + + +def embed_file(path: Path) -> dict: + """Read a file and return an embedded representation.""" + ext = path.suffix.lower() + mime = get_mime_type(path) + + if ext in TEXT_EXTENSIONS: + try: + content = path.read_text(errors="replace") + except OSError: + content = "(Error reading file)" + return { + "name": path.name, + "type": "text", + "content": content, + } + elif ext in IMAGE_EXTENSIONS: + try: + raw = path.read_bytes() + b64 = base64.b64encode(raw).decode("ascii") + except OSError: + return {"name": path.name, "type": "error", "content": "(Error reading file)"} + return { + "name": path.name, + "type": "image", + "mime": mime, + "data_uri": f"data:{mime};base64,{b64}", + } + elif ext == ".pdf": + try: + raw = path.read_bytes() + b64 = base64.b64encode(raw).decode("ascii") + except OSError: + return {"name": path.name, "type": "error", "content": "(Error reading file)"} + return { + "name": path.name, + "type": "pdf", + "data_uri": f"data:{mime};base64,{b64}", + } + elif ext == ".xlsx": + try: + raw = path.read_bytes() + b64 = base64.b64encode(raw).decode("ascii") + except OSError: + return {"name": path.name, "type": "error", "content": "(Error reading file)"} + return { + "name": path.name, + "type": "xlsx", + "data_b64": b64, + } + else: + # Binary / unknown — base64 download link + try: + raw = path.read_bytes() + b64 = base64.b64encode(raw).decode("ascii") + except OSError: + return {"name": path.name, "type": "error", "content": "(Error reading file)"} + return { + "name": path.name, + "type": "binary", + "mime": mime, + "data_uri": f"data:{mime};base64,{b64}", + } + + +def load_previous_iteration(workspace: Path) -> dict[str, dict]: + """Load previous iteration's feedback and outputs. + + Returns a map of run_id -> {"feedback": str, "outputs": list[dict]}. + """ + result: dict[str, dict] = {} + + # Load feedback + feedback_map: dict[str, str] = {} + feedback_path = workspace / "feedback.json" + if feedback_path.exists(): + try: + data = json.loads(feedback_path.read_text()) + feedback_map = { + r["run_id"]: r["feedback"] + for r in data.get("reviews", []) + if r.get("feedback", "").strip() + } + except (json.JSONDecodeError, OSError, KeyError): + pass + + # Load runs (to get outputs) + prev_runs = find_runs(workspace) + for run in prev_runs: + result[run["id"]] = { + "feedback": feedback_map.get(run["id"], ""), + "outputs": run.get("outputs", []), + } + + # Also add feedback for run_ids that had feedback but no matching run + for run_id, fb in feedback_map.items(): + if run_id not in result: + result[run_id] = {"feedback": fb, "outputs": []} + + return result + + +def generate_html( + runs: list[dict], + skill_name: str, + previous: dict[str, dict] | None = None, + benchmark: dict | None = None, +) -> str: + """Generate the complete standalone HTML page with embedded data.""" + template_path = Path(__file__).parent / "viewer.html" + template = template_path.read_text() + + # Build previous_feedback and previous_outputs maps for the template + previous_feedback: dict[str, str] = {} + previous_outputs: dict[str, list[dict]] = {} + if previous: + for run_id, data in previous.items(): + if data.get("feedback"): + previous_feedback[run_id] = data["feedback"] + if data.get("outputs"): + previous_outputs[run_id] = data["outputs"] + + embedded = { + "skill_name": skill_name, + "runs": runs, + "previous_feedback": previous_feedback, + "previous_outputs": previous_outputs, + } + if benchmark: + embedded["benchmark"] = benchmark + + data_json = json.dumps(embedded) + + return template.replace("/*__EMBEDDED_DATA__*/", f"const EMBEDDED_DATA = {data_json};") + + +# --------------------------------------------------------------------------- +# HTTP server (stdlib only, zero dependencies) +# --------------------------------------------------------------------------- + +def _kill_port(port: int) -> None: + """Kill any process listening on the given port.""" + try: + result = subprocess.run( + ["lsof", "-ti", f":{port}"], + capture_output=True, text=True, timeout=5, + ) + for pid_str in result.stdout.strip().split("\n"): + if pid_str.strip(): + try: + os.kill(int(pid_str.strip()), signal.SIGTERM) + except (ProcessLookupError, ValueError): + pass + if result.stdout.strip(): + time.sleep(0.5) + except subprocess.TimeoutExpired: + pass + except FileNotFoundError: + print("Note: lsof not found, cannot check if port is in use", file=sys.stderr) + +class ReviewHandler(BaseHTTPRequestHandler): + """Serves the review HTML and handles feedback saves. + + Regenerates the HTML on each page load so that refreshing the browser + picks up new eval outputs without restarting the server. + """ + + def __init__( + self, + workspace: Path, + skill_name: str, + feedback_path: Path, + previous: dict[str, dict], + benchmark_path: Path | None, + *args, + **kwargs, + ): + self.workspace = workspace + self.skill_name = skill_name + self.feedback_path = feedback_path + self.previous = previous + self.benchmark_path = benchmark_path + super().__init__(*args, **kwargs) + + def do_GET(self) -> None: + if self.path == "/" or self.path == "/index.html": + # Regenerate HTML on each request (re-scans workspace for new outputs) + runs = find_runs(self.workspace) + benchmark = None + if self.benchmark_path and self.benchmark_path.exists(): + try: + benchmark = json.loads(self.benchmark_path.read_text()) + except (json.JSONDecodeError, OSError): + pass + html = generate_html(runs, self.skill_name, self.previous, benchmark) + content = html.encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + elif self.path == "/api/feedback": + data = b"{}" + if self.feedback_path.exists(): + data = self.feedback_path.read_bytes() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + else: + self.send_error(404) + + def do_POST(self) -> None: + if self.path == "/api/feedback": + length = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(length) + try: + data = json.loads(body) + if not isinstance(data, dict) or "reviews" not in data: + raise ValueError("Expected JSON object with 'reviews' key") + self.feedback_path.write_text(json.dumps(data, indent=2) + "\n") + resp = b'{"ok":true}' + self.send_response(200) + except (json.JSONDecodeError, OSError, ValueError) as e: + resp = json.dumps({"error": str(e)}).encode() + self.send_response(500) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(resp))) + self.end_headers() + self.wfile.write(resp) + else: + self.send_error(404) + + def log_message(self, format: str, *args: object) -> None: + # Suppress request logging to keep terminal clean + pass + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate and serve eval review") + parser.add_argument("workspace", type=Path, help="Path to workspace directory") + parser.add_argument("--port", "-p", type=int, default=3117, help="Server port (default: 3117)") + parser.add_argument("--skill-name", "-n", type=str, default=None, help="Skill name for header") + parser.add_argument( + "--previous-workspace", type=Path, default=None, + help="Path to previous iteration's workspace (shows old outputs and feedback as context)", + ) + parser.add_argument( + "--benchmark", type=Path, default=None, + help="Path to benchmark.json to show in the Benchmark tab", + ) + parser.add_argument( + "--static", "-s", type=Path, default=None, + help="Write standalone HTML to this path instead of starting a server", + ) + args = parser.parse_args() + + workspace = args.workspace.resolve() + if not workspace.is_dir(): + print(f"Error: {workspace} is not a directory", file=sys.stderr) + sys.exit(1) + + runs = find_runs(workspace) + if not runs: + print(f"No runs found in {workspace}", file=sys.stderr) + sys.exit(1) + + skill_name = args.skill_name or workspace.name.replace("-workspace", "") + feedback_path = workspace / "feedback.json" + + previous: dict[str, dict] = {} + if args.previous_workspace: + previous = load_previous_iteration(args.previous_workspace.resolve()) + + benchmark_path = args.benchmark.resolve() if args.benchmark else None + benchmark = None + if benchmark_path and benchmark_path.exists(): + try: + benchmark = json.loads(benchmark_path.read_text()) + except (json.JSONDecodeError, OSError): + pass + + if args.static: + html = generate_html(runs, skill_name, previous, benchmark) + args.static.parent.mkdir(parents=True, exist_ok=True) + args.static.write_text(html) + print(f"\n Static viewer written to: {args.static}\n") + sys.exit(0) + + # Kill any existing process on the target port + port = args.port + _kill_port(port) + handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path) + try: + server = HTTPServer(("127.0.0.1", port), handler) + except OSError: + # Port still in use after kill attempt — find a free one + server = HTTPServer(("127.0.0.1", 0), handler) + port = server.server_address[1] + + url = f"http://localhost:{port}" + print(f"\n Eval Viewer") + print(f" ─────────────────────────────────") + print(f" URL: {url}") + print(f" Workspace: {workspace}") + print(f" Feedback: {feedback_path}") + if previous: + print(f" Previous: {args.previous_workspace} ({len(previous)} runs)") + if benchmark_path: + print(f" Benchmark: {benchmark_path}") + print(f"\n Press Ctrl+C to stop.\n") + + webbrowser.open(url) + + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nStopped.") + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/viewer.html b/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/viewer.html new file mode 100644 index 0000000..6d8e963 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/eval-viewer/viewer.html @@ -0,0 +1,1325 @@ + + + + + + Eval Review + + + + + + + +
+
+
+

Eval Review:

+
Review each output and leave feedback below. Navigate with arrow keys or buttons. When done, copy feedback and paste into Claude Code.
+
+
+
+ + + + + +
+
+ +
+
Prompt
+
+
+
+
+ + +
+
Output
+
+
No output files found
+
+
+ + + + + + + + +
+
Your Feedback
+
+ + + +
+
+
+ + +
+ + +
+
+
No benchmark data available. Run a benchmark to see quantitative results here.
+
+
+
+ + +
+
+

Review Complete

+

Your feedback has been saved. Go back to your Claude Code session and tell Claude you're done reviewing.

+
+ +
+
+
+ + +
+ + + + diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/references/schemas.md b/1-Vue3-Dev/.agents/skills/skill-creator/references/schemas.md new file mode 100644 index 0000000..b6eeaa2 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/references/schemas.md @@ -0,0 +1,430 @@ +# JSON Schemas + +This document defines the JSON schemas used by skill-creator. + +--- + +## evals.json + +Defines the evals for a skill. Located at `evals/evals.json` within the skill directory. + +```json +{ + "skill_name": "example-skill", + "evals": [ + { + "id": 1, + "prompt": "User's example prompt", + "expected_output": "Description of expected result", + "files": ["evals/files/sample1.pdf"], + "expectations": [ + "The output includes X", + "The skill used script Y" + ] + } + ] +} +``` + +**Fields:** +- `skill_name`: Name matching the skill's frontmatter +- `evals[].id`: Unique integer identifier +- `evals[].prompt`: The task to execute +- `evals[].expected_output`: Human-readable description of success +- `evals[].files`: Optional list of input file paths (relative to skill root) +- `evals[].expectations`: List of verifiable statements + +--- + +## history.json + +Tracks version progression in Improve mode. Located at workspace root. + +```json +{ + "started_at": "2026-01-15T10:30:00Z", + "skill_name": "pdf", + "current_best": "v2", + "iterations": [ + { + "version": "v0", + "parent": null, + "expectation_pass_rate": 0.65, + "grading_result": "baseline", + "is_current_best": false + }, + { + "version": "v1", + "parent": "v0", + "expectation_pass_rate": 0.75, + "grading_result": "won", + "is_current_best": false + }, + { + "version": "v2", + "parent": "v1", + "expectation_pass_rate": 0.85, + "grading_result": "won", + "is_current_best": true + } + ] +} +``` + +**Fields:** +- `started_at`: ISO timestamp of when improvement started +- `skill_name`: Name of the skill being improved +- `current_best`: Version identifier of the best performer +- `iterations[].version`: Version identifier (v0, v1, ...) +- `iterations[].parent`: Parent version this was derived from +- `iterations[].expectation_pass_rate`: Pass rate from grading +- `iterations[].grading_result`: "baseline", "won", "lost", or "tie" +- `iterations[].is_current_best`: Whether this is the current best version + +--- + +## grading.json + +Output from the grader agent. Located at `/grading.json`. + +```json +{ + "expectations": [ + { + "text": "The output includes the name 'John Smith'", + "passed": true, + "evidence": "Found in transcript Step 3: 'Extracted names: John Smith, Sarah Johnson'" + }, + { + "text": "The spreadsheet has a SUM formula in cell B10", + "passed": false, + "evidence": "No spreadsheet was created. The output was a text file." + } + ], + "summary": { + "passed": 2, + "failed": 1, + "total": 3, + "pass_rate": 0.67 + }, + "execution_metrics": { + "tool_calls": { + "Read": 5, + "Write": 2, + "Bash": 8 + }, + "total_tool_calls": 15, + "total_steps": 6, + "errors_encountered": 0, + "output_chars": 12450, + "transcript_chars": 3200 + }, + "timing": { + "executor_duration_seconds": 165.0, + "grader_duration_seconds": 26.0, + "total_duration_seconds": 191.0 + }, + "claims": [ + { + "claim": "The form has 12 fillable fields", + "type": "factual", + "verified": true, + "evidence": "Counted 12 fields in field_info.json" + } + ], + "user_notes_summary": { + "uncertainties": ["Used 2023 data, may be stale"], + "needs_review": [], + "workarounds": ["Fell back to text overlay for non-fillable fields"] + }, + "eval_feedback": { + "suggestions": [ + { + "assertion": "The output includes the name 'John Smith'", + "reason": "A hallucinated document that mentions the name would also pass" + } + ], + "overall": "Assertions check presence but not correctness." + } +} +``` + +**Fields:** +- `expectations[]`: Graded expectations with evidence +- `summary`: Aggregate pass/fail counts +- `execution_metrics`: Tool usage and output size (from executor's metrics.json) +- `timing`: Wall clock timing (from timing.json) +- `claims`: Extracted and verified claims from the output +- `user_notes_summary`: Issues flagged by the executor +- `eval_feedback`: (optional) Improvement suggestions for the evals, only present when the grader identifies issues worth raising + +--- + +## metrics.json + +Output from the executor agent. Located at `/outputs/metrics.json`. + +```json +{ + "tool_calls": { + "Read": 5, + "Write": 2, + "Bash": 8, + "Edit": 1, + "Glob": 2, + "Grep": 0 + }, + "total_tool_calls": 18, + "total_steps": 6, + "files_created": ["filled_form.pdf", "field_values.json"], + "errors_encountered": 0, + "output_chars": 12450, + "transcript_chars": 3200 +} +``` + +**Fields:** +- `tool_calls`: Count per tool type +- `total_tool_calls`: Sum of all tool calls +- `total_steps`: Number of major execution steps +- `files_created`: List of output files created +- `errors_encountered`: Number of errors during execution +- `output_chars`: Total character count of output files +- `transcript_chars`: Character count of transcript + +--- + +## timing.json + +Wall clock timing for a run. Located at `/timing.json`. + +**How to capture:** When a subagent task completes, the task notification includes `total_tokens` and `duration_ms`. Save these immediately — they are not persisted anywhere else and cannot be recovered after the fact. + +```json +{ + "total_tokens": 84852, + "duration_ms": 23332, + "total_duration_seconds": 23.3, + "executor_start": "2026-01-15T10:30:00Z", + "executor_end": "2026-01-15T10:32:45Z", + "executor_duration_seconds": 165.0, + "grader_start": "2026-01-15T10:32:46Z", + "grader_end": "2026-01-15T10:33:12Z", + "grader_duration_seconds": 26.0 +} +``` + +--- + +## benchmark.json + +Output from Benchmark mode. Located at `benchmarks//benchmark.json`. + +```json +{ + "metadata": { + "skill_name": "pdf", + "skill_path": "/path/to/pdf", + "executor_model": "claude-sonnet-4-20250514", + "analyzer_model": "most-capable-model", + "timestamp": "2026-01-15T10:30:00Z", + "evals_run": [1, 2, 3], + "runs_per_configuration": 3 + }, + + "runs": [ + { + "eval_id": 1, + "eval_name": "Ocean", + "configuration": "with_skill", + "run_number": 1, + "result": { + "pass_rate": 0.85, + "passed": 6, + "failed": 1, + "total": 7, + "time_seconds": 42.5, + "tokens": 3800, + "tool_calls": 18, + "errors": 0 + }, + "expectations": [ + {"text": "...", "passed": true, "evidence": "..."} + ], + "notes": [ + "Used 2023 data, may be stale", + "Fell back to text overlay for non-fillable fields" + ] + } + ], + + "run_summary": { + "with_skill": { + "pass_rate": {"mean": 0.85, "stddev": 0.05, "min": 0.80, "max": 0.90}, + "time_seconds": {"mean": 45.0, "stddev": 12.0, "min": 32.0, "max": 58.0}, + "tokens": {"mean": 3800, "stddev": 400, "min": 3200, "max": 4100} + }, + "without_skill": { + "pass_rate": {"mean": 0.35, "stddev": 0.08, "min": 0.28, "max": 0.45}, + "time_seconds": {"mean": 32.0, "stddev": 8.0, "min": 24.0, "max": 42.0}, + "tokens": {"mean": 2100, "stddev": 300, "min": 1800, "max": 2500} + }, + "delta": { + "pass_rate": "+0.50", + "time_seconds": "+13.0", + "tokens": "+1700" + } + }, + + "notes": [ + "Assertion 'Output is a PDF file' passes 100% in both configurations - may not differentiate skill value", + "Eval 3 shows high variance (50% ± 40%) - may be flaky or model-dependent", + "Without-skill runs consistently fail on table extraction expectations", + "Skill adds 13s average execution time but improves pass rate by 50%" + ] +} +``` + +**Fields:** +- `metadata`: Information about the benchmark run + - `skill_name`: Name of the skill + - `timestamp`: When the benchmark was run + - `evals_run`: List of eval names or IDs + - `runs_per_configuration`: Number of runs per config (e.g. 3) +- `runs[]`: Individual run results + - `eval_id`: Numeric eval identifier + - `eval_name`: Human-readable eval name (used as section header in the viewer) + - `configuration`: Must be `"with_skill"` or `"without_skill"` (the viewer uses this exact string for grouping and color coding) + - `run_number`: Integer run number (1, 2, 3...) + - `result`: Nested object with `pass_rate`, `passed`, `total`, `time_seconds`, `tokens`, `errors` +- `run_summary`: Statistical aggregates per configuration + - `with_skill` / `without_skill`: Each contains `pass_rate`, `time_seconds`, `tokens` objects with `mean` and `stddev` fields + - `delta`: Difference strings like `"+0.50"`, `"+13.0"`, `"+1700"` +- `notes`: Freeform observations from the analyzer + +**Important:** The viewer reads these field names exactly. Using `config` instead of `configuration`, or putting `pass_rate` at the top level of a run instead of nested under `result`, will cause the viewer to show empty/zero values. Always reference this schema when generating benchmark.json manually. + +--- + +## comparison.json + +Output from blind comparator. Located at `/comparison-N.json`. + +```json +{ + "winner": "A", + "reasoning": "Output A provides a complete solution with proper formatting and all required fields. Output B is missing the date field and has formatting inconsistencies.", + "rubric": { + "A": { + "content": { + "correctness": 5, + "completeness": 5, + "accuracy": 4 + }, + "structure": { + "organization": 4, + "formatting": 5, + "usability": 4 + }, + "content_score": 4.7, + "structure_score": 4.3, + "overall_score": 9.0 + }, + "B": { + "content": { + "correctness": 3, + "completeness": 2, + "accuracy": 3 + }, + "structure": { + "organization": 3, + "formatting": 2, + "usability": 3 + }, + "content_score": 2.7, + "structure_score": 2.7, + "overall_score": 5.4 + } + }, + "output_quality": { + "A": { + "score": 9, + "strengths": ["Complete solution", "Well-formatted", "All fields present"], + "weaknesses": ["Minor style inconsistency in header"] + }, + "B": { + "score": 5, + "strengths": ["Readable output", "Correct basic structure"], + "weaknesses": ["Missing date field", "Formatting inconsistencies", "Partial data extraction"] + } + }, + "expectation_results": { + "A": { + "passed": 4, + "total": 5, + "pass_rate": 0.80, + "details": [ + {"text": "Output includes name", "passed": true} + ] + }, + "B": { + "passed": 3, + "total": 5, + "pass_rate": 0.60, + "details": [ + {"text": "Output includes name", "passed": true} + ] + } + } +} +``` + +--- + +## analysis.json + +Output from post-hoc analyzer. Located at `/analysis.json`. + +```json +{ + "comparison_summary": { + "winner": "A", + "winner_skill": "path/to/winner/skill", + "loser_skill": "path/to/loser/skill", + "comparator_reasoning": "Brief summary of why comparator chose winner" + }, + "winner_strengths": [ + "Clear step-by-step instructions for handling multi-page documents", + "Included validation script that caught formatting errors" + ], + "loser_weaknesses": [ + "Vague instruction 'process the document appropriately' led to inconsistent behavior", + "No script for validation, agent had to improvise" + ], + "instruction_following": { + "winner": { + "score": 9, + "issues": ["Minor: skipped optional logging step"] + }, + "loser": { + "score": 6, + "issues": [ + "Did not use the skill's formatting template", + "Invented own approach instead of following step 3" + ] + } + }, + "improvement_suggestions": [ + { + "priority": "high", + "category": "instructions", + "suggestion": "Replace 'process the document appropriately' with explicit steps", + "expected_impact": "Would eliminate ambiguity that caused inconsistent behavior" + } + ], + "transcript_insights": { + "winner_execution_pattern": "Read skill -> Followed 5-step process -> Used validation script", + "loser_execution_pattern": "Read skill -> Unclear on approach -> Tried 3 different methods" + } +} +``` diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/__init__.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/aggregate_benchmark.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/aggregate_benchmark.py new file mode 100644 index 0000000..3e66e8c --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/aggregate_benchmark.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python3 +""" +Aggregate individual run results into benchmark summary statistics. + +Reads grading.json files from run directories and produces: +- run_summary with mean, stddev, min, max for each metric +- delta between with_skill and without_skill configurations + +Usage: + python aggregate_benchmark.py + +Example: + python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/ + +The script supports two directory layouts: + + Workspace layout (from skill-creator iterations): + / + └── eval-N/ + ├── with_skill/ + │ ├── run-1/grading.json + │ └── run-2/grading.json + └── without_skill/ + ├── run-1/grading.json + └── run-2/grading.json + + Legacy layout (with runs/ subdirectory): + / + └── runs/ + └── eval-N/ + ├── with_skill/ + │ └── run-1/grading.json + └── without_skill/ + └── run-1/grading.json +""" + +import argparse +import json +import math +import sys +from datetime import datetime, timezone +from pathlib import Path + + +def calculate_stats(values: list[float]) -> dict: + """Calculate mean, stddev, min, max for a list of values.""" + if not values: + return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0} + + n = len(values) + mean = sum(values) / n + + if n > 1: + variance = sum((x - mean) ** 2 for x in values) / (n - 1) + stddev = math.sqrt(variance) + else: + stddev = 0.0 + + return { + "mean": round(mean, 4), + "stddev": round(stddev, 4), + "min": round(min(values), 4), + "max": round(max(values), 4) + } + + +def load_run_results(benchmark_dir: Path) -> dict: + """ + Load all run results from a benchmark directory. + + Returns dict keyed by config name (e.g. "with_skill"/"without_skill", + or "new_skill"/"old_skill"), each containing a list of run results. + """ + # Support both layouts: eval dirs directly under benchmark_dir, or under runs/ + runs_dir = benchmark_dir / "runs" + if runs_dir.exists(): + search_dir = runs_dir + elif list(benchmark_dir.glob("eval-*")): + search_dir = benchmark_dir + else: + print(f"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}") + return {} + + results: dict[str, list] = {} + + for eval_idx, eval_dir in enumerate(sorted(search_dir.glob("eval-*"))): + metadata_path = eval_dir / "eval_metadata.json" + if metadata_path.exists(): + try: + with open(metadata_path) as mf: + eval_id = json.load(mf).get("eval_id", eval_idx) + except (json.JSONDecodeError, OSError): + eval_id = eval_idx + else: + try: + eval_id = int(eval_dir.name.split("-")[1]) + except ValueError: + eval_id = eval_idx + + # Discover config directories dynamically rather than hardcoding names + for config_dir in sorted(eval_dir.iterdir()): + if not config_dir.is_dir(): + continue + # Skip non-config directories (inputs, outputs, etc.) + if not list(config_dir.glob("run-*")): + continue + config = config_dir.name + if config not in results: + results[config] = [] + + for run_dir in sorted(config_dir.glob("run-*")): + run_number = int(run_dir.name.split("-")[1]) + grading_file = run_dir / "grading.json" + + if not grading_file.exists(): + print(f"Warning: grading.json not found in {run_dir}") + continue + + try: + with open(grading_file) as f: + grading = json.load(f) + except json.JSONDecodeError as e: + print(f"Warning: Invalid JSON in {grading_file}: {e}") + continue + + # Extract metrics + result = { + "eval_id": eval_id, + "run_number": run_number, + "pass_rate": grading.get("summary", {}).get("pass_rate", 0.0), + "passed": grading.get("summary", {}).get("passed", 0), + "failed": grading.get("summary", {}).get("failed", 0), + "total": grading.get("summary", {}).get("total", 0), + } + + # Extract timing — check grading.json first, then sibling timing.json + timing = grading.get("timing", {}) + result["time_seconds"] = timing.get("total_duration_seconds", 0.0) + timing_file = run_dir / "timing.json" + if result["time_seconds"] == 0.0 and timing_file.exists(): + try: + with open(timing_file) as tf: + timing_data = json.load(tf) + result["time_seconds"] = timing_data.get("total_duration_seconds", 0.0) + result["tokens"] = timing_data.get("total_tokens", 0) + except json.JSONDecodeError: + pass + + # Extract metrics if available + metrics = grading.get("execution_metrics", {}) + result["tool_calls"] = metrics.get("total_tool_calls", 0) + if not result.get("tokens"): + result["tokens"] = metrics.get("output_chars", 0) + result["errors"] = metrics.get("errors_encountered", 0) + + # Extract expectations — viewer requires fields: text, passed, evidence + raw_expectations = grading.get("expectations", []) + for exp in raw_expectations: + if "text" not in exp or "passed" not in exp: + print(f"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}") + result["expectations"] = raw_expectations + + # Extract notes from user_notes_summary + notes_summary = grading.get("user_notes_summary", {}) + notes = [] + notes.extend(notes_summary.get("uncertainties", [])) + notes.extend(notes_summary.get("needs_review", [])) + notes.extend(notes_summary.get("workarounds", [])) + result["notes"] = notes + + results[config].append(result) + + return results + + +def aggregate_results(results: dict) -> dict: + """ + Aggregate run results into summary statistics. + + Returns run_summary with stats for each configuration and delta. + """ + run_summary = {} + configs = list(results.keys()) + + for config in configs: + runs = results.get(config, []) + + if not runs: + run_summary[config] = { + "pass_rate": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, + "time_seconds": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, + "tokens": {"mean": 0, "stddev": 0, "min": 0, "max": 0} + } + continue + + pass_rates = [r["pass_rate"] for r in runs] + times = [r["time_seconds"] for r in runs] + tokens = [r.get("tokens", 0) for r in runs] + + run_summary[config] = { + "pass_rate": calculate_stats(pass_rates), + "time_seconds": calculate_stats(times), + "tokens": calculate_stats(tokens) + } + + # Calculate delta between the first two configs (if two exist) + if len(configs) >= 2: + primary = run_summary.get(configs[0], {}) + baseline = run_summary.get(configs[1], {}) + else: + primary = run_summary.get(configs[0], {}) if configs else {} + baseline = {} + + delta_pass_rate = primary.get("pass_rate", {}).get("mean", 0) - baseline.get("pass_rate", {}).get("mean", 0) + delta_time = primary.get("time_seconds", {}).get("mean", 0) - baseline.get("time_seconds", {}).get("mean", 0) + delta_tokens = primary.get("tokens", {}).get("mean", 0) - baseline.get("tokens", {}).get("mean", 0) + + run_summary["delta"] = { + "pass_rate": f"{delta_pass_rate:+.2f}", + "time_seconds": f"{delta_time:+.1f}", + "tokens": f"{delta_tokens:+.0f}" + } + + return run_summary + + +def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict: + """ + Generate complete benchmark.json from run results. + """ + results = load_run_results(benchmark_dir) + run_summary = aggregate_results(results) + + # Build runs array for benchmark.json + runs = [] + for config in results: + for result in results[config]: + runs.append({ + "eval_id": result["eval_id"], + "configuration": config, + "run_number": result["run_number"], + "result": { + "pass_rate": result["pass_rate"], + "passed": result["passed"], + "failed": result["failed"], + "total": result["total"], + "time_seconds": result["time_seconds"], + "tokens": result.get("tokens", 0), + "tool_calls": result.get("tool_calls", 0), + "errors": result.get("errors", 0) + }, + "expectations": result["expectations"], + "notes": result["notes"] + }) + + # Determine eval IDs from results + eval_ids = sorted(set( + r["eval_id"] + for config in results.values() + for r in config + )) + + benchmark = { + "metadata": { + "skill_name": skill_name or "", + "skill_path": skill_path or "", + "executor_model": "", + "analyzer_model": "", + "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "evals_run": eval_ids, + "runs_per_configuration": 3 + }, + "runs": runs, + "run_summary": run_summary, + "notes": [] # To be filled by analyzer + } + + return benchmark + + +def generate_markdown(benchmark: dict) -> str: + """Generate human-readable benchmark.md from benchmark data.""" + metadata = benchmark["metadata"] + run_summary = benchmark["run_summary"] + + # Determine config names (excluding "delta") + configs = [k for k in run_summary if k != "delta"] + config_a = configs[0] if len(configs) >= 1 else "config_a" + config_b = configs[1] if len(configs) >= 2 else "config_b" + label_a = config_a.replace("_", " ").title() + label_b = config_b.replace("_", " ").title() + + lines = [ + f"# Skill Benchmark: {metadata['skill_name']}", + "", + f"**Model**: {metadata['executor_model']}", + f"**Date**: {metadata['timestamp']}", + f"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)", + "", + "## Summary", + "", + f"| Metric | {label_a} | {label_b} | Delta |", + "|--------|------------|---------------|-------|", + ] + + a_summary = run_summary.get(config_a, {}) + b_summary = run_summary.get(config_b, {}) + delta = run_summary.get("delta", {}) + + # Format pass rate + a_pr = a_summary.get("pass_rate", {}) + b_pr = b_summary.get("pass_rate", {}) + lines.append(f"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |") + + # Format time + a_time = a_summary.get("time_seconds", {}) + b_time = b_summary.get("time_seconds", {}) + lines.append(f"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |") + + # Format tokens + a_tokens = a_summary.get("tokens", {}) + b_tokens = b_summary.get("tokens", {}) + lines.append(f"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |") + + # Notes section + if benchmark.get("notes"): + lines.extend([ + "", + "## Notes", + "" + ]) + for note in benchmark["notes"]: + lines.append(f"- {note}") + + return "\n".join(lines) + + +def main(): + parser = argparse.ArgumentParser( + description="Aggregate benchmark run results into summary statistics" + ) + parser.add_argument( + "benchmark_dir", + type=Path, + help="Path to the benchmark directory" + ) + parser.add_argument( + "--skill-name", + default="", + help="Name of the skill being benchmarked" + ) + parser.add_argument( + "--skill-path", + default="", + help="Path to the skill being benchmarked" + ) + parser.add_argument( + "--output", "-o", + type=Path, + help="Output path for benchmark.json (default: /benchmark.json)" + ) + + args = parser.parse_args() + + if not args.benchmark_dir.exists(): + print(f"Directory not found: {args.benchmark_dir}") + sys.exit(1) + + # Generate benchmark + benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path) + + # Determine output paths + output_json = args.output or (args.benchmark_dir / "benchmark.json") + output_md = output_json.with_suffix(".md") + + # Write benchmark.json + with open(output_json, "w") as f: + json.dump(benchmark, f, indent=2) + print(f"Generated: {output_json}") + + # Write benchmark.md + markdown = generate_markdown(benchmark) + with open(output_md, "w") as f: + f.write(markdown) + print(f"Generated: {output_md}") + + # Print summary + run_summary = benchmark["run_summary"] + configs = [k for k in run_summary if k != "delta"] + delta = run_summary.get("delta", {}) + + print(f"\nSummary:") + for config in configs: + pr = run_summary[config]["pass_rate"]["mean"] + label = config.replace("_", " ").title() + print(f" {label}: {pr*100:.1f}% pass rate") + print(f" Delta: {delta.get('pass_rate', '—')}") + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/generate_report.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/generate_report.py new file mode 100644 index 0000000..959e30a --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/generate_report.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 +"""Generate an HTML report from run_loop.py output. + +Takes the JSON output from run_loop.py and generates a visual HTML report +showing each description attempt with check/x for each test case. +Distinguishes between train and test queries. +""" + +import argparse +import html +import json +import sys +from pathlib import Path + + +def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str: + """Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag.""" + history = data.get("history", []) + holdout = data.get("holdout", 0) + title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else "" + + # Get all unique queries from train and test sets, with should_trigger info + train_queries: list[dict] = [] + test_queries: list[dict] = [] + if history: + for r in history[0].get("train_results", history[0].get("results", [])): + train_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) + if history[0].get("test_results"): + for r in history[0].get("test_results", []): + test_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) + + refresh_tag = ' \n' if auto_refresh else "" + + html_parts = [""" + + + +""" + refresh_tag + """ """ + title_prefix + """Skill Description Optimization + + + + + + +

""" + title_prefix + """Skill Description Optimization

+
+ Optimizing your skill's description. This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The "Train" score shows performance on queries used to improve the description; the "Test" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill. +
+"""] + + # Summary section + best_test_score = data.get('best_test_score') + best_train_score = data.get('best_train_score') + html_parts.append(f""" +
+

Original: {html.escape(data.get('original_description', 'N/A'))}

+

Best: {html.escape(data.get('best_description', 'N/A'))}

+

Best Score: {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}

+

Iterations: {data.get('iterations_run', 0)} | Train: {data.get('train_size', '?')} | Test: {data.get('test_size', '?')}

+
+""") + + # Legend + html_parts.append(""" +
+ Query columns: + Should trigger + Should NOT trigger + Train + Test +
+""") + + # Table header + html_parts.append(""" +
+ + + + + + + +""") + + # Add column headers for train queries + for qinfo in train_queries: + polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" + html_parts.append(f' \n') + + # Add column headers for test queries (different color) + for qinfo in test_queries: + polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" + html_parts.append(f' \n') + + html_parts.append(""" + + +""") + + # Find best iteration for highlighting + if test_queries: + best_iter = max(history, key=lambda h: h.get("test_passed") or 0).get("iteration") + else: + best_iter = max(history, key=lambda h: h.get("train_passed", h.get("passed", 0))).get("iteration") + + # Add rows for each iteration + for h in history: + iteration = h.get("iteration", "?") + train_passed = h.get("train_passed", h.get("passed", 0)) + train_total = h.get("train_total", h.get("total", 0)) + test_passed = h.get("test_passed") + test_total = h.get("test_total") + description = h.get("description", "") + train_results = h.get("train_results", h.get("results", [])) + test_results = h.get("test_results", []) + + # Create lookups for results by query + train_by_query = {r["query"]: r for r in train_results} + test_by_query = {r["query"]: r for r in test_results} if test_results else {} + + # Compute aggregate correct/total runs across all retries + def aggregate_runs(results: list[dict]) -> tuple[int, int]: + correct = 0 + total = 0 + for r in results: + runs = r.get("runs", 0) + triggers = r.get("triggers", 0) + total += runs + if r.get("should_trigger", True): + correct += triggers + else: + correct += runs - triggers + return correct, total + + train_correct, train_runs = aggregate_runs(train_results) + test_correct, test_runs = aggregate_runs(test_results) + + # Determine score classes + def score_class(correct: int, total: int) -> str: + if total > 0: + ratio = correct / total + if ratio >= 0.8: + return "score-good" + elif ratio >= 0.5: + return "score-ok" + return "score-bad" + + train_class = score_class(train_correct, train_runs) + test_class = score_class(test_correct, test_runs) + + row_class = "best-row" if iteration == best_iter else "" + + html_parts.append(f""" + + + + +""") + + # Add result for each train query + for qinfo in train_queries: + r = train_by_query.get(qinfo["query"], {}) + did_pass = r.get("pass", False) + triggers = r.get("triggers", 0) + runs = r.get("runs", 0) + + icon = "✓" if did_pass else "✗" + css_class = "pass" if did_pass else "fail" + + html_parts.append(f' \n') + + # Add result for each test query (with different background) + for qinfo in test_queries: + r = test_by_query.get(qinfo["query"], {}) + did_pass = r.get("pass", False) + triggers = r.get("triggers", 0) + runs = r.get("runs", 0) + + icon = "✓" if did_pass else "✗" + css_class = "pass" if did_pass else "fail" + + html_parts.append(f' \n') + + html_parts.append(" \n") + + html_parts.append(""" +
IterTrainTestDescription{html.escape(qinfo["query"])}{html.escape(qinfo["query"])}
{iteration}{train_correct}/{train_runs}{test_correct}/{test_runs}{html.escape(description)}{icon}{triggers}/{runs}{icon}{triggers}/{runs}
+
+""") + + html_parts.append(""" + + +""") + + return "".join(html_parts) + + +def main(): + parser = argparse.ArgumentParser(description="Generate HTML report from run_loop output") + parser.add_argument("input", help="Path to JSON output from run_loop.py (or - for stdin)") + parser.add_argument("-o", "--output", default=None, help="Output HTML file (default: stdout)") + parser.add_argument("--skill-name", default="", help="Skill name to include in the report title") + args = parser.parse_args() + + if args.input == "-": + data = json.load(sys.stdin) + else: + data = json.loads(Path(args.input).read_text()) + + html_output = generate_html(data, skill_name=args.skill_name) + + if args.output: + Path(args.output).write_text(html_output) + print(f"Report written to {args.output}", file=sys.stderr) + else: + print(html_output) + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/improve_description.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/improve_description.py new file mode 100644 index 0000000..06bcec7 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/improve_description.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Improve a skill description based on eval results. + +Takes eval results (from run_eval.py) and generates an improved description +by calling `claude -p` as a subprocess (same auth pattern as run_eval.py — +uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed). +""" + +import argparse +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +from scripts.utils import parse_skill_md + + +def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str: + """Run `claude -p` with the prompt on stdin and return the text response. + + Prompt goes over stdin (not argv) because it embeds the full SKILL.md + body and can easily exceed comfortable argv length. + """ + cmd = ["claude", "-p", "--output-format", "text"] + if model: + cmd.extend(["--model", model]) + + # Remove CLAUDECODE env var to allow nesting claude -p inside a + # Claude Code session. The guard is for interactive terminal conflicts; + # programmatic subprocess usage is safe. Same pattern as run_eval.py. + env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} + + result = subprocess.run( + cmd, + input=prompt, + capture_output=True, + text=True, + env=env, + timeout=timeout, + ) + if result.returncode != 0: + raise RuntimeError( + f"claude -p exited {result.returncode}\nstderr: {result.stderr}" + ) + return result.stdout + + +def improve_description( + skill_name: str, + skill_content: str, + current_description: str, + eval_results: dict, + history: list[dict], + model: str, + test_results: dict | None = None, + log_dir: Path | None = None, + iteration: int | None = None, +) -> str: + """Call Claude to improve the description based on eval results.""" + failed_triggers = [ + r for r in eval_results["results"] + if r["should_trigger"] and not r["pass"] + ] + false_triggers = [ + r for r in eval_results["results"] + if not r["should_trigger"] and not r["pass"] + ] + + # Build scores summary + train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}" + if test_results: + test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}" + scores_summary = f"Train: {train_score}, Test: {test_score}" + else: + scores_summary = f"Train: {train_score}" + + prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples. + +The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones. + +Here's the current description: + +"{current_description}" + + +Current scores ({scores_summary}): + +""" + if failed_triggers: + prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n" + for r in failed_triggers: + prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' + prompt += "\n" + + if false_triggers: + prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n" + for r in false_triggers: + prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' + prompt += "\n" + + if history: + prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n" + for h in history: + train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}" + test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None + score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "") + prompt += f'\n' + prompt += f'Description: "{h["description"]}"\n' + if "results" in h: + prompt += "Train results:\n" + for r in h["results"]: + status = "PASS" if r["pass"] else "FAIL" + prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n' + if h.get("note"): + prompt += f'Note: {h["note"]}\n' + prompt += "\n\n" + + prompt += f""" + +Skill content (for context on what the skill does): + +{skill_content} + + +Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold: + +1. Avoid overfitting +2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description. + +Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it. + +Here are some tips that we've found to work well in writing these descriptions: +- The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does" +- The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works. +- The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable. +- If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings. + +I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end. + +Please respond with only the new description text in tags, nothing else.""" + + text = _call_claude(prompt, model) + + match = re.search(r"(.*?)", text, re.DOTALL) + description = match.group(1).strip().strip('"') if match else text.strip().strip('"') + + transcript: dict = { + "iteration": iteration, + "prompt": prompt, + "response": text, + "parsed_description": description, + "char_count": len(description), + "over_limit": len(description) > 1024, + } + + # Safety net: the prompt already states the 1024-char hard limit, but if + # the model blew past it anyway, make one fresh single-turn call that + # quotes the too-long version and asks for a shorter rewrite. (The old + # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we + # inline the prior output into the new prompt instead.) + if len(description) > 1024: + shorten_prompt = ( + f"{prompt}\n\n" + f"---\n\n" + f"A previous attempt produced this description, which at " + f"{len(description)} characters is over the 1024-character hard limit:\n\n" + f'"{description}"\n\n' + f"Rewrite it to be under 1024 characters while keeping the most " + f"important trigger words and intent coverage. Respond with only " + f"the new description in tags." + ) + shorten_text = _call_claude(shorten_prompt, model) + match = re.search(r"(.*?)", shorten_text, re.DOTALL) + shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"') + + transcript["rewrite_prompt"] = shorten_prompt + transcript["rewrite_response"] = shorten_text + transcript["rewrite_description"] = shortened + transcript["rewrite_char_count"] = len(shortened) + description = shortened + + transcript["final_description"] = description + + if log_dir: + log_dir.mkdir(parents=True, exist_ok=True) + log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json" + log_file.write_text(json.dumps(transcript, indent=2)) + + return description + + +def main(): + parser = argparse.ArgumentParser(description="Improve a skill description based on eval results") + parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)") + parser.add_argument("--skill-path", required=True, help="Path to skill directory") + parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)") + parser.add_argument("--model", required=True, help="Model for improvement") + parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr") + args = parser.parse_args() + + skill_path = Path(args.skill_path) + if not (skill_path / "SKILL.md").exists(): + print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) + sys.exit(1) + + eval_results = json.loads(Path(args.eval_results).read_text()) + history = [] + if args.history: + history = json.loads(Path(args.history).read_text()) + + name, _, content = parse_skill_md(skill_path) + current_description = eval_results["description"] + + if args.verbose: + print(f"Current: {current_description}", file=sys.stderr) + print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr) + + new_description = improve_description( + skill_name=name, + skill_content=content, + current_description=current_description, + eval_results=eval_results, + history=history, + model=args.model, + ) + + if args.verbose: + print(f"Improved: {new_description}", file=sys.stderr) + + # Output as JSON with both the new description and updated history + output = { + "description": new_description, + "history": history + [{ + "description": current_description, + "passed": eval_results["summary"]["passed"], + "failed": eval_results["summary"]["failed"], + "total": eval_results["summary"]["total"], + "results": eval_results["results"], + }], + } + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/package_skill.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/package_skill.py new file mode 100644 index 0000000..f48eac4 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/package_skill.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +""" +Skill Packager - Creates a distributable .skill file of a skill folder + +Usage: + python utils/package_skill.py [output-directory] + +Example: + python utils/package_skill.py skills/public/my-skill + python utils/package_skill.py skills/public/my-skill ./dist +""" + +import fnmatch +import sys +import zipfile +from pathlib import Path +from scripts.quick_validate import validate_skill + +# Patterns to exclude when packaging skills. +EXCLUDE_DIRS = {"__pycache__", "node_modules"} +EXCLUDE_GLOBS = {"*.pyc"} +EXCLUDE_FILES = {".DS_Store"} +# Directories excluded only at the skill root (not when nested deeper). +ROOT_EXCLUDE_DIRS = {"evals"} + + +def should_exclude(rel_path: Path) -> bool: + """Check if a path should be excluded from packaging.""" + parts = rel_path.parts + if any(part in EXCLUDE_DIRS for part in parts): + return True + # rel_path is relative to skill_path.parent, so parts[0] is the skill + # folder name and parts[1] (if present) is the first subdir. + if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS: + return True + name = rel_path.name + if name in EXCLUDE_FILES: + return True + return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS) + + +def package_skill(skill_path, output_dir=None): + """ + Package a skill folder into a .skill file. + + Args: + skill_path: Path to the skill folder + output_dir: Optional output directory for the .skill file (defaults to current directory) + + Returns: + Path to the created .skill file, or None if error + """ + skill_path = Path(skill_path).resolve() + + # Validate skill folder exists + if not skill_path.exists(): + print(f"❌ Error: Skill folder not found: {skill_path}") + return None + + if not skill_path.is_dir(): + print(f"❌ Error: Path is not a directory: {skill_path}") + return None + + # Validate SKILL.md exists + skill_md = skill_path / "SKILL.md" + if not skill_md.exists(): + print(f"❌ Error: SKILL.md not found in {skill_path}") + return None + + # Run validation before packaging + print("🔍 Validating skill...") + valid, message = validate_skill(skill_path) + if not valid: + print(f"❌ Validation failed: {message}") + print(" Please fix the validation errors before packaging.") + return None + print(f"✅ {message}\n") + + # Determine output location + skill_name = skill_path.name + if output_dir: + output_path = Path(output_dir).resolve() + output_path.mkdir(parents=True, exist_ok=True) + else: + output_path = Path.cwd() + + skill_filename = output_path / f"{skill_name}.skill" + + # Create the .skill file (zip format) + try: + with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: + # Walk through the skill directory, excluding build artifacts + for file_path in skill_path.rglob('*'): + if not file_path.is_file(): + continue + arcname = file_path.relative_to(skill_path.parent) + if should_exclude(arcname): + print(f" Skipped: {arcname}") + continue + zipf.write(file_path, arcname) + print(f" Added: {arcname}") + + print(f"\n✅ Successfully packaged skill to: {skill_filename}") + return skill_filename + + except Exception as e: + print(f"❌ Error creating .skill file: {e}") + return None + + +def main(): + if len(sys.argv) < 2: + print("Usage: python utils/package_skill.py [output-directory]") + print("\nExample:") + print(" python utils/package_skill.py skills/public/my-skill") + print(" python utils/package_skill.py skills/public/my-skill ./dist") + sys.exit(1) + + skill_path = sys.argv[1] + output_dir = sys.argv[2] if len(sys.argv) > 2 else None + + print(f"📦 Packaging skill: {skill_path}") + if output_dir: + print(f" Output directory: {output_dir}") + print() + + result = package_skill(skill_path, output_dir) + + if result: + sys.exit(0) + else: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/quick_validate.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/quick_validate.py new file mode 100644 index 0000000..ed8e1dd --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/quick_validate.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +""" +Quick validation script for skills - minimal version +""" + +import sys +import os +import re +import yaml +from pathlib import Path + +def validate_skill(skill_path): + """Basic validation of a skill""" + skill_path = Path(skill_path) + + # Check SKILL.md exists + skill_md = skill_path / 'SKILL.md' + if not skill_md.exists(): + return False, "SKILL.md not found" + + # Read and validate frontmatter + content = skill_md.read_text() + if not content.startswith('---'): + return False, "No YAML frontmatter found" + + # Extract frontmatter + match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL) + if not match: + return False, "Invalid frontmatter format" + + frontmatter_text = match.group(1) + + # Parse YAML frontmatter + try: + frontmatter = yaml.safe_load(frontmatter_text) + if not isinstance(frontmatter, dict): + return False, "Frontmatter must be a YAML dictionary" + except yaml.YAMLError as e: + return False, f"Invalid YAML in frontmatter: {e}" + + # Define allowed properties + ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata', 'compatibility'} + + # Check for unexpected properties (excluding nested keys under metadata) + unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES + if unexpected_keys: + return False, ( + f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. " + f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}" + ) + + # Check required fields + if 'name' not in frontmatter: + return False, "Missing 'name' in frontmatter" + if 'description' not in frontmatter: + return False, "Missing 'description' in frontmatter" + + # Extract name for validation + name = frontmatter.get('name', '') + if not isinstance(name, str): + return False, f"Name must be a string, got {type(name).__name__}" + name = name.strip() + if name: + # Check naming convention (kebab-case: lowercase with hyphens) + if not re.match(r'^[a-z0-9-]+$', name): + return False, f"Name '{name}' should be kebab-case (lowercase letters, digits, and hyphens only)" + if name.startswith('-') or name.endswith('-') or '--' in name: + return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens" + # Check name length (max 64 characters per spec) + if len(name) > 64: + return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters." + + # Extract and validate description + description = frontmatter.get('description', '') + if not isinstance(description, str): + return False, f"Description must be a string, got {type(description).__name__}" + description = description.strip() + if description: + # Check for angle brackets + if '<' in description or '>' in description: + return False, "Description cannot contain angle brackets (< or >)" + # Check description length (max 1024 characters per spec) + if len(description) > 1024: + return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters." + + # Validate compatibility field if present (optional) + compatibility = frontmatter.get('compatibility', '') + if compatibility: + if not isinstance(compatibility, str): + return False, f"Compatibility must be a string, got {type(compatibility).__name__}" + if len(compatibility) > 500: + return False, f"Compatibility is too long ({len(compatibility)} characters). Maximum is 500 characters." + + return True, "Skill is valid!" + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python quick_validate.py ") + sys.exit(1) + + valid, message = validate_skill(sys.argv[1]) + print(message) + sys.exit(0 if valid else 1) \ No newline at end of file diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_eval.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_eval.py new file mode 100644 index 0000000..e58c70b --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_eval.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +"""Run trigger evaluation for a skill description. + +Tests whether a skill's description causes Claude to trigger (read the skill) +for a set of queries. Outputs results as JSON. +""" + +import argparse +import json +import os +import select +import subprocess +import sys +import time +import uuid +from concurrent.futures import ProcessPoolExecutor, as_completed +from pathlib import Path + +from scripts.utils import parse_skill_md + + +def find_project_root() -> Path: + """Find the project root by walking up from cwd looking for .claude/. + + Mimics how Claude Code discovers its project root, so the command file + we create ends up where claude -p will look for it. + """ + current = Path.cwd() + for parent in [current, *current.parents]: + if (parent / ".claude").is_dir(): + return parent + return current + + +def run_single_query( + query: str, + skill_name: str, + skill_description: str, + timeout: int, + project_root: str, + model: str | None = None, +) -> bool: + """Run a single query and return whether the skill was triggered. + + Creates a command file in .claude/commands/ so it appears in Claude's + available_skills list, then runs `claude -p` with the raw query. + Uses --include-partial-messages to detect triggering early from + stream events (content_block_start) rather than waiting for the + full assistant message, which only arrives after tool execution. + """ + unique_id = uuid.uuid4().hex[:8] + clean_name = f"{skill_name}-skill-{unique_id}" + project_commands_dir = Path(project_root) / ".claude" / "commands" + command_file = project_commands_dir / f"{clean_name}.md" + + try: + project_commands_dir.mkdir(parents=True, exist_ok=True) + # Use YAML block scalar to avoid breaking on quotes in description + indented_desc = "\n ".join(skill_description.split("\n")) + command_content = ( + f"---\n" + f"description: |\n" + f" {indented_desc}\n" + f"---\n\n" + f"# {skill_name}\n\n" + f"This skill handles: {skill_description}\n" + ) + command_file.write_text(command_content) + + cmd = [ + "claude", + "-p", query, + "--output-format", "stream-json", + "--verbose", + "--include-partial-messages", + ] + if model: + cmd.extend(["--model", model]) + + # Remove CLAUDECODE env var to allow nesting claude -p inside a + # Claude Code session. The guard is for interactive terminal conflicts; + # programmatic subprocess usage is safe. + env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} + + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + cwd=project_root, + env=env, + ) + + triggered = False + start_time = time.time() + buffer = "" + # Track state for stream event detection + pending_tool_name = None + accumulated_json = "" + + try: + while time.time() - start_time < timeout: + if process.poll() is not None: + remaining = process.stdout.read() + if remaining: + buffer += remaining.decode("utf-8", errors="replace") + break + + ready, _, _ = select.select([process.stdout], [], [], 1.0) + if not ready: + continue + + chunk = os.read(process.stdout.fileno(), 8192) + if not chunk: + break + buffer += chunk.decode("utf-8", errors="replace") + + while "\n" in buffer: + line, buffer = buffer.split("\n", 1) + line = line.strip() + if not line: + continue + + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + + # Early detection via stream events + if event.get("type") == "stream_event": + se = event.get("event", {}) + se_type = se.get("type", "") + + if se_type == "content_block_start": + cb = se.get("content_block", {}) + if cb.get("type") == "tool_use": + tool_name = cb.get("name", "") + if tool_name in ("Skill", "Read"): + pending_tool_name = tool_name + accumulated_json = "" + else: + return False + + elif se_type == "content_block_delta" and pending_tool_name: + delta = se.get("delta", {}) + if delta.get("type") == "input_json_delta": + accumulated_json += delta.get("partial_json", "") + if clean_name in accumulated_json: + return True + + elif se_type in ("content_block_stop", "message_stop"): + if pending_tool_name: + return clean_name in accumulated_json + if se_type == "message_stop": + return False + + # Fallback: full assistant message + elif event.get("type") == "assistant": + message = event.get("message", {}) + for content_item in message.get("content", []): + if content_item.get("type") != "tool_use": + continue + tool_name = content_item.get("name", "") + tool_input = content_item.get("input", {}) + if tool_name == "Skill" and clean_name in tool_input.get("skill", ""): + triggered = True + elif tool_name == "Read" and clean_name in tool_input.get("file_path", ""): + triggered = True + return triggered + + elif event.get("type") == "result": + return triggered + finally: + # Clean up process on any exit path (return, exception, timeout) + if process.poll() is None: + process.kill() + process.wait() + + return triggered + finally: + if command_file.exists(): + command_file.unlink() + + +def run_eval( + eval_set: list[dict], + skill_name: str, + description: str, + num_workers: int, + timeout: int, + project_root: Path, + runs_per_query: int = 1, + trigger_threshold: float = 0.5, + model: str | None = None, +) -> dict: + """Run the full eval set and return results.""" + results = [] + + with ProcessPoolExecutor(max_workers=num_workers) as executor: + future_to_info = {} + for item in eval_set: + for run_idx in range(runs_per_query): + future = executor.submit( + run_single_query, + item["query"], + skill_name, + description, + timeout, + str(project_root), + model, + ) + future_to_info[future] = (item, run_idx) + + query_triggers: dict[str, list[bool]] = {} + query_items: dict[str, dict] = {} + for future in as_completed(future_to_info): + item, _ = future_to_info[future] + query = item["query"] + query_items[query] = item + if query not in query_triggers: + query_triggers[query] = [] + try: + query_triggers[query].append(future.result()) + except Exception as e: + print(f"Warning: query failed: {e}", file=sys.stderr) + query_triggers[query].append(False) + + for query, triggers in query_triggers.items(): + item = query_items[query] + trigger_rate = sum(triggers) / len(triggers) + should_trigger = item["should_trigger"] + if should_trigger: + did_pass = trigger_rate >= trigger_threshold + else: + did_pass = trigger_rate < trigger_threshold + results.append({ + "query": query, + "should_trigger": should_trigger, + "trigger_rate": trigger_rate, + "triggers": sum(triggers), + "runs": len(triggers), + "pass": did_pass, + }) + + passed = sum(1 for r in results if r["pass"]) + total = len(results) + + return { + "skill_name": skill_name, + "description": description, + "results": results, + "summary": { + "total": total, + "passed": passed, + "failed": total - passed, + }, + } + + +def main(): + parser = argparse.ArgumentParser(description="Run trigger evaluation for a skill description") + parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") + parser.add_argument("--skill-path", required=True, help="Path to skill directory") + parser.add_argument("--description", default=None, help="Override description to test") + parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") + parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") + parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") + parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") + parser.add_argument("--model", default=None, help="Model to use for claude -p (default: user's configured model)") + parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") + args = parser.parse_args() + + eval_set = json.loads(Path(args.eval_set).read_text()) + skill_path = Path(args.skill_path) + + if not (skill_path / "SKILL.md").exists(): + print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) + sys.exit(1) + + name, original_description, content = parse_skill_md(skill_path) + description = args.description or original_description + project_root = find_project_root() + + if args.verbose: + print(f"Evaluating: {description}", file=sys.stderr) + + output = run_eval( + eval_set=eval_set, + skill_name=name, + description=description, + num_workers=args.num_workers, + timeout=args.timeout, + project_root=project_root, + runs_per_query=args.runs_per_query, + trigger_threshold=args.trigger_threshold, + model=args.model, + ) + + if args.verbose: + summary = output["summary"] + print(f"Results: {summary['passed']}/{summary['total']} passed", file=sys.stderr) + for r in output["results"]: + status = "PASS" if r["pass"] else "FAIL" + rate_str = f"{r['triggers']}/{r['runs']}" + print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}", file=sys.stderr) + + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_loop.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_loop.py new file mode 100644 index 0000000..30a263d --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/run_loop.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Run the eval + improve loop until all pass or max iterations reached. + +Combines run_eval.py and improve_description.py in a loop, tracking history +and returning the best description found. Supports train/test split to prevent +overfitting. +""" + +import argparse +import json +import random +import sys +import tempfile +import time +import webbrowser +from pathlib import Path + +from scripts.generate_report import generate_html +from scripts.improve_description import improve_description +from scripts.run_eval import find_project_root, run_eval +from scripts.utils import parse_skill_md + + +def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]: + """Split eval set into train and test sets, stratified by should_trigger.""" + random.seed(seed) + + # Separate by should_trigger + trigger = [e for e in eval_set if e["should_trigger"]] + no_trigger = [e for e in eval_set if not e["should_trigger"]] + + # Shuffle each group + random.shuffle(trigger) + random.shuffle(no_trigger) + + # Calculate split points + n_trigger_test = max(1, int(len(trigger) * holdout)) + n_no_trigger_test = max(1, int(len(no_trigger) * holdout)) + + # Split + test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test] + train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:] + + return train_set, test_set + + +def run_loop( + eval_set: list[dict], + skill_path: Path, + description_override: str | None, + num_workers: int, + timeout: int, + max_iterations: int, + runs_per_query: int, + trigger_threshold: float, + holdout: float, + model: str, + verbose: bool, + live_report_path: Path | None = None, + log_dir: Path | None = None, +) -> dict: + """Run the eval + improvement loop.""" + project_root = find_project_root() + name, original_description, content = parse_skill_md(skill_path) + current_description = description_override or original_description + + # Split into train/test if holdout > 0 + if holdout > 0: + train_set, test_set = split_eval_set(eval_set, holdout) + if verbose: + print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr) + else: + train_set = eval_set + test_set = [] + + history = [] + exit_reason = "unknown" + + for iteration in range(1, max_iterations + 1): + if verbose: + print(f"\n{'='*60}", file=sys.stderr) + print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr) + print(f"Description: {current_description}", file=sys.stderr) + print(f"{'='*60}", file=sys.stderr) + + # Evaluate train + test together in one batch for parallelism + all_queries = train_set + test_set + t0 = time.time() + all_results = run_eval( + eval_set=all_queries, + skill_name=name, + description=current_description, + num_workers=num_workers, + timeout=timeout, + project_root=project_root, + runs_per_query=runs_per_query, + trigger_threshold=trigger_threshold, + model=model, + ) + eval_elapsed = time.time() - t0 + + # Split results back into train/test by matching queries + train_queries_set = {q["query"] for q in train_set} + train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set] + test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set] + + train_passed = sum(1 for r in train_result_list if r["pass"]) + train_total = len(train_result_list) + train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total} + train_results = {"results": train_result_list, "summary": train_summary} + + if test_set: + test_passed = sum(1 for r in test_result_list if r["pass"]) + test_total = len(test_result_list) + test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total} + test_results = {"results": test_result_list, "summary": test_summary} + else: + test_results = None + test_summary = None + + history.append({ + "iteration": iteration, + "description": current_description, + "train_passed": train_summary["passed"], + "train_failed": train_summary["failed"], + "train_total": train_summary["total"], + "train_results": train_results["results"], + "test_passed": test_summary["passed"] if test_summary else None, + "test_failed": test_summary["failed"] if test_summary else None, + "test_total": test_summary["total"] if test_summary else None, + "test_results": test_results["results"] if test_results else None, + # For backward compat with report generator + "passed": train_summary["passed"], + "failed": train_summary["failed"], + "total": train_summary["total"], + "results": train_results["results"], + }) + + # Write live report if path provided + if live_report_path: + partial_output = { + "original_description": original_description, + "best_description": current_description, + "best_score": "in progress", + "iterations_run": len(history), + "holdout": holdout, + "train_size": len(train_set), + "test_size": len(test_set), + "history": history, + } + live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name)) + + if verbose: + def print_eval_stats(label, results, elapsed): + pos = [r for r in results if r["should_trigger"]] + neg = [r for r in results if not r["should_trigger"]] + tp = sum(r["triggers"] for r in pos) + pos_runs = sum(r["runs"] for r in pos) + fn = pos_runs - tp + fp = sum(r["triggers"] for r in neg) + neg_runs = sum(r["runs"] for r in neg) + tn = neg_runs - fp + total = tp + tn + fp + fn + precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0 + recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0 + accuracy = (tp + tn) / total if total > 0 else 0.0 + print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr) + for r in results: + status = "PASS" if r["pass"] else "FAIL" + rate_str = f"{r['triggers']}/{r['runs']}" + print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr) + + print_eval_stats("Train", train_results["results"], eval_elapsed) + if test_summary: + print_eval_stats("Test ", test_results["results"], 0) + + if train_summary["failed"] == 0: + exit_reason = f"all_passed (iteration {iteration})" + if verbose: + print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr) + break + + if iteration == max_iterations: + exit_reason = f"max_iterations ({max_iterations})" + if verbose: + print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr) + break + + # Improve the description based on train results + if verbose: + print(f"\nImproving description...", file=sys.stderr) + + t0 = time.time() + # Strip test scores from history so improvement model can't see them + blinded_history = [ + {k: v for k, v in h.items() if not k.startswith("test_")} + for h in history + ] + new_description = improve_description( + skill_name=name, + skill_content=content, + current_description=current_description, + eval_results=train_results, + history=blinded_history, + model=model, + log_dir=log_dir, + iteration=iteration, + ) + improve_elapsed = time.time() - t0 + + if verbose: + print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr) + + current_description = new_description + + # Find the best iteration by TEST score (or train if no test set) + if test_set: + best = max(history, key=lambda h: h["test_passed"] or 0) + best_score = f"{best['test_passed']}/{best['test_total']}" + else: + best = max(history, key=lambda h: h["train_passed"]) + best_score = f"{best['train_passed']}/{best['train_total']}" + + if verbose: + print(f"\nExit reason: {exit_reason}", file=sys.stderr) + print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr) + + return { + "exit_reason": exit_reason, + "original_description": original_description, + "best_description": best["description"], + "best_score": best_score, + "best_train_score": f"{best['train_passed']}/{best['train_total']}", + "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None, + "final_description": current_description, + "iterations_run": len(history), + "holdout": holdout, + "train_size": len(train_set), + "test_size": len(test_set), + "history": history, + } + + +def main(): + parser = argparse.ArgumentParser(description="Run eval + improve loop") + parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") + parser.add_argument("--skill-path", required=True, help="Path to skill directory") + parser.add_argument("--description", default=None, help="Override starting description") + parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") + parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") + parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations") + parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") + parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") + parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)") + parser.add_argument("--model", required=True, help="Model for improvement") + parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") + parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)") + parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here") + args = parser.parse_args() + + eval_set = json.loads(Path(args.eval_set).read_text()) + skill_path = Path(args.skill_path) + + if not (skill_path / "SKILL.md").exists(): + print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) + sys.exit(1) + + name, _, _ = parse_skill_md(skill_path) + + # Set up live report path + if args.report != "none": + if args.report == "auto": + timestamp = time.strftime("%Y%m%d_%H%M%S") + live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html" + else: + live_report_path = Path(args.report) + # Open the report immediately so the user can watch + live_report_path.write_text("

Starting optimization loop...

") + webbrowser.open(str(live_report_path)) + else: + live_report_path = None + + # Determine output directory (create before run_loop so logs can be written) + if args.results_dir: + timestamp = time.strftime("%Y-%m-%d_%H%M%S") + results_dir = Path(args.results_dir) / timestamp + results_dir.mkdir(parents=True, exist_ok=True) + else: + results_dir = None + + log_dir = results_dir / "logs" if results_dir else None + + output = run_loop( + eval_set=eval_set, + skill_path=skill_path, + description_override=args.description, + num_workers=args.num_workers, + timeout=args.timeout, + max_iterations=args.max_iterations, + runs_per_query=args.runs_per_query, + trigger_threshold=args.trigger_threshold, + holdout=args.holdout, + model=args.model, + verbose=args.verbose, + live_report_path=live_report_path, + log_dir=log_dir, + ) + + # Save JSON output + json_output = json.dumps(output, indent=2) + print(json_output) + if results_dir: + (results_dir / "results.json").write_text(json_output) + + # Write final HTML report (without auto-refresh) + if live_report_path: + live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name)) + print(f"\nReport: {live_report_path}", file=sys.stderr) + + if results_dir and live_report_path: + (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name)) + + if results_dir: + print(f"Results saved to: {results_dir}", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/1-Vue3-Dev/.agents/skills/skill-creator/scripts/utils.py b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/utils.py new file mode 100644 index 0000000..51b6a07 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/skill-creator/scripts/utils.py @@ -0,0 +1,47 @@ +"""Shared utilities for skill-creator scripts.""" + +from pathlib import Path + + + +def parse_skill_md(skill_path: Path) -> tuple[str, str, str]: + """Parse a SKILL.md file, returning (name, description, full_content).""" + content = (skill_path / "SKILL.md").read_text() + lines = content.split("\n") + + if lines[0].strip() != "---": + raise ValueError("SKILL.md missing frontmatter (no opening ---)") + + end_idx = None + for i, line in enumerate(lines[1:], start=1): + if line.strip() == "---": + end_idx = i + break + + if end_idx is None: + raise ValueError("SKILL.md missing frontmatter (no closing ---)") + + name = "" + description = "" + frontmatter_lines = lines[1:end_idx] + i = 0 + while i < len(frontmatter_lines): + line = frontmatter_lines[i] + if line.startswith("name:"): + name = line[len("name:"):].strip().strip('"').strip("'") + elif line.startswith("description:"): + value = line[len("description:"):].strip() + # Handle YAML multiline indicators (>, |, >-, |-) + if value in (">", "|", ">-", "|-"): + continuation_lines: list[str] = [] + i += 1 + while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")): + continuation_lines.append(frontmatter_lines[i].strip()) + i += 1 + description = " ".join(continuation_lines) + continue + else: + description = value.strip('"').strip("'") + i += 1 + + return name, description, content diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/SKILL.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/SKILL.md new file mode 100644 index 0000000..feacd70 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/SKILL.md @@ -0,0 +1,154 @@ +--- +name: vue-best-practices +description: MUST be used for Vue.js tasks. Strongly recommends Composition API with ` + + +``` + +## Common Animation Patterns + +### Pulse on Success + +```vue + + + + + +``` + +### Highlight on Change + +```vue + + + + + +``` + +### Bounce Attention + +```vue + + + + + +``` + +## Using animationend Event + +Instead of `setTimeout`, use the `animationend` event for cleaner code: + +```vue + + + +``` + +## Composable for Reusable Animations + +```javascript +// composables/useAnimation.js +import { ref } from 'vue' + +export function useAnimation(duration = 500) { + const isAnimating = ref(false) + + function trigger() { + isAnimating.value = true + setTimeout(() => { + isAnimating.value = false + }, duration) + } + + return { + isAnimating, + trigger + } +} +``` + +```vue + + + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md new file mode 100644 index 0000000..26b0120 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md @@ -0,0 +1,291 @@ +--- +title: State-driven Animations with CSS Transitions and Style Bindings +impact: LOW +impactDescription: Combining Vue's reactive style bindings with CSS transitions creates smooth, interactive animations +type: best-practice +tags: [vue3, animation, css, transition, style-binding, state, interactive] +--- + +# State-driven Animations with CSS Transitions and Style Bindings + +**Impact: LOW** - For responsive, interactive animations that react to user input or state changes, combine Vue's dynamic style bindings with CSS transitions. This creates smooth animations that interpolate values in real-time based on state. + +## Task List + +- Use `:style` binding for dynamic properties that change frequently +- Add CSS `transition` property to smoothly animate between values +- Consider using `transform` and `opacity` for GPU-accelerated animations +- For complex value interpolation, use watchers with animation libraries + +## Basic Pattern + +```vue + + + + + +``` + +## Common Use Cases + +### Following Mouse Position + +```vue + + + + + +``` + +### Progress Animation + +```vue + + + + + +``` + +### Scroll-based Animation + +```vue + + + + + +``` + +### Color Theme Transition + +```vue + + + + + +``` + +## Advanced: Numerical Tweening with Watchers + +For smooth number animations (counters, stats), use watchers with animation libraries: + +```vue + + + +``` + +## Performance Considerations + +```vue + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-async.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-async.md new file mode 100644 index 0000000..b39310d --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-async.md @@ -0,0 +1,97 @@ +--- +title: Async Component Best Practices +impact: MEDIUM +impactDescription: Poor async component strategy can delay interactivity in SSR apps and create loading UI flicker +type: best-practice +tags: [vue3, async-components, ssr, hydration, performance, ux] +--- + +# Async Component Best Practices + +**Impact: MEDIUM** - Async components should reduce JavaScript cost without degrading perceived performance. Focus on hydration timing in SSR and stable loading UX. + +## Task List + +- Use lazy hydration strategies for non-critical SSR component trees +- Import only the hydration helpers you actually use +- Keep `loadingComponent` delay near the default `200ms` unless real UX data suggests otherwise +- Configure `delay` and `timeout` together for predictable loading behavior + +## Use Lazy Hydration Strategies in SSR + +In Vue 3.5+, async components can delay hydration until idle time, visibility, media query match, or user interaction. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Prevent Loading Spinner Flicker + +Avoid showing loading UI immediately for components that usually resolve quickly. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Delay Guidelines + +| Scenario | Recommended Delay | +|----------|-------------------| +| Small component, fast network | `200ms` | +| Known heavy component | `100ms` | +| Background or non-critical UI | `300-500ms` | diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-data-flow.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-data-flow.md new file mode 100644 index 0000000..e1add1e --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-data-flow.md @@ -0,0 +1,307 @@ +--- +title: Component Data Flow Best Practices +impact: HIGH +impactDescription: Clear data flow between components prevents state bugs, stale UI, and brittle coupling +type: best-practice +tags: [vue3, props, emits, v-model, provide-inject, data-flow, typescript] +--- + +# Component Data Flow Best Practices + +**Impact: HIGH** - Vue components stay reliable when data flow is explicit: props go down, events go up, `v-model` handles two-way bindings, and provide/inject supports cross-tree dependencies. Blurring these boundaries leads to stale state, hidden coupling, and hard-to-debug UI. + +The main principle of data flow in Vue.js is **Props Down / Events Up**. This is the most maintainable default, and one-way flow scales well. + +## Task List + +- Treat props as read-only inputs +- Use props/emit for component communication; reserve refs for imperative actions +- When refs are required for imperative APIs, type them with template refs +- Emit events instead of mutating parent state directly +- Use `defineModel` for v-model in modern Vue (3.4+) +- Handle v-model modifiers deliberately in child components +- Use symbols for provide/inject keys to avoid props drilling (over ~3 layers) +- Keep mutations in the provider or expose explicit actions +- In TypeScript projects, prefer type-based `defineProps`, `defineEmits`, and `InjectionKey` + +## Props: One-Way Data Down + +Props are inputs. Do not mutate them in the child. + +**BAD:** +```vue + +``` + +**GOOD:** + +If state needs to change, emit an event, use `v-model` or create a local copy. + +## Prefer props/emit over component refs + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Type component refs when imperative access is required + +Prefer props/emits by default. When a parent must call an exposed child method, type the ref explicitly and expose only the intended API from the child with `defineExpose`. + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + +``` + +```vue + + + + +``` + +## Emits: Explicit Events Up + +Component events do not bubble. If a parent needs to know about an event, re-emit it explicitly. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + + + +``` + +**Event naming:** use kebab-case in templates and camelCase in script: +```vue + + + +``` + +## `v-model`: Predictable Two-Way Bindings + +Use `defineModel` by default for component bindings and emit updates on input. Only use the `modelValue` + `update:modelValue` pattern if you are on Vue < 3.4. + +**BAD:** +```vue + + + +``` + +**GOOD (Vue 3.4+):** +```vue + + + +``` + +**GOOD (Vue < 3.4):** +```vue + + + +``` + +If you need the updated value immediately after a change, use the input event value or `nextTick` in the parent. + +## Provide/Inject: Shared Context Without Prop Drilling + +Use provide/inject for cross-tree state, but keep mutations centralized in the provider and expose explicit actions. + +**BAD:** +```vue +// Provider.vue +provide('theme', reactive({ dark: false })) + +// Consumer.vue +const theme = inject('theme') +// Mutating shared state from any depth becomes hard to track +theme.dark = true +``` + +**GOOD:** +```vue +// Provider.vue +const theme = reactive({ dark: false }) +const toggleTheme = () => { theme.dark = !theme.dark } + +provide(themeKey, readonly(theme)) +provide(themeActionsKey, { toggleTheme }) + +// Consumer.vue +const theme = inject(themeKey) +const { toggleTheme } = inject(themeActionsKey) +``` + +Use symbols for keys to avoid collisions in large apps: +```ts +export const themeKey = Symbol('theme') +export const themeActionsKey = Symbol('theme-actions') +``` + +## Use TypeScript Contracts for Public Component APIs + +In TypeScript projects, type component boundaries directly with `defineProps`, `defineEmits`, and `InjectionKey` so invalid payloads and mismatched injections fail at compile time. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md new file mode 100644 index 0000000..5362fa4 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md @@ -0,0 +1,174 @@ +--- +title: Component Fallthrough Attributes Best Practices +impact: MEDIUM +impactDescription: Incorrect $attrs access and reactivity assumptions can cause undefined values and watchers that never run +type: best-practice +tags: [vue3, attrs, fallthrough-attributes, composition-api, reactivity] +--- + +# Component Fallthrough Attributes Best Practices + +**Impact: MEDIUM** - Fallthrough attributes are straightforward once you follow Vue's conventions: hyphenated names use bracket notation, listener keys are camelCase `onX`, and `useAttrs()` is current-but-not-reactive. + +## Task List + +- Access hyphenated attribute names with bracket notation (for example `attrs['data-testid']`) +- Access event listeners with camelCase `onX` keys (for example `attrs.onClick`) +- Do not `watch()` values returned from `useAttrs()`; those watchers do not trigger on attr changes +- Use `onUpdated()` for attr-driven side effects +- Promote frequently observed attrs to props when reactive observation is required + +## Access Attribute and Listener Keys Correctly + +Hyphenated attribute names preserve their original casing in JavaScript, so dot notation does not work for keys that include `-`. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +### Naming Reference + +| Parent Usage | Access in `attrs` | +|--------------|-------------------| +| `class="foo"` | `attrs.class` | +| `data-id="123"` | `attrs['data-id']` | +| `aria-label="..."` | `attrs['aria-label']` | +| `foo-bar="baz"` | `attrs['foo-bar']` | +| `@click="fn"` | `attrs.onClick` | +| `@custom-event="fn"` | `attrs.onCustomEvent` | +| `@update:modelValue="fn"` | `attrs['onUpdate:modelValue']` | + +## `useAttrs()` Is Not Reactive + +`useAttrs()` always reflects the latest values, but it is intentionally not reactive for watcher tracking. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Common Patterns + +### Check for optional attrs safely + +```vue + +``` + +### Forward listeners after internal logic + +```vue + + + +``` + +## TypeScript Notes + +`useAttrs()` is typed as `Record`, so cast individual keys when needed. + +```vue + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-keep-alive.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-keep-alive.md new file mode 100644 index 0000000..f887691 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-keep-alive.md @@ -0,0 +1,137 @@ +--- +title: KeepAlive Component Best Practices +impact: HIGH +impactDescription: KeepAlive caches component instances; misuse causes stale data, memory growth, or unexpected lifecycle behavior +type: best-practice +tags: [vue3, keepalive, cache, performance, router, dynamic-components] +--- + +# KeepAlive Component Best Practices + +**Impact: HIGH** - `` caches component instances instead of destroying them. Use it to preserve state across switches, but manage cache size and freshness explicitly to avoid memory growth or stale UI. + +## Task List + +- Use KeepAlive only where state preservation improves UX +- Set a reasonable `max` to cap cache size +- Declare component names for include/exclude matching +- Use `onActivated`/`onDeactivated` for cache-aware logic +- Decide how and when cached views refresh their data +- Avoid caching memory-heavy or security-sensitive views + +## When to Use KeepAlive + +Use KeepAlive when switching between views where state should persist (tabs, multi-step forms, dashboards). Avoid it when each visit should start fresh. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## When NOT to Use KeepAlive + +- Search or filter pages where users expect fresh results +- Memory-heavy components (maps, large tables, media players) +- Sensitive flows where data must be cleared on exit +- Components with heavy background activity you cannot pause + +## Limit and Control the Cache + +Always cap cache size with `max` and restrict caching to specific components when possible. + +```vue + +``` + +## Ensure Component Names Match include/exclude + +`include` and `exclude` match the component `name` option. Explicitly set names for reliable caching. + +```vue + + +``` + +```vue + +``` + +## Cache Invalidation Strategies + +Vue 3 has no direct API to remove a specific cached instance. Use keys or dynamic include/exclude to force refreshes. + +```vue + + + +``` + +## Lifecycle Hooks for Cached Components + +Cached components are not destroyed on switch. Use activation hooks for refresh and cleanup. + +```vue + +``` + +## Router Caching and Freshness + +Decide whether navigation should show cached state or a fresh view. A common pattern is to key by route when params change. + +```vue + +``` + +If you want cache reuse but fresh data, refresh in `onActivated` and compare query/params before fetching. diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-slots.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-slots.md new file mode 100644 index 0000000..f77a91c --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-slots.md @@ -0,0 +1,216 @@ +--- +title: Component Slots Best Practices +impact: MEDIUM +impactDescription: Poor slot API design causes empty DOM wrappers, weak TypeScript safety, brittle defaults, and unnecessary component overhead +type: best-practice +tags: [vue3, slots, components, typescript, composables] +--- + +# Component Slots Best Practices + +**Impact: MEDIUM** - Slots are a core component API surface in Vue. Structure them intentionally so templates stay predictable, typed, and performant. + +## Task List + +- Use shorthand syntax for named slots (`#` instead of `v-slot:`) +- Render optional slot wrapper elements only when slot content exists (`$slots` checks) +- Type scoped slot contracts with `defineSlots` in TypeScript components +- Provide fallback content for optional slots +- Prefer composables over renderless components for pure logic reuse + +## Shorthand syntax for named slots + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Conditionally Render Optional Slot Wrappers + +Use `$slots` checks when wrapper elements add spacing, borders, or layout constraints. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + +``` + +## Type Scoped Slot Props with defineSlots + +In ` + + +``` + +**GOOD:** +```vue + + + + +``` + +## Provide Slot Fallback Content + +Fallback content makes components resilient when parents omit optional slots. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + +``` + +## Prefer Composables for Pure Logic Reuse + +Renderless components are still useful for slot-driven composition, but composables are usually cleaner for logic-only reuse. + +**BAD:** +```vue + + + + +``` + +**GOOD:** +```ts +// composables/useMouse.ts +import { ref, onMounted, onUnmounted } from 'vue' + +export function useMouse() { + const x = ref(0) + const y = ref(0) + + function onMove(event: MouseEvent) { + x.value = event.pageX + y.value = event.pageY + } + + onMounted(() => window.addEventListener('mousemove', onMove)) + onUnmounted(() => window.removeEventListener('mousemove', onMove)) + + return { x, y } +} +``` + +```vue + + + + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-suspense.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-suspense.md new file mode 100644 index 0000000..4d9ecab --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-suspense.md @@ -0,0 +1,228 @@ +--- +title: Suspense Component Best Practices +impact: MEDIUM +impactDescription: Suspense coordinates async dependencies with fallback UI; misconfiguration leads to missing loading states or confusing UX +type: best-practice +tags: [vue3, suspense, async-components, async-setup, loading, fallback, router, transition, keepalive] +--- + +# Suspense Component Best Practices + +**Impact: MEDIUM** - `` coordinates async dependencies (async components or async setup) and renders a fallback while they resolve. Misconfiguration leads to missing loading states, empty renders, or subtle UX bugs. + +## Task List + +- Wrap default and fallback slot content in a single root node +- Use `timeout` when you need the fallback to appear on reverts +- Force root replacement with `:key` when you need Suspense to re-trigger +- Add `suspensible` to nested Suspense boundaries (Vue 3.3+) +- Use `@pending`, `@resolve`, and `@fallback` for programmatic loading state +- Nest `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` in that order +- Keep Suspense usage centralized and documented in production + +## Single Root in Default and Fallback Slots + +Suspense tracks a single immediate child in both slots. Wrap multiple elements in a single element or component. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Fallback Timing on Reverts (`timeout`) + +When Suspense is already resolved and new async work starts, the previous content remains visible until the timeout elapses. Use `timeout="0"` for immediate fallback or a short delay to avoid flicker. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Pending State Only Re-triggers on Root Replacement + +Once resolved, Suspense only re-enters pending when the root node of the default slot changes. If async work happens deeper in the tree, no fallback appears. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `suspensible` for Nested Suspense (Vue 3.3+) + +Nested Suspense boundaries need `suspensible` on the inner boundary so the parent can coordinate loading state. Without it, inner async content may render empty nodes until resolved. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Track Loading with Suspense Events + +Use `@pending`, `@resolve`, and `@fallback` for analytics, global loading indicators, or coordinating UI outside the Suspense boundary. + +```vue + + + +``` + +## Recommended Nesting with RouterView, Transition, KeepAlive + +When combining these components, the nesting order should be `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` so each wrapper works correctly. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Treat Suspense Cautiously in Production + +In production code, keep Suspense boundaries minimal, document where they are used, and have a fallback loading strategy if you ever need to replace or refactor them. diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-teleport.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-teleport.md new file mode 100644 index 0000000..db48db2 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-teleport.md @@ -0,0 +1,108 @@ +--- +title: Teleport Component Best Practices +impact: MEDIUM +impactDescription: Teleport renders content outside the component's DOM position, which is essential for overlays but affects styling and layout +type: best-practice +tags: [vue3, teleport, modal, overlay, positioning, responsive] +--- + +# Teleport Component Best Practices + +**Impact: MEDIUM** - `` renders part of a component's template in a different place in the DOM while preserving the Vue component hierarchy. Use it for overlays (modals, toasts, tooltips) or any UI that must escape stacking contexts, overflow, or fixed positioning constraints. + +## Task List + +- Teleport overlays to `body` or a dedicated container outside the app root +- Keep a shared target for similar UI (`#modals`, `#notifications`) and control layering with order or z-index +- Use `:disabled` for responsive layouts that should render inline on small screens +- Remember props, emits, and provide/inject still work through teleport +- Avoid relying on parent stacking contexts or transforms for teleported UI + +## Teleport Overlays Out of Transformed Containers + +When an ancestor has `transform`, `filter`, or `perspective`, fixed-position overlays can behave like they are locally positioned. Teleport escapes that context. + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + +``` + +## Responsive Layouts with `disabled` + +Use `:disabled` to render inline on mobile and teleport on larger screens: + +```vue + + + +``` + +## Logical Hierarchy Is Preserved + +Teleport changes DOM position, not the Vue component tree. Props, emits, slots, and provide/inject still work: + +```vue + +``` + +## Multiple Teleports to the Same Target + +Teleports to the same target append in declaration order: + +```vue + +``` + +Use a shared container to keep stacking predictable, and apply z-index only when you need explicit layering. diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition-group.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition-group.md new file mode 100644 index 0000000..d0339ff --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition-group.md @@ -0,0 +1,128 @@ +--- +title: TransitionGroup Component Best Practices +impact: MEDIUM +impactDescription: TransitionGroup animates list items; missing keys or misuse leads to broken list transitions +type: best-practice +tags: [vue3, transition-group, animation, lists, keys] +--- + +# TransitionGroup Component Best Practices + +**Impact: MEDIUM** - `` animates lists of items entering, leaving, and moving. Use it for `v-for` lists or dynamic collections where individual items change over time. + +## Task List + +- Use `` only for lists and repeated items +- Provide unique, stable keys for every direct child +- Use `tag` when you need semantic or layout wrappers +- Avoid the `mode` prop (not supported) +- Use JavaScript hooks for staggered effects + +## Use TransitionGroup for Lists + +`` is designed for list items. Use `tag` to control the wrapper element when needed. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Always Provide Stable Keys + +Keys are required. Without stable keys, Vue cannot track item positions and animations break. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Do Not Use `mode` on TransitionGroup + +`mode` is only for `` because it swaps a single element. Use `` if you need in/out sequencing. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Stagger List Animations with Data Attributes + +For cascading list animations, pass the index to JavaScript hooks and compute delay per item. + +```vue + + + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition.md new file mode 100644 index 0000000..e6abed7 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/component-transition.md @@ -0,0 +1,125 @@ +--- +title: Transition Component Best Practices +impact: MEDIUM +impactDescription: Transition animates a single element or component; incorrect structure or keys prevent animations +type: best-practice +tags: [vue3, transition, animation, performance, keys] +--- + +# Transition Component Best Practices + +**Impact: MEDIUM** - `` animates entering/leaving of a single element or component. It is ideal for toggling UI states, swapping views, or animating one component at a time. + +## Task List + +- Wrap a single element or component inside `` +- Provide a `key` when switching between same element types +- Use `mode="out-in"` when you need sequential swaps +- Prefer `transform` and `opacity` for smooth animations + +## Use Transition for a Single Root Element + +`` only supports one direct child. Wrap multiple nodes in a single element or component. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Force Transitions Between Same Element Types + +Vue reuses the same DOM element when the tag type does not change. Add `key` so Vue treats it as a new element and triggers enter/leave. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `mode` to Avoid Overlap During Swaps + +When swapping components or views, use `mode="out-in"` to prevent both from being visible at the same time. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Animate `transform` and `opacity` for Performance + +Avoid layout-triggering properties such as `height`, `margin`, or `top`. Use `transform` and `opacity` for smooth, GPU-friendly transitions. + +**BAD:** +```css +.slide-enter-active, +.slide-leave-active { + transition: height 0.3s ease; +} + +.slide-enter-from, +.slide-leave-to { + height: 0; +} +``` + +**GOOD:** +```css +.slide-enter-active, +.slide-leave-active { + transition: transform 0.3s ease, opacity 0.3s ease; +} + +.slide-enter-from { + transform: translateX(-12px); + opacity: 0; +} + +.slide-leave-to { + transform: translateX(12px); + opacity: 0; +} +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/composables.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/composables.md new file mode 100644 index 0000000..cb18a6f --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/composables.md @@ -0,0 +1,290 @@ +--- +title: Composable Organization Patterns +impact: MEDIUM +impactDescription: Well-structured composables improve maintainability, reusability, and update performance +type: best-practice +tags: [vue3, composables, composition-api, code-organization, api-design, readonly, utilities] +--- + +# Composable Organization Patterns + +**Impact: MEDIUM** - Treat composables as reusable, stateful building blocks and keep their code organized by feature concern. This keeps large components maintainable and prevents hard-to-debug mutation and API design issues. + +## Task List + +- Compose complex behavior from small, focused composables +- Use options objects for composables with multiple optional parameters +- Return readonly state when updates must flow through explicit actions +- Keep pure utility functions as plain utilities, not composables +- Organize composable and component code by feature concern, and extract composables when components grow + +## Compose Composables from Smaller Primitives + +**BAD:** +```vue + +``` + +**GOOD:** +```javascript +// composables/useEventListener.js +import { onMounted, onUnmounted, toValue } from 'vue' + +export function useEventListener(target, event, callback) { + onMounted(() => toValue(target).addEventListener(event, callback)) + onUnmounted(() => toValue(target).removeEventListener(event, callback)) +} +``` + +```javascript +// composables/useMouse.js +import { ref } from 'vue' +import { useEventListener } from './useEventListener' + +export function useMouse() { + const x = ref(0) + const y = ref(0) + + useEventListener(window, 'mousemove', (e) => { + x.value = e.pageX + y.value = e.pageY + }) + + return { x, y } +} +``` + +```javascript +// composables/useMouseInElement.js +import { computed } from 'vue' +import { useMouse } from './useMouse' + +export function useMouseInElement(elementRef) { + const { x, y } = useMouse() + + const isOutside = computed(() => { + if (!elementRef.value) return true + const rect = elementRef.value.getBoundingClientRect() + return x.value < rect.left || x.value > rect.right || + y.value < rect.top || y.value > rect.bottom + }) + + return { x, y, isOutside } +} +``` + +## Use Options Object Pattern for Composable Parameters + +**BAD:** +```javascript +export function useFetch(url, method, headers, timeout, retries, immediate) { + // hard to read and easy to misorder +} + +useFetch('/api/users', 'GET', null, 5000, 3, true) +``` + +**GOOD:** +```javascript +export function useFetch(url, options = {}) { + const { + method = 'GET', + headers = {}, + timeout = 30000, + retries = 0, + immediate = true + } = options + + // implementation + return { method, headers, timeout, retries, immediate } +} + +useFetch('/api/users', { + method: 'POST', + timeout: 5000, + retries: 3 +}) +``` + +```typescript +interface UseCounterOptions { + initial?: number + min?: number + max?: number + step?: number +} + +export function useCounter(options: UseCounterOptions = {}) { + const { initial = 0, min = -Infinity, max = Infinity, step = 1 } = options + // implementation +} +``` + +## Return Readonly State with Explicit Actions + +**BAD:** +```javascript +export function useCart() { + const items = ref([]) + const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0)) + return { items, total } // any consumer can mutate directly +} + +const { items } = useCart() +items.value.push({ id: 1, price: 10 }) +``` + +**GOOD:** +```javascript +import { ref, computed, readonly } from 'vue' + +export function useCart() { + const _items = ref([]) + + const total = computed(() => + _items.value.reduce((sum, item) => sum + item.price * item.quantity, 0) + ) + + function addItem(product, quantity = 1) { + const existing = _items.value.find(item => item.id === product.id) + if (existing) { + existing.quantity += quantity + return + } + _items.value.push({ ...product, quantity }) + } + + function removeItem(productId) { + _items.value = _items.value.filter(item => item.id !== productId) + } + + return { + items: readonly(_items), + total, + addItem, + removeItem + } +} +``` + +## Keep Utilities as Utilities + +**BAD:** +```javascript +export function useFormatters() { + const formatDate = (date) => new Intl.DateTimeFormat('en-US').format(date) + const formatCurrency = (amount) => + new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount) + return { formatDate, formatCurrency } +} + +const { formatDate } = useFormatters() +``` + +**GOOD:** +```javascript +// utils/formatters.js +export function formatDate(date) { + return new Intl.DateTimeFormat('en-US').format(date) +} + +export function formatCurrency(amount) { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount) +} +``` + +```javascript +// composables/useInvoiceSummary.js +import { computed } from 'vue' +import { formatCurrency } from '@/utils/formatters' + +export function useInvoiceSummary(invoiceRef) { + const totalLabel = computed(() => formatCurrency(invoiceRef.value.total)) + return { totalLabel } +} +``` + +## Organize Composable and Component Code by Feature Concern + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +```javascript +// composables/useItems.js +import { ref, onMounted } from 'vue' + +export function useItems() { + const items = ref([]) + const loading = ref(false) + + async function fetchItems() { + loading.value = true + try { + items.value = await api.getItems() + } finally { + loading.value = false + } + } + + onMounted(fetchItems) + return { items, loading, fetchItems } +} +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/directives.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/directives.md new file mode 100644 index 0000000..8412fbc --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/directives.md @@ -0,0 +1,162 @@ +--- +title: Directive Best Practices +impact: MEDIUM +impactDescription: Custom directives are powerful but easy to misuse; following patterns prevents leaks, invalid usage, and unclear abstractions +type: best-practice +tags: [vue3, directives, custom-directives, composition, typescript] +--- + +# Directive Best Practices + +**Impact: MEDIUM** - Directives are for low-level DOM access. Use them sparingly, keep them side-effect safe, and prefer components or composables when you need stateful or reusable UI behavior. + +## Task List + +- Use directives only when you need direct DOM access +- Do not mutate directive arguments or binding objects +- Clean up timers, listeners, and observers in `unmounted` +- Register directives in ` + + +``` + +## Clean Up Side Effects in `unmounted` + +Any timers, listeners, or observers must be removed to avoid leaks. + +```ts +const vResize = { + mounted(el) { + const observer = new ResizeObserver(() => {}) + observer.observe(el) + el._observer = observer + }, + unmounted(el) { + el._observer?.disconnect() + } +} +``` + +## Prefer Function Shorthand for Single-Hook Directives + +If you only need `mounted`/`updated`, use the function form. + +```ts +const vAutofocus = (el) => el.focus() +``` + +## Use the `v-` Prefix and Script Setup Registration + +```vue + + + +``` + +## Type Custom Directives in TypeScript Projects + +Use `Directive` so `binding.value` is typed, and augment Vue's template types so directives are recognized in SFC templates. + +**BAD:** +```ts +// Untyped directive value and no template type augmentation +export const vHighlight = { + mounted(el, binding) { + el.style.backgroundColor = binding.value + } +} +``` + +**GOOD:** +```ts +import type { Directive } from 'vue' + +type HighlightValue = string + +export const vHighlight = { + mounted(el, binding) { + el.style.backgroundColor = binding.value + } +} satisfies Directive + +declare module 'vue' { + interface ComponentCustomProperties { + vHighlight: typeof vHighlight + } +} +``` + +## Handle SSR with `getSSRProps` + +Directive hooks such as `mounted` and `updated` do not run during SSR. If a directive sets attributes/classes that affect rendered HTML, provide an SSR equivalent via `getSSRProps` to avoid hydration mismatches. + +**BAD:** +```ts +const vTooltip = { + mounted(el, binding) { + el.setAttribute('data-tooltip', binding.value) + el.classList.add('has-tooltip') + } +} +``` + +**GOOD:** +```ts +const vTooltip = { + mounted(el, binding) { + el.setAttribute('data-tooltip', binding.value) + el.classList.add('has-tooltip') + }, + getSSRProps(binding) { + return { + 'data-tooltip': binding.value, + class: 'has-tooltip' + } + } +} +``` + +## Prefer Declarative Templates When Possible + +If a standard attribute or binding works, use it instead of a directive. + +## Decide Between Directives and Components + +Use a directive for DOM-level behavior. Use a component when behavior affects structure, state, or rendering. diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md new file mode 100644 index 0000000..44f98ff --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md @@ -0,0 +1,159 @@ +--- +title: Avoid Excessive Component Abstraction in Large Lists +impact: MEDIUM +impactDescription: Each component instance has memory and render overhead - abstractions multiply this in lists +type: efficiency +tags: [vue3, performance, components, abstraction, lists, optimization] +--- + +# Avoid Excessive Component Abstraction in Large Lists + +**Impact: MEDIUM** - Component instances are more expensive than plain DOM nodes. While abstractions improve code organization, unnecessary nesting creates overhead. In large lists, this overhead multiplies - 100 items with 3 levels of abstraction means 300+ component instances instead of 100. + +Don't avoid abstraction entirely, but be mindful of component depth in frequently-rendered elements like list items. + +## Task List + +- Review list item components for unnecessary wrapper components +- Consider flattening component hierarchies in hot paths +- Use native elements when a component adds no value +- Profile component counts using Vue DevTools +- Focus optimization efforts on the most-rendered components + +**BAD:** +```vue + + + + + + + +``` + +**GOOD:** +```vue + + + + + + + + + +``` + +## When Abstraction Is Still Worth It + +```vue + + + + + + + + + + + + + + + +``` + +## Measuring Component Overhead + +```javascript +// In development, profile component counts +import { onMounted, getCurrentInstance } from 'vue' + +onMounted(() => { + const instance = getCurrentInstance() + let count = 0 + + function countComponents(vnode) { + if (vnode.component) count++ + if (vnode.children) { + vnode.children.forEach(child => { + if (child.component || child.children) countComponents(child) + }) + } + } + + // Use Vue DevTools instead for accurate counts + console.log('Check Vue DevTools Components tab for instance counts') +}) +``` + +## Alternatives to Wrapper Components + +```vue + + + + +{{ content }} + + +
+ +
+ + +``` + +## Impact Calculation + +| List Size | Components per Item | Total Instances | Memory Impact | +|-----------|---------------------|-----------------|---------------| +| 100 items | 1 (flat) | 100 | Baseline | +| 100 items | 3 (nested) | 300 | ~3x memory | +| 100 items | 5 (deeply nested) | 500 | ~5x memory | +| 1000 items | 1 (flat) | 1000 | High | +| 1000 items | 5 (deeply nested) | 5000 | Very High | diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md new file mode 100644 index 0000000..ce5f688 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md @@ -0,0 +1,182 @@ +--- +title: Use v-once and v-memo to Skip Unnecessary Updates +impact: MEDIUM +impactDescription: v-once skips all future updates for static content; v-memo conditionally memoizes subtrees +type: efficiency +tags: [vue3, performance, v-once, v-memo, optimization, directives] +--- + +# Use v-once and v-memo to Skip Unnecessary Updates + +**Impact: MEDIUM** - Vue re-evaluates templates on every reactive change. For content that never changes or changes infrequently, `v-once` and `v-memo` tell Vue to skip updates, reducing render work. + +Use `v-once` for truly static content and `v-memo` for conditionally-static content in lists. + +## Task List + +- Apply `v-once` to elements that use runtime data but never need updating +- Apply `v-memo` to list items that should only update on specific condition changes +- Verify memoized content doesn't need to respond to other state changes +- Profile with Vue DevTools to confirm update skipping + +## v-once: Render Once, Never Update + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## v-memo: Conditional Memoization for Lists + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## v-memo with Multiple Dependencies + +```vue + + + +``` + +## v-memo with Empty Array = v-once + +```vue + +``` + +## When NOT to Use These Directives + +```vue + +``` + +## Performance Comparison + +| Scenario | Without Directive | With v-once/v-memo | +|----------|-------------------|-------------------| +| Static header, parent re-renders 100x | Re-evaluated 100x | Evaluated 1x | +| 1000 items, selection changes | 1000 items re-render | 2 items re-render | +| Complex child component | Full re-render | Skipped if memoized | + +## Debugging Memoized Components + +```vue + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md new file mode 100644 index 0000000..78a8a1c --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md @@ -0,0 +1,187 @@ +--- +title: Virtualize Large Lists to Avoid DOM Overload +impact: HIGH +impactDescription: Rendering thousands of list items creates excessive DOM nodes, causing slow renders and high memory usage +type: efficiency +tags: [vue3, performance, virtual-list, large-data, dom, optimization] +--- + +# Virtualize Large Lists to Avoid DOM Overload + +**Impact: HIGH** - Rendering all items in a large list (hundreds or thousands) creates massive amounts of DOM nodes. Each node consumes memory, slows down initial render, and makes updates expensive. List virtualization only renders visible items, dramatically improving performance. + +Use a virtualization library when dealing with lists that could exceed 50-100 items, especially if items have complex content. + +## Task List + +- Identify lists that render more than 50-100 items +- Install a virtualization library (vue-virtual-scroller, @tanstack/vue-virtual) +- Replace standard `v-for` with virtualized component +- Ensure list items have consistent or estimable heights +- Test with realistic data volumes during development + +## Recommended Libraries + +| Library | Best For | Notes | +|---------|----------|-------| +| `vue-virtual-scroller` | General use, easy setup | Most popular, good defaults | +| `@tanstack/vue-virtual` | Complex layouts, headless | Framework-agnostic, flexible | +| `vue-virtual-scroll-grid` | Grid layouts | 2D virtualization | +| `vueuc/VVirtualList` | Naive UI projects | Part of Naive UI ecosystem | + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + + + +``` + +## Using @tanstack/vue-virtual + +```vue + + + + + +``` + +## Dynamic Heights with vue-virtual-scroller + +```vue + + + +``` + +## Performance Comparison + +| Approach | 100 Items | 1,000 Items | 10,000 Items | +|----------|-----------|-------------|--------------| +| Regular v-for | ~100 DOM nodes | ~1,000 DOM nodes | ~10,000 DOM nodes | +| Virtualized | ~20 DOM nodes | ~20 DOM nodes | ~20 DOM nodes | +| Initial render | Fast | Slow | Very slow / crashes | +| Virtualized render | Fast | Fast | Fast | + +## When NOT to Virtualize + +- Lists under 50 items with simple content +- Lists where all items must be accessible to screen readers simultaneously +- Print layouts where all content must render +- SEO-critical content that must be in initial HTML diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/plugins.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/plugins.md new file mode 100644 index 0000000..190cee8 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/plugins.md @@ -0,0 +1,166 @@ +--- +title: Vue Plugin Best Practices +impact: MEDIUM +impactDescription: Incorrect plugin structure or injection key strategy causes install failures, collisions, and unsafe APIs +type: best-practice +tags: [vue3, plugins, provide-inject, typescript, dependency-injection] +--- + +# Vue Plugin Best Practices + +**Impact: MEDIUM** - Vue plugins should follow the `app.use()` contract, expose explicit capabilities, and use collision-safe injection keys. This keeps plugin setup predictable and composable across large apps. + +## Task List + +- Export plugins as an object with `install()` or as an install function +- Use the `app` instance in `install()` to register components/directives/provides +- Type plugin APIs with `Plugin` (and options tuple types when needed) +- Use symbol keys (prefer `InjectionKey`) for `provide/inject` in plugins +- Add a small typed composable wrapper for required injections to fail fast + +## Structure Plugins for `app.use()` + +A Vue plugin must be either: +- An object with `install(app, options?)` +- A function with the same signature + +**BAD:** +```ts +const notAPlugin = { + doSomething() {} +} + +app.use(notAPlugin) +``` + +**GOOD:** +```ts +import type { App } from 'vue' + +interface PluginOptions { + prefix?: string + debug?: boolean +} + +const myPlugin = { + install(app: App, options: PluginOptions = {}) { + const { prefix = 'my', debug = false } = options + + if (debug) { + console.log('Installing myPlugin with prefix:', prefix) + } + + app.provide('myPlugin', { prefix }) + } +} + +app.use(myPlugin, { prefix: 'custom', debug: true }) +``` + +**GOOD:** +```ts +import type { App } from 'vue' + +function simplePlugin(app: App, options?: { message: string }) { + app.config.globalProperties.$greet = () => options?.message ?? 'Hello!' +} + +app.use(simplePlugin, { message: 'Welcome!' }) +``` + +## Register Capabilities Explicitly in `install()` + +Inside `install()`, wire behavior through Vue application APIs: +- `app.component()` for global components +- `app.directive()` for global directives +- `app.provide()` for injectable services and config +- `app.config.globalProperties` for optional global helpers (sparingly) + +**BAD:** +```ts +const uselessPlugin = { + install(app, options) { + const service = createService(options) + } +} +``` + +**GOOD:** +```ts +const usefulPlugin = { + install(app, options) { + const service = createService(options) + app.provide(serviceKey, service) + } +} +``` + +## Type Plugin Contracts + +Use Vue's `Plugin` type to keep install signatures and options type-safe. + +```ts +import type { App, Plugin } from 'vue' + +interface MyOptions { + apiKey: string +} + +const myPlugin: Plugin<[MyOptions]> = { + install(app: App, options: MyOptions) { + app.provide(apiKeyKey, options.apiKey) + } +} +``` + +## Use Symbol Injection Keys in Plugins + +String keys can collide (`'http'`, `'config'`, `'i18n'`). Use symbol keys with `InjectionKey` so injections are unique and typed. + +**BAD:** +```ts +export default { + install(app) { + app.provide('http', axios) + app.provide('config', appConfig) + } +} +``` + +**GOOD:** +```ts +import type { InjectionKey } from 'vue' +import type { AxiosInstance } from 'axios' + +interface AppConfig { + apiUrl: string + timeout: number +} + +export const httpKey: InjectionKey = Symbol('http') +export const configKey: InjectionKey = Symbol('appConfig') + +export default { + install(app) { + app.provide(httpKey, axios) + app.provide(configKey, { apiUrl: '/api', timeout: 5000 }) + } +} +``` + +## Provide Required Injection Helpers + +Wrap required injections in composables that throw clear setup errors. + +```ts +import { inject } from 'vue' +import { authKey, type AuthService } from '@/injection-keys' + +export function useAuth(): AuthService { + const auth = inject(authKey) + if (!auth) { + throw new Error('Auth plugin not installed. Did you forget app.use(authPlugin)?') + } + return auth +} +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/reactivity.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/reactivity.md new file mode 100644 index 0000000..4cf0ad3 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/reactivity.md @@ -0,0 +1,344 @@ +--- +title: Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch) +impact: MEDIUM +impactDescription: Clear reactivity choices keep state predictable and reduce unnecessary updates in Vue 3 apps +type: efficiency +tags: [vue3, reactivity, ref, reactive, shallowRef, computed, watch, watchEffect, external-state, best-practice] +--- + +# Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch) + +**Impact: MEDIUM** - Choose the right reactive primitive first, derive with `computed`, and use watchers only for side effects. + +This reference covers the core reactivity decisions for local state, external data, derived values, and effects. + +## Task List + +- Declare reactive state correctly + - Always use `shallowRef()` instead of `ref()` for primitive values + - Choose the correct reactive declaration method for objects/arrays/map/set +- Follow best practices for `reactive` + - Avoid destructuring from `reactive()` directly + - Watch correctly for `reactive` +- Follow best practices for `computed` + - Prefer `computed` over watcher-assigned derived refs + - Keep filtered/sorted derivations out of templates + - Use `computed` for reusable class/style logic + - Keep computed getters pure (no side effects) and put side effects in watchers +- Follow best practices for watchers + - Use `immediate: true` instead of duplicate initial calls + - Clean up async effects for watchers + +## Declare reactive state correctly + +### Always use `shallowRef()` instead of `ref()` for primitive values (string, number, boolean, null, etc.) for better performance. + +**Incorrect:** +```ts +import { ref } from 'vue' +const count = ref(0) +``` + +**Correct:** +```ts +import { shallowRef } from 'vue' +const count = shallowRef(0) +``` + +### Choose the correct reactive declaration method for objects/arrays/map/set + +Use `ref()` when you often **replace the entire value** (`state.value = newObj`) and still want deep reactivity inside it, usually used for: + +- Frequently reassigned state (replace fetched object/list, reset to defaults, switch presets). +- Composable return values where updates happen mostly via `.value` reassignment. + +Use `reactive()` when you mainly **mutate properties** and full replacement is uncommon, usually used for: + +- “Single state object” patterns (stores/forms): `state.count++`, `state.items.push(...)`, `state.user.name = ...`. +- Situations where you want to avoid `.value` and update nested fields in place. + +```ts +import { reactive } from 'vue' + +const state = reactive({ + count: 0, + user: { name: 'Alice', age: 30 } +}) + +state.count++ // ✅ reactive +state.user.age = 31 // ✅ reactive +// ❌ avoid replacing the reactive object reference: +// state = reactive({ count: 1 }) +``` + +Use `shallowRef()` when the value is **opaque / should not be proxied** (class instances, external library objects, very large nested data) and you only want updates to trigger when you **replace** `state.value` (no deep tracking), usually used for: + +- Storing external instances/handles (SDK clients, class instances) without Vue proxying internals. +- Large data where you update by replacing the root reference (immutable-style updates). + +```ts +import { shallowRef } from 'vue' + +const user = shallowRef({ name: 'Alice', age: 30 }) + +user.value.age = 31 // ❌ not reactive +user.value = { name: 'Bob', age: 25 } // ✅ triggers update +``` + +Use `shallowReactive()` when you want **only top-level properties** reactive; nested objects remain raw, usually used for: + +- Container objects where only top-level keys change and nested payloads should stay unmanaged/unproxied. +- Mixed structures where Vue tracks the wrapper object, but not deeply nested or foreign objects. + +```ts +import { shallowReactive } from 'vue' + +const state = shallowReactive({ + count: 0, + user: { name: 'Alice', age: 30 } +}) + +state.count++ // ✅ reactive +state.user.age = 31 // ❌ not reactive +``` + +## Best practices for `reactive` + +### Avoid destructuring from `reactive()` directly + +**BAD:** + +```ts +import { reactive } from 'vue' + +const state = reactive({ count: 0 }) +const { count } = state // ❌ disconnected from reactivity +``` + +### Watch correctly for reactive + +**BAD:** + +passing a non-getter value into `watch()` + +```ts +import { reactive, watch } from 'vue' + +const state = reactive({ count: 0 }) + +// ❌ watch expects a getter, ref, reactive object, or array of these +watch(state.count, () => { /* ... */ }) +``` + +**GOOD:** + +preserve reactivity with `toRefs()` and use a getter for `watch()` + +```ts +import { reactive, toRefs, watch } from 'vue' + +const state = reactive({ count: 0 }) +const { count } = toRefs(state) // ✅ count is a ref + +watch(count, () => { /* ... */ }) // ✅ +watch(() => state.count, () => { /* ... */ }) // ✅ +``` + +## Best practices for `computed` + +### Prefer `computed` over watcher-assigned derived refs + +**BAD:** +```ts +import { ref, watchEffect } from 'vue' + +const items = ref([{ price: 10 }, { price: 20 }]) +const total = ref(0) + +watchEffect(() => { + total.value = items.value.reduce((sum, item) => sum + item.price, 0) +}) +``` + +**GOOD:** +```ts +import { ref, computed } from 'vue' + +const items = ref([{ price: 10 }, { price: 20 }]) +const total = computed(() => + items.value.reduce((sum, item) => sum + item.price, 0) +) +``` + +### Keep filtered/sorted derivations out of templates + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +### Use `computed` for reusable class/style logic + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +### Keep computed getters pure (no side effects) and put side effects in watchers instead + +A computed getter should only derive a value. No mutation, no API calls, no storage writes, no event emits. +([Reference](https://vuejs.org/guide/essentials/computed.html#best-practices)) + +**BAD:** + +side effects inside computed + +```ts +const count = ref(0) + +const doubled = computed(() => { + // ❌ side effect + if (count.value > 10) console.warn('Too big!') + return count.value * 2 +}) +``` + +**GOOD:** + +pure computed + `watch()` for side effects + +```ts +const count = ref(0) +const doubled = computed(() => count.value * 2) + +watch(count, (value) => { + if (value > 10) console.warn('Too big!') +}) +``` + +## Best practices for watchers + +### Use `immediate: true` instead of duplicate initial calls + +**BAD:** +```ts +import { ref, watch, onMounted } from 'vue' + +const userId = ref(1) + +function loadUser(id) { + // ... +} + +onMounted(() => loadUser(userId.value)) +watch(userId, (id) => loadUser(id)) +``` + +**GOOD:** +```ts +import { ref, watch } from 'vue' + +const userId = ref(1) + +watch( + userId, + (id) => loadUser(id), + { immediate: true } +) +``` + +### Clean up async effects for watchers + +When reacting to rapid changes (search boxes, filters), cancel the previous request. + +**GOOD:** + +```ts +const query = ref('') +const results = ref([]) + +watch(query, async (q, _prev, onCleanup) => { + const controller = new AbortController() + onCleanup(() => controller.abort()) + + const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { + signal: controller.signal, + }) + + results.value = await res.json() +}) +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/render-functions.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/render-functions.md new file mode 100644 index 0000000..b64942c --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/render-functions.md @@ -0,0 +1,201 @@ +--- +title: Render Function Patterns and Performance +impact: MEDIUM +impactDescription: Render functions require explicit patterns for lists, events, v-model, and performance to stay correct and maintainable +type: best-practice +tags: [vue3, render-function, h, v-model, directives, performance, jsx] +--- + +# Render Function Patterns and Performance + +**Impact: MEDIUM** - Render functions are powerful but opt out of template compiler optimizations. Use them intentionally and apply the key patterns below to keep output correct and performant. + +## Task List + +- Prefer templates; use render functions only when templates cannot express the logic +- Always add stable keys when rendering lists with `h()`/JSX +- Use `withModifiers` / `withKeys` for event modifiers +- Implement `v-model` via `modelValue` + `onUpdate:modelValue` +- Apply custom directives with `withDirectives` +- Use functional components for stateless presentational UI + +## Prefer templates over render functions + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## Always add keys for list rendering + +**BAD:** +```javascript +import { h, ref } from 'vue' + +export default { + setup() { + const items = ref([{ id: 1, name: 'Apple' }]) + + return () => h('ul', + items.value.map(item => h('li', item.name)) + ) + } +} +``` + +**GOOD:** +```javascript +import { h, ref } from 'vue' + +export default { + setup() { + const items = ref([{ id: 1, name: 'Apple' }]) + + return () => h('ul', + items.value.map(item => h('li', { key: item.id }, item.name)) + ) + } +} +``` + +## Use `withModifiers` / `withKeys` for event modifiers + +**BAD:** +```javascript +import { h } from 'vue' + +export default { + setup() { + const handleClick = (e) => { + e.stopPropagation() + e.preventDefault() + } + + return () => h('button', { onClick: handleClick }, 'Click') + } +} +``` + +**GOOD:** +```javascript +import { h, withModifiers, withKeys } from 'vue' + +export default { + setup() { + const handleClick = () => {} + const handleEnter = () => {} + + return () => h('div', [ + h('button', { + onClick: withModifiers(handleClick, ['stop', 'prevent']) + }, 'Click'), + h('input', { + onKeyup: withKeys(handleEnter, ['enter']) + }) + ]) + } +} +``` + +## Implement `v-model` explicitly + +**BAD:** +```javascript +import { h, ref } from 'vue' +import CustomInput from './CustomInput.vue' + +export default { + setup() { + const text = ref('') + return () => h(CustomInput, { modelValue: text.value }) + } +} +``` + +**GOOD:** +```javascript +import { h, ref } from 'vue' +import CustomInput from './CustomInput.vue' + +export default { + setup() { + const text = ref('') + return () => h(CustomInput, { + modelValue: text.value, + 'onUpdate:modelValue': (value) => { text.value = value } + }) + } +} +``` + +## Use `withDirectives` for custom directives + +**BAD:** +```javascript +import { h } from 'vue' + +const vFocus = { mounted: (el) => el.focus() } + +export default { + setup() { + return () => h('input', { 'v-focus': true }) + } +} +``` + +**GOOD:** +```javascript +import { h, withDirectives } from 'vue' + +const vFocus = { mounted: (el) => el.focus() } + +export default { + setup() { + return () => withDirectives(h('input'), [[vFocus]]) + } +} +``` + +## Prefer functional components for stateless UI + +**BAD:** +```javascript +import { h } from 'vue' + +export default { + setup() { + return () => h('span', { class: 'badge' }, 'New') + } +} +``` + +**GOOD:** +```javascript +import { h } from 'vue' + +function Badge(props, { slots }) { + return h('span', { class: 'badge' }, slots.default?.()) +} + +Badge.props = ['variant'] + +export default Badge +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/sfc.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/sfc.md new file mode 100644 index 0000000..d1c3981 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/sfc.md @@ -0,0 +1,310 @@ +--- +title: Single-File Component Structure, Styling, and Template Patterns +impact: MEDIUM +impactDescription: Consistent SFC structure and styling choices improve maintainability, tooling support, and render performance +type: best-practice +tags: [vue3, sfc, scoped-css, styles, build-tools, performance, template, v-html, v-for, computed, v-if, v-show] +--- + +# Single-File Component Structure, Styling, and Template Patterns + +**Impact: MEDIUM** - Using SFCs with consistent structure and performant styling keeps components easier to maintain and avoids unnecessary render overhead. + +## Task List + +- Use `.vue` SFCs instead of separate `.js`/`.ts` and `.css` files for components +- Colocate template, script, and styles in the same SFC by default +- Use PascalCase for component names in templates and filenames +- Prefer component-scoped styles +- Prefer class selectors (not element selectors) in scoped CSS for performance +- Access DOM / component refs with `useTemplateRef()` in Vue 3.5+ +- Use camelCase keys in `:style` bindings for consistency and IDE support +- Use `v-for` and `v-if` correctly +- Never use `v-html` with untrusted/user-provided content +- Choose `v-if` vs `v-show` based on toggle frequency and initial render cost + +## Colocate template, script, and styles + +**BAD:** +``` +components/ +├── UserCard.vue +├── UserCard.js +└── UserCard.css +``` + +**GOOD:** +```vue + + + + + + +``` + +## Use PascalCase for component names + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Best practices for ` +``` + +**GOOD:** + +```vue + +``` + +**GOOD:** + +```css +/* src/assets/main.css */ +/* ✅ resets, tokens, typography, app-wide rules */ +:root { --radius: 999px; } +``` + +### Use class selectors in scoped CSS + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Access DOM / component refs with `useTemplateRef()` + +For Vue 3.5+: use `useTemplateRef()` to access template refs. + +```vue + + + +``` + +## Use camelCase in `:style` bindings + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `v-for` and `v-if` correctly + +### Always provide a stable `:key` + +- Prefer primitive keys (`string | number`). +- Avoid using objects as keys. + +**GOOD:** + +```vue +
  • + +
  • +``` + +### Avoid `v-if` and `v-for` on the same element + +It leads to unclear intent and unnecessary work. +([Reference](https://vuejs.org/guide/essentials/list.html#v-for-with-v-if)) + +**To filter items** +**BAD:** + +```vue +
  • + {{ user.name }} +
  • +``` + +**GOOD:** + +```vue + + + +``` + +**To conditionally show/hide the entire list** +**GOOD:** + +```vue +
      +
    • + {{ user.name }} +
    • +
    +``` + +## Never render untrusted HTML with `v-html` + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## Choose `v-if` vs `v-show` by toggle behavior + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/state-management.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/state-management.md new file mode 100644 index 0000000..02423ab --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/state-management.md @@ -0,0 +1,135 @@ +--- +title: State Management Strategy +impact: HIGH +impactDescription: Choosing the wrong store pattern can cause SSR request leaks, brittle mutation flows, and poor scaling +type: best-practice +tags: [vue3, state-management, pinia, composables, ssr, vueuse] +--- + +# State Management Strategy + +**Impact: HIGH** - Use the lightest state solution that fits your app architecture. SPA-only apps can use lightweight global composables, while SSR/Nuxt apps should default to Pinia for request-safe isolation and predictable tooling. + +## Task List + +- Keep state local first, then promote to shared/global only when needed +- Use singleton composables only in non-SSR applications +- Expose global state as readonly and mutate through explicit actions +- Prefer Pinia for SSR/Nuxt, large apps, and advanced debugging/plugin needs +- Avoid exporting mutable module-level reactive state directly + +## Choose the Lightest Store Approach + +- **Feature composable:** Default for reusable logic with local/feature-level state. +- **Singleton composable or VueUse `createGlobalState`:** Small non-SSR apps needing shared app state. +- **Pinia:** SSR/Nuxt apps, medium-to-large apps, and cases requiring DevTools, plugins, or action tracing. + +## Avoid Exporting Mutable Module State + +**BAD:** +```ts +// store/cart.ts +import { reactive } from 'vue' + +export const cart = reactive({ + items: [] as Array<{ id: string; qty: number }> +}) +``` + +**GOOD:** +```ts +// composables/useCartStore.ts +import { reactive, readonly } from 'vue' + +let _store: ReturnType | null = null + +function createCartStore() { + const state = reactive({ + items: [] as Array<{ id: string; qty: number }> + }) + + function addItem(id: string, qty = 1) { + const existing = state.items.find((item) => item.id === id) + if (existing) { + existing.qty += qty + return + } + state.items.push({ id, qty }) + } + + return { + state: readonly(state), + addItem + } +} + +export function useCartStore() { + if (!_store) _store = createCartStore() + return _store +} +``` + +## Do Not Use Runtime Singletons in SSR + +Module singletons live for the runtime lifetime. In SSR this can leak state between requests. + +**BAD:** +```ts +// shared singleton reused across requests +const cartStore = useCartStore() + +export function useServerCart() { + return cartStore +} +``` + +**GOOD:** + +> `pinia` dependency required. + +```ts +// stores/cart.ts +import { defineStore } from 'pinia' + +export const useCartStore = defineStore('cart', { + state: () => ({ + items: [] as Array<{ id: string; qty: number }> + }), + actions: { + addItem(id: string, qty = 1) { + const existing = this.items.find((item) => item.id === id) + if (existing) { + existing.qty += qty + return + } + this.items.push({ id, qty }) + } + } +}) +``` + +## Use `createGlobalState` for Small SPA Global State + +> `@vueuse/core` dependency required. + +If the app is non-SSR and already uses VueUse, `createGlobalState` removes singleton boilerplate. + +```ts +import { createGlobalState } from '@vueuse/core' +import { computed, ref } from 'vue' + +export const useAuthState = createGlobalState(() => { + const token = ref(null) + const isAuthenticated = computed(() => token.value !== null) + + function setToken(next: string | null) { + token.value = next + } + + return { + token, + isAuthenticated, + setToken + } +}) +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-best-practices/references/updated-hook-performance.md b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/updated-hook-performance.md new file mode 100644 index 0000000..6375e86 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-best-practices/references/updated-hook-performance.md @@ -0,0 +1,187 @@ +--- +title: Avoid Expensive Operations in Updated Hook +impact: MEDIUM +impactDescription: Heavy computations in updated hook cause performance bottlenecks and potential infinite loops +type: capability +tags: [vue3, vue2, lifecycle, updated, performance, optimization, reactivity] +--- + +# Avoid Expensive Operations in Updated Hook + +**Impact: MEDIUM** - The `updated` hook runs after every reactive state change that causes a re-render. Placing expensive operations, API calls, or state mutations here can cause severe performance degradation, infinite loops, and dropped frames below the optimal 60fps threshold. + +Use `updated`/`onUpdated` sparingly for post-DOM-update operations that cannot be handled by watchers or computed properties. For most reactive data handling, prefer watchers (`watch`/`watchEffect`) which provide more control over what triggers the callback. + +## Task List + +- Never perform API calls in updated hook +- Never mutate reactive state inside updated (causes infinite loops) +- Use conditional checks to verify updates are relevant before acting +- Prefer `watch` or `watchEffect` for reacting to specific data changes +- Use throttling/debouncing if updated operations are expensive +- Reserve updated for low-level DOM synchronization tasks + +**BAD:** +```javascript +// BAD: API call in updated - fires on every re-render +export default { + data() { + return { items: [], lastUpdate: null } + }, + updated() { + // This runs after every single state change! + fetch('/api/sync', { + method: 'POST', + body: JSON.stringify(this.items) + }) + } +} +``` + +```javascript +// BAD: State mutation in updated - infinite loop +export default { + data() { + return { renderCount: 0 } + }, + updated() { + // This causes another update, which triggers updated again! + this.renderCount++ // Infinite loop + } +} +``` + +```javascript +// BAD: Heavy computation on every update +export default { + updated() { + // Expensive operation runs on every keystroke, every state change + this.processedData = this.heavyComputation(this.rawData) + this.analytics = this.calculateMetrics(this.allData) + } +} +``` + +**GOOD:** +```javascript +import debounce from 'lodash-es/debounce' + +// GOOD: Use watcher for specific data changes +export default { + data() { + return { items: [] } + }, + watch: { + // Only fires when items actually changes + items: { + handler(newItems) { + this.syncToServer(newItems) + }, + deep: true + } + }, + methods: { + syncToServer: debounce(function(items) { + fetch('/api/sync', { + method: 'POST', + body: JSON.stringify(items) + }) + }, 500) + } +} +``` + +```vue + + +``` + +```javascript +// GOOD: Conditional check in updated hook +export default { + data() { + return { + content: '', + lastSyncedContent: '' + } + }, + updated() { + // Only act if specific condition is met + if (this.content !== this.lastSyncedContent) { + this.syncContent() + this.lastSyncedContent = this.content + } + }, + methods: { + syncContent: debounce(function() { + // Sync logic + }, 300) + } +} +``` + +## Valid Use Cases for Updated Hook + +```javascript +// GOOD: Low-level DOM synchronization +export default { + updated() { + // Sync third-party library with Vue's DOM + this.thirdPartyWidget.refresh() + + // Update scroll position after content change + this.$nextTick(() => { + this.maintainScrollPosition() + }) + } +} +``` + +## Prefer Computed Properties for Derived Data + +```javascript +// BAD: Calculating derived data in updated +export default { + data() { + return { numbers: [1, 2, 3, 4, 5] } + }, + updated() { + this.sum = this.numbers.reduce((a, b) => a + b, 0) // Causes another update! + } +} + +// GOOD: Use computed property instead +export default { + data() { + return { numbers: [1, 2, 3, 4, 5] } + }, + computed: { + sum() { + return this.numbers.reduce((a, b) => a + b, 0) + } + } +} +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/SKILL.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/SKILL.md new file mode 100644 index 0000000..2ec6350 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/SKILL.md @@ -0,0 +1,202 @@ +--- +name: vue-debug-guides +description: Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues. +--- + +Vue 3 debugging and error handling for runtime issues, warnings, async failures, and hydration bugs. +For development best practices and common gotchas, use `vue-best-practices`. + +### Reactivity +- Tracing unexpected re-renders and state updates → See [reactivity-debugging-hooks](reference/reactivity-debugging-hooks.md) +- Ref values not updating due to missing .value access → See [ref-value-access](reference/ref-value-access.md) +- State stops updating after destructuring reactive objects → See [reactive-destructuring](reference/reactive-destructuring.md) +- Refs inside arrays, Maps, or Sets not unwrapping → See [refs-in-collections-need-value](reference/refs-in-collections-need-value.md) +- Nested refs rendering as [object Object] in templates → See [template-ref-unwrapping-top-level](reference/template-ref-unwrapping-top-level.md) +- Reactive proxy identity comparisons always return false → See [reactivity-proxy-identity-hazard](reference/reactivity-proxy-identity-hazard.md) +- Third-party instances breaking when proxied → See [reactivity-markraw-for-non-reactive](reference/reactivity-markraw-for-non-reactive.md) +- Watchers only firing once per tick unexpectedly → See [reactivity-same-tick-batching](reference/reactivity-same-tick-batching.md) + +### Computed +- Computed getter triggers mutations or requests unexpectedly → See [computed-no-side-effects](reference/computed-no-side-effects.md) +- Mutating computed values causes changes to disappear → See [computed-return-value-readonly](reference/computed-return-value-readonly.md) +- Computed value never updates after conditional logic → See [computed-conditional-dependencies](reference/computed-conditional-dependencies.md) +- Sorting or reversing arrays breaks original state → See [computed-array-mutation](reference/computed-array-mutation.md) +- Passing parameters to computed properties fails → See [computed-no-parameters](reference/computed-no-parameters.md) + +### Watchers +- Async operations overwriting with stale data → See [watch-async-cleanup](reference/watch-async-cleanup.md) +- Creating watchers inside async callbacks → See [watch-async-creation-memory-leak](reference/watch-async-creation-memory-leak.md) +- Watcher never triggers for reactive object properties → See [watch-reactive-property-getter](reference/watch-reactive-property-getter.md) +- Async watchEffect misses dependencies after await → See [watcheffect-async-dependency-tracking](reference/watcheffect-async-dependency-tracking.md) +- DOM reads are stale inside watcher callbacks → See [watch-flush-timing](reference/watch-flush-timing.md) +- Deep watchers report identical old/new values → See [watch-deep-same-object-reference](reference/watch-deep-same-object-reference.md) +- watchEffect runs before template refs update → See [watcheffect-flush-post-for-refs](reference/watcheffect-flush-post-for-refs.md) + +### Components +- Child component throws "component not found" error → See [local-components-not-in-descendants](reference/local-components-not-in-descendants.md) +- Click listener doesn't fire on custom component → See [click-events-on-components](reference/click-events-on-components.md) +- Parent can't access child ref data in script setup → See [component-ref-requires-defineexpose](reference/component-ref-requires-defineexpose.md) +- HTML template parsing breaks Vue component syntax → See [in-dom-template-parsing-caveats](reference/in-dom-template-parsing-caveats.md) +- Wrong component renders due to naming collisions → See [component-naming-conflicts](reference/component-naming-conflicts.md) +- Parent styles don't apply to multi-root component → See [multi-root-component-class-attrs](reference/multi-root-component-class-attrs.md) + +### Props & Emits +- Variables referenced in defineProps cause errors → See [prop-defineprops-scope-limitation](reference/prop-defineprops-scope-limitation.md) +- Component emits undeclared event causing warnings → See [declare-emits-for-documentation](reference/declare-emits-for-documentation.md) +- defineEmits used inside function or conditional → See [defineEmits-must-be-top-level](reference/defineEmits-must-be-top-level.md) +- defineEmits has both type and runtime arguments → See [defineEmits-no-runtime-and-type-mixed](reference/defineEmits-no-runtime-and-type-mixed.md) +- Native event listeners not responding to clicks → See [native-event-collision-with-emits](reference/native-event-collision-with-emits.md) +- Component event fires twice when clicking → See [undeclared-emits-double-firing](reference/undeclared-emits-double-firing.md) + +### Templates +- Getting template compilation errors with statements → See [template-expressions-restrictions](reference/template-expressions-restrictions.md) +- "Cannot read property of undefined" runtime errors → See [v-if-null-check-order](reference/v-if-null-check-order.md) +- Dynamic directive arguments not working properly → See [dynamic-argument-constraints](reference/dynamic-argument-constraints.md) +- v-else elements rendering unconditionally always → See [v-else-must-follow-v-if](reference/v-else-must-follow-v-if.md) +- Mixing v-if with v-for causes precedence bugs and migration breakage → See [no-v-if-with-v-for](reference/no-v-if-with-v-for.md) +- Template function calls mutating state cause unpredictable re-render bugs → See [template-functions-no-side-effects](reference/template-functions-no-side-effects.md) +- Child components in loops showing undefined data → See [v-for-component-props](reference/v-for-component-props.md) +- Array order changing after sorting or reversing → See [v-for-computed-reverse-sort](reference/v-for-computed-reverse-sort.md) +- List items disappearing or swapping state unexpectedly → See [v-for-key-attribute](reference/v-for-key-attribute.md) +- Getting off-by-one errors with range iteration → See [v-for-range-starts-at-one](reference/v-for-range-starts-at-one.md) +- v-show or v-else not working on template elements → See [v-show-template-limitation](reference/v-show-template-limitation.md) + +### Template Refs +- Ref becomes null when element is conditionally hidden → See [template-ref-null-with-v-if](reference/template-ref-null-with-v-if.md) +- Ref array indices don't match data array in loops → See [template-ref-v-for-order](reference/template-ref-v-for-order.md) +- Refactoring template ref names breaks silently in code → See [use-template-ref-vue35](reference/use-template-ref-vue35.md) + +### Forms & v-model +- Initial form values not showing when using v-model → See [v-model-ignores-html-attributes](reference/v-model-ignores-html-attributes.md) +- Textarea content changes not updating the ref → See [textarea-no-interpolation](reference/textarea-no-interpolation.md) +- iOS users cannot select dropdown first option → See [select-initial-value-ios-bug](reference/select-initial-value-ios-bug.md) +- Parent and child components have different values → See [define-model-default-value-sync](reference/define-model-default-value-sync.md) +- Object property changes not syncing to parent → See [definemodel-object-mutation-no-emit](reference/definemodel-object-mutation-no-emit.md) +- Real-time search/validation broken for Chinese/Japanese input → See [v-model-ime-composition](reference/v-model-ime-composition.md) +- Number input returns empty string instead of zero → See [v-model-number-modifier-behavior](reference/v-model-number-modifier-behavior.md) +- Custom checkbox values not submitted in forms → See [checkbox-true-false-value-form-submission](reference/checkbox-true-false-value-form-submission.md) + +### Events & Modifiers +- Chaining multiple event modifiers produces unexpected results → See [event-modifier-order-matters](reference/event-modifier-order-matters.md) +- Keyboard shortcuts don't fire with system modifier keys → See [keyup-modifier-timing](reference/keyup-modifier-timing.md) +- Keyboard shortcuts fire with unintended modifier combinations → See [exact-modifier-for-precise-shortcuts](reference/exact-modifier-for-precise-shortcuts.md) +- Combining passive and prevent modifiers breaks event behavior → See [no-passive-with-prevent](reference/no-passive-with-prevent.md) + +### Lifecycle +- Memory leaks from unremoved event listeners → See [cleanup-side-effects](reference/cleanup-side-effects.md) +- DOM access fails before component mounts → See [lifecycle-dom-access-timing](reference/lifecycle-dom-access-timing.md) +- DOM reads return stale values after state changes → See [dom-update-timing-nexttick](reference/dom-update-timing-nexttick.md) +- SSR rendering differs from client hydration → See [lifecycle-ssr-awareness](reference/lifecycle-ssr-awareness.md) +- Lifecycle hooks registered asynchronously never run → See [lifecycle-hooks-synchronous-registration](reference/lifecycle-hooks-synchronous-registration.md) + +### Slots +- Accessing child component data in slot content returns undefined values → See [slot-render-scope-parent-only](reference/slot-render-scope-parent-only.md) +- Mixing named and scoped slots together causes compilation errors → See [slot-named-scoped-explicit-default](reference/slot-named-scoped-explicit-default.md) +- Using v-slot on native HTML elements causes compilation errors → See [slot-v-slot-on-components-or-templates-only](reference/slot-v-slot-on-components-or-templates-only.md) +- Unexpected content placement from implicit default slot behavior → See [slot-implicit-default-content](reference/slot-implicit-default-content.md) +- Scoped slot props missing expected name property → See [slot-name-reserved-prop](reference/slot-name-reserved-prop.md) +- Wrapper components breaking child slot functionality → See [slot-forwarding-to-child-components](reference/slot-forwarding-to-child-components.md) + +### Provide/Inject +- Calling provide after async operations fails silently → See [provide-inject-synchronous-setup](reference/provide-inject-synchronous-setup.md) +- Tracing where provided values come from → See [provide-inject-debugging-challenges](reference/provide-inject-debugging-challenges.md) +- Injected values not updating when provider changes → See [provide-inject-reactivity-not-automatic](reference/provide-inject-reactivity-not-automatic.md) +- Multiple components share same default object → See [provide-inject-default-value-factory](reference/provide-inject-default-value-factory.md) + +### Attrs +- Both internal and fallthrough event handlers execute → See [attrs-event-listener-merging](reference/attrs-event-listener-merging.md) +- Explicit attributes overwritten by fallthrough values → See [fallthrough-attrs-overwrite-vue3](reference/fallthrough-attrs-overwrite-vue3.md) +- Attributes applying to wrong element in wrappers → See [inheritattrs-false-for-wrapper-components](reference/inheritattrs-false-for-wrapper-components.md) + +### Composables +- Composable called outside setup context or asynchronously → See [composable-call-location-restrictions](reference/composable-call-location-restrictions.md) +- Composable reactive dependency not updating when input changes → See [composable-tovalue-inside-watcheffect](reference/composable-tovalue-inside-watcheffect.md) +- Composable mutates external state unexpectedly → See [composable-avoid-hidden-side-effects](reference/composable-avoid-hidden-side-effects.md) +- Destructuring composable returns breaks reactivity unexpectedly → See [composable-naming-return-pattern](reference/composable-naming-return-pattern.md) + +### Composition API +- Lifecycle hooks failing silently after async operations → See [composition-api-script-setup-async-context](reference/composition-api-script-setup-async-context.md) +- Parent component refs unable to access exposed properties → See [define-expose-before-await](reference/define-expose-before-await.md) +- Functional-programming patterns break expected Vue reactivity behavior → See [composition-api-not-functional-programming](reference/composition-api-not-functional-programming.md) +- React Hook mental model causes incorrect Composition API usage → See [composition-api-vs-react-hooks-differences](reference/composition-api-vs-react-hooks-differences.md) + +### Animation +- Animations fail to trigger when DOM nodes are reused → See [animation-key-for-rerender](reference/animation-key-for-rerender.md) +- TransitionGroup list updates feel laggy under load → See [animation-transitiongroup-performance](reference/animation-transitiongroup-performance.md) + +### TypeScript +- Mutable prop defaults leak state between component instances → See [ts-withdefaults-mutable-factory-function](reference/ts-withdefaults-mutable-factory-function.md) +- reactive() generic typing causes ref unwrapping mismatches → See [ts-reactive-no-generic-argument](reference/ts-reactive-no-generic-argument.md) +- Template refs throw null access errors before mount or after v-if unmount → See [ts-template-ref-null-handling](reference/ts-template-ref-null-handling.md) +- Optional boolean props behave as false instead of undefined → See [ts-defineprops-boolean-default-false](reference/ts-defineprops-boolean-default-false.md) +- Imported defineProps types fail with unresolvable or complex type references → See [ts-defineprops-imported-types-limitations](reference/ts-defineprops-imported-types-limitations.md) +- Untyped DOM event handlers fail under strict TypeScript settings → See [ts-event-handler-explicit-typing](reference/ts-event-handler-explicit-typing.md) +- Dynamic component refs trigger reactive component warnings → See [ts-shallowref-for-dynamic-components](reference/ts-shallowref-for-dynamic-components.md) +- Union-typed template expressions fail type checks without narrowing → See [ts-template-type-casting](reference/ts-template-type-casting.md) + +### Async Components +- Route components misconfigured with defineAsyncComponent lazy loading → See [async-component-vue-router](reference/async-component-vue-router.md) +- Network failures or timeouts loading components → See [async-component-error-handling](reference/async-component-error-handling.md) +- Template refs undefined after component reactivation → See [async-component-keepalive-ref-issue](reference/async-component-keepalive-ref-issue.md) + +### Render Functions +- Render function output stays static after state changes → See [rendering-render-function-return-from-setup](reference/rendering-render-function-return-from-setup.md) +- Reused vnode instances render incorrectly → See [render-function-vnodes-must-be-unique](reference/render-function-vnodes-must-be-unique.md) +- String component names render as HTML elements → See [rendering-resolve-component-for-string-names](reference/rendering-resolve-component-for-string-names.md) +- Accessing vnode internals breaks on Vue updates → See [render-function-avoid-internal-vnode-properties](reference/render-function-avoid-internal-vnode-properties.md) +- Vue 2 render function patterns crash in Vue 3 → See [rendering-render-function-h-import-vue3](reference/rendering-render-function-h-import-vue3.md) +- Slot content not rendering from h() → See [rendering-render-function-slots-as-functions](reference/rendering-render-function-slots-as-functions.md) + +### KeepAlive +- Child components mount twice with nested Vue Router routes → See [keepalive-router-nested-double-mount](reference/keepalive-router-nested-double-mount.md) +- Memory grows when combining KeepAlive with Transition animations → See [keepalive-transition-memory-leak](reference/keepalive-transition-memory-leak.md) + +### Transitions +- JavaScript transition hooks hang without done callback → See [transition-js-hooks-done-callback](reference/transition-js-hooks-done-callback.md) +- Move animations fail on inline list elements → See [transition-group-flip-inline-elements](reference/transition-group-flip-inline-elements.md) +- List items jump instead of smoothly animating → See [transition-group-move-animation-position-absolute](reference/transition-group-move-animation-position-absolute.md) +- Vue 2 to Vue 3 TransitionGroup wrapper changes break layout → See [transition-group-no-default-wrapper-vue3](reference/transition-group-no-default-wrapper-vue3.md) +- Nested transitions cut off before finishing → See [transition-nested-duration](reference/transition-nested-duration.md) +- Scoped styles stop working in reusable transition wrappers → See [transition-reusable-scoped-style](reference/transition-reusable-scoped-style.md) +- RouterView transitions animate unexpectedly on first render → See [transition-router-view-appear](reference/transition-router-view-appear.md) +- Mixing CSS transitions and animations causes timing issues → See [transition-type-when-mixed](reference/transition-type-when-mixed.md) +- Cleanup hooks missed during rapid transition swaps → See [transition-unmount-hook-timing](reference/transition-unmount-hook-timing.md) + +### Teleport +- Teleport target element not found in DOM → See [teleport-target-must-exist](reference/teleport-target-must-exist.md) +- Teleported content breaks SSR hydration → See [teleport-ssr-hydration](reference/teleport-ssr-hydration.md) +- Scoped styles not applying to teleported content → See [teleport-scoped-styles-limitation](reference/teleport-scoped-styles-limitation.md) + +### Suspense +- Need to handle async errors from Suspense components → See [suspense-no-builtin-error-handling](reference/suspense-no-builtin-error-handling.md) +- Using Suspense with server-side rendering → See [suspense-ssr-hydration-issues](reference/suspense-ssr-hydration-issues.md) +- Async component loading/error UI ignored under Suspense → See [async-component-suspense-control](reference/async-component-suspense-control.md) + +### SSR +- HTML differs between server and client renders → See [ssr-hydration-mismatch-causes](reference/ssr-hydration-mismatch-causes.md) +- User state leaks between requests from shared singleton stores → See [state-ssr-cross-request-pollution](reference/state-ssr-cross-request-pollution.md) +- Browser-only APIs crash server rendering in universal code paths → See [ssr-platform-specific-apis](reference/ssr-platform-specific-apis.md) + +### Performance +- List children re-render unnecessarily because parent passes unstable props → See [perf-props-stability-update-optimization](reference/perf-props-stability-update-optimization.md) +- Computed objects retrigger effects despite equivalent values → See [perf-computed-object-stability](reference/perf-computed-object-stability.md) + +### SFC (Single File Components) +- Trying to use named exports from component script blocks → See [sfc-named-exports-forbidden](reference/sfc-named-exports-forbidden.md) +- Variables not updating in template after changes → See [sfc-script-setup-reactivity](reference/sfc-script-setup-reactivity.md) +- Scoped styles not applying to child component elements → See [sfc-scoped-css-child-component-styling](reference/sfc-scoped-css-child-component-styling.md) +- Scoped styles not applying to dynamic v-html content → See [sfc-scoped-css-dynamic-content](reference/sfc-scoped-css-dynamic-content.md) +- Scoped styles not applying to slot content → See [sfc-scoped-css-slot-content](reference/sfc-scoped-css-slot-content.md) +- Tailwind classes missing when built dynamically → See [tailwind-dynamic-class-generation](reference/tailwind-dynamic-class-generation.md) +- Recursive components not rendering due to name conflicts → See [self-referencing-component-name](reference/self-referencing-component-name.md) + +### Plugins +- Debugging why global properties cause naming conflicts → See [plugin-global-properties-sparingly](reference/plugin-global-properties-sparingly.md) +- Plugin not working or inject returns undefined → See [plugin-install-before-mount](reference/plugin-install-before-mount.md) +- Plugin global properties are unavailable in setup-based components → See [plugin-prefer-provide-inject-over-global-properties](reference/plugin-prefer-provide-inject-over-global-properties.md) +- Plugin type augmentation mistakes break ComponentCustomProperties typing → See [plugin-typescript-type-augmentation](reference/plugin-typescript-type-augmentation.md) + +### App Configuration +- App configuration methods not working after mount call → See [configure-app-before-mount](reference/configure-app-before-mount.md) +- Chaining app config off mount() fails because mount returns component instance → See [mount-return-value](reference/mount-return-value.md) +- require.context-based component auto-registration fails in Vite → See [dynamic-component-registration-vite](reference/dynamic-component-registration-vite.md) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-key-for-rerender.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-key-for-rerender.md new file mode 100644 index 0000000..5ea8407 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-key-for-rerender.md @@ -0,0 +1,160 @@ +--- +title: Use Key Attribute to Force Re-render Animations +impact: MEDIUM +impactDescription: Without key attributes, Vue reuses DOM elements and animation libraries like AutoAnimate cannot detect changes to animate +type: gotcha +tags: [vue3, animation, key, autoanimate, rerender, dom] +--- + +# Use Key Attribute to Force Re-render Animations + +**Impact: MEDIUM** - Vue optimizes performance by reusing DOM elements when possible. However, this optimization can prevent animation libraries (like AutoAnimate) from detecting changes, because the element is updated in place rather than re-created. Adding a `:key` attribute forces Vue to treat changed elements as new, triggering proper animations. + +## Task Checklist + +- [ ] Add `:key` to elements that should animate when their content changes +- [ ] Use unique, changing values for keys (not indices) +- [ ] For route transitions, add `:key="$route.fullPath"` to `` +- [ ] Apply `v-auto-animate` to the parent element of keyed children + +**Problematic Code:** +```vue + + + +``` + +**Correct Code:** +```vue + + + +``` + +## Why This Works + +When Vue sees a `:key` change: +1. It considers the old element and new element as different +2. The old element is removed (triggering leave animation) +3. A new element is created (triggering enter animation) + +Without `:key`: +1. Vue sees the same element type in the same position +2. It updates the element's properties in place +3. No DOM addition/removal occurs, so no animation triggers + +## Common Use Cases + +### Animating Text Content Changes + +```vue + +``` + +### Animating Dynamic Components + +```vue + +``` + +### Animating Route Transitions + +```vue + +``` + +## With Vue's Built-in Transition + +The same principle applies to Vue's `` component: + +```vue + +``` + +## Caution: Performance Implications + +Using `:key` forces full component re-creation. For frequently changing data: +- The entire component tree under the keyed element is destroyed and recreated +- Any component state is lost +- Consider whether the animation is worth the performance cost + +```vue + + + +``` + +## Reference +- [Vue.js Animation Techniques](https://vuejs.org/guide/extras/animation.html) +- [AutoAnimate with Vue](https://auto-animate.formkit.com/#usage-vue) +- [Vue.js v-for with key](https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-transitiongroup-performance.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-transitiongroup-performance.md new file mode 100644 index 0000000..587da0e --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/animation-transitiongroup-performance.md @@ -0,0 +1,241 @@ +--- +title: TransitionGroup Performance with Large Lists and CSS Frameworks +impact: MEDIUM +impactDescription: TransitionGroup can cause noticeable DOM update lag when animating list changes, especially with CSS frameworks +type: gotcha +tags: [vue3, transition-group, animation, performance, list, css-framework] +--- + +# TransitionGroup Performance with Large Lists and CSS Frameworks + +**Impact: MEDIUM** - Vue's `` can experience significant DOM update lag when animating list changes, particularly when: +- Using CSS frameworks (Tailwind, Bootstrap, etc.) +- Performing array operations like `slice()` that change multiple items +- Working with larger lists + +Without TransitionGroup, DOM updates occur instantly. With it, there can be noticeable delay before the UI reflects changes. + +## Task Checklist + +- [ ] For frequently updated lists, consider if transition animations are necessary +- [ ] Use CSS `content-visibility: auto` for long lists to reduce render cost +- [ ] Minimize CSS framework classes on list items during transitions +- [ ] Consider virtual scrolling for very large animated lists +- [ ] Profile with Vue DevTools to identify transition bottlenecks + +**Problematic Pattern:** +```vue + + + + + +``` + +**Optimized Approach:** +```vue + + + + + +``` + +## Performance Optimization Strategies + +### 1. Skip Animations for Bulk Operations + +```vue + + + +``` + +### 2. Virtual Scrolling for Large Lists + +```vue + + + +``` + +### 3. Reduce CSS Complexity During Transitions + +```vue + +``` + +### 4. Use CSS content-visibility + +```css +/* For very long lists, defer rendering of off-screen items */ +.list-item { + content-visibility: auto; + contain-intrinsic-size: 0 50px; /* Estimated height */ +} +``` + +## When to Avoid TransitionGroup + +Consider alternatives when: +- List updates are frequent (real-time data) +- List contains 100+ items +- Items have complex CSS or nested components +- Performance is critical (mobile, low-end devices) + +```vue + +
      +
    • + {{ item.name }} +
    • +
    + + +``` + +## Reference +- [Vue.js TransitionGroup](https://vuejs.org/guide/built-ins/transition-group.html) +- [GitHub Issue: transition-group DOM update lag](https://github.com/vuejs/vue/issues/5845) +- [Vue Virtual Scroller](https://github.com/Akryum/vue-virtual-scroller) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-error-handling.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-error-handling.md new file mode 100644 index 0000000..7ea42c2 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-error-handling.md @@ -0,0 +1,115 @@ +# Async Component Error Handling + +## Rule + +Always configure error handling for async components using `errorComponent` and/or `onError` callback. Without proper error handling, failed component loads can leave the UI in an undefined state with no user feedback. + +## Why This Matters + +Network failures, timeouts, and server errors are common in production. Without error handling, users see blank spaces or broken UIs with no indication of what went wrong or how to recover. + +## Bad Code + +```vue + +``` + +```vue + +``` + +## Good Code + +```vue + +``` + +```vue + +``` + +```vue + +``` + +## onError Callback Parameters + +The `onError` callback receives four arguments: + +| Parameter | Type | Description | +|-----------|------|-------------| +| `error` | `Error` | The error that caused the load to fail | +| `retry` | `Function` | Call to retry loading the component | +| `fail` | `Function` | Call to give up and show errorComponent | +| `attempts` | `number` | Number of load attempts so far | + +## Key Points + +1. Always provide an `errorComponent` for production applications +2. Use `timeout` to prevent indefinite loading states +3. Consider retry logic with `onError` for transient network issues +4. The `delay` option (default 200ms) prevents loading flicker on fast networks +5. Use the fallback pattern (`.catch()` in loader) when you want a seamless degradation + +## SSR Warning + +Using `onError` with SSR can cause issues in some configurations, potentially leading to infinite loading. Test thoroughly in SSR environments. + +## References + +- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async) +- [Handling Async Components' loading errors](https://awad.dev/blog/handling-async-component-loading-errors/) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-keepalive-ref-issue.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-keepalive-ref-issue.md new file mode 100644 index 0000000..e5b7d23 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-keepalive-ref-issue.md @@ -0,0 +1,112 @@ +# Async Components with keep-alive Ref Issues + +## Rule + +When using ``, ``, and `defineAsyncComponent` together, be aware that template refs can become undefined when the component is re-activated after being deactivated. + +## Why This Matters + +This is a known Vue issue where the ref binding works correctly on first activation but becomes undefined on subsequent activations. This can cause runtime errors when trying to access component methods or properties through refs. + +## Problem Scenario + +```vue + + + +``` + +## Workarounds + +### Option 1: Use onActivated to re-establish ref access + +```vue + +``` + +### Option 2: Avoid mixing all three patterns + +If possible, use one of these alternatives: + +```vue + + + + + + +``` + +### Option 3: Use provide/inject instead of refs + +```vue + + + + + +``` + +## Key Points + +1. This is a known issue when combining ``, ``, and `defineAsyncComponent` +2. Refs may become undefined after component deactivation/reactivation +3. Use `nextTick` and null checks when accessing refs +4. Consider alternative patterns like provide/inject for cross-component communication +5. Test thoroughly when using this combination + +## References + +- [Vue.js GitHub Discussion #11334](https://github.com/orgs/vuejs/discussions/11334) +- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-suspense-control.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-suspense-control.md new file mode 100644 index 0000000..b34d14c --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-suspense-control.md @@ -0,0 +1,84 @@ +--- +title: Suspense Overrides Async Component Loading and Error Options +impact: MEDIUM +impactDescription: Async component loading/error options are ignored under a parent Suspense, leading to missing spinners and error UIs +type: gotcha +tags: [vue3, suspense, async-components, loading, error-handling] +--- + +# Suspense Overrides Async Component Loading and Error Options + +**Impact: MEDIUM** - When an async component renders inside a parent ``, its `loadingComponent`, `errorComponent`, `delay`, and `timeout` options do not run. The parent Suspense controls loading and error UX instead. + +## Task Checklist + +- [ ] Confirm whether the async component is inside a `` boundary +- [ ] Use `suspensible: false` when the component must manage its own loading/error UI +- [ ] Or move loading/error UI to the parent `` fallback and an error boundary (`onErrorCaptured`) +- [ ] Provide a retry path for failed loads + +**Incorrect:** +```vue + + + +``` + +**Correct (component handles its own states):** +```vue + + + +``` + +**Correct (parent Suspense owns loading/error UI):** +```vue + + + +``` diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-vue-router.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-vue-router.md new file mode 100644 index 0000000..ed75751 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/async-component-vue-router.md @@ -0,0 +1,109 @@ +# Do Not Use defineAsyncComponent with Vue Router + +## Rule + +Never use `defineAsyncComponent` when configuring Vue Router route components. Vue Router has its own lazy loading mechanism using dynamic imports directly. + +## Why This Matters + +Vue Router's lazy loading is specifically designed for route-level code splitting. Using `defineAsyncComponent` for routes adds unnecessary overhead and can cause unexpected behavior with navigation guards, loading states, and route transitions. + +## Bad Code + +```javascript +import { defineAsyncComponent } from 'vue' +import { createRouter, createWebHistory } from 'vue-router' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { + path: '/dashboard', + // WRONG: Don't use defineAsyncComponent here + component: defineAsyncComponent(() => + import('./views/Dashboard.vue') + ) + }, + { + path: '/profile', + // WRONG: This also won't work as expected + component: defineAsyncComponent({ + loader: () => import('./views/Profile.vue'), + loadingComponent: LoadingSpinner + }) + } + ] +}) +``` + +## Good Code + +```javascript +import { createRouter, createWebHistory } from 'vue-router' + +const router = createRouter({ + history: createWebHistory(), + routes: [ + { + path: '/dashboard', + // CORRECT: Use dynamic import directly + component: () => import('./views/Dashboard.vue') + }, + { + path: '/profile', + // CORRECT: Simple arrow function with import + component: () => import('./views/Profile.vue') + } + ] +}) +``` + +## Handling Loading States with Vue Router + +For route-level loading states, use Vue Router's navigation guards or a global loading indicator: + +```vue + + + +``` + +## When to Use defineAsyncComponent + +Use `defineAsyncComponent` for: +- Components loaded conditionally within a page +- Heavy components that aren't always needed +- Modal dialogs or panels that load on demand + +Use Vue Router's lazy loading for: +- Route-level components (views/pages) +- Any component configured in route definitions + +## Key Points + +1. Vue Router and `defineAsyncComponent` are separate lazy loading mechanisms +2. Route components should use direct dynamic imports: `() => import('./View.vue')` +3. Use navigation guards for route-level loading indicators +4. `defineAsyncComponent` is for component-level lazy loading within pages + +## References + +- [Vue Router Lazy Loading Routes](https://router.vuejs.org/guide/advanced/lazy-loading.html) +- [Vue.js Async Components Documentation](https://vuejs.org/guide/components/async) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/attrs-event-listener-merging.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/attrs-event-listener-merging.md new file mode 100644 index 0000000..9a18598 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/attrs-event-listener-merging.md @@ -0,0 +1,205 @@ +# Fallthrough Event Listeners Are Additive + +## Rule + +When an event listener is passed to a component as a fallthrough attribute, it is added to the root element's existing listeners of the same type - both will trigger. This is different from props where values are replaced. Be aware that both the component's internal handler and the parent's handler will execute. + +## Why This Matters + +- Developers may expect event listeners to override like props +- Both handlers execute, which can cause double submissions, duplicate API calls +- Order of execution: internal handler first, then fallthrough handler +- This is actually useful for composition but can cause bugs if unexpected + +## Bad Code + +```vue + + + + + + + + + + + +``` + +## Good Code + +### Option 1: Prevent fallthrough with inheritAttrs: false + +```vue + + + + +``` + +### Option 2: Document the additive behavior + +```vue + + + + + + + +``` + +### Option 3: Use stopPropagation if needed + +```vue + + + + +``` + +## Using Additive Behavior Intentionally + +The additive behavior can be useful for extending functionality: + +```vue + + + + + + + +``` + +## Execution Order + +```vue + + + + + + +``` + +## Best Practices + +1. **For UI components**: Use `inheritAttrs: false` and emit custom events +2. **For HOCs/wrappers**: Document that listeners are additive +3. **For analytics/tracking**: Leverage additive behavior intentionally +4. **Avoid side effects**: Don't assume your handler is the only one running + +## References + +- [Fallthrough Attributes - v-on Listener Inheritance](https://vuejs.org/guide/components/attrs.html#v-on-listener-inheritance) +- [Component Events](https://vuejs.org/guide/components/events.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/checkbox-true-false-value-form-submission.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/checkbox-true-false-value-form-submission.md new file mode 100644 index 0000000..ddd9d0a --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/checkbox-true-false-value-form-submission.md @@ -0,0 +1,118 @@ +--- +title: Checkbox true-value/false-value Not Submitted in Forms +impact: MEDIUM +impactDescription: true-value and false-value attributes don't affect form submission - unchecked boxes send nothing +type: capability +tags: [vue3, v-model, forms, checkbox, form-submission] +--- + +# Checkbox true-value/false-value Not Submitted in Forms + +**Impact: MEDIUM** - Vue's `true-value` and `false-value` attributes only affect the JavaScript binding, NOT the actual form submission. Unchecked checkboxes are never included in form submissions by browsers, regardless of `false-value`. + +This is a browser limitation, not a Vue issue. If you need to submit one of two values (like "yes"/"no" or "active"/"inactive"), use radio buttons instead of a checkbox. + +## Task Checklist + +- [ ] Don't rely on `false-value` for form submissions - it won't be sent +- [ ] Use radio buttons when you need to submit one of exactly two values +- [ ] Remember `true-value`/`false-value` are for JavaScript state only +- [ ] For form submissions with custom values, handle the transformation server-side or in submit handler + +**Problem - false-value not submitted:** +```html + + + +``` + +**Solution 1 - Use radio buttons for two-value submission:** +```html + + + +``` + +**Solution 2 - Handle in submit handler (for SPA/AJAX):** +```html + + + +``` + +**Solution 3 - Hidden input fallback:** +```html + +``` + +## Reference +- [Vue.js Form Input Bindings - Checkbox](https://vuejs.org/guide/essentials/forms.html#checkbox) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/cleanup-side-effects.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/cleanup-side-effects.md new file mode 100644 index 0000000..1b17972 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/cleanup-side-effects.md @@ -0,0 +1,172 @@ +--- +title: Clean Up Event Listeners and Intervals in onUnmounted +impact: HIGH +impactDescription: Failing to clean up side effects causes memory leaks and ghost event handlers +type: capability +tags: [vue3, lifecycle, memory-leak, event-listeners, intervals, cleanup] +--- + +# Clean Up Event Listeners and Intervals in onUnmounted + +**Impact: HIGH** - Failing to clean up event listeners, intervals, timeouts, and subscriptions when a component unmounts causes memory leaks and ghost handlers that continue running, leading to performance degradation and subtle bugs in Single Page Applications. + +When using custom events, timers, WebSocket connections, or third-party libraries, always clean up in `onUnmounted` (Composition API) or `unmounted` (Options API). + +## Task Checklist + +- [ ] Track all addEventListener calls and remove them in onUnmounted +- [ ] Clear all setInterval and setTimeout calls in onUnmounted +- [ ] Unsubscribe from external event emitters and observables +- [ ] Disconnect WebSocket connections and third-party library instances +- [ ] Use `onBeforeUnmount` if cleanup must happen before DOM removal + +**Incorrect:** +```javascript +// Composition API - WRONG: No cleanup +import { onMounted } from 'vue' + +export default { + setup() { + onMounted(() => { + // These keep running after component unmounts! + window.addEventListener('resize', handleResize) + setInterval(pollServer, 5000) + socket.on('message', handleMessage) + }) + } +} +``` + +```javascript +// Options API - WRONG: No cleanup +export default { + mounted() { + window.addEventListener('scroll', this.handleScroll) + this.timer = setInterval(this.refresh, 10000) + } + // Component unmounts, but listeners and timers persist! +} +``` + +**Correct:** +```javascript +// Composition API - CORRECT: Proper cleanup +import { onMounted, onUnmounted, ref } from 'vue' + +export default { + setup() { + const intervalId = ref(null) + + const handleResize = () => { + // handle resize + } + + const handleMessage = (msg) => { + // handle message + } + + onMounted(() => { + window.addEventListener('resize', handleResize) + intervalId.value = setInterval(pollServer, 5000) + socket.on('message', handleMessage) + }) + + onUnmounted(() => { + // Clean up everything! + window.removeEventListener('resize', handleResize) + + if (intervalId.value) { + clearInterval(intervalId.value) + } + + socket.off('message', handleMessage) + }) + } +} +``` + +```javascript +// Options API - CORRECT: Proper cleanup +export default { + data() { + return { + timer: null + } + }, + mounted() { + window.addEventListener('scroll', this.handleScroll) + this.timer = setInterval(this.refresh, 10000) + }, + unmounted() { + window.removeEventListener('scroll', this.handleScroll) + if (this.timer) { + clearInterval(this.timer) + } + }, + methods: { + handleScroll() { /* ... */ }, + refresh() { /* ... */ } + } +} +``` + +## Using Composable Pattern for Auto-Cleanup + +```javascript +// Reusable composable with automatic cleanup +import { onMounted, onUnmounted } from 'vue' + +export function useEventListener(target, event, handler) { + onMounted(() => { + target.addEventListener(event, handler) + }) + + onUnmounted(() => { + target.removeEventListener(event, handler) + }) +} + +export function useInterval(callback, delay) { + let intervalId = null + + onMounted(() => { + intervalId = setInterval(callback, delay) + }) + + onUnmounted(() => { + if (intervalId) clearInterval(intervalId) + }) +} + +// Usage - cleanup is automatic +import { useEventListener, useInterval } from './composables' + +export default { + setup() { + useEventListener(window, 'resize', handleResize) + useInterval(pollServer, 5000) + // No manual cleanup needed! + } +} +``` + +## VueUse Alternative + +```javascript +// VueUse provides cleanup-aware composables +import { useEventListener, useIntervalFn } from '@vueuse/core' + +export default { + setup() { + // Automatically cleaned up on unmount + useEventListener(window, 'resize', handleResize) + + const { pause, resume } = useIntervalFn(pollServer, 5000) + // Also provides pause/resume controls + } +} +``` + +## Reference +- [Vue.js Lifecycle Hooks](https://vuejs.org/guide/essentials/lifecycle.html) +- [VueUse - useEventListener](https://vueuse.org/core/useEventListener/) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/click-events-on-components.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/click-events-on-components.md new file mode 100644 index 0000000..747d651 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/click-events-on-components.md @@ -0,0 +1,180 @@ +--- +title: Click Events on Custom Components Require Emit or Fallthrough +impact: HIGH +impactDescription: Native click events on custom components won't work without proper emit declaration or attribute fallthrough +type: gotcha +tags: [vue3, events, components, emit, click, migration] +--- + +# Click Events on Custom Components Require Emit or Fallthrough + +**Impact: HIGH** - Unlike native HTML elements, custom Vue components don't automatically forward native DOM events like `click`. You must either emit the event explicitly, rely on attribute fallthrough to a single root element, or use the `.native` modifier (Vue 2 only, removed in Vue 3). This is a common source of confusion and migration issues. + +## Task Checklist + +- [ ] Declare emitted events using `defineEmits` in child components +- [ ] Emit click events from child component when needed +- [ ] Understand that single-root components automatically forward attrs to root +- [ ] Remove `.native` modifier when migrating from Vue 2 to Vue 3 +- [ ] For multi-root components, explicitly bind `$attrs` or emit events + +**Incorrect:** +```html + + +``` + +```html + + +``` + +```html + + + +``` + +**Correct:** +```html + + + + + + + + +``` + +```html + + + + + + +``` + +```html + + + + + +``` + +## Component Events Don't Bubble + +```javascript +// Important: Component-emitted events do NOT bubble +// You can only listen to events from direct children + +// WRONG: Trying to catch grandchild events + + + + + + +// CORRECT: Each level must relay the event + + + + + +``` + +## Vue 3 Native Event Behavior + +```javascript +// In Vue 3, if you declare an event in emits: +defineEmits(['click']) + +// Then @click on the component ONLY listens to emitted events +// NOT native click events + +// If you don't declare 'click' in emits: +defineEmits(['custom-event']) + +// Then @click on single-root component will: +// 1. Fall through to root element as native listener +// 2. Fire on native click +``` + +## Composition API Emit Pattern + +```vue + + + +``` + +## Migration from Vue 2 + +```html + + + + + + + +``` + +## Reference +- [Vue.js Component Events](https://vuejs.org/guide/components/events.html) +- [Vue.js Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html) +- [Vue 3 Migration - .native Modifier Removed](https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-naming-conflicts.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-naming-conflicts.md new file mode 100644 index 0000000..96e5f8f --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-naming-conflicts.md @@ -0,0 +1,159 @@ +--- +title: Avoid Component Naming Conflicts Between Global and Local +impact: HIGH +impactDescription: Naming conflicts cause unexpected component rendering and hard-to-debug issues +type: gotcha +tags: [vue3, component-registration, naming-conflicts, global-local, debugging] +--- + +# Avoid Component Naming Conflicts Between Global and Local + +**Impact: HIGH** - When a global component and a local component have the same name (or resolve to the same name due to casing differences), unexpected behavior occurs. The precedence rules can be confusing, and the wrong component may render silently without any error. This is particularly problematic when using third-party component libraries. + +## Task Checklist + +- [ ] Use unique, prefixed names for global components (e.g., `BaseButton`, `AppHeader`) +- [ ] Check for naming conflicts when adding global components +- [ ] Explicitly alias local components if there's potential conflict +- [ ] When overriding third-party components, document and test thoroughly + +**Incorrect:** +```javascript +// main.js +import { createApp } from 'vue' +import Button from './components/Button.vue' + +const app = createApp(App) +app.component('Button', Button) // Global Button +``` + +```vue + + + + +``` + +```vue + + + + +``` + +**Correct:** +```javascript +// main.js - use prefixes for global components +import { createApp } from 'vue' +import BaseButton from './components/BaseButton.vue' +import BaseIcon from './components/BaseIcon.vue' + +const app = createApp(App) +app.component('BaseButton', BaseButton) +app.component('BaseIcon', BaseIcon) +``` + +```vue + + + + +``` + +## Explicit Aliasing for Clarity + +When you intentionally want to override or have similar names, use explicit aliasing: + +```vue + + + +``` + +```vue + + +``` + +## Resolution Order + +Understanding Vue's component resolution order helps debug issues: + +1. **Local registration** takes precedence over global +2. **Exact case match** takes precedence over case-insensitive match +3. Self-referencing component name (file name) has lowest priority + +```vue + + + + +``` + +## Third-Party Library Conflicts + +```vue + + + +``` + +## Naming Convention Strategy + +| Component Type | Naming Pattern | Example | +|----------------|---------------|---------| +| Base/Global | `Base*` or `App*` prefix | `BaseButton`, `AppHeader` | +| Domain-specific | Domain prefix | `UserCard`, `ProductList` | +| Page components | `*Page` or `*View` suffix | `HomePage`, `UserView` | +| Layout components | `*Layout` suffix | `DefaultLayout`, `AdminLayout` | + +## Reference +- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html) +- [GitHub Issue: Global component naming conflicts](https://github.com/vuejs/vue/issues/4434) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-ref-requires-defineexpose.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-ref-requires-defineexpose.md new file mode 100644 index 0000000..f223e17 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/component-ref-requires-defineexpose.md @@ -0,0 +1,176 @@ +--- +title: Component Refs Require defineExpose with Script Setup +impact: HIGH +impactDescription: Parent components cannot access child ref properties unless explicitly exposed +type: gotcha +tags: [vue3, template-refs, script-setup, defineExpose, component-communication] +--- + +# Component Refs Require defineExpose with Script Setup + +**Impact: HIGH** - Components using ` + + +``` + +```vue + + + + +``` + +**Correct:** +```vue + + + + +``` + +```vue + + + + +``` + +```vue + + + + +``` + +```javascript +// Options API equivalent using expose option +export default { + expose: ['count', 'increment', 'reset'], + data() { + return { + count: 0, + internalState: 'private' + } + }, + methods: { + increment() { this.count++ }, + reset() { this.count = 0 } + } +} +``` + +## Best Practice Reminder + +Component refs create tight coupling between parent and child. Prefer standard patterns: + +```vue + + + + +``` + +## Reference +- [Vue.js Component Refs](https://vuejs.org/guide/essentials/template-refs.html#ref-on-component) +- [Script Setup - defineExpose](https://vuejs.org/api/sfc-script-setup.html#defineexpose) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-avoid-hidden-side-effects.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-avoid-hidden-side-effects.md new file mode 100644 index 0000000..71222e1 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-avoid-hidden-side-effects.md @@ -0,0 +1,208 @@ +--- +title: Avoid Hidden Side Effects in Composables +impact: HIGH +impactDescription: Side effects hidden in composables make debugging difficult and create implicit coupling between components +type: best-practice +tags: [vue3, composables, composition-api, side-effects, provide-inject, global-state] +--- + +# Avoid Hidden Side Effects in Composables + +**Impact: HIGH** - Composables should encapsulate stateful logic, not hide side effects that affect things outside their scope. Hidden side effects like modifying global state, using provide/inject internally, or manipulating the DOM directly make composables unpredictable and hard to debug. + +When a composable has unexpected side effects, consumers can't reason about what calling it will do. This leads to bugs that are difficult to trace and composables that can't be safely reused. + +## Task Checklist + +- [ ] Avoid using provide/inject inside composables (make dependencies explicit) +- [ ] Don't modify Pinia/Vuex store state internally (accept store as parameter instead) +- [ ] Don't manipulate DOM directly (use template refs passed as arguments) +- [ ] Document any unavoidable side effects clearly +- [ ] Keep composables focused on returning reactive state and methods + +**Incorrect:** +```javascript +// WRONG: Hidden provide/inject dependency +export function useTheme() { + // Consumer has no idea this depends on a provided theme + const theme = inject('theme') // What if nothing provides this? + + const isDark = computed(() => theme?.mode === 'dark') + return { isDark } +} + +// WRONG: Modifying global store internally +import { useUserStore } from '@/stores/user' + +export function useLogin() { + const userStore = useUserStore() + + async function login(credentials) { + const user = await api.login(credentials) + // Hidden side effect: modifying global state + userStore.setUser(user) + userStore.setToken(user.token) + // Consumer doesn't know the store was modified! + } + + return { login } +} + +// WRONG: Hidden DOM manipulation +export function useFocusTrap() { + onMounted(() => { + // Which element? Consumer has no control + document.querySelector('.modal')?.focus() + }) +} + +// WRONG: Hidden provide that affects descendants +export function useFormContext() { + const form = reactive({ values: {}, errors: {} }) + // Components calling this have no idea it provides something + provide('form-context', form) + return form +} +``` + +**Correct:** +```javascript +// CORRECT: Explicit dependency injection +export function useTheme(injectedTheme) { + // If no theme passed, consumer must handle it + const theme = injectedTheme ?? { mode: 'light' } + + const isDark = computed(() => theme.mode === 'dark') + return { isDark } +} + +// Usage - dependency is explicit +const theme = inject('theme', { mode: 'light' }) +const { isDark } = useTheme(theme) + +// CORRECT: Return actions, let consumer decide when to call them +export function useLogin() { + const user = ref(null) + const token = ref(null) + const isLoading = ref(false) + const error = ref(null) + + async function login(credentials) { + isLoading.value = true + error.value = null + try { + const response = await api.login(credentials) + user.value = response.user + token.value = response.token + return response + } catch (e) { + error.value = e + throw e + } finally { + isLoading.value = false + } + } + + return { user, token, isLoading, error, login } +} + +// Consumer decides what to do with the result +const { user, token, login } = useLogin() +const userStore = useUserStore() + +async function handleLogin(credentials) { + await login(credentials) + // Consumer explicitly updates the store + userStore.setUser(user.value) + userStore.setToken(token.value) +} + +// CORRECT: Accept element as parameter +export function useFocusTrap(targetRef) { + onMounted(() => { + targetRef.value?.focus() + }) + + onUnmounted(() => { + // Cleanup focus trap + }) +} + +// Usage - consumer controls which element +const modalRef = ref(null) +useFocusTrap(modalRef) + +// CORRECT: Separate composable from provider +export function useFormContext() { + const form = reactive({ values: {}, errors: {} }) + return form +} + +// In parent component - explicit provide +const form = useFormContext() +provide('form-context', form) +``` + +## Acceptable Side Effects (With Documentation) + +Some side effects are acceptable when they're the core purpose of the composable: + +```javascript +/** + * Tracks mouse position globally. + * + * SIDE EFFECTS: + * - Adds 'mousemove' event listener to window (cleaned up on unmount) + * + * @returns {Object} Mouse coordinates { x, y } + */ +export function useMouse() { + const x = ref(0) + const y = ref(0) + + // This side effect is the whole point of the composable + // and is properly cleaned up + onMounted(() => window.addEventListener('mousemove', update)) + onUnmounted(() => window.removeEventListener('mousemove', update)) + + function update(event) { + x.value = event.pageX + y.value = event.pageY + } + + return { x, y } +} +``` + +## Pattern: Dependency Injection for Flexibility + +```javascript +// Composable accepts its dependencies +export function useDataFetcher(apiClient, cache = null) { + const data = ref(null) + + async function fetch(url) { + if (cache) { + const cached = cache.get(url) + if (cached) { + data.value = cached + return + } + } + + data.value = await apiClient.get(url) + cache?.set(url, data.value) + } + + return { data, fetch } +} + +// Usage - dependencies are explicit and testable +const apiClient = inject('apiClient') +const cache = inject('cache', null) +const { data, fetch } = useDataFetcher(apiClient, cache) +``` + +## Reference +- [Vue.js Composables](https://vuejs.org/guide/reusability/composables.html) +- [Common Mistakes Creating Composition Functions](https://www.telerik.com/blogs/common-mistakes-creating-composition-functions-vue) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-call-location-restrictions.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-call-location-restrictions.md new file mode 100644 index 0000000..d6bfd49 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-call-location-restrictions.md @@ -0,0 +1,141 @@ +--- +title: Call Composables Only in Setup Context Synchronously +impact: HIGH +impactDescription: Composables called outside setup context or asynchronously fail to register lifecycle hooks and may cause memory leaks +type: gotcha +tags: [vue3, composables, composition-api, setup, async, lifecycle] +--- + +# Call Composables Only in Setup Context Synchronously + +**Impact: HIGH** - Composables must be called synchronously within ` +``` + +**Correct:** +```vue + +``` + +## Exception: Calling in Lifecycle Hooks + +Composables CAN be called inside lifecycle hooks because Vue maintains the component context: + +```vue + +``` + +## Special Case: Async Setup in ` +``` + +## Why This Matters + +When you call a composable, Vue needs to know which component instance to associate it with. This association happens through an internal "current instance" that's only set during synchronous setup execution. + +```javascript +// Inside a composable +export function useFetch(url) { + const data = ref(null) + + // These need the current component instance! + onMounted(() => { /* ... */ }) + onUnmounted(() => { /* cleanup */ }) + + // If called outside setup context, Vue can't find the instance + // and these hooks are silently ignored + return { data } +} +``` + +## Reference +- [Vue.js Composables - Usage Restrictions](https://vuejs.org/guide/reusability/composables.html#usage-restrictions) +- [Vue.js Composition API - Setup Context](https://vuejs.org/api/composition-api-setup.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-naming-return-pattern.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-naming-return-pattern.md new file mode 100644 index 0000000..db1cf86 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-naming-return-pattern.md @@ -0,0 +1,139 @@ +--- +title: Follow Composable Naming Convention and Return Pattern +impact: MEDIUM +impactDescription: Inconsistent composable patterns lead to confusing APIs and reactivity issues when destructuring +type: best-practice +tags: [vue3, composables, composition-api, naming, conventions, refs] +--- + +# Follow Composable Naming Convention and Return Pattern + +**Impact: MEDIUM** - Vue composables should follow established conventions: prefix names with "use" and return plain objects containing refs (not reactive objects). Returning reactive objects causes reactivity loss when destructuring, while inconsistent naming makes code harder to understand. + +## Task Checklist + +- [ ] Name composables with "use" prefix (e.g., `useMouse`, `useFetch`, `useAuth`) +- [ ] Return a plain object containing refs, not a reactive object +- [ ] Allow both destructuring and object-style access +- [ ] Document the returned refs for consumers + +**Incorrect:** +```javascript +// WRONG: No "use" prefix - unclear it's a composable +export function mousePosition() { + const x = ref(0) + const y = ref(0) + return { x, y } +} + +// WRONG: Returning reactive object - destructuring loses reactivity +export function useMouse() { + const state = reactive({ + x: 0, + y: 0 + }) + // When consumer destructures: const { x, y } = useMouse() + // x and y become plain values, not reactive! + return state +} + +// WRONG: Returning single ref directly - inconsistent API +export function useCounter() { + const count = ref(0) + return count // Consumer must use .value everywhere +} +``` + +**Correct:** +```javascript +// CORRECT: "use" prefix and returns plain object with refs +export function useMouse() { + const x = ref(0) + const y = ref(0) + + function update(event) { + x.value = event.pageX + y.value = event.pageY + } + + onMounted(() => window.addEventListener('mousemove', update)) + onUnmounted(() => window.removeEventListener('mousemove', update)) + + // Return plain object containing refs + return { x, y } +} + +// Consumer can destructure and keep reactivity +const { x, y } = useMouse() +watch(x, (newX) => console.log('x changed:', newX)) // Works! + +// Or use as object if preferred +const mouse = useMouse() +console.log(mouse.x.value) +``` + +## Using reactive() Wrapper for Auto-Unwrapping + +If consumers prefer auto-unwrapping (no `.value`), they can wrap the result: + +```javascript +import { reactive } from 'vue' +import { useMouse } from './composables/useMouse' + +// Wrapping in reactive() links the refs +const mouse = reactive(useMouse()) + +// Now access without .value +console.log(mouse.x) // Auto-unwrapped, still reactive + +// But DON'T destructure from this! +const { x } = reactive(useMouse()) // WRONG: loses reactivity again +``` + +## Pattern: Returning Both State and Actions + +```javascript +// Composable with state AND methods +export function useCounter(initialValue = 0) { + const count = ref(initialValue) + const doubleCount = computed(() => count.value * 2) + + function increment() { + count.value++ + } + + function decrement() { + count.value-- + } + + function reset() { + count.value = initialValue + } + + // Return all refs and functions in plain object + return { + count, + doubleCount, + increment, + decrement, + reset + } +} + +// Usage +const { count, doubleCount, increment, reset } = useCounter(10) +``` + +## Naming Convention Examples + +| Good Name | Bad Name | Reason | +|-----------|----------|--------| +| `useFetch` | `fetch` | Conflicts with native fetch | +| `useAuth` | `authStore` | "Store" implies Pinia/Vuex | +| `useLocalStorage` | `localStorage` | Conflicts with native API | +| `useFormValidation` | `validateForm` | Sounds like a one-shot function | +| `useWindowSize` | `getWindowSize` | "get" implies synchronous getter | + +## Reference +- [Vue.js Composables - Conventions and Best Practices](https://vuejs.org/guide/reusability/composables.html#conventions-and-best-practices) +- [Vue.js Composables - Return Values](https://vuejs.org/guide/reusability/composables.html#return-values) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-tovalue-inside-watcheffect.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-tovalue-inside-watcheffect.md new file mode 100644 index 0000000..c7b7d0f --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composable-tovalue-inside-watcheffect.md @@ -0,0 +1,182 @@ +--- +title: Call toValue() Inside watchEffect for Proper Dependency Tracking +impact: HIGH +impactDescription: Calling toValue() outside watchEffect prevents reactive dependency tracking, causing the effect to never re-run +type: gotcha +tags: [vue3, composables, composition-api, watchEffect, toValue, reactivity] +--- + +# Call toValue() Inside watchEffect for Proper Dependency Tracking + +**Impact: HIGH** - When writing composables that accept `MaybeRefOrGetter` arguments, you must call `toValue()` inside the `watchEffect` callback, not outside. If you extract the value before the watchEffect, Vue cannot track the dependency and the effect will never re-run when the source changes. + +This is a subtle but critical mistake that leads to composables that work with initial values but never update. + +## Task Checklist + +- [ ] Always call `toValue()` inside `watchEffect` callbacks, not before +- [ ] Similarly, access `.value` on refs inside watchEffect, not outside +- [ ] For `watch()`, use a getter function that calls `toValue()` +- [ ] Test that composables update when their inputs change + +**Incorrect:** +```javascript +import { ref, watchEffect, toValue } from 'vue' + +export function useFetch(url) { + const data = ref(null) + const error = ref(null) + + // WRONG: toValue called outside watchEffect + // This extracts the value ONCE and passes a static string + const urlValue = toValue(url) + + watchEffect(async () => { + try { + // urlValue is a static string - no dependency tracked! + const response = await fetch(urlValue) + data.value = await response.json() + } catch (e) { + error.value = e + } + }) + + return { data, error } +} + +// When used like this: +const apiUrl = ref('/api/users') +const { data } = useFetch(apiUrl) + +// Later... +apiUrl.value = '/api/products' // useFetch will NOT refetch! +``` + +**Correct:** +```javascript +import { ref, watchEffect, toValue } from 'vue' + +export function useFetch(url) { + const data = ref(null) + const error = ref(null) + + watchEffect(async () => { + // CORRECT: toValue called INSIDE watchEffect + // Vue tracks this as a dependency + const urlValue = toValue(url) + + try { + const response = await fetch(urlValue) + data.value = await response.json() + } catch (e) { + error.value = e + } + }) + + return { data, error } +} + +// Now when used: +const apiUrl = ref('/api/users') +const { data } = useFetch(apiUrl) + +// Later... +apiUrl.value = '/api/products' // useFetch WILL refetch! +``` + +## The Same Applies to Direct Ref Access + +```javascript +// WRONG: Accessing .value outside the effect +export function useDebounce(source, delay = 300) { + // This captures the initial value, not a reactive dependency + const initialValue = source.value // or toValue(source) + + watchEffect(() => { + // initialValue is static - this only runs once + console.log('Value:', initialValue) + }) +} + +// CORRECT: Access inside the effect +export function useDebounce(source, delay = 300) { + watchEffect(() => { + // Vue tracks source.value or toValue(source) as dependency + console.log('Value:', toValue(source)) + }) +} +``` + +## Pattern: Using watch() with Getter Functions + +For `watch()`, wrap `toValue()` in a getter: + +```javascript +import { ref, watch, toValue } from 'vue' + +export function useLocalStorage(key, defaultValue) { + const data = ref(defaultValue) + + // CORRECT: Use getter function with watch + watch( + () => toValue(key), // Getter calls toValue, tracks dependency + (newKey) => { + const stored = localStorage.getItem(newKey) + data.value = stored ? JSON.parse(stored) : defaultValue + }, + { immediate: true } + ) + + return data +} +``` + +## Why This Happens + +Vue's reactivity tracking works by detecting property accesses during effect execution: + +```javascript +watchEffect(() => { + // When this runs, Vue is "recording" what reactive sources are accessed + const value = someRef.value // Vue records: "this effect depends on someRef" +}) + +// But if you extract the value before: +const value = someRef.value // Vue isn't recording yet +watchEffect(() => { + console.log(value) // Just using a plain JavaScript variable +}) +``` + +`toValue()` works the same way - it accesses `.value` internally, so it must happen during effect execution for tracking to work. + +## Quick Checklist for Composable Authors + +When accepting `MaybeRefOrGetter` inputs: + +1. Store the raw argument (don't call `toValue` during setup) +2. Call `toValue()` inside any reactive context (`watchEffect`, `watch`, `computed`) +3. Test with both static values AND refs that change + +```javascript +export function useMyComposable(input) { + // Store raw - don't extract value here + // const value = toValue(input) // WRONG + + const result = computed(() => { + // Extract value inside reactive context + return transform(toValue(input)) // CORRECT + }) + + watchEffect(() => { + // Extract value inside reactive context + doSomething(toValue(input)) // CORRECT + }) + + return { result } +} +``` + +## Reference +- [Vue.js Reactivity API - toValue](https://vuejs.org/api/reactivity-utilities.html#tovalue) +- [Vue.js Composables - Accepting Ref Arguments](https://vuejs.org/guide/reusability/composables.html#accepting-reactive-state) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-not-functional-programming.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-not-functional-programming.md new file mode 100644 index 0000000..55e912d --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-not-functional-programming.md @@ -0,0 +1,120 @@ +--- +title: Composition API Uses Mutable Reactivity, Not Functional Programming +impact: MEDIUM +impactDescription: Misunderstanding the paradigm leads to incorrect state management patterns +type: gotcha +tags: [vue3, composition-api, reactivity, functional-programming, paradigm] +--- + +# Composition API Uses Mutable Reactivity, Not Functional Programming + +**Impact: MEDIUM** - Despite being function-based, the Composition API follows Vue's mutable, fine-grained reactivity paradigm—NOT functional programming principles. Treating it like a functional paradigm leads to incorrect patterns like unnecessary cloning, immutable-style updates, or avoiding mutation when mutation is the intended pattern. + +Vue's Composition API leverages imported functions to organize code, but the underlying model is based on mutable reactive state that Vue tracks and responds to. This is fundamentally different from functional programming with immutability (like Redux reducers). + +## Task Checklist + +- [ ] Mutate reactive state directly - don't create new objects for every update +- [ ] Don't apply immutability patterns unnecessarily (spreading, Object.assign for updates) +- [ ] Understand that `ref()` and `reactive()` enable mutable state tracking +- [ ] Use Vue's reactivity as intended: direct mutation with automatic tracking + +**Incorrect:** +```javascript +import { ref } from 'vue' + +const todos = ref([]) + +// WRONG: Treating Vue like Redux/functional - unnecessary immutability +function addTodo(todo) { + // Creating a new array every time is wasteful in Vue + todos.value = [...todos.value, todo] +} + +function updateTodo(id, updates) { + // Unnecessary spread - Vue tracks mutations directly + todos.value = todos.value.map(t => + t.id === id ? { ...t, ...updates } : t + ) +} + +const user = ref({ name: 'John', age: 30 }) + +// WRONG: Creating new object for simple update +function updateName(newName) { + user.value = { ...user.value, name: newName } +} +``` + +**Correct:** +```javascript +import { ref, reactive } from 'vue' + +const todos = ref([]) + +// CORRECT: Mutate directly - Vue tracks the change +function addTodo(todo) { + todos.value.push(todo) // Direct mutation is the Vue way +} + +function updateTodo(id, updates) { + const todo = todos.value.find(t => t.id === id) + if (todo) { + Object.assign(todo, updates) // Direct mutation + } +} + +const user = ref({ name: 'John', age: 30 }) + +// CORRECT: Mutate the property directly +function updateName(newName) { + user.value.name = newName // Vue tracks this! +} + +// Or with reactive(): +const state = reactive({ name: 'John', age: 30 }) + +function updateNameReactive(newName) { + state.name = newName // Direct mutation, reactivity preserved +} +``` + +## When Immutability Patterns Make Sense + +```javascript +// Immutability IS appropriate when: + +// 1. Replacing the entire state (e.g., from API response) +const users = ref([]) +async function fetchUsers() { + users.value = await api.getUsers() // Complete replacement is fine +} + +// 2. When you need a snapshot for comparison +const previousState = { ...currentState } // For undo/redo + +// 3. When passing data to external libraries expecting immutable data +const chartData = computed(() => [...rawData.value]) // Copy for chart lib +``` + +## The Vue Mental Model + +```javascript +// Vue's reactivity is like a spreadsheet: +// - Cell A1 contains a value (ref) +// - Cell B1 has a formula referencing A1 (computed) +// - Change A1, and B1 automatically updates + +const a1 = ref(10) +const b1 = computed(() => a1.value * 2) + +// You CHANGE A1 (mutate), you don't create a new A1 +a1.value = 20 // b1 automatically becomes 40 + +// This is fundamentally different from: +// state = reducer(state, action) // Functional/Redux pattern +``` + +## Reference +- [Composition API FAQ](https://vuejs.org/guide/extras/composition-api-faq.html) +- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-script-setup-async-context.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-script-setup-async-context.md new file mode 100644 index 0000000..23202ac --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/composition-api-script-setup-async-context.md @@ -0,0 +1,203 @@ +--- +title: Top-Level await in script setup Preserves Component Context +impact: HIGH +impactDescription: Misunderstanding async context causes lifecycle hooks and watchers to silently fail +type: gotcha +tags: [vue3, composition-api, script-setup, async, await, suspense] +--- + +# Top-Level await in script setup Preserves Component Context + +**Impact: HIGH** - In ` + + + +``` + +**Nested Async Breaks Context:** +```vue + +``` + +**Correct Patterns:** +```vue + +``` + +**setup() Function (Not script setup):** +```javascript +// In regular setup(), await ALWAYS breaks context +export default { + async setup() { + const data = ref(null) + + // WRONG: Hooks after await won't register + const config = await fetchConfig() + + onMounted(() => { + console.log('Never runs!') // Silent failure! + }) + + return { data } + } +} + +// CORRECT: Register hooks before any await +export default { + async setup() { + const data = ref(null) + + // Register hooks FIRST (synchronous) + onMounted(async () => { + const config = await fetchConfig() + data.value = await fetchData(config) + }) + + // Now you can await if needed + // But hooks must be registered before this point + + return { data } + } +} +``` + +## Why This Happens + +```javascript +// Vue tracks the "current component instance" during setup +// This is like a global variable that gets set and cleared + +// During synchronous setup: +function setup() { + currentInstance = this // Vue sets this + + onMounted(cb) // Uses currentInstance to register + + // After await, JavaScript resumes in a microtask + await something() + + // currentInstance is now null or different! + onMounted(cb) // Can't find the instance - silently fails +} + +// +``` + +## Reference +- [Composition API FAQ - Relationship with React Hooks](https://vuejs.org/guide/extras/composition-api-faq.html#relationship-with-react-hooks) +- [Reactivity Fundamentals](https://vuejs.org/guide/essentials/reactivity-fundamentals.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-array-mutation.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-array-mutation.md new file mode 100644 index 0000000..0ba3018 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-array-mutation.md @@ -0,0 +1,148 @@ +--- +title: Avoid Mutating Methods on Arrays in Computed Properties +impact: HIGH +impactDescription: Array mutating methods in computed modify source data causing unexpected behavior +type: capability +tags: [vue3, computed, arrays, mutation, sort, reverse] +--- + +# Avoid Mutating Methods on Arrays in Computed Properties + +**Impact: HIGH** - JavaScript array methods like `reverse()`, `sort()`, `splice()`, `push()`, `pop()`, `shift()`, and `unshift()` mutate the original array. Using them directly on reactive arrays inside computed properties will modify your source data, causing unexpected side effects and bugs. + +## Task Checklist + +- [ ] Always create a copy of arrays before using mutating methods +- [ ] Use spread operator `[...array]` or `slice()` to copy arrays +- [ ] Prefer non-mutating alternatives when available +- [ ] Be aware which array methods mutate vs return new arrays + +**Incorrect:** +```vue + + + +``` + +**Correct:** +```vue + + + +``` + +## Mutating vs Non-Mutating Array Methods + +| Mutating (Avoid in Computed) | Non-Mutating (Safe) | +|------------------------------|---------------------| +| `sort()` | `toSorted()` (ES2023) | +| `reverse()` | `toReversed()` (ES2023) | +| `splice()` | `toSpliced()` (ES2023) | +| `push()` | `concat()` | +| `pop()` | `slice(0, -1)` | +| `shift()` | `slice(1)` | +| `unshift()` | `[item, ...array]` | +| `fill()` | `map()` with new values | + +## ES2023 Non-Mutating Alternatives + +Modern JavaScript (ES2023) provides non-mutating versions of common array methods: + +```javascript +// These return NEW arrays, safe for computed properties +const sorted = array.toSorted((a, b) => a - b) +const reversed = array.toReversed() +const spliced = array.toSpliced(1, 2, 'new') +const withReplaced = array.with(0, 'newFirst') +``` + +## Deep Copy for Nested Arrays + +For arrays of objects where you might mutate nested properties: + +```javascript +const items = ref([{ name: 'A', values: [1, 2, 3] }]) + +// Shallow copy - nested arrays still shared +const copied = computed(() => [...items.value]) + +// Deep copy if you need to mutate nested structures +const deepCopied = computed(() => { + return JSON.parse(JSON.stringify(items.value)) + // Or use structuredClone(): + // return structuredClone(items.value) +}) +``` + +## Reference +- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value) +- [MDN Array Methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-conditional-dependencies.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-conditional-dependencies.md new file mode 100644 index 0000000..3f173e1 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-conditional-dependencies.md @@ -0,0 +1,147 @@ +--- +title: Ensure All Dependencies Are Accessed in Computed Properties +impact: HIGH +impactDescription: Conditional logic can prevent dependency tracking causing stale computed values +type: capability +tags: [vue3, computed, reactivity, dependency-tracking, gotcha] +--- + +# Ensure All Dependencies Are Accessed in Computed Properties + +**Impact: HIGH** - Vue tracks computed property dependencies by monitoring which reactive properties are accessed during execution. If conditional logic prevents a property from being accessed on the first run, Vue won't track it as a dependency, causing the computed property to not update when that property changes. + +This is a subtle but common source of bugs, especially with short-circuit evaluation (`&&`, `||`) and early returns. + +## Task Checklist + +- [ ] Access all reactive dependencies before any conditional logic +- [ ] Be cautious with short-circuit operators (`&&`, `||`) that may skip property access +- [ ] Store all dependencies in variables at the start of the computed getter +- [ ] Test computed properties with different initial states + +**Incorrect:** +```vue + +``` + +**Correct:** +```vue + +``` + +## The Dependency Tracking Mechanism + +Vue's reactivity system works by tracking which reactive properties are accessed when a computed property runs: + +```javascript +// How Vue tracks dependencies (simplified): +// 1. Start tracking +// 2. Run the getter function +// 3. Record every .value or reactive property access +// 4. Stop tracking + +const computed = computed(() => { + // Vue starts tracking here + if (conditionA.value) { // conditionA is tracked + return valueB.value // valueB is ONLY tracked if conditionA is true + } + return 'default' // If conditionA is false, valueB is NOT tracked! +}) +``` + +## Pattern: Destructure All Dependencies First + +```javascript +// GOOD PATTERN: Destructure/access everything at the top +const result = computed(() => { + // Access all potential dependencies + const { user, settings, items } = toRefs(store) + const userVal = user.value + const settingsVal = settings.value + const itemsVal = items.value + + // Now use conditional logic safely + if (!userVal) return [] + if (!settingsVal.enabled) return [] + return itemsVal.filter(i => i.active) +}) +``` + +## Reference +- [Vue.js Reactivity in Depth](https://vuejs.org/guide/extras/reactivity-in-depth.html) +- [GitHub Discussion: Dependency collection gotcha with conditionals](https://github.com/vuejs/Discussion/issues/15) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-parameters.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-parameters.md new file mode 100644 index 0000000..b626d69 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-parameters.md @@ -0,0 +1,159 @@ +--- +title: Computed Properties Cannot Accept Parameters +impact: MEDIUM +impactDescription: Attempting to pass arguments to computed properties fails or defeats caching +type: capability +tags: [vue3, computed, methods, parameters, common-mistake] +--- + +# Computed Properties Cannot Accept Parameters + +**Impact: MEDIUM** - Computed properties are designed to derive values from reactive state without parameters. Attempting to pass arguments defeats the caching mechanism or causes errors. Use methods or computed properties that return functions instead. + +## Task Checklist + +- [ ] Use methods when you need to pass parameters +- [ ] Consider if the parameter can be reactive state instead +- [ ] If you must parameterize, understand that returning a function loses caching benefits +- [ ] Prefer method calls in templates for parameterized operations + +**Incorrect:** +```vue + + + +``` + +```vue + +``` + +**Correct:** +```vue + + + +``` + +## Workaround: Computed Returning a Function + +If you need something computed-like with parameters, you can return a function. **However, this defeats the caching benefit:** + +```vue + + + +``` + +## When to Use Each Approach + +| Scenario | Approach | Caching | +|----------|----------|---------| +| Fixed filter based on reactive state | Computed | Yes | +| Dynamic filter passed as argument | Method | No | +| Filter options from user selection | Computed + reactive param | Yes | +| Formatting with variable parameters | Method | No | +| Composed derivation with argument | Computed returning function | Partial | + +## Make Parameters Reactive + +The best pattern is often to make the "parameter" a reactive value: + +```vue + +``` + +## Reference +- [Vue.js Computed Properties](https://vuejs.org/guide/essentials/computed.html) +- [Vue.js Methods](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#declaring-methods) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-side-effects.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-side-effects.md new file mode 100644 index 0000000..b58a6f9 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-no-side-effects.md @@ -0,0 +1,107 @@ +--- +title: Computed Property Getters Must Be Side-Effect Free +impact: HIGH +impactDescription: Side effects in computed getters break reactivity and cause unpredictable behavior +type: efficiency +tags: [vue3, computed, reactivity, side-effects, best-practices] +--- + +# Computed Property Getters Must Be Side-Effect Free + +**Impact: HIGH** - Computed getter functions should only perform pure computation. Side effects in computed getters break Vue's reactivity model and cause bugs that are difficult to trace. + +Computed properties are designed to declaratively describe how to derive a value from other reactive state. They are not meant to perform actions or modify state. + +## Task Checklist + +- [ ] Never mutate other reactive state inside a computed getter +- [ ] Never make async requests or API calls inside a computed getter +- [ ] Never perform DOM mutations inside a computed getter +- [ ] Use watchers for reacting to state changes with side effects +- [ ] Use event handlers for user-triggered actions + +**Incorrect:** +```vue + +``` + +**Correct:** +```vue + +``` + +## What Counts as a Side Effect + +| Side Effect Type | Example | Alternative | +|-----------------|---------|-------------| +| State mutation | `otherRef.value = x` | Use watcher | +| API calls | `fetch()`, `axios()` | Use watcher or lifecycle hook | +| DOM manipulation | `document.title = x` | Use watcher | +| Console logging | `console.log()` | Remove or use watcher | +| Storage access | `localStorage.setItem()` | Use watcher | +| Timer setup | `setTimeout()` | Use lifecycle hook | + +## Reference +- [Vue.js Computed Properties - Getters Should Be Side-Effect Free](https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-return-value-readonly.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-return-value-readonly.md new file mode 100644 index 0000000..3c22447 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/computed-return-value-readonly.md @@ -0,0 +1,160 @@ +--- +title: Never Mutate Computed Property Return Values +impact: HIGH +impactDescription: Mutating computed values causes silent failures and lost changes +type: capability +tags: [vue3, computed, reactivity, immutability, common-mistake] +--- + +# Never Mutate Computed Property Return Values + +**Impact: HIGH** - The returned value from a computed property is derived state - a temporary snapshot. Mutating this value leads to bugs that are difficult to debug. + +**Important:** Mutations DO persist while the computed cache remains valid, but are lost when recomputation occurs. The danger lies in unpredictable cache invalidation timing - any change to the computed's dependencies triggers recomputation, silently discarding your mutations. This makes bugs intermittent and hard to reproduce. + +Every time the source state changes, a new snapshot is created. Mutating a snapshot is meaningless because it will be discarded on the next recalculation. + +## Task Checklist + +- [ ] Treat computed return values as read-only +- [ ] Update the source state instead of the computed value +- [ ] Use writable computed properties if bidirectional binding is needed +- [ ] Avoid array mutating methods (push, pop, splice, reverse, sort) on computed arrays + +**Incorrect:** +```vue + +``` + +```vue + +``` + +**Correct:** +```vue + +``` + +```vue + +``` + +## Writable Computed for Bidirectional Binding + +If you genuinely need to "set" a computed value, use a writable computed property: + +```vue + +``` + +## Reference +- [Vue.js Computed Properties - Avoid Mutating Computed Value](https://vuejs.org/guide/essentials/computed.html#avoid-mutating-computed-value) +- [Vue.js Computed Properties - Writable Computed](https://vuejs.org/guide/essentials/computed.html#writable-computed) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/configure-app-before-mount.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/configure-app-before-mount.md new file mode 100644 index 0000000..897d3be --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/configure-app-before-mount.md @@ -0,0 +1,89 @@ +--- +title: Configure Vue App Before Calling mount() +impact: HIGH +impactDescription: App configurations after mount() are silently ignored, causing missing plugins and handlers +type: capability +tags: [vue3, createApp, mount, configuration, setup] +--- + +# Configure Vue App Before Calling mount() + +**Impact: HIGH** - Any app configurations applied after `.mount()` is called are silently ignored. This includes error handlers, global components, directives, and plugins, leading to mysterious missing functionality. + +The `.mount()` method should always be called after all app configurations and asset registrations are done. This is a critical ordering requirement that, when violated, produces no errors but causes features to silently fail. + +## Task Checklist + +- [ ] Register all plugins (router, store, etc.) before mount() +- [ ] Configure error handlers before mount() +- [ ] Register global components and directives before mount() +- [ ] Set all `app.config` properties before mount() +- [ ] Call `.mount()` as the final step in app initialization + +**Incorrect:** +```javascript +import { createApp } from 'vue' +import App from './App.vue' +import router from './router' + +const app = createApp(App) + +// WRONG: Mounting first, then configuring +app.mount('#app') + +// These are silently IGNORED - app is already mounted! +app.use(router) +app.config.errorHandler = (err) => { + console.error('Global error:', err) +} +app.component('GlobalButton', GlobalButton) +``` + +**Correct:** +```javascript +import { createApp } from 'vue' +import App from './App.vue' +import router from './router' +import { createPinia } from 'pinia' +import GlobalButton from './components/GlobalButton.vue' + +const app = createApp(App) + +// Configure everything FIRST +app.use(router) +app.use(createPinia()) + +// Set up error handling +app.config.errorHandler = (err, instance, info) => { + console.error('Global error:', err) + console.log('Component:', instance) + console.log('Error info:', info) +} + +// Register global components +app.component('GlobalButton', GlobalButton) + +// Mount LAST - after all configuration is complete +app.mount('#app') +``` + +## Common Mistake: Chaining with Mount + +```javascript +// WRONG: Chaining mount in the middle of configuration +createApp(App) + .use(router) + .mount('#app') // Everything after this line is a problem + .use(pinia) // This doesn't even work - mount returns component instance! + +// CORRECT: Either complete chain before mount, or use intermediate variable +createApp(App) + .use(router) + .use(pinia) + .component('GlobalButton', GlobalButton) + .mount('#app') // Mount at the very end +``` + +## Reference +- [Vue.js - Creating a Vue Application](https://vuejs.org/guide/essentials/application.html) +- [Vue.js Application API](https://vuejs.org/api/application.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/declare-emits-for-documentation.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/declare-emits-for-documentation.md new file mode 100644 index 0000000..a65f990 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/declare-emits-for-documentation.md @@ -0,0 +1,212 @@ +--- +title: Always Declare Emits for Documentation and Validation +impact: MEDIUM +impactDescription: Undeclared emits cause warnings, break TypeScript inference, and prevent event validation +type: best-practice +tags: [vue3, emits, defineEmits, component-events, typescript, documentation] +--- + +# Always Declare Emits for Documentation and Validation + +**Impact: MEDIUM** - Declaring emitted events with `defineEmits()` or the `emits` option is technically optional, but strongly recommended. Without declarations, Vue shows runtime warnings, TypeScript can't infer event types, and you lose the ability to validate event payloads. + +Declared emits also serve as self-documentation, making it immediately clear what events a component can emit. + +## Task Checklist + +- [ ] Use `defineEmits()` in ` +``` + +Vue warns: +``` +[Vue warn]: Component emitted event "select" but it is neither declared +in the emits option nor as an "onSelect" prop. +``` + +## Basic Declaration + +**Correct - Array syntax:** +```vue + +``` + +**Correct - Options API:** +```js +export default { + emits: ['submit', 'cancel', 'update'], + + methods: { + handleSubmit() { + this.$emit('submit', this.formData) + } + } +} +``` + +## TypeScript Typed Emits + +**Correct - Type-based declaration (recommended for TypeScript):** +```vue + +``` + +**Alternative syntax (Vue 3.3+):** +```vue + +``` + +## Event Validation + +You can validate event payloads at runtime: + +**Correct - Validation functions:** +```vue + +``` + +Returning `false` from a validator logs a console warning but doesn't prevent the event from being emitted. + +## Benefits of Declaring Emits + +### 1. Fallthrough Attribute Separation + +Without declaration, native event listeners fall through to the root element: + +```vue + + +``` + +```vue + + +``` + +With declaration, Vue knows it's a component event: + +```vue + +``` + +### 2. Self-Documentation + +```vue + +``` + +### 3. IDE Support + +With declarations, your IDE can: +- Autocomplete event names when using the component +- Show event payload types +- Warn about typos in event names +- Navigate to event definitions + +## $emit in Template vs emit in Script + +```vue + + + +``` + +## Reference +- [Vue.js Component Events - Declaring Emitted Events](https://vuejs.org/guide/components/events.html#declaring-emitted-events) +- [Vue.js Component Events - Events Validation](https://vuejs.org/guide/components/events.html#events-validation) +- [Vue 3 Migration - emits Option](https://v3-migration.vuejs.org/breaking-changes/emits-option) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/define-expose-before-await.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/define-expose-before-await.md new file mode 100644 index 0000000..745e135 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/define-expose-before-await.md @@ -0,0 +1,192 @@ +--- +title: defineExpose Must Be Called Before Any Await +impact: HIGH +impactDescription: Properties exposed after await are inaccessible to parent component refs +type: gotcha +tags: [vue3, script-setup, defineExpose, async, component-refs] +--- + +# defineExpose Must Be Called Before Any Await + +**Impact: HIGH** - In ` + + +``` + +```vue + + + + +``` + +**Correct:** +```vue + + + + +``` + +```vue + + + + +``` + +```vue + + +``` + +## Why This Happens + +Vue's compiler transforms ` + + +``` + +```html + + + + +``` + +**Solution 1 - Always provide initial value from parent:** +```html + + + + +``` + +**Solution 2 - Child emits default on mount (if parent control not possible):** +```html + + + + +``` + +**Solution 3 - Use required prop or explicit undefined handling:** +```html + + + + +``` + +**Best Practice - Document expected initial values:** +```html + + +``` + +## Reference +- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html) +- [Vue School - defineModel Guide](https://vueschool.io/articles/vuejs-tutorials/v-model-and-definemodel-a-comprehensive-guide-to-two-way-binding-in-vue-js-3/) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/defineEmits-must-be-top-level.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/defineEmits-must-be-top-level.md new file mode 100644 index 0000000..9d3e508 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/defineEmits-must-be-top-level.md @@ -0,0 +1,164 @@ +--- +title: defineEmits Must Be Used at Top Level of script setup +impact: HIGH +impactDescription: Using defineEmits inside functions causes compilation errors - macros must be at module scope +type: gotcha +tags: [vue3, defineEmits, script-setup, macros, composition-api] +--- + +# defineEmits Must Be Used at Top Level of script setup + +**Impact: HIGH** - The `defineEmits()` macro can only be used directly within ` +``` + +**Incorrect - Inside a conditional:** +```vue + +``` + +**Incorrect - Referencing local variables:** +```vue + +``` + +## Correct Usage + +**Correct - Top level declaration:** +```vue + +``` + +**Correct - With TypeScript types:** +```vue + +``` + +**Correct - Using constant arrays (compile-time constant):** +```vue + +``` + +## Why This Restriction Exists + +Vue's compiler processes ` +``` + +```js +// composables/useFormEvents.js +export function useFormEvents(emit) { + function handleSubmit(data) { + emit('submit', data) + } + + function handleCancel() { + emit('cancel') + } + + return { handleSubmit, handleCancel } +} +``` + +## ESLint Rule + +The `eslint-plugin-vue` provides the `vue/valid-define-emits` rule that catches these errors: + +```js +// eslint.config.js +export default [ + { + rules: { + 'vue/valid-define-emits': 'error' + } + } +] +``` + +This rule reports: +- `defineEmits` used inside functions +- `defineEmits` referencing local variables +- Multiple `defineEmits` calls in the same component +- `defineEmits` used outside ` +``` + +**Compiler error:** +``` +defineEmits() cannot accept both type and non-type arguments at the same time. +Use one or the other. +``` + +**Also incorrect:** +```vue + +``` + +## Correct: Type-Based Declaration (TypeScript) + +```vue + +``` + +**Alternative call signature syntax:** +```vue + +``` + +## Correct: Runtime Declaration (JavaScript or Simple Cases) + +**Array syntax:** +```vue + +``` + +**Object syntax with validation:** +```vue + +``` + +## Adding Validation to Type-Based Emits + +If you want TypeScript types AND runtime validation, define the validator separately: + +```vue + + + +``` + +## Choosing Between Styles + +| Style | Use When | Benefits | +|-------|----------|----------| +| Type-based | TypeScript project | Compile-time checking, IDE support | +| Array | JavaScript, simple events | Simple, no types needed | +| Object | Need runtime validation | Validates payloads at runtime | + +**Recommendation:** In TypeScript projects, use type-based declaration. It provides the best developer experience with autocompletion and type checking. + +## Same Rule Applies to defineProps + +This restriction also applies to `defineProps`: + +```vue + +``` + +## Reference +- [Vue.js SFC script setup - defineEmits](https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits) +- [Vue.js TypeScript with Composition API](https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/definemodel-object-mutation-no-emit.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/definemodel-object-mutation-no-emit.md new file mode 100644 index 0000000..db3727a --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/definemodel-object-mutation-no-emit.md @@ -0,0 +1,148 @@ +--- +title: defineModel Object Properties Must Be Replaced, Not Mutated +impact: HIGH +impactDescription: Mutating object properties via defineModel doesn't emit update events, breaking parent sync +type: gotcha +tags: [vue3, v-model, defineModel, objects, reactivity, two-way-binding] +--- + +# defineModel Object Properties Must Be Replaced, Not Mutated + +**Impact: HIGH** - When using `defineModel()` with objects or arrays, directly mutating nested properties like `model.value.prop = x` does NOT emit the `update:modelValue` event. The parent component never receives the change notification, causing silent sync failures. + +This happens because Vue only detects when the `model.value` reference itself changes, not when properties of the object are mutated in place. + +## Task Checklist + +- [ ] Never mutate object properties directly: `model.value.prop = x` +- [ ] Always create a new object reference when updating: `model.value = {...model.value, prop: x}` +- [ ] For arrays, use spread or slice: `model.value = [...model.value, newItem]` +- [ ] Consider using structuredClone for deeply nested objects + +**Incorrect - Mutation without event emission:** +```vue + +``` + +**Correct - Replace object reference to trigger event:** +```vue + +``` + +## Deep Nesting Requires Full Path Replacement + +```vue + +``` + +## Race Condition Warning with Spread Operator + +When multiple updates occur rapidly, earlier changes can be lost: + +```vue + +``` + +## Alternative: VueUse's useVModel with Deep Option + +For complex objects, consider VueUse: + +```vue + +``` + +## Reference +- [Vue.js Component v-model](https://vuejs.org/guide/components/v-model.html) +- [GitHub Discussion: defineModel with objects](https://github.com/orgs/vuejs/discussions/10538) +- [SIMPL Engineering: Vue defineModel Pitfalls](https://engineering.simpl.de/post/vue_definemodel/) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dom-update-timing-nexttick.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dom-update-timing-nexttick.md new file mode 100644 index 0000000..99a93ee --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dom-update-timing-nexttick.md @@ -0,0 +1,90 @@ +--- +title: Use nextTick() to Wait for DOM Updates +impact: MEDIUM +impactDescription: DOM updates are batched and asynchronous - direct DOM access after state changes sees stale values +type: capability +tags: [vue3, dom, nextTick, reactivity, async] +--- + +# Use nextTick() to Wait for DOM Updates + +**Impact: MEDIUM** - Vue batches DOM updates asynchronously for performance. If you access the DOM immediately after changing reactive state, you'll see the old values. Use `nextTick()` to wait for the DOM to update. + +When you modify reactive state, Vue doesn't update the DOM synchronously. Instead, it buffers changes and applies them in the next "tick" of the event loop. This is a performance optimization, but it can cause bugs when you need to read from or manipulate the DOM after state changes. + +## Task Checklist + +- [ ] Use `await nextTick()` when you need to access updated DOM elements after state changes +- [ ] Use `nextTick()` when measuring DOM elements (heights, widths) after data changes +- [ ] Use `nextTick()` when focusing inputs or scrolling after content updates +- [ ] Consider if you really need DOM access - often you can work with reactive data instead + +**Incorrect:** +```javascript +import { ref } from 'vue' + +const message = ref('Hello') +const messageEl = ref(null) + +function updateMessage() { + message.value = 'Updated!' + + // WRONG: DOM still shows "Hello" at this point + console.log(messageEl.value.textContent) // "Hello" - stale! + + // WRONG: Scrolling/focusing may not work correctly + scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight +} +``` + +**Correct:** +```javascript +import { ref, nextTick } from 'vue' + +const message = ref('Hello') +const messageEl = ref(null) + +async function updateMessage() { + message.value = 'Updated!' + + // CORRECT: Wait for DOM to update + await nextTick() + + // Now the DOM is updated + console.log(messageEl.value.textContent) // "Updated!" + + // Scrolling and focusing now work correctly + scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight +} + +// Alternative: callback syntax +function updateWithCallback() { + message.value = 'Updated!' + + nextTick(() => { + console.log(messageEl.value.textContent) // "Updated!" + }) +} +``` + +```vue + +``` + +## Reference +- [Vue.js Reactivity Fundamentals - DOM Update Timing](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#dom-update-timing) +- [Vue.js nextTick API](https://vuejs.org/api/general.html#nexttick) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-argument-constraints.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-argument-constraints.md new file mode 100644 index 0000000..f6e66ce --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-argument-constraints.md @@ -0,0 +1,146 @@ +--- +title: Dynamic Directive Arguments Have Syntax Constraints +impact: MEDIUM +impactDescription: Invalid dynamic arguments cause silent failures or browser compatibility issues +type: capability +tags: [vue3, template, directives, v-bind, v-on, dynamic-arguments] +--- + +# Dynamic Directive Arguments Have Syntax Constraints + +**Impact: MEDIUM** - Dynamic directive arguments (e.g., `:[attributeName]`, `@[eventName]`) have value and syntax constraints that can cause silent failures. In-DOM templates also have case sensitivity issues with browsers lowercasing attribute names. + +Dynamic arguments allow runtime determination of which attribute or event to bind, but they have restrictions that differ from static arguments. + +## Task Checklist + +- [ ] Ensure dynamic arguments evaluate to strings or `null` +- [ ] Avoid spaces and quotes inside dynamic argument brackets +- [ ] Use computed properties for complex dynamic argument expressions +- [ ] In in-DOM templates, use lowercase attribute names or switch to SFCs +- [ ] Use `null` to explicitly remove a binding + +**Incorrect:** +```vue + + + +``` + +**Correct:** +```vue + + + +``` + +## In-DOM Template Workaround + +When writing templates directly in HTML (not SFCs), use lowercase: + +```html + +
    + + Link +
    + + +``` + +## SFC vs In-DOM Templates + +| Feature | SFC (.vue files) | In-DOM (HTML) | +|---------|------------------|---------------| +| Case sensitivity | Preserved | Lowercased by browser | +| Dynamic arguments | Full support | Lowercase only | +| Recommendation | Preferred | Use for progressive enhancement | + +## Valid Dynamic Argument Values + +```vue + +``` + +## Reference +- [Vue.js Template Syntax - Dynamic Arguments](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-arguments) +- [Vue.js Template Syntax - Dynamic Argument Value Constraints](https://vuejs.org/guide/essentials/template-syntax.html#dynamic-argument-value-constraints) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-component-registration-vite.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-component-registration-vite.md new file mode 100644 index 0000000..9ec1554 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/dynamic-component-registration-vite.md @@ -0,0 +1,147 @@ +--- +title: Use import.meta.glob for Dynamic Component Registration in Vite +impact: MEDIUM +impactDescription: require.context from Webpack doesn't work in Vite projects +type: gotcha +tags: [vue3, component-registration, vite, dynamic-import, migration, webpack] +--- + +# Use import.meta.glob for Dynamic Component Registration in Vite + +**Impact: MEDIUM** - When migrating from Webpack to Vite or starting a new Vite project, the `require.context` pattern for dynamically registering components won't work. Vite uses `import.meta.glob` instead. Using the wrong approach will cause build errors or runtime failures. + +## Task Checklist + +- [ ] Replace `require.context` with `import.meta.glob` in Vite projects +- [ ] Update component registration patterns when migrating from Vue CLI to Vite +- [ ] Use `{ eager: true }` for synchronous loading when needed +- [ ] Handle async components appropriately with `defineAsyncComponent` + +**Incorrect (Webpack pattern - doesn't work in Vite):** +```javascript +// main.js - WRONG for Vite +import { createApp } from 'vue' +import App from './App.vue' + +const app = createApp(App) + +// This Webpack-specific API doesn't exist in Vite +const requireComponent = require.context( + './components/base', + false, + /Base[A-Z]\w+\.vue$/ +) + +requireComponent.keys().forEach(fileName => { + const componentConfig = requireComponent(fileName) + const componentName = fileName + .split('/') + .pop() + .replace(/\.\w+$/, '') + + app.component(componentName, componentConfig.default || componentConfig) +}) + +app.mount('#app') +``` + +**Correct (Vite pattern):** +```javascript +// main.js - Correct for Vite +import { createApp } from 'vue' +import App from './App.vue' + +const app = createApp(App) + +// Vite's glob import - eager loading for synchronous registration +const modules = import.meta.glob('./components/base/Base*.vue', { eager: true }) + +for (const path in modules) { + // Extract component name from path: './components/base/BaseButton.vue' -> 'BaseButton' + const componentName = path.split('/').pop().replace('.vue', '') + app.component(componentName, modules[path].default) +} + +app.mount('#app') +``` + +## Lazy Loading with Async Components + +```javascript +// main.js - Lazy loading variant +import { createApp, defineAsyncComponent } from 'vue' +import App from './App.vue' + +const app = createApp(App) + +// Without { eager: true }, returns functions that return Promises +const modules = import.meta.glob('./components/base/Base*.vue') + +for (const path in modules) { + const componentName = path.split('/').pop().replace('.vue', '') + // Wrap in defineAsyncComponent for lazy loading + app.component(componentName, defineAsyncComponent(modules[path])) +} + +app.mount('#app') +``` + +## Glob Pattern Examples + +```javascript +// All .vue files in a directory (not recursive) +import.meta.glob('./components/*.vue', { eager: true }) + +// All .vue files recursively +import.meta.glob('./components/**/*.vue', { eager: true }) + +// Specific naming pattern +import.meta.glob('./components/Base*.vue', { eager: true }) + +// Multiple patterns +import.meta.glob([ + './components/Base*.vue', + './components/App*.vue' +], { eager: true }) + +// Exclude patterns +import.meta.glob('./components/**/*.vue', { + eager: true, + ignore: ['**/*.test.vue', '**/*.spec.vue'] +}) +``` + +## TypeScript Support + +```typescript +// main.ts - with proper typing +import { createApp, Component } from 'vue' +import App from './App.vue' + +const app = createApp(App) + +const modules = import.meta.glob<{ default: Component }>( + './components/base/Base*.vue', + { eager: true } +) + +for (const path in modules) { + const componentName = path.split('/').pop()!.replace('.vue', '') + app.component(componentName, modules[path].default) +} + +app.mount('#app') +``` + +## Migration Checklist (Webpack to Vite) + +| Webpack | Vite | +|---------|------| +| `require.context(dir, recursive, regex)` | `import.meta.glob(pattern, options)` | +| Synchronous by default | Use `{ eager: true }` for sync | +| `.keys()` returns array | Returns object with paths as keys | +| Returns module directly | Access via `.default` for ES modules | + +## Reference +- [Vite - Glob Import](https://vitejs.dev/guide/features.html#glob-import) +- [Vue.js Component Registration](https://vuejs.org/guide/components/registration.html) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/event-modifier-order-matters.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/event-modifier-order-matters.md new file mode 100644 index 0000000..080d4da --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/event-modifier-order-matters.md @@ -0,0 +1,101 @@ +--- +title: Event Modifier Order Matters +impact: MEDIUM +impactDescription: Modifier order affects event handling behavior - wrong order causes unexpected propagation or prevention +type: gotcha +tags: [vue3, events, modifiers, v-on, click, form] +--- + +# Event Modifier Order Matters + +**Impact: MEDIUM** - When chaining event modifiers, the order determines behavior because Vue generates code in the same sequence. Using `.prevent.self` vs `.self.prevent` produces different results that can cause subtle bugs in event handling. + +## Task Checklist + +- [ ] Always consider modifier order when chaining multiple modifiers +- [ ] Use `.prevent.self` to prevent default on element AND children +- [ ] Use `.self.prevent` to prevent default ONLY on the element itself +- [ ] Test event behavior on both the element and its children + +**Incorrect:** +```html + + +``` + +```html + + +``` + +**Correct:** +```html + + +``` + +```html + + +``` + +```html + + +``` + +## How Modifier Order Works + +```javascript +// Vue compiles modifiers in order, so: + +// @click.prevent.self compiles to: +// event.preventDefault() +// if (event.target !== event.currentTarget) return +// handler() + +// @click.self.prevent compiles to: +// if (event.target !== event.currentTarget) return +// event.preventDefault() +// handler() +``` + +## Common Modifier Combinations + +```html + +Link + + +
    ...
    + + + +``` + +## Reference +- [Vue.js Event Handling - Event Modifiers](https://vuejs.org/guide/essentials/event-handling.html#event-modifiers) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/exact-modifier-for-precise-shortcuts.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/exact-modifier-for-precise-shortcuts.md new file mode 100644 index 0000000..e4374c1 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/exact-modifier-for-precise-shortcuts.md @@ -0,0 +1,155 @@ +--- +title: Use .exact Modifier for Precise Keyboard/Mouse Shortcuts +impact: MEDIUM +impactDescription: Without .exact, shortcuts fire even when additional modifier keys are pressed, causing unintended behavior +type: best-practice +tags: [vue3, events, keyboard, modifiers, shortcuts, accessibility] +--- + +# Use .exact Modifier for Precise Keyboard/Mouse Shortcuts + +**Impact: MEDIUM** - By default, Vue's modifier key handlers (`.ctrl`, `.alt`, `.shift`, `.meta`) fire even when other modifier keys are also pressed. Use `.exact` to require that ONLY the specified modifiers are pressed, preventing accidental triggering of shortcuts. + +## Task Checklist + +- [ ] Use `.exact` when you need precise modifier combinations +- [ ] Without `.exact`: `@click.ctrl` fires for Ctrl+Click AND Ctrl+Shift+Click +- [ ] With `.exact`: `@click.ctrl.exact` fires ONLY for Ctrl+Click +- [ ] Use `@click.exact` for plain clicks with no modifiers + +**Incorrect:** +```html + + +``` + +```html + + +``` + +**Correct:** +```html + + +``` + +```html + + +``` + +```html + + +``` + +## Behavior Comparison + +```javascript +// WITHOUT .exact +@click.ctrl="handler" +// Fires when: Ctrl+Click, Ctrl+Shift+Click, Ctrl+Alt+Click, Ctrl+Shift+Alt+Click +// Does NOT fire: Click (without Ctrl) + +// WITH .exact +@click.ctrl.exact="handler" +// Fires when: ONLY Ctrl+Click +// Does NOT fire: Ctrl+Shift+Click, Ctrl+Alt+Click, Click + +// ONLY .exact (no other modifiers) +@click.exact="handler" +// Fires when: Plain click with NO modifiers +// Does NOT fire: Ctrl+Click, Shift+Click, Alt+Click +``` + +## Practical Example: File Browser Selection + +```vue + + + +``` + +## Keyboard Shortcuts with .exact + +```html + +``` + +## Reference +- [Vue.js Event Handling - .exact Modifier](https://vuejs.org/guide/essentials/event-handling.html#exact-modifier) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/fallthrough-attrs-overwrite-vue3.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/fallthrough-attrs-overwrite-vue3.md new file mode 100644 index 0000000..c373b36 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/fallthrough-attrs-overwrite-vue3.md @@ -0,0 +1,159 @@ +# Fallthrough Attributes Overwrite Explicit Attributes in Vue 3 + +## Rule + +In Vue 3, fallthrough attributes overwrite explicitly set attributes on the root element (except `class` and `style` which are merged). This is a breaking change from Vue 2. To preserve explicit attribute values, use `inheritAttrs: false` and manually bind `$attrs` before the explicit attribute. + +## Why This Matters + +- Silent behavior change from Vue 2 to Vue 3 +- Can cause unexpected attribute values in migrated codebases +- Only `class` and `style` merge intelligently; other attributes are overwritten +- Affects component composition patterns and wrapper components + +## Bad Code + +```vue + + + + + + + +``` + +### Another common case with data attributes + +```vue + + + + + + + + +``` + +## Good Code + +### Option 1: Control attribute order with inheritAttrs: false + +```vue + + + + + + +``` + +### Option 2: Exclude specific attrs from fallthrough + +```vue + + + +``` + +### Option 3: For wrapper components, declare as prop + +```vue + + + + +``` + +## Class and Style Are Special + +Unlike other attributes, `class` and `style` merge rather than overwrite: + +```vue + + + + + + + +``` + +## Vue 2 to Vue 3 Migration Checklist + +When migrating components that rely on attribute precedence: + +1. Identify components that set explicit attributes on root elements +2. Check if parent components pass the same attributes +3. If explicit values should take precedence: + - Add `inheritAttrs: false` + - Use `v-bind="$attrs"` before explicit attributes + +## References + +- [Fallthrough Attributes](https://vuejs.org/guide/components/attrs.html) +- [Vue 3 Migration Guide - Attribute Coercion Behavior](https://v3-migration.vuejs.org/breaking-changes/) +- [Vue Fallthrough Attributes behaviour changes from Vue 2 to Vue 3](https://lukes.tips/posts/vue-3-fallthough-attributes-changes/) diff --git a/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/in-dom-template-parsing-caveats.md b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/in-dom-template-parsing-caveats.md new file mode 100644 index 0000000..a437cf4 --- /dev/null +++ b/1-Vue3-Dev/.agents/skills/vue-debug-guides/reference/in-dom-template-parsing-caveats.md @@ -0,0 +1,149 @@ +--- +title: In-DOM Template Parsing Caveats +impact: HIGH +impactDescription: Browser HTML parsing before Vue compilation causes case sensitivity, self-closing tag, and element nesting issues +type: gotcha +tags: [vue3, templates, in-dom, html-parsing, kebab-case, self-closing-tags] +--- + +# In-DOM Template Parsing Caveats + +**Impact: HIGH** - When writing Vue templates directly in the DOM (not in `.vue` files), the browser's native HTML parser processes the template BEFORE Vue sees it. This causes three critical issues: case sensitivity problems, self-closing tag failures, and element placement restrictions. + +These issues do NOT apply to Single-File Components (SFCs) or string templates where Vue's compiler handles parsing directly. + +## Task Checklist + +- [ ] Use kebab-case for component names in in-DOM templates +- [ ] Use kebab-case for prop names in in-DOM templates +- [ ] Use explicit closing tags (not self-closing) in in-DOM templates +- [ ] Use `is="vue:component-name"` for components inside restricted elements +- [ ] Prefer SFCs to avoid all in-DOM parsing issues + +## Issue 1: Case Insensitivity + +HTML is case-insensitive. The browser lowercases everything before Vue sees it. + +**Incorrect (in-DOM template):** +```html + + +``` + +**Correct (in-DOM template):** +```html + + +``` + +**In SFCs, PascalCase works fine:** +```vue + + +``` + +## Issue 2: Self-Closing Tags Fail + +HTML only allows self-closing syntax for void elements (``, ``, etc.). For all others, the browser expects closing tags. + +**Incorrect (in-DOM template):** +```html + + + +``` + +**Correct (in-DOM template):** +```html + + + +``` + +**In SFCs, self-closing works fine:** +```vue + +``` + +## Issue 3: Element Placement Restrictions + +Some HTML elements have strict rules about valid children. Invalid elements are hoisted out by the browser before Vue sees the template. + +**Restricted parent elements:** +- `
      `, `
        ` - only allow `
      1. ` +- `` - only allows ``, ``, ``, ``, `` +- `` - only allows ` + + + +``` + +## When Do These Apply? + +| Template Type | Affected? | Example | +|---------------|-----------|---------| +| Single-File Component (`.vue`) | No | `
        `, `
        `, `` +- ` + +
        + + + + +
        +``` + +**Correct (in-DOM template):** +```html + + + +
        +``` + +```html +
          +
        • +
        +``` + +**Important:** The `vue:` prefix is required! Without it, `is` is treated as a native customized built-in element attribute. + +```html + +