@boyingliu01/dsh-plugin-xp-gate 0.19.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.
Files changed (80) hide show
  1. package/README.md +25 -0
  2. package/cordis.patch.yml +7 -0
  3. package/lib/command.d.ts +27 -0
  4. package/lib/command.d.ts.map +1 -0
  5. package/lib/command.js +62 -0
  6. package/lib/command.js.map +1 -0
  7. package/lib/gate-runner.d.ts +18 -0
  8. package/lib/gate-runner.d.ts.map +1 -0
  9. package/lib/gate-runner.js +46 -0
  10. package/lib/gate-runner.js.map +1 -0
  11. package/lib/index.d.ts +5 -0
  12. package/lib/index.d.ts.map +1 -0
  13. package/lib/index.js +79 -0
  14. package/lib/index.js.map +1 -0
  15. package/package.json +70 -0
  16. package/skills/admin-template-guidelines/SKILL.md +113 -0
  17. package/skills/admin-template-guidelines/references/rule-1.md +91 -0
  18. package/skills/admin-template-guidelines/references/rule-2.md +155 -0
  19. package/skills/admin-template-guidelines/references/rule-3.md +70 -0
  20. package/skills/admin-template-guidelines/references/rule-4.md +154 -0
  21. package/skills/admin-template-guidelines/references/rule-5.md +126 -0
  22. package/skills/admin-template-guidelines/references/rule-6.md +180 -0
  23. package/skills/batch-grill-me/SKILL.md +15 -0
  24. package/skills/delphi-review/.delphi-config.json.example +70 -0
  25. package/skills/delphi-review/AGENTS.md +67 -0
  26. package/skills/delphi-review/INSTALL.md +150 -0
  27. package/skills/delphi-review/SKILL.md +559 -0
  28. package/skills/delphi-review/hooks.md +19 -0
  29. package/skills/delphi-review/opencode.json.delphi.example +52 -0
  30. package/skills/delphi-review/references/code-walkthrough.md +470 -0
  31. package/skills/delphi-review/references/orchestrator-dispatch.md +64 -0
  32. package/skills/delphi-review/references/requirements.md +402 -0
  33. package/skills/delphi-review/references/round-templates.md +134 -0
  34. package/skills/delphi-review/scripts/verify-consensus.sh +43 -0
  35. package/skills/delphi-review/tools.md +29 -0
  36. package/skills/domain-modeling/ADR-FORMAT.md +64 -0
  37. package/skills/domain-modeling/CONTEXT-FORMAT.md +60 -0
  38. package/skills/domain-modeling/SKILL.md +74 -0
  39. package/skills/grill-with-docs/SKILL.md +7 -0
  40. package/skills/grilling/SKILL.md +12 -0
  41. package/skills/improve-codebase-architecture/SKILL.md +156 -0
  42. package/skills/ralph-loop/SKILL.md +198 -0
  43. package/skills/ralph-loop/references/components.md +113 -0
  44. package/skills/ralph-loop/references/phase-2-build-ralph.md +89 -0
  45. package/skills/ralph-loop/references/workflow-details.md +99 -0
  46. package/skills/ralph-loop/templates/progress-log.md +36 -0
  47. package/skills/sprint-flow/AGENTS.md +103 -0
  48. package/skills/sprint-flow/SKILL.md +411 -0
  49. package/skills/sprint-flow/__tests__/sprint-flow.test.cjs +457 -0
  50. package/skills/sprint-flow/hooks.md +18 -0
  51. package/skills/sprint-flow/references/components/memory.md +87 -0
  52. package/skills/sprint-flow/references/components/middleware.md +75 -0
  53. package/skills/sprint-flow/references/components/skill-invocations.md +105 -0
  54. package/skills/sprint-flow/references/components/system-prompt.md +27 -0
  55. package/skills/sprint-flow/references/components/tool-descriptions.md +95 -0
  56. package/skills/sprint-flow/references/force-levels.md +204 -0
  57. package/skills/sprint-flow/references/orchestration-rules.md +236 -0
  58. package/skills/sprint-flow/references/phase-1-prep.md +294 -0
  59. package/skills/sprint-flow/references/phase-2-design.md +273 -0
  60. package/skills/sprint-flow/references/phase-3-build.md +348 -0
  61. package/skills/sprint-flow/references/phase-4-verify.md +225 -0
  62. package/skills/sprint-flow/references/phase-5-ship.md +222 -0
  63. package/skills/sprint-flow/references/phase-6-close.md +266 -0
  64. package/skills/sprint-flow/references/phase-overview.md +486 -0
  65. package/skills/sprint-flow/scripts/verify-sprint-state.sh +38 -0
  66. package/skills/sprint-flow/templates/auto-estimate-learning-log.md +136 -0
  67. package/skills/sprint-flow/templates/auto-estimate-output-template.md +110 -0
  68. package/skills/sprint-flow/templates/emergent-issues-template.md +120 -0
  69. package/skills/sprint-flow/templates/pain-document-template.md +115 -0
  70. package/skills/sprint-flow/templates/sprint-progress-template.md +140 -0
  71. package/skills/sprint-flow/templates/sprint-summary-template.md +121 -0
  72. package/skills/sprint-flow/tools.md +29 -0
  73. package/skills/test-driven-development/SKILL.md +371 -0
  74. package/skills/test-driven-development/testing-anti-patterns.md +299 -0
  75. package/skills/test-specification-alignment/AGENTS.md +56 -0
  76. package/skills/test-specification-alignment/SKILL.md +205 -0
  77. package/skills/test-specification-alignment/references/alignment-verification-algorithm.md +493 -0
  78. package/skills/test-specification-alignment/references/phase2-constraint-enforcement.md +431 -0
  79. package/skills/test-specification-alignment/references/specification-format.md +348 -0
  80. package/skills/to-issues/SKILL.md +277 -0
