pi-scenes 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,8 @@ active resources = common layer ∪ current scene
24
24
  - **Full spatial isolation for scene packages (v0.11)** — *every* scene package (plain `npm:` specs included, not just filtered git bundles) now lands in the project layer as a universal delta (`{source, autoload:false, skills:["**"], extensions:["**"], ...}`) with a zero-exposure global anchor — one shared install, zero disk duplication, and a fresh directory loads **only the common layer**. Fixes the v0.7-v0.10 behavior where plain npm scene packages leaked into global settings and loaded in every project while the scene was active. Re-activating an existing scene migrates the leaked entries automatically (borrow semantics for user-configured globals is preserved)
25
25
  - **Scene-scoped prompt templates (v0.8)** — each scene can also bundle workflow templates (`prompts` field): fixed checklists that pin down step-by-step procedures so the model can't take shortcuts. Scene = **tools + skills + workflow templates** as one unit
26
26
  - Switching rewrites `packages`/`skills` in `settings.json`, then `ctx.reload()` hot-reloads — **no pi restart, session untouched**; prompt templates take a different path: injected via pi's `resources_discover` event with **zero settings writes**
27
+ - **Scene-scoped MCP servers (v0.13)** — each scene can declare its own `mcpServers`. Switching injects the scene's MCP tools into settings, and cleanly unmounts them when switching away. User-configured MCP servers are protected via borrow semantics
28
+ - **Claude Plugin interoperability (v0.13)** — `/scene import <dir>` imports any Claude Code / Cowork plugin (from `anthropics/knowledge-work-plugins` or local) as a native scene, transpiling `plugin.json`, `skills/`, `commands/` (to prompts), and `.mcp.json` automatically
27
29
  - Every switch stamps a persistent **status-bar badge** (`◆ coding`, or a per-scene `icon` like `💻 coding`) so the bar always answers *"which scene am I in"* — restored at session start, cleared by `/scene off`
28
30
  - **Zero-memory discoverability (v0.4.1)** — the command hint lists your scene names, and Tab completion shows every scene (icon + description + current marker) plus subcommands: type `/scene c` + Tab → `/scene coding`
29
31
  - The data model reserves an `extends` chain (with cycle detection) for future **parent → child scene** hierarchies
@@ -266,6 +268,17 @@ Before uninstalling, `/scene off` and prune entries you don't want to keep from
266
268
 
267
269
  ## Changelog
268
270
 
271
+ ### v0.12.0 (2026-09-30)
272
+
273
+ * **学习场景 (learning) 重磅升级**:
274
+ * **内置 `course-book` v2.5 出版级书稿工厂技能**:
275
+ * 支持从学习对话中增量沉淀 HTML 出版物,自动提取【模块 ➔ 章节 ➔ 小节】三级树状大纲并生成点导线(Dots Leader)目录;
276
+ * 内置**真·A4 物理拆页装订引擎**与**代码块防跨页撕裂保护**(上一页优雅留白,代码块完整推入新页顶部);
277
+ * 内置**沉浸式纸质书单页键盘翻阅系统 (`paging.js`)**,支持键盘 `←` / `→` / `Space` / `PageUp/Down` 秒级翻书;
278
+ * 经典动物版画排印风格,配备真双面印刷页眉(`模块 • 章节` 单行防折行)与连续真实流水页脚(`— 第 N 页 —`)。
279
+ * **升级 `eli5` 教学技能**:注入实战淬炼的「比喻三分法(直觉建立 ➔ 理性归位 ➔ 平实直说)」终版铁律与「诚实教学六诫」;
280
+ * **预置 `/notes` 交互提示词模板**:打通浏览器内画线批注到 AI 针对性审校修改的双向闭环。
281
+
269
282
  ### v0.11.1 (2026-09-24)
270
283
 
271
284
  - **Anchor-form fix for borrowed detection** — a pre-existing zero-exposure anchor entry (`{source, autoload:false, skills:[]}`) in user settings (e.g. written by ≤v0.10 without being recorded in the anchors ledger) is no longer misjudged as a user-configured global: re-activation now normalizes it back into the anchor ledger and lands the project delta instead of skipping it as borrowed
@@ -330,6 +343,8 @@ pi 的 `packages` / `skills` 是全局平铺的:所有已安装扩展、所有
330
343
  - **资产/激活分离(v0.7)**——包只全局装一份、所有项目共享;git 技能包在全局层钉为零暴露**锚点**(`{source, autoload:false, skills:[]}`),项目层写 **delta**(`{source, autoload:false, skills:[白名单]}`)按场景启用——借 pi 原生 delta 机制做到「一份克隆、每项目各自的精选」
331
344
  - **场景包全面空间隔离(v0.11)**——所有场景包(含裸 `npm:` 串,不再限于带白名单的 git 包)统一落项目层通用 delta(`{source, autoload:false, skills:["**"], extensions:["**"], ...}`)+ 全局零暴露锚点——共享一份安装、零磁盘复制,新目录只加载通用层。修复 v0.7~v0.10 裸 npm 场景包泄漏到全局 settings、场景激活期间所有项目都加载的问题;存量泄漏在重新激活场景时自动迁移修复(用户手配的全局同包仍保持借用语义)
332
345
  - **场景化 prompt 模板(v0.8)**——每个场景可携带流程模板(`prompts` 字段):把固定流程的步骤清单固化成 `/命令`,模型无法挑最快路径跳步。场景成为**工具 + 技能 + 流程模板**三位一体
346
+ - **场景级 MCP 动态调度(v0.13)**——每个场景可声明专属 `mcpServers`。切换时动态挂载对应工具,切走时精确卸载;用户预配的 MCP 走借用保护不篡改
347
+ - **Claude Plugin 原生协议互通(v0.13)**——`/scene import <dir>` 一键将 Claude Code / Cowork 插件(如 Anthropic 官方知识工作流插件或社区生态)转换为原生场景,自动转译 `plugin.json`、`skills/`、`commands/`(转为 prompt 模板)及 `.mcp.json`
333
348
  - 切换 = 改写 `settings.json` 的 `packages`/`skills` → `ctx.reload()` 热重载,**无需重启 pi**;prompt 模板走另一条路:经 pi 的 `resources_discover` 事件动态注入,**零 settings 写入**
334
349
  - 每次切换成功后状态栏常驻**场景徽标**(`◆ coding`,或每场景自定义 `icon` 如 `💻 coding`),状态栏随时回答「我现在在哪个场景」——会话启动自动恢复,`/scene off` 清除
335
350
  - **零记忆可发现性(v0.4.1)**——命令提示行直接拼入场景名清单;Tab 补全列出全部场景(icon + 描述 + 当前标记)与子命令:`/scene c` + Tab → `/scene coding`
@@ -378,8 +393,9 @@ pi install git:github.com/Feng-H/pi-scenes
378
393
  | `pm` | `npm:pi-web-access`、`npm:pi-goal-x`、`npm:@juicesharp/rpiv-todo` | 竞品/市场调研、目标规划与完成度审计、需求/任务清单 overlay |
379
394
  | `research` | `npm:pi-web-access`、`npm:pi-subagents` | 多源搜索/抓取/PDF/视频,并行多角度深挖 |
380
395
  | `writing` | `npm:pi-web-access` | 素材检索与事实核查(引用溯源) |
381
- | `data` | `npm:pi-docparser`、`npm:pi-mcp-adapter` | 表格结构化抽取、接任意 MCP server(数据库/BI) |
396
+ | `data` | `npm:pi-docparser`、`npm:pi-mcp-adapter` | 表格结构化抽取、接任意 MCP server(预置 SQL 编写与数据校验技能) |
382
397
  | `learning` | `npm:pi-web-access`、`npm:pi-subagents` | 学习材料获取、并行多视角学习;预置 skill:eli5(大白话解释) |
398
+ | `productivity` | `npm:pi-carryover` | 个人生产力:任务清单驱动工作流与重要上下文沉淀(基于 Anthropic 知识插件规范) |
383
399
 
384
400
  v0.8 起每个预设场景还携带流程模板(coding→`/pre-commit`、office→`/doc-from-notes`、pm→`/prd-skeleton`、research→`/deep-dive`、writing→`/fact-check`、data→`/data-audit`;v0.9 learning 场景→`/feynman` 费曼内化 + `/socratic` 苏格拉底检验 + `/flashcards` 闪卡复习,三件套),切换后直接可用;自己加模板只需往 `~/.pi/agent/scenes/<名>/prompts/` 丢 `.md` 文件。
385
401
 
@@ -0,0 +1,20 @@
1
+ ---
2
+ description: 处理书稿备注——读课程书里的提问/批注/作答,逐条解释、烧录、批改
3
+ argument-hint: "[书目录名,缺省=全部]"
4
+ ---
5
+ 处理课程书的备注闭环(目标书:$@ 为空则扫描 book/*/annotations.json 全部书)。
6
+
7
+ **先读 course-book 技能的「处理书稿备注」流程一节,严格照办。** 核心规则摘要:
8
+
9
+ 1. **找书**:读 `book/<name>/annotations.json`,列出 open 标注(无则明确告知"备注箱是空的"并停)。
10
+ 2. **逐条处理,优先级 bug > question > answer > suggest > discuss**。每条:
11
+ - **先在会话里解释**(教学时刻:讲透概念、可举例,确认学生懂了——无论 disposition 如何不能跳过)
12
+ - **备注文本含明确指令**(重写:/改为:/删掉)→ 照指令执行,优先于 disposition
13
+ - disposition=sidebar → 锚点附近烧录 `<aside class="callout qa">`;rewrite → 改写对应段落;chat → 只解释不改书
14
+ - type=answer → 批改练习作答,把学生答案+批注烧进该练习 `<details class="answer">`
15
+ - 标记 resolved + resolution.summary
16
+ 3. **烧录后自检**:dist/book.html 去标签纯文本中,锚点文本与对应问答距离 <600 字符(脚本比对)。
17
+ 4. **重建**:`python3 book/<name>/build.py`;若书桌在跑会自动热刷新。
18
+ 5. **报告**:处理表格(备注→处理→去向)+ open 剩余数。
19
+
20
+ 禁止:跳过会话解释直接改书;整章重生成;未自检就宣布完成。
@@ -0,0 +1,10 @@
1
+ ---
2
+ description: 梳理当日任务与待办清单(TASKS.md)
3
+ ---
4
+
5
+ 请阅读当前目录的 `TASKS.md`,执行以下梳理:
6
+
7
+ 1. **当前重点(Active)**:列出进行中与高优先级任务,标出卡点或到期日。
8
+ 2. **等待事项(Waiting On)**:盘点正在等待他人反馈或依赖的任务与等待时长。
9
+ 3. **完成复盘(Done)**:总结近期完成项,清理归档超时条目。
10
+ 4. **行动建议**:给出今日建议聚焦攻坚的 1~3 个关键任务。
@@ -0,0 +1,383 @@
1
+ ---
2
+ name: validate-data
3
+ description: QA an analysis before sharing -- methodology, accuracy, and bias checks. Use when reviewing an analysis before a stakeholder presentation, spot-checking calculations and aggregation logic, verifying a SQL query's results look right, or assessing whether conclusions are actually supported by the data.
4
+ argument-hint: "<analysis to review>"
5
+ ---
6
+
7
+ # /validate-data - Validate Analysis Before Sharing
8
+
9
+ > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../../CONNECTORS.md).
10
+
11
+ Review an analysis for accuracy, methodology, and potential biases before sharing with stakeholders. Generates a confidence assessment and improvement suggestions.
12
+
13
+ ## Usage
14
+
15
+ ```
16
+ /validate-data <analysis to review>
17
+ ```
18
+
19
+ The analysis can be:
20
+ - A document or report in the conversation
21
+ - A file (markdown, notebook, spreadsheet)
22
+ - SQL queries and their results
23
+ - Charts and their underlying data
24
+ - A description of methodology and findings
25
+
26
+ ## Workflow
27
+
28
+ ### 1. Review Methodology and Assumptions
29
+
30
+ Examine:
31
+
32
+ - **Question framing**: Is the analysis answering the right question? Could the question be interpreted differently?
33
+ - **Data selection**: Are the right tables/datasets being used? Is the time range appropriate?
34
+ - **Population definition**: Is the analysis population correctly defined? Are there unintended exclusions?
35
+ - **Metric definitions**: Are metrics defined clearly and consistently? Do they match how stakeholders understand them?
36
+ - **Baseline and comparison**: Is the comparison fair? Are time periods, cohort sizes, and contexts comparable?
37
+
38
+ ### 2. Run the Pre-Delivery QA Checklist
39
+
40
+ Work through the checklist below — data quality, calculation, reasonableness, and presentation checks.
41
+
42
+ ### 3. Check for Common Analytical Pitfalls
43
+
44
+ Systematically review against the detailed pitfall catalog below (join explosion, survivorship bias, incomplete period comparison, denominator shifting, average of averages, timezone mismatches, selection bias).
45
+
46
+ ### 4. Verify Calculations and Aggregations
47
+
48
+ Where possible, spot-check:
49
+
50
+ - Recalculate a few key numbers independently
51
+ - Verify that subtotals sum to totals
52
+ - Check that percentages sum to 100% (or close to it) where expected
53
+ - Confirm that YoY/MoM comparisons use the correct base periods
54
+ - Validate that filters are applied consistently across all metrics
55
+
56
+ Apply the result sanity-checking techniques below (magnitude checks, cross-validation, red-flag detection).
57
+
58
+ ### 5. Assess Visualizations
59
+
60
+ If the analysis includes charts:
61
+
62
+ - Do axes start at appropriate values (zero for bar charts)?
63
+ - Are scales consistent across comparison charts?
64
+ - Do chart titles accurately describe what's shown?
65
+ - Could the visualization mislead a quick reader?
66
+ - Are there truncated axes, inconsistent intervals, or 3D effects that distort perception?
67
+
68
+ ### 6. Evaluate Narrative and Conclusions
69
+
70
+ Review whether:
71
+
72
+ - Conclusions are supported by the data shown
73
+ - Alternative explanations are acknowledged
74
+ - Uncertainty is communicated appropriately
75
+ - Recommendations follow logically from findings
76
+ - The level of confidence matches the strength of evidence
77
+
78
+ ### 7. Suggest Improvements
79
+
80
+ Provide specific, actionable suggestions:
81
+
82
+ - Additional analyses that would strengthen the conclusions
83
+ - Caveats or limitations that should be noted
84
+ - Better visualizations or framings for key points
85
+ - Missing context that stakeholders would want
86
+
87
+ ### 8. Generate Confidence Assessment
88
+
89
+ Rate the analysis on a 3-level scale:
90
+
91
+ **Ready to share** -- Analysis is methodologically sound, calculations verified, caveats noted. Minor suggestions for improvement but nothing blocking.
92
+
93
+ **Share with noted caveats** -- Analysis is largely correct but has specific limitations or assumptions that must be communicated to stakeholders. List the required caveats.
94
+
95
+ **Needs revision** -- Found specific errors, methodological issues, or missing analyses that should be addressed before sharing. List the required changes with priority order.
96
+
97
+ ## Output Format
98
+
99
+ ```
100
+ ## Validation Report
101
+
102
+ ### Overall Assessment: [Ready to share | Share with caveats | Needs revision]
103
+
104
+ ### Methodology Review
105
+ [Findings about approach, data selection, definitions]
106
+
107
+ ### Issues Found
108
+ 1. [Severity: High/Medium/Low] [Issue description and impact]
109
+ 2. ...
110
+
111
+ ### Calculation Spot-Checks
112
+ - [Metric]: [Verified / Discrepancy found]
113
+ - ...
114
+
115
+ ### Visualization Review
116
+ [Any issues with charts or visual presentation]
117
+
118
+ ### Suggested Improvements
119
+ 1. [Improvement and why it matters]
120
+ 2. ...
121
+
122
+ ### Required Caveats for Stakeholders
123
+ - [Caveat that must be communicated]
124
+ - ...
125
+ ```
126
+
127
+ ---
128
+
129
+ ## Pre-Delivery QA Checklist
130
+
131
+ Run through this checklist before sharing any analysis with stakeholders.
132
+
133
+ ### Data Quality Checks
134
+
135
+ - [ ] **Source verification**: Confirmed which tables/data sources were used. Are they the right ones for this question?
136
+ - [ ] **Freshness**: Data is current enough for the analysis. Noted the "as of" date.
137
+ - [ ] **Completeness**: No unexpected gaps in time series or missing segments.
138
+ - [ ] **Null handling**: Checked null rates in key columns. Nulls are handled appropriately (excluded, imputed, or flagged).
139
+ - [ ] **Deduplication**: Confirmed no double-counting from bad joins or duplicate source records.
140
+ - [ ] **Filter verification**: All WHERE clauses and filters are correct. No unintended exclusions.
141
+
142
+ ### Calculation Checks
143
+
144
+ - [ ] **Aggregation logic**: GROUP BY includes all non-aggregated columns. Aggregation level matches the analysis grain.
145
+ - [ ] **Denominator correctness**: Rate and percentage calculations use the right denominator. Denominators are non-zero.
146
+ - [ ] **Date alignment**: Comparisons use the same time period length. Partial periods are excluded or noted.
147
+ - [ ] **Join correctness**: JOIN types are appropriate (INNER vs LEFT). Many-to-many joins haven't inflated counts.
148
+ - [ ] **Metric definitions**: Metrics match how stakeholders define them. Any deviations are noted.
149
+ - [ ] **Subtotals sum**: Parts add up to the whole where expected. If they don't, explain why (e.g., overlap).
150
+
151
+ ### Reasonableness Checks
152
+
153
+ - [ ] **Magnitude**: Numbers are in a plausible range. Revenue isn't negative. Percentages are between 0-100%.
154
+ - [ ] **Trend continuity**: No unexplained jumps or drops in time series.
155
+ - [ ] **Cross-reference**: Key numbers match other known sources (dashboards, previous reports, finance data).
156
+ - [ ] **Order of magnitude**: Total revenue is in the right ballpark. User counts match known figures.
157
+ - [ ] **Edge cases**: What happens at the boundaries? Empty segments, zero-activity periods, new entities.
158
+
159
+ ### Presentation Checks
160
+
161
+ - [ ] **Chart accuracy**: Bar charts start at zero. Axes are labeled. Scales are consistent across panels.
162
+ - [ ] **Number formatting**: Appropriate precision. Consistent currency/percentage formatting. Thousands separators where needed.
163
+ - [ ] **Title clarity**: Titles state the insight, not just the metric. Date ranges are specified.
164
+ - [ ] **Caveat transparency**: Known limitations and assumptions are stated explicitly.
165
+ - [ ] **Reproducibility**: Someone else could recreate this analysis from the documentation provided.
166
+
167
+ ## Common Data Analysis Pitfalls
168
+
169
+ ### Join Explosion
170
+
171
+ **The problem**: A many-to-many join silently multiplies rows, inflating counts and sums.
172
+
173
+ **How to detect**:
174
+ ```sql
175
+ -- Check row count before and after join
176
+ SELECT COUNT(*) FROM table_a; -- 1,000
177
+ SELECT COUNT(*) FROM table_a a JOIN table_b b ON a.id = b.a_id; -- 3,500 (uh oh)
178
+ ```
179
+
180
+ **How to prevent**:
181
+ - Always check row counts after joins
182
+ - If counts increase, investigate the join relationship (is it really 1:1 or 1:many?)
183
+ - Use `COUNT(DISTINCT a.id)` instead of `COUNT(*)` when counting entities through joins
184
+
185
+ ### Survivorship Bias
186
+
187
+ **The problem**: Analyzing only entities that exist today, ignoring those that were deleted, churned, or failed.
188
+
189
+ **Examples**:
190
+ - Analyzing user behavior of "current users" misses churned users
191
+ - Looking at "companies using our product" ignores those who evaluated and left
192
+ - Studying properties of "successful" outcomes without "unsuccessful" ones
193
+
194
+ **How to prevent**: Ask "who is NOT in this dataset?" before drawing conclusions.
195
+
196
+ ### Incomplete Period Comparison
197
+
198
+ **The problem**: Comparing a partial period to a full period.
199
+
200
+ **Examples**:
201
+ - "January revenue is $500K vs. December's $800K" -- but January isn't over yet
202
+ - "This week's signups are down" -- checked on Wednesday, comparing to a full prior week
203
+
204
+ **How to prevent**: Always filter to complete periods, or compare same-day-of-month / same-number-of-days.
205
+
206
+ ### Denominator Shifting
207
+
208
+ **The problem**: The denominator changes between periods, making rates incomparable.
209
+
210
+ **Examples**:
211
+ - Conversion rate improves because you changed how you count "eligible" users
212
+ - Churn rate changes because the definition of "active" was updated
213
+
214
+ **How to prevent**: Use consistent definitions across all compared periods. Note any definition changes.
215
+
216
+ ### Average of Averages
217
+
218
+ **The problem**: Averaging pre-computed averages gives wrong results when group sizes differ.
219
+
220
+ **Example**:
221
+ - Group A: 100 users, average revenue $50
222
+ - Group B: 10 users, average revenue $200
223
+ - Wrong: Average of averages = ($50 + $200) / 2 = $125
224
+ - Right: Weighted average = (100*$50 + 10*$200) / 110 = $63.64
225
+
226
+ **How to prevent**: Always aggregate from raw data. Never average pre-aggregated averages.
227
+
228
+ ### Timezone Mismatches
229
+
230
+ **The problem**: Different data sources use different timezones, causing misalignment.
231
+
232
+ **Examples**:
233
+ - Event timestamps in UTC vs. user-facing dates in local time
234
+ - Daily rollups that use different cutoff times
235
+
236
+ **How to prevent**: Standardize all timestamps to a single timezone (UTC recommended) before analysis. Document the timezone used.
237
+
238
+ ### Selection Bias in Segmentation
239
+
240
+ **The problem**: Segments are defined by the outcome you're measuring, creating circular logic.
241
+
242
+ **Examples**:
243
+ - "Users who completed onboarding have higher retention" -- obviously, they self-selected
244
+ - "Power users generate more revenue" -- they became power users BY generating revenue
245
+
246
+ **How to prevent**: Define segments based on pre-treatment characteristics, not outcomes.
247
+
248
+ ### Other Statistical Traps
249
+
250
+ - **Simpson's paradox**: Trend reverses when data is aggregated vs. segmented
251
+ - **Correlation presented as causation** without supporting evidence
252
+ - **Small sample sizes** leading to unreliable conclusions
253
+ - **Outliers disproportionately affecting averages** (should medians be used instead?)
254
+ - **Multiple testing / cherry-picking** significant results
255
+ - **Look-ahead bias**: Using future information to explain past events
256
+ - **Cherry-picked time ranges** that favor a particular narrative
257
+
258
+ ## Result Sanity Checking
259
+
260
+ ### Magnitude Checks
261
+
262
+ For any key number in your analysis, verify it passes the "smell test":
263
+
264
+ | Metric Type | Sanity Check |
265
+ |---|---|
266
+ | User counts | Does this match known MAU/DAU figures? |
267
+ | Revenue | Is this in the right order of magnitude vs. known ARR? |
268
+ | Conversion rates | Is this between 0% and 100%? Does it match dashboard figures? |
269
+ | Growth rates | Is 50%+ MoM growth realistic, or is there a data issue? |
270
+ | Averages | Is the average reasonable given what you know about the distribution? |
271
+ | Percentages | Do segment percentages sum to ~100%? |
272
+
273
+ ### Cross-Validation Techniques
274
+
275
+ 1. **Calculate the same metric two different ways** and verify they match
276
+ 2. **Spot-check individual records** -- pick a few specific entities and trace their data manually
277
+ 3. **Compare to known benchmarks** -- match against published dashboards, finance reports, or prior analyses
278
+ 4. **Reverse engineer** -- if total revenue is X, does per-user revenue times user count approximately equal X?
279
+ 5. **Boundary checks** -- what happens when you filter to a single day, a single user, or a single category? Are those micro-results sensible?
280
+
281
+ ### Red Flags That Warrant Investigation
282
+
283
+ - Any metric that changed by more than 50% period-over-period without an obvious cause
284
+ - Counts or sums that are exact round numbers (suggests a filter or default value issue)
285
+ - Rates exactly at 0% or 100% (may indicate incomplete data)
286
+ - Results that perfectly confirm the hypothesis (reality is usually messier)
287
+ - Identical values across time periods or segments (suggests the query is ignoring a dimension)
288
+
289
+ ## Documentation Standards for Reproducibility
290
+
291
+ ### Analysis Documentation Template
292
+
293
+ Every non-trivial analysis should include:
294
+
295
+ ```markdown
296
+ ## Analysis: [Title]
297
+
298
+ ### Question
299
+ [The specific question being answered]
300
+
301
+ ### Data Sources
302
+ - Table: [schema.table_name] (as of [date])
303
+ - Table: [schema.other_table] (as of [date])
304
+ - File: [filename] (source: [where it came from])
305
+
306
+ ### Definitions
307
+ - [Metric A]: [Exactly how it's calculated]
308
+ - [Segment X]: [Exactly how membership is determined]
309
+ - [Time period]: [Start date] to [end date], [timezone]
310
+
311
+ ### Methodology
312
+ 1. [Step 1 of the analysis approach]
313
+ 2. [Step 2]
314
+ 3. [Step 3]
315
+
316
+ ### Assumptions and Limitations
317
+ - [Assumption 1 and why it's reasonable]
318
+ - [Limitation 1 and its potential impact on conclusions]
319
+
320
+ ### Key Findings
321
+ 1. [Finding 1 with supporting evidence]
322
+ 2. [Finding 2 with supporting evidence]
323
+
324
+ ### SQL Queries
325
+ [All queries used, with comments]
326
+
327
+ ### Caveats
328
+ - [Things the reader should know before acting on this]
329
+ ```
330
+
331
+ ### Code Documentation
332
+
333
+ For any code (SQL, Python) that may be reused:
334
+
335
+ ```python
336
+ """
337
+ Analysis: Monthly Cohort Retention
338
+ Author: [Name]
339
+ Date: [Date]
340
+ Data Source: events table, users table
341
+ Last Validated: [Date] -- results matched dashboard within 2%
342
+
343
+ Purpose:
344
+ Calculate monthly user retention cohorts based on first activity date.
345
+
346
+ Assumptions:
347
+ - "Active" means at least one event in the month
348
+ - Excludes test/internal accounts (user_type != 'internal')
349
+ - Uses UTC dates throughout
350
+
351
+ Output:
352
+ Cohort retention matrix with cohort_month rows and months_since_signup columns.
353
+ Values are retention rates (0-100%).
354
+ """
355
+ ```
356
+
357
+ ### Version Control for Analyses
358
+
359
+ - Save queries and code in version control (git) or a shared docs system
360
+ - Note the date of the data snapshot used
361
+ - If an analysis is re-run with updated data, document what changed and why
362
+ - Link to prior versions of recurring analyses for trend comparison
363
+
364
+ ## Examples
365
+
366
+ ```
367
+ /validate-data Review this quarterly revenue analysis before I send it to the exec team: [analysis]
368
+ ```
369
+
370
+ ```
371
+ /validate-data Check my churn analysis -- I'm comparing Q4 churn rates to Q3 but Q4 has a shorter measurement window
372
+ ```
373
+
374
+ ```
375
+ /validate-data Here's a SQL query and its results for our conversion funnel. Does the logic look right? [query + results]
376
+ ```
377
+
378
+ ## Tips
379
+
380
+ - Run /validate-data before any high-stakes presentation or decision
381
+ - Even quick analyses benefit from a sanity check -- it takes a minute and can save your credibility
382
+ - If the validation finds issues, fix them and re-validate
383
+ - Share the validation output alongside your analysis to build stakeholder confidence
@@ -0,0 +1,122 @@
1
+ ---
2
+ name: write-query
3
+ description: Write optimized SQL for your dialect with best practices. Use when translating a natural-language data need into SQL, building a multi-CTE query with joins and aggregations, optimizing a query against a large partitioned table, or getting dialect-specific syntax for Snowflake, BigQuery, Postgres, etc.
4
+ argument-hint: "<description of what data you need>"
5
+ ---
6
+
7
+ # /write-query - Write Optimized SQL
8
+
9
+ > If you see unfamiliar placeholders or need to check which tools are connected, see [CONNECTORS.md](../../CONNECTORS.md).
10
+
11
+ Write a SQL query from a natural language description, optimized for your specific SQL dialect and following best practices.
12
+
13
+ ## Usage
14
+
15
+ ```
16
+ /write-query <description of what data you need>
17
+ ```
18
+
19
+ ## Workflow
20
+
21
+ ### 1. Understand the Request
22
+
23
+ Parse the user's description to identify:
24
+
25
+ - **Output columns**: What fields should the result include?
26
+ - **Filters**: What conditions limit the data (time ranges, segments, statuses)?
27
+ - **Aggregations**: Are there GROUP BY operations, counts, sums, averages?
28
+ - **Joins**: Does this require combining multiple tables?
29
+ - **Ordering**: How should results be sorted?
30
+ - **Limits**: Is there a top-N or sample requirement?
31
+
32
+ ### 2. Determine SQL Dialect
33
+
34
+ If the user's SQL dialect is not already known, ask which they use:
35
+
36
+ - **PostgreSQL** (including Aurora, RDS, Supabase, Neon)
37
+ - **Snowflake**
38
+ - **BigQuery** (Google Cloud)
39
+ - **Redshift** (Amazon)
40
+ - **Databricks SQL**
41
+ - **MySQL** (including Aurora MySQL, PlanetScale)
42
+ - **SQL Server** (Microsoft)
43
+ - **DuckDB**
44
+ - **SQLite**
45
+ - **Other** (ask for specifics)
46
+
47
+ Remember the dialect for future queries in the same session.
48
+
49
+ ### 3. Discover Schema (If Warehouse Connected)
50
+
51
+ If a data warehouse MCP server is connected:
52
+
53
+ 1. Search for relevant tables based on the user's description
54
+ 2. Inspect column names, types, and relationships
55
+ 3. Check for partitioning or clustering keys that affect performance
56
+ 4. Look for pre-built views or materialized views that might simplify the query
57
+
58
+ ### 4. Write the Query
59
+
60
+ Follow these best practices:
61
+
62
+ **Structure:**
63
+ - Use CTEs (WITH clauses) for readability when queries have multiple logical steps
64
+ - One CTE per logical transformation or data source
65
+ - Name CTEs descriptively (e.g., `daily_signups`, `active_users`, `revenue_by_product`)
66
+
67
+ **Performance:**
68
+ - Never use `SELECT *` in production queries -- specify only needed columns
69
+ - Filter early (push WHERE clauses as close to the base tables as possible)
70
+ - Use partition filters when available (especially date partitions)
71
+ - Prefer `EXISTS` over `IN` for subqueries with large result sets
72
+ - Use appropriate JOIN types (don't use LEFT JOIN when INNER JOIN is correct)
73
+ - Avoid correlated subqueries when a JOIN or window function works
74
+ - Be mindful of exploding joins (many-to-many)
75
+
76
+ **Readability:**
77
+ - Add comments explaining the "why" for non-obvious logic
78
+ - Use consistent indentation and formatting
79
+ - Alias tables with meaningful short names (not just `a`, `b`, `c`)
80
+ - Put each major clause on its own line
81
+
82
+ **Dialect-specific optimizations:**
83
+ - Apply dialect-specific syntax and functions (see `sql-queries` skill for details)
84
+ - Use dialect-appropriate date functions, string functions, and window syntax
85
+ - Note any dialect-specific performance features (e.g., Snowflake clustering, BigQuery partitioning)
86
+
87
+ ### 5. Present the Query
88
+
89
+ Provide:
90
+
91
+ 1. **The complete query** in a SQL code block with syntax highlighting
92
+ 2. **Brief explanation** of what each CTE or section does
93
+ 3. **Performance notes** if relevant (expected cost, partition usage, potential bottlenecks)
94
+ 4. **Modification suggestions** -- how to adjust for common variations (different time range, different granularity, additional filters)
95
+
96
+ ### 6. Offer to Execute
97
+
98
+ If a data warehouse is connected, offer to run the query and analyze the results. If the user wants to run it themselves, the query is ready to copy-paste.
99
+
100
+ ## Examples
101
+
102
+ **Simple aggregation:**
103
+ ```
104
+ /write-query Count of orders by status for the last 30 days
105
+ ```
106
+
107
+ **Complex analysis:**
108
+ ```
109
+ /write-query Cohort retention analysis -- group users by their signup month, then show what percentage are still active (had at least one event) at 1, 3, 6, and 12 months after signup
110
+ ```
111
+
112
+ **Performance-critical:**
113
+ ```
114
+ /write-query We have a 500M row events table partitioned by date. Find the top 100 users by event count in the last 7 days with their most recent event type.
115
+ ```
116
+
117
+ ## Tips
118
+
119
+ - Mention your SQL dialect upfront to get the right syntax immediately
120
+ - If you know the table names, include them -- otherwise Claude will help you find them
121
+ - Specify if you need the query to be idempotent (safe to re-run) or one-time
122
+ - For recurring queries, mention if it should be parameterized for date ranges