@@ -0,0 +1,155 @@
1
+ # Rule 2: Test Consistency — Examples
2
+
3
+ ## ❌ 错误示例:每个测试文件自建实例
4
+
5
+ ```typescript
6
+ // test/admin/templates.test.ts — 反模式
7
+ import Fastify from 'fastify';
8
+ import { registerTemplateRoutes } from '../../admin/routes/templates';
9
+
10
+ describe('Template Routes', () => {
11
+ let fastify: any;
12
+
13
+ beforeEach(async () => {
14
+ fastify = Fastify();
15
+ await fastify.register(prismaPlugin, { datasource: {} }); // 每次自建
16
+ await fastify.register(registerTemplateRoutes);
17
+ await fastify.ready();
18
+ });
19
+
20
+ afterEach(async () => {
21
+ await fastify.close(); // 每个文件重复 teardown 逻辑
22
+ });
23
+
24
+ it('should list templates', async () => {
25
+ const res = await fastify.inject({ method: 'GET', url: '/admin/templates' });
26
+ expect(res.statusCode).toBe(200);
27
+ });
28
+ });
29
+ ```
30
+
31
+ ```typescript
32
+ // test/admin/plans.test.ts — 同样重复,但细节不同
33
+ import Fastify from 'fastify';
34
+ import { registerPlanRoutes } from '../../admin/routes/plans';
35
+
36
+ describe('Plan Routes', () => {
37
+ let app: any;
38
+
39
+ beforeAll(async () => {
40
+ app = Fastify({ logger: false }); // 不一致的配置
41
+ await app.register(prismaPlugin, { datasource: {}, skipMigrate: true });
42
+ await app.register(registerPlanRoutes);
43
+ await app.listen({ port: 0 });
44
+ });
45
+
46
+ afterAll(async () => {
47
+ await app.server.close(); // 与 templates.test.ts teardown 方式不同
48
+ });
49
+ });
50
+ ```
51
+
52
+ ## ✅ 正确示例:共享 Helper
53
+
54
+ ```typescript
55
+ // test/helpers/create-admin-test-app.ts
56
+ import Fastify, { FastifyInstance } from 'fastify';
57
+ import { prisma } from '@prisma/client';
58
+ import { registerAllAdminRoutes } from '../../admin/routes';
59
+
60
+ export interface AdminTestApp {
61
+ fastify: FastifyInstance;
62
+ inject: FastifyInstance['inject'];
63
+ close: () => Promise<void>;
64
+ }
65
+
66
+ export async function createAdminTestApp(): Promise<AdminTestApp> {
67
+ const fastify = Fastify({
68
+ logger: false,
69
+ trustProxy: true,
70
+ });
71
+
72
+ // 注册 Prisma 插件
73
+ await fastify.register(async (instance) => {
74
+ instance.decorate('prisma', prisma);
75
+ });
76
+
77
+ // 注册所有 Admin 路由
78
+ await registerAllAdminRoutes(fastify);
79
+
80
+ await fastify.ready();
81
+
82
+ return {
83
+ fastify,
84
+ inject: fastify.inject.bind(fastify),
85
+ close: async () => {
86
+ await fastify.close();
87
+ },
88
+ };
89
+ }
90
+ ```
91
+
92
+ ```typescript
93
+ // test/admin/templates.test.ts
94
+ import { createAdminTestApp, AdminTestApp } from '../helpers/create-admin-test-app';
95
+
96
+ describe('Template Routes', () => {
97
+ let app: AdminTestApp;
98
+
99
+ beforeEach(async () => {
100
+ app = await createAdminTestApp();
101
+ });
102
+
103
+ afterEach(async () => {
104
+ await app.close();
105
+ });
106
+
107
+ it('should list templates', async () => {
108
+ const res = await app.inject({
109
+ method: 'GET',
110
+ url: '/admin/templates',
111
+ });
112
+ expect(res.statusCode).toBe(200);
113
+ const body = JSON.parse(res.body);
114
+ expect(Array.isArray(body.templates)).toBe(true);
115
+ });
116
+
117
+ it('should create a template', async () => {
118
+ const res = await app.inject({
119
+ method: 'POST',
120
+ url: '/admin/templates',
121
+ payload: {
122
+ name: 'New Template',
123
+ content: '<h1>Hello</h1>',
124
+ },
125
+ });
126
+ expect(res.statusCode).toBe(302);
127
+ expect(res.headers.location).toContain('/admin/templates');
128
+ });
129
+ });
130
+ ```
131
+
132
+ ```typescript
133
+ // test/admin/plans.test.ts — 使用同一个 helper,零重复
134
+ import { createAdminTestApp, AdminTestApp } from '../helpers/create-admin-test-app';
135
+
136
+ describe('Plan Routes', () => {
137
+ let app: AdminTestApp;
138
+
139
+ beforeEach(async () => {
140
+ app = await createAdminTestApp();
141
+ });
142
+
143
+ afterEach(async () => {
144
+ await app.close();
145
+ });
146
+
147
+ it('should list plans', async () => {
148
+ const res = await app.inject({
149
+ method: 'GET',
150
+ url: '/admin/plans',
151
+ });
152
+ expect(res.statusCode).toBe(200);
153
+ });
154
+ });
155
+ ```
@@ -0,0 +1,70 @@
1
+ # Rule 3: Nunjucks Parentheses — Examples
2
+
3
+ ## 优先级规则
4
+
5
+ ```
6
+ 表达式: A <= B | lower
7
+ 实际解析: A <= (B | lower) ← filter 先执行,比较的是 A 和 "lower" 后的 B
8
+ 预期语义: (A <= B) | lower ← 先比较,结果再经 filter
9
+ ```
10
+
11
+ ## ❌ 错误示例
12
+
13
+ ```nunjucks
14
+ {# admin/views/plans.njk — 反模式 #}
15
+
16
+ {# 比较在 filter 之后执行 → 逻辑错误 #}
17
+ {% if plan._interviews.length <= 15 | lower %}
18
+ <span class="badge badge-small">Small Plan</span>
19
+ {% endif %}
20
+
21
+ {# 实际等价于: plan._interviews.length <= "lower" → 始终 true #}
22
+
23
+ {# 条件渲染中的陷阱 #}
24
+ {% if plan.status == 'completed' | title %}
25
+ <span class="status-done">Done</span>
26
+ {% endif %}
27
+
28
+ {# 字符串格式化错误 #}
29
+ {{ plan.completionRate * 100 | round | default(0) }}
30
+ {# 当 completionRate 为 null 时,null * 100 = NaN → round(NaN) → 错误 #}
31
+ ```
32
+
33
+ ## ✅ 正确示例
34
+
35
+ ```nunjucks
36
+ {# admin/views/plans.njk #}
37
+
38
+ {# 括号确保比较先执行 #}
39
+ {% if (plan._interviews.length <= 15) | lower %}
40
+ <span class="badge badge-small">Small Plan</span>
41
+ {% endif %}
42
+
43
+ {# 条件判断中的正确使用 #}
44
+ {% if (plan.status == 'completed') | title %}
45
+ <span class="status-done">Done</span>
46
+ {% endif %}
47
+
48
+ {# 数值计算中先处理 null #}
49
+ {{ (plan.completionRate ?? 0) * 100 | round(1) | default('0.0') }}%
50
+
51
+ {# 多层比较与 filter 组合 #}
52
+ {% if (plan._interviews.length >= 15 and plan._interviews.length <= 60) | bool %}
53
+ <span class="badge badge-medium">Medium Plan</span>
54
+ {% elif (plan._interviews.length > 60) | bool %}
55
+ <span class="badge badge-large">Large Plan</span>
56
+ {% endif %}
57
+
58
+ {# 安全渲染可选字段 #}
59
+ {% if (plan.description | length) > 0 %}
60
+ <p class="description">{{ plan.description | truncate(120) }}</p>
61
+ {% else %}
62
+ <p class="description text-muted">No description provided.</p>
63
+ {% endif %}
64
+ ```
65
+
66
+ ## 验证清单
67
+
68
+ - [ ] 所有 `{{ A <= B | filter }}` 改为 `{{ (A <= B) | filter }}`
69
+ - [ ] 所有 `{% if A == B | filter %}` 改为 `{% if (A == B) | filter %}`
70
+ - [ ] 使用 `| bool` 而非裸布尔表达式配合逻辑运算符
@@ -0,0 +1,154 @@
1
+ # Rule 4: View Model Mapper — Examples
2
+
3
+ ## ❌ 错误示例:路由内联转换
4
+
5
+ ```typescript
6
+ // admin/routes/plans.ts — 反模式
7
+ fastify.get('/admin/plans', async (req, reply) => {
8
+ const plans = await prisma.plan.findMany({
9
+ include: { _count: { select: { interviews: true } } },
10
+ });
11
+
12
+ // 每个路由都在做同样的转换
13
+ const viewModels = plans.map((plan) => ({
14
+ id: plan.id,
15
+ name: plan.name,
16
+ status: plan.status,
17
+ interviewCount: plan._count?.interviews ?? 0,
18
+ completedCount: plan.interviews?.filter((i) => i.status === 'COMPLETED').length ?? 0,
19
+ completionRate: plan.interviews?.filter((i) => i.status === 'COMPLETED').length ?? 0
20
+ / (plan._count?.interviews ?? 1) * 100,
21
+ createdAt: plan.createdAt.toISOString().split('T')[0],
22
+ }));
23
+
24
+ return reply.view('admin/plans/list.njk', { plans: viewModels });
25
+ });
26
+ ```
27
+
28
+ ## ✅ 正确示例:提取 ViewModel 模块
29
+
30
+ ```typescript
31
+ // admin/view-models.ts
32
+ import { Plan, Interview, Template } from '@prisma/client';
33
+
34
+ export interface PlanViewModel {
35
+ id: string;
36
+ name: string;
37
+ status: string;
38
+ interviewCount: number;
39
+ completedCount: number;
40
+ completionRate: number;
41
+ createdAt: string;
42
+ }
43
+
44
+ export interface TemplateViewModel {
45
+ id: string;
46
+ name: string;
47
+ content: string;
48
+ interviewCount: number;
49
+ lastUsed: string | null;
50
+ }
51
+
52
+ /**
53
+ * 将 Prisma Plan 记录转换为视图模型
54
+ */
55
+ export function mapPlanToViewModel(
56
+ plan: Plan & { _count?: { interviews: number } },
57
+ interviews?: Interview[]
58
+ ): PlanViewModel {
59
+ const completedCount = interviews?.filter((i) => i.status === 'COMPLETED').length ?? 0;
60
+ const interviewCount = plan._count?.interviews ?? interviews?.length ?? 0;
61
+
62
+ return {
63
+ id: plan.id,
64
+ name: plan.name,
65
+ status: plan.status,
66
+ interviewCount,
67
+ completedCount,
68
+ completionRate: interviewCount > 0 ? (completedCount / interviewCount) * 100 : 0,
69
+ createdAt: plan.createdAt.toISOString().split('T')[0],
70
+ };
71
+ }
72
+
73
+ /**
74
+ * 批量转换 Plan 列表
75
+ */
76
+ export function mapPlansToViewModels(
77
+ plans: (Plan & { _count?: { interviews: number } })[],
78
+ interviewsMap?: Map<string, Interview[]>
79
+ ): PlanViewModel[] {
80
+ return plans.map((plan) =>
81
+ mapPlanToViewModel(plan, interviewsMap?.get(plan.id))
82
+ );
83
+ }
84
+
85
+ /**
86
+ * 将 Prisma Template 记录转换为视图模型
87
+ */
88
+ export function mapTemplateToViewModel(
89
+ template: Template & { _count?: { interviews: number }; interviews?: Interview[] }
90
+ ): TemplateViewModel {
91
+ const interviewCount = template._count?.interviews ?? template.interviews?.length ?? 0;
92
+ const lastUsed = template.interviews?.length
93
+ ? Math.max(...template.interviews.map((i) => i.createdAt.getTime()))
94
+ : null;
95
+
96
+ return {
97
+ id: template.id,
98
+ name: template.name,
99
+ content: template.content,
100
+ interviewCount,
101
+ lastUsed: lastUsed ? new Date(lastUsed).toISOString().split('T')[0] : null,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * 过滤出已完成的计划
107
+ */
108
+ export function filterCompletedPlans(plans: PlanViewModel[]): PlanViewModel[] {
109
+ return plans.filter((p) => p.status === 'COMPLETED');
110
+ }
111
+
112
+ /**
113
+ * 计算统计摘要
114
+ */
115
+ export function calculatePlanStats(plans: PlanViewModel[]) {
116
+ const total = plans.length;
117
+ const completed = plans.filter((p) => p.status === 'COMPLETED').length;
118
+ const inProgress = plans.filter((p) => p.status === 'IN_PROGRESS').length;
119
+ const avgCompletionRate =
120
+ total > 0 ? plans.reduce((sum, p) => sum + p.completionRate, 0) / total : 0;
121
+
122
+ return { total, completed, inProgress, avgCompletionRate: Math.round(avgCompletionRate) };
123
+ }
124
+ ```
125
+
126
+ ```typescript
127
+ // admin/routes/plans.ts — 使用 ViewModel
128
+ import { mapPlansToViewModels, filterCompletedPlans, calculatePlanStats } from '../view-models';
129
+
130
+ fastify.get('/admin/plans', async (req, reply) => {
131
+ const plans = await prisma.plan.findMany({
132
+ include: { _count: { select: { interviews: true } } },
133
+ });
134
+
135
+ const viewModels = mapPlansToViewModels(plans);
136
+
137
+ return reply.view('admin/plans/list.njk', {
138
+ plans: viewModels,
139
+ stats: calculatePlanStats(viewModels),
140
+ });
141
+ });
142
+
143
+ fastify.get('/admin/plans/completed', async (req, reply) => {
144
+ const plans = await prisma.plan.findMany({
145
+ where: { status: 'COMPLETED' },
146
+ include: { _count: { select: { interviews: true } } },
147
+ });
148
+
149
+ const viewModels = mapPlansToViewModels(plans);
150
+ const completed = filterCompletedPlans(viewModels);
151
+
152
+ return reply.view('admin/plans/completed.njk', { plans: completed });
153
+ });
154
+ ```
@@ -0,0 +1,126 @@
1
+ # Rule 5: Auth Protection — Examples
2
+
3
+ ## ❌ 错误示例:GET 路由未认证
4
+
5
+ ```typescript
6
+ // admin/routes/plans.ts — 反模式
7
+ import { FastifyInstance } from 'fastify';
8
+
9
+ export async function registerPlanRoutes(fastify: FastifyInstance) {
10
+ // GET 路由缺少认证 — 任何人都可查看所有计划
11
+ fastify.get('/admin/plans', async (req, reply) => {
12
+ const plans = await prisma.plan.findMany();
13
+ return reply.view('admin/plans/list.njk', { plans });
14
+ });
15
+
16
+ // 只有 POST 有认证
17
+ fastify.post('/admin/plans', { onRequest: [authenticateAdmin] }, async (req, reply) => {
18
+ // ...
19
+ });
20
+ }
21
+ ```
22
+
23
+ ```typescript
24
+ // admin/routes/analytics.ts — 使用不安全的 API Key
25
+ import { FastifyInstance } from 'fastify';
26
+
27
+ export async function registerAnalyticsRoutes(fastify: FastifyInstance) {
28
+ fastify.get('/admin/analytics', {
29
+ onRequest: [
30
+ // 通过 Header 传递 API Key — 易泄露、不安全
31
+ async (req: FastifyRequest, reply: FastifyReply) => {
32
+ const apiKey = req.headers['x-api-key'];
33
+ if (apiKey !== process.env.ADMIN_API_KEY) {
34
+ return reply.code(401).send({ error: 'Unauthorized' });
35
+ }
36
+ },
37
+ ],
38
+ }, async (req, reply) => {
39
+ // ...
40
+ });
41
+ }
42
+ ```
43
+
44
+ ## ✅ 正确示例:所有路由统一认证
45
+
46
+ ```typescript
47
+ // admin/middleware/authenticate-admin.ts
48
+ import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify';
49
+
50
+ export async function authenticateAdmin(
51
+ req: FastifyRequest,
52
+ reply: FastifyReply,
53
+ done: HookHandlerDoneFunction
54
+ ) {
55
+ const session = req.session;
56
+
57
+ if (!session?.userId) {
58
+ return reply
59
+ .code(302)
60
+ .header('Location', '/login?redirect=' + encodeURIComponent(req.url))
61
+ .send();
62
+ }
63
+
64
+ // 验证用户具有 Admin 角色
65
+ const user = await prisma.user.findUnique({
66
+ where: { id: session.userId },
67
+ select: { role: true },
68
+ });
69
+
70
+ if (user?.role !== 'ADMIN') {
71
+ return reply.code(403).view('admin/errors/forbidden.njk', {
72
+ message: 'You do not have permission to access the admin panel.',
73
+ });
74
+ }
75
+
76
+ // 将用户信息附加到请求
77
+ req.user = user;
78
+ done();
79
+ }
80
+ ```
81
+
82
+ ```typescript
83
+ // admin/routes/admin-shared.ts — 全局注册认证中间件
84
+ import { FastifyInstance } from 'fastify';
85
+ import { authenticateAdmin } from '../middleware/authenticate-admin';
86
+
87
+ export function registerAdminShared(fastify: FastifyInstance) {
88
+ // 为所有 /admin/* 路由注册认证 hook
89
+ fastify.addHook('onRequest', authenticateAdmin);
90
+ }
91
+ ```
92
+
93
+ ```typescript
94
+ // admin/routes/plans.ts — 继承全局认证
95
+ import { FastifyInstance } from 'fastify';
96
+
97
+ export async function registerPlanRoutes(fastify: FastifyInstance) {
98
+ // 所有路由自动继承 authenticateAdmin
99
+ // 无需在每个 route 上重复声明
100
+ fastify.get('/admin/plans', async (req, reply) => {
101
+ const plans = await prisma.plan.findMany();
102
+ return reply.view('admin/plans/list.njk', { plans });
103
+ });
104
+
105
+ fastify.post('/admin/plans', async (req, reply) => {
106
+ await prisma.plan.create({ data: req.body as any });
107
+ return reply.redirect('/admin/plans');
108
+ });
109
+ }
110
+ ```
111
+
112
+ ```typescript
113
+ // admin/routes/analytics.ts — 同样保护
114
+ import { FastifyInstance } from 'fastify';
115
+
116
+ export async function registerAnalyticsRoutes(fastify: FastifyInstance) {
117
+ // GET 路由同样受认证保护
118
+ fastify.get('/admin/analytics', async (req, reply) => {
119
+ const stats = await prisma.plan.aggregate({
120
+ _count: { id: true },
121
+ _avg: { completionRate: true },
122
+ });
123
+ return reply.view('admin/analytics/dashboard.njk', { stats });
124
+ });
125
+ }
126
+ ```
@@ -0,0 +1,180 @@
1
+ # Rule 6: HTMX + Alpine Separation — Examples
2
+
3
+ ## ❌ 错误示例:HTMX 与 Alpine 混用
4
+
5
+ ```nunjucks
6
+ {# admin/views/plans.njk — 反模式 #}
7
+
8
+ {# 使用 Alpine 做服务端请求 — 职责错误 #}
9
+ <div x-data="{ plans: [], loading: false }"
10
+ x-init="loading = true; fetch('/admin/api/plans').then(r => r.json()).then(d => plans = d); loading = false">
11
+ <template x-for="plan in plans" :key="plan.id">
12
+ <div>
13
+ <span x-text="plan.name"></span>
14
+ {# 删除操作使用 Alpine 而非 HTMX — 失去服务端渲染优势 #}
15
+ <button @click="fetch('/admin/plans/' + plan.id, { method: 'DELETE' })
16
+ .then(() => plans = plans.filter(p => p.id !== plan.id))">
17
+ Delete
18
+ </button>
19
+ </div>
20
+ </template>
21
+ </div>
22
+
23
+ {# HTMX 驱动下拉菜单状态 — 职责错误 #}
24
+ <div hx-get="/admin/plans" hx-swap="innerHTML">
25
+ <button hx-on::after-request="this.nextElementSibling.style.display = 'block'">
26
+ Show Filters
27
+ </button>
28
+ <div style="display: none">
29
+ <input type="text" name="search" placeholder="Search..."
30
+ hx-get="/admin/plans" hx-trigger="keyup changed delay:300ms" />
31
+ </div>
32
+ </div>
33
+ ```
34
+
35
+ ## ✅ 正确示例:职责分离
36
+
37
+ ```nunjucks
38
+ {# admin/views/plans.njk #}
39
+
40
+ {# 整体布局与内容列表由 HTMX 驱动 #}
41
+ <div id="plans-content" hx-boost="true">
42
+ <div class="header-bar" x-data="{ showFilters: false }">
43
+ <h1>Interview Plans</h1>
44
+
45
+ {# 下拉菜单状态由 Alpine 管理 #}
46
+ <button type="button" @click="showFilters = !showFilters"
47
+ :class="{ 'active': showFilters }">
48
+ Filters
49
+ </button>
50
+
51
+ {# Alpine 控制本地显示/隐藏 #}
52
+ <div x-show="showFilters" x-transition class="filter-panel">
53
+ {# 搜索输入通过 HTMX 触发服务端请求 #}
54
+ <input type="text" name="search" placeholder="Search plans..."
55
+ hx-get="/admin/plans"
56
+ hx-target="#plans-list"
57
+ hx-trigger="keyup changed delay:300ms"
58
+ hx-indicator=".search-spinner" />
59
+ </div>
60
+ </div>
61
+
62
+ {# 列表内容完全由 HTMX 服务端渲染 #}
63
+ <div id="plans-list">
64
+ {% for plan in plans %}
65
+ <div class="plan-card" id="plan-{{ plan.id }}">
66
+ <h3>{{ plan.name }}</h3>
67
+ <p>Status: {{ plan.status | upper }}</p>
68
+ <p>Completion: {{ plan.completionRate | round(1) }}%</p>
69
+
70
+ <div class="actions">
71
+ {# 删除操作通过 HTMX 提交,服务端响应更新 DOM #}
72
+ <button class="btn-danger"
73
+ hx-delete="/admin/plans/{{ plan.id }}"
74
+ hx-target="#plan-{{ plan.id }}"
75
+ hx-swap="outerHTML"
76
+ hx-confirm="Are you sure you want to delete this plan?"
77
+ x-data="{ deleting: false }"
78
+ hx-on::before-request="deleting = true"
79
+ hx-on::after-request="deleting = false">
80
+ <span x-show="!deleting">Delete</span>
81
+ <span x-show="deleting" class="spinner">Deleting...</span>
82
+ </button>
83
+ </div>
84
+ </div>
85
+ {% endfor %}
86
+ </div>
87
+ </div>
88
+ ```
89
+
90
+ ```nunjucks
91
+ {# admin/views/modals/confirm-delete.njk — Modal 由 Alpine 管理 #}
92
+
93
+ <div x-data="{ open: false, targetId: null, targetName: '' }"
94
+ @open-modal.window="open = true; targetId = $event.detail.id; targetName = $event.detail.name"
95
+ x-show="open"
96
+ x-cloak
97
+ class="modal-backdrop"
98
+ @click.self="open = false">
99
+
100
+ <div class="modal-content" x-transition>
101
+ <h2>Confirm Delete</h2>
102
+ <p>Are you sure you want to delete "<span x-text="targetName"></span>"?</p>
103
+
104
+ <div class="modal-actions">
105
+ <button @click="open = false">Cancel</button>
106
+
107
+ {# 真正的删除操作通过 HTMX 提交 #}
108
+ <button class="btn-danger"
109
+ hx-delete="/admin/plans/"
110
+ hx-vals='js:{ id: targetId }'
111
+ hx-target="#plans-list"
112
+ @click="open = false">
113
+ Confirm Delete
114
+ </button>
115
+ </div>
116
+ </div>
117
+ </div>
118
+ ```
119
+
120
+ ```nunjucks
121
+ {# admin/views/templates/edit.njk — 表单字段本地验证由 Alpine 管理 #}
122
+
123
+ <form x-data="{
124
+ name: '',
125
+ nameError: '',
126
+ content: '',
127
+ contentError: '',
128
+ get isValid() {
129
+ return this.name.length > 0 && this.content.length > 0 && !this.nameError && !this.contentError;
130
+ },
131
+ validateName(value) {
132
+ this.name = value;
133
+ this.nameError = value.length < 3 ? 'Name must be at least 3 characters.' : '';
134
+ },
135
+ validateContent(value) {
136
+ this.content = value;
137
+ this.contentError = value.trim().length === 0 ? 'Content cannot be empty.' : '';
138
+ }
139
+ }" hx-post="/admin/templates/{{ template.id }}"
140
+ hx-target="#form-result"
141
+ hx-swap="innerHTML"
142
+ hx-on::before-request="if (!isValid) { $event.preventDefault(); }">
143
+
144
+ <div class="form-group">
145
+ <label for="name">Template Name</label>
146
+ <input type="text" id="name" name="name"
147
+ x-model="name"
148
+ @input="validateName(name)"
149
+ :class="{ 'error': nameError }"
150
+ value="{{ template.name }}" />
151
+ <span x-show="nameError" x-text="nameError" class="field-error"></span>
152
+ </div>
153
+
154
+ <div class="form-group">
155
+ <label for="content">Template Content</label>
156
+ <textarea id="content" name="content" rows="20"
157
+ x-model="content"
158
+ @input="validateContent(content)"
159
+ :class="{ 'error': contentError }">{{ template.content }}</textarea>
160
+ <span x-show="contentError" x-text="contentError" class="field-error"></span>
161
+ </div>
162
+
163
+ <div class="form-actions">
164
+ <button type="submit" :disabled="!isValid" class="btn-primary">
165
+ Save Template
166
+ </button>
167
+ <a href="/admin/templates" class="btn-secondary">Cancel</a>
168
+ </div>
169
+ </form>
170
+
171
+ {# HTMX 响应结果区域 #}
172
+ <div id="form-result"></div>
173
+ ```
174
+
175
+ ## 分离原则
176
+
177
+ 1. **HTMX 是服务端与 DOM 之间的桥梁** — 所有数据变更、页面导航、内容更新必须通过 HTMX
178
+ 2. **Alpine 是组件状态的管理者** — 只管理不需要服务端参与的 UI 状态(开关、显隐、验证)
179
+ 3. **HTMX 属性不应操作 DOM 状态** — `hx-on::after-request` 里不应出现 `element.style.display`
180
+ 4. **Alpine 方法不应发起 fetch** — `@click="fetch('/api/...')"` 是反模式,应用 `hx-get/hx-post`
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: batch-grill-me
3
+ description: A relentless interview that asks every frontier question at once, round by round.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it.
8
+
9
+ Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled — the questions you can ask *now* without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round.
10
+
11
+ Each round the user answers reshapes the tree — settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a *later* round, not this one.
12
+
13
+ Finding *facts* is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it — don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report — ask the rest of the frontier now. The *decisions* are the user's — put each to them and wait.
14
+
15
+ The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding.