-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsetup_ai_harness.sh
More file actions
executable file
·2243 lines (1843 loc) · 86.6 KB
/
Copy pathsetup_ai_harness.sh
File metadata and controls
executable file
·2243 lines (1843 loc) · 86.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# ============================================================================
# setup_ai_harness.sh — C++ (CMake) 项目 AI 编程 Harness 一键初始化
#
# 用法:在项目根目录执行
# bash setup_ai_harness.sh
# bash setup_ai_harness.sh --force # 备份并覆盖已生成文件
#
# 生成文件:
# CLAUDE.md — Claude Code 项目级 Harness 配置
# AGENTS.md — GPT/Codex 项目级 Harness 配置
# .claude/settings.json — Claude Code 权限 + Hooks
# .claude/skills/full-code-review/SKILL.md — Claude Code 全项目代码 Review Skill
# .codex/skills/full-code-review/ — Codex 全项目代码 Review Skill
# docs/ai/*.md — 按需读取的细节规则
# .cursorrules — Cursor 项目配置
# .vscode/settings.json — VS Code + Copilot 配置
# .vscode/extensions.json — VS Code 推荐扩展
# .clang-format — 代码格式化配置(被 Hook 引用)
# claude-progress.txt — 长任务接力状态
# session-state.md — 当前接力轮次状态
# spec.md — Planner 产出的规格说明
# evaluation.md — Evaluator 产出的验收报告
# debt-register.md — 技术债登记表
# todo.md — 长任务 TODO
# verification.md — 验证记录
# ai_snapshot.json — 新会话机器可读恢复快照
# defect-rca.md — 缺陷根因分析和规约沉淀记录
# init.sh — 环境恢复入口
# prompts/init.md — 第一轮初始化 Prompt
# prompts/resume.md — 后续接力 Prompt
# prompts/handoff.md — 上下文重启交接 Prompt
# prompts/planner.md — 规划者 Prompt
# prompts/generator.md — 生成者 Prompt
# prompts/evaluator.md — 验收者 Prompt
# prompts/full-code-review.md — 全项目代码 Review Prompt
# prompts/rca.md — 缺陷 RCA 和规约自愈 Prompt
# prompts/task.md — Task 沙盒执行 Prompt
# prompts/debt-scan.md — 技术债扫描 Prompt
# prompts/debt-fix.md — 小步偿还技术债 Prompt
# scripts/context_reset_check.sh — 接力自检脚本
# scripts/snapshot_update.sh — 更新 ai_snapshot.json
# scripts/resume_from_snapshot.sh — 从快照恢复上下文
# scripts/quick_brief_check.sh — Quick Brief 覆盖检查
# scripts/task_new.sh — 创建 Task 沙盒
# scripts/rca_new.sh — 创建缺陷 RCA 模板
# scripts/ai_debt_scan.sh — 本地技术债启发式扫描
# .gitignore (追加) — 忽略构建产物和敏感文件
#
# 特性:幂等(已存在的文件不覆盖)、纯 bash、无额外依赖
# ============================================================================
set -euo pipefail
FORCE=0
BACKUP_SUFFIX="$(date +%Y%m%d%H%M%S)"
usage() {
cat <<'EOF'
用法:
bash setup_ai_harness.sh [--force]
选项:
--force 备份并覆盖已存在的 harness 文件
-h,--help 显示帮助
默认行为:已存在文件会跳过,避免覆盖人工修改。
EOF
}
for arg in "$@"; do
case "$arg" in
--force)
FORCE=1
;;
-h|--help)
usage
exit 0
;;
*)
echo "[ERR] 未知参数: $arg" >&2
usage
exit 1
;;
esac
done
# --- 颜色 ---
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'
info() { echo -e "${BLUE}[INFO]${NC} $*"; }
ok() { echo -e "${GREEN}[OK]${NC} $*"; }
skip() { echo -e "${YELLOW}[SKIP]${NC} $* (已存在)"; }
err() { echo -e "${RED}[ERR]${NC} $*"; }
# --- 安全写入:文件已存在则跳过 ---
safe_write() {
local filepath="$1"
local content="$2"
local dir
dir=$(dirname "$filepath")
[ -d "$dir" ] || mkdir -p "$dir"
if [ -f "$filepath" ]; then
if [ "$FORCE" -eq 1 ]; then
cp "$filepath" "${filepath}.bak.${BACKUP_SUFFIX}"
printf '%s\n' "$content" > "$filepath"
ok "$filepath (已覆盖,备份: ${filepath}.bak.${BACKUP_SUFFIX})"
return 0
fi
skip "$filepath"
return 0
fi
printf '%s\n' "$content" > "$filepath"
ok "$filepath"
return 0
}
# --- .gitignore 追加(去重) ---
append_gitignore() {
local pattern="$1"
if [ -f .gitignore ] && grep -qxF "$pattern" .gitignore 2>/dev/null; then
return
fi
echo "$pattern" >> .gitignore
}
# ============================================================================
# 交互式输入
# ============================================================================
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ C++ 项目 AI Harness 一键初始化 ║${NC}"
echo -e "${GREEN}║ 配置 Claude Code / GPT-Codex / Cursor / Copilot ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""
# 项目名称
default_name=$(basename "$(pwd)")
read -rp "项目名称 [${default_name}]: " PROJECT_NAME
PROJECT_NAME="${PROJECT_NAME:-$default_name}"
# C++ 标准
echo ""
echo "选择 C++ 标准:"
echo " 1) C++17"
echo " 2) C++20"
echo " 3) C++23"
read -rp "请选择 [1]: " cpp_choice
case "${cpp_choice:-1}" in
1) CPP_STD="17" ;;
2) CPP_STD="20" ;;
3) CPP_STD="23" ;;
*) CPP_STD="17" ;;
esac
# 测试框架
echo ""
echo "选择测试框架:"
echo " 1) Google Test (GTest)"
echo " 2) Catch2"
echo " 3) 暂不配置"
read -rp "请选择 [1]: " test_choice
case "${test_choice:-1}" in
1) TEST_FW="gtest" ; TEST_FW_NAME="Google Test" ;;
2) TEST_FW="catch2" ; TEST_FW_NAME="Catch2" ;;
3) TEST_FW="none" ; TEST_FW_NAME="未配置" ;;
*) TEST_FW="gtest" ; TEST_FW_NAME="Google Test" ;;
esac
echo ""
info "项目: ${PROJECT_NAME} | C++${CPP_STD} | 测试: ${TEST_FW_NAME}"
echo "-----------------------------------------------------------"
echo ""
# ============================================================================
# 1. CLAUDE.md — 项目级 Harness 配置(控制在 ~100 行)
# ============================================================================
# 根据测试框架生成测试命令
if [ "$TEST_FW" = "none" ]; then
TEST_COMMANDS="- 测试框架未配置;添加测试后运行 \`cd build && ctest --output-on-failure\`"
TEST_RULE="- 测试框架待定,添加后请更新此文件"
else
TEST_COMMANDS="- \`cd build && ctest --output-on-failure\` — 运行测试
- \`cd build && ctest -R <name> --output-on-failure\` — 运行指定测试"
if [ "$TEST_FW" = "gtest" ]; then
TEST_RULE="- 使用 Google Test,测试文件命名 *_test.cpp
- 每个 TEST/TEST_F 只测一个行为,名字用 MethodName_Scenario_Expected"
else
TEST_RULE="- 使用 Catch2,测试文件命名 *_test.cpp
- TEST_CASE 名用自然语言描述行为,SECTION 分正常/异常"
fi
fi
# 根据 C++ 标准生成错误处理建议,避免在 C++17/20 中误用 std::expected。
if [ "$CPP_STD" = "23" ]; then
ERROR_RULE="- 错误处理:库代码可使用 std::expected 或异常,应用代码用错误码/异常按场景选择"
SRC_RECOVERABLE_RULE="- 运行时可恢复错误:优先返回 std::optional 或 std::expected"
else
ERROR_RULE="- 错误处理:库代码用异常或 std::optional;不要使用 std::expected,除非项目显式引入兼容实现"
SRC_RECOVERABLE_RULE="- 运行时可恢复错误:返回 std::optional,或在引入兼容库后使用 expected 类型"
fi
FULL_CODE_REVIEW_PROMPT='# Full Code Review Prompt
你正在做项目开发完成后的全仓库代码 review。目标是深入阅读一方代码,找真实 bug、风险和有效优化点;不要把输出变成重复的补测试清单。
## Operating Rules
- Review the whole first-party project, not only the latest diff, unless the user explicitly narrows scope.
- Do not ask the user to approve each review slice. Build a repo map, inspect systematically, and continue until the full pass is complete or a hard blocker prevents progress.
- Do not edit code during the review unless the user explicitly asks for fixes. The output is findings and recommendations.
- Respect dirty worktrees. Treat existing local changes as user work; do not revert or overwrite them.
- Use source evidence. A finding should cite file and line references whenever possible and explain the failure mode.
- Avoid generic test advice. Mention tests only when tied to a concrete defect/regression path, or once in a short residual-risk note.
- If the repository is too large to inspect every generated or vendored file, explicitly exclude generated/vendor/build artifacts and list any first-party areas that could not be reviewed.
## Review Workflow
1. Establish the repo root and state.
- Run `git rev-parse --show-toplevel` when available.
- Run `git status --short` to notice user changes.
- Build the inventory with `git ls-files`; fall back to `rg --files`.
2. Create a project map before judging code.
- Read `README`, package manifests, dependency files, build configs, framework configs, CI/deploy files, environment examples, schema/migration files, and main entry points.
- If `.zread/wiki/current` exists, read the relevant generated pages for orientation, but verify important claims against source.
- Classify files into app source, API/backend, frontend/UI, data/schema, scripts/jobs, infrastructure/config, tests, docs, generated/vendor/build artifacts.
3. Inspect all first-party implementation areas systematically.
- Walk directory by directory rather than sampling only suspicious files.
- Trace important user flows end to end: input validation, auth/permission checks, persistence, background jobs, external calls, error handling, retries, cancellation, and UI state transitions.
- Check shared contracts: API schemas, database models, environment variables, serialization formats, route names, feature flags, and build/runtime assumptions.
- Use targeted searches to find risk patterns: `TODO`, `FIXME`, `HACK`, `XXX`, `debugger`, `console.log`, broad catches, ignored lint/type errors, unsafe casts, unchecked `any`, raw SQL, shell execution, eval-like behavior, secrets, auth bypasses, hard-coded URLs, and duplicated business rules.
4. Run low-risk verification commands when discoverable.
- Prefer existing scripts from package manifests, Makefiles, task runners, or CI configs.
- Run static checks, type checks, linters, builds, or focused smoke commands when practical.
- Do not make test coverage the center of the review. Use command results to support or disprove concrete concerns.
5. Triage findings.
- Lead with high-confidence issues that can cause wrong behavior, data loss, security exposure, production failures, or broken user workflows.
- Include optimization opportunities only when they are meaningful: clear performance wins, simpler architecture, reduced duplication, less fragile state handling, or easier operational debugging.
- Do not report style preferences as findings unless they create real maintenance risk.
## Output Format
Start with findings, ordered by severity. Use this structure:
```text
Findings
- High/Medium/Low: <short title> - <file:line>
Impact: <what can go wrong>
Evidence: <why the code behaves that way>
Recommendation: <specific fix direction>
```
Then include:
- `Optimization Opportunities`: only concrete, worthwhile improvements.
- `Coverage`: directories or subsystems reviewed, commands run, and any exclusions.
- `Residual Risk`: short note for areas that could not be verified. Mention test gaps here only once, and only if relevant.
If no high-confidence problems are found, say so clearly and still include coverage and residual risk.'
safe_write "CLAUDE.md" "# ${PROJECT_NAME} — AI Harness Index
本文件是短索引,不是规则大全。先读这里,再按任务需要读取 docs/ai/ 下的细节文件。
## Project Facts
- 语言:C++${CPP_STD}
- 构建:CMake 3.20+
- 编译器:GCC 12+ / Clang 15+ 均需兼容
- 测试:${TEST_FW_NAME}
- 格式化:clang-format,由 Claude hook 或编辑器触发
## Project Structure
- 保持现有项目结构,不为了 harness 新建业务目录
- build/:构建产物,禁止手动编辑
- docs/ai/:按需读取的详细 AI 规则
- AGENTS.md:GPT/Codex 项目入口,和本文件共享同一套规则源
## State Files
- ai_snapshot.json:机器可读恢复快照,优先用于新会话秒级恢复
- claude-progress.txt:当前任务状态、下一步、风险
- session-state.md:当前接力轮次、上下文健康和交接摘要
- spec.md:Planner 产出的规格、验收标准和非目标
- evaluation.md:Evaluator 产出的真实验收证据
- todo.md:可接力的剩余任务
- verification.md:已跑和未跑的验证
- debt-register.md:技术债、偏离原则和偿还记录
- defect-rca.md:缺陷 RCA、复盘结论和新规约沉淀
- init.sh:新会话恢复环境和查看状态
## Read Only What You Need
- Claude Code 读 CLAUDE.md;GPT/Codex 读 AGENTS.md;细节统一从 docs/ai/ 读取
- 新会话或接力时先读 ai_snapshot.json,再按快照声明的 must_read 文件恢复
- 阅读长文档时先看文件头部 Quick Brief;需要细节时再读正文
- 做架构、抽象或重构判断前读 docs/ai/golden-principles.md
- 改 C++ 代码前读 docs/ai/cpp.md;如目标目录已有局部 CLAUDE.md/AGENTS.md,也一并读取
- 改测试前读 docs/ai/testing.md;如测试目录已有局部 CLAUDE.md/AGENTS.md,也一并读取
- 改构建、命令或依赖前读 docs/ai/build.md
- 做规划、实现或验收前读 docs/ai/evaluation.md
- 长任务、新会话接力或上下文变长时读 docs/ai/workflow.md
- 拆分复杂任务前读 docs/ai/task-sandbox.md
- 修复缺陷或重复失败后读 docs/ai/rca.md,并更新 docs/ai/check-rules.md
- 项目完成后的全代码 Review:Claude Code 使用项目 Skill \`/full-code-review\` 或读取 prompts/full-code-review.md
- 为长文件补充摘要前读 docs/ai/quick-brief.md
- 做技术债巡检或修复前读 debt-register.md 和 prompts/debt-*.md
## Default Commands
- 配置:\`cmake -B build -DCMAKE_BUILD_TYPE=Debug\`
- 编译:\`cmake --build build -j\$(nproc)\`
${TEST_COMMANDS}
## Reuse Before New Code
- 开发前先用 \`rg\`、目录浏览和已有测试查找同类实现、公共 helper、工具脚本、CMake target 和 fixture
- 优先复用、扩展或轻量抽取现有逻辑;只有现有逻辑不满足 spec 且复用会扩大风险时,才新增实现
- 新增公共 helper 后必须登记到本文件 Shared Utilities 或对应 docs/ai/,避免下一轮重复造轮子
## Non-Negotiables
- 不要手动编辑 build/ 目录
- 不要在代码中硬编码文件路径、IP、端口
- 不要引入新第三方依赖,除非先说明理由并获得确认
- 优先选择成熟、无聊、仓库已使用的技术;不要为炫技引入新栈
- 不要重复造轮子:先查找已有逻辑、共享工具和测试辅助,能复用就复用
- 不要把未运行的验证说成已通过
- 生产和验收必须分离;Generator 不给自己的实现打最终分
- 不要 git push --force 到 main 分支
## Role Split
- Planner:把模糊需求写成 spec.md,不改业务代码
- Generator:按 spec.md 实现,不写最终验收结论
- Evaluator:像 QA 一样运行真实命令,把证据写入 evaluation.md
## Long-Running Work
- 每轮开始先读 ai_snapshot.json、claude-progress.txt、todo.md、verification.md
- 按 spec.md、todo.md 或当前 Task 的有序开发队列连续推进;完成一项并验证后,自动领取下一项
- 每个子项仍保持小而可验证,完成后及时记录验证和状态,避免攒到最后回忆
- 长任务优先拆入 tasks/TASK-*/,每个 Task 独立维护 task.md、ai_snapshot.json、verification.md、defect-rca.md
- 只有遇到阻塞、验收失败、需求不清、范围扩大、上下文变浑浊或需要人类决策时,才使用 prompts/handoff.md
- 结束前运行 scripts/snapshot_update.sh 更新 ai_snapshot.json,保证下一轮可直接恢复
## Shared Utilities
> 新增公共工具函数后在这里登记名称和位置,避免重复实现。"
safe_write "AGENTS.md" "# ${PROJECT_NAME} — GPT/Codex Harness Index
本文件是 GPT/Codex 的短索引。不要把细节规则堆在这里;需要细节时按任务读取 docs/ai/。
## Project Facts
- 语言:C++${CPP_STD}
- 构建:CMake 3.20+
- 编译器:GCC 12+ / Clang 15+ 均需兼容
- 测试:${TEST_FW_NAME}
- Claude Code 入口:CLAUDE.md
- GPT/Codex 入口:AGENTS.md
## State Files
- ai_snapshot.json:机器可读恢复快照,优先用于新会话秒级恢复
- claude-progress.txt:当前任务状态、下一步、风险
- session-state.md:当前接力轮次、上下文健康和交接摘要
- spec.md:Planner 产出的规格、验收标准和非目标
- evaluation.md:Evaluator 产出的真实验收证据
- todo.md:可接力的剩余任务
- verification.md:已跑和未跑的验证
- debt-register.md:技术债、偏离原则和偿还记录
- defect-rca.md:缺陷 RCA、复盘结论和新规约沉淀
## Read Only What You Need
- 新会话或接力:ai_snapshot.json,然后按快照声明的 must_read 文件恢复
- 工具/账号/模型配置说明:docs/ai/tooling.md
- 项目完成后的全代码 Review:Codex 使用 Skill \`\$full-code-review\`;Claude 使用项目 Skill \`/full-code-review\` 或 prompts/full-code-review.md
- 架构、抽象或重构判断:docs/ai/golden-principles.md
- C++ 代码:docs/ai/cpp.md
- 测试:docs/ai/testing.md
- 构建、命令或依赖:docs/ai/build.md
- 规划、实现或验收:docs/ai/evaluation.md
- 长任务、新会话接力或上下文变长:docs/ai/workflow.md
- 复杂需求拆分:docs/ai/task-sandbox.md
- 缺陷复盘和规约自愈:docs/ai/rca.md、docs/ai/check-rules.md
- 长文档摘要和分层阅读:docs/ai/quick-brief.md
## Default Commands
- 配置:\`cmake -B build -DCMAKE_BUILD_TYPE=Debug\`
- 编译:\`cmake --build build -j\$(nproc)\`
${TEST_COMMANDS}
## Reuse Before New Code
- 开发前先用 \`rg\`、目录浏览和已有测试查找同类实现、公共 helper、工具脚本、CMake target 和 fixture
- 优先复用、扩展或轻量抽取现有逻辑;只有现有逻辑不满足 spec 且复用会扩大风险时,才新增实现
- 新增公共 helper 后必须登记到相关 docs/ai/ 或共享工具清单,避免后续 GPT/Codex 轮次重复实现
## Non-Negotiables
- 不要手动编辑 build/ 目录
- 不要把 API key、token 或本机认证文件写进仓库
- 不要引入新第三方依赖,除非先说明理由并获得确认
- 不要重复造轮子:先查找已有逻辑、共享工具和测试辅助,能复用就复用
- 不要把未运行的验证说成已通过
- Generator 不给自己的实现写最终通过结论
- 不要 git push --force 到 main 分支
## Role Split
- Planner:把模糊需求写成 spec.md,不改业务代码
- Generator:按 spec.md 实现,不写最终验收结论
- Evaluator:像 QA 一样运行真实命令,把证据写入 evaluation.md
## Long-Running Work
- 每轮开始先运行 scripts/resume_from_snapshot.sh 或 scripts/context_reset_check.sh
- 按 spec.md、todo.md 或当前 Task 的有序开发队列连续推进;完成一项并验证后,自动领取下一项
- 每个子项仍保持小而可验证,完成后及时记录验证和状态,避免攒到最后回忆
- 长任务优先拆入 tasks/TASK-*/,每个 Task 独立维护 task.md、ai_snapshot.json、verification.md、defect-rca.md
- 只有遇到阻塞、验收失败、需求不清、范围扩大、上下文变浑浊或需要人类决策时,才使用 prompts/handoff.md
- 结束前运行 scripts/snapshot_update.sh 更新 ai_snapshot.json,保证下一轮可直接恢复
## Shared Utilities
> 新增公共工具函数后在这里登记名称和位置,避免重复实现。
"
safe_write "docs/ai/cpp.md" "# C++ Rules
## Hard Rules
- 优先使用智能指针和对象所有权表达,裸 new/delete 必须说明理由。
- 所有资源通过 RAII 管理,禁止手动 open/close、lock/unlock 配对散落在业务逻辑中。
- 新增功能前先搜索已有模块、公共 helper、测试 fixture 和标准库能力,优先复用,不要为局部需求反复手写 helper。
- 不修改的参数用 const&,不修改成员的方法标记 const。
- 零容忍未定义行为:不越界访问、不解引用空指针、不使用悬挂引用。
- 头文件统一使用 #pragma once。
- 单参数构造函数标记 explicit。
- 有虚函数的基类必须声明 virtual ~ClassName() = default。
## Style
- 函数建议不超过 40 行,超过时优先拆分清晰的私有函数。
- 优先用标准库算法和容器,不为简单遍历引入复杂抽象。
- 命名:类型 PascalCase,函数/变量 snake_case,常量 kPascalCase,宏 UPPER_CASE。
- include 顺序:对应头文件、项目头文件、第三方、标准库。
## Error Handling
${ERROR_RULE}
- 构造函数中的错误:抛异常,保证对象不会半初始化。
${SRC_RECOVERABLE_RULE}
- 不可恢复错误:抛 std::runtime_error 派生异常。
## Concurrency
- 共享可变状态必须用 mutex 保护,并注释锁保护的状态范围。
- 优先使用 std::lock_guard 或 std::scoped_lock。
"
safe_write "docs/ai/golden-principles.md" "# Golden Principles
这些原则用于防止 Agent 复制坏模式。发现代码与原则冲突时,先登记到 debt-register.md;能在小范围内安全修复时,再用 prompts/debt-fix.md 处理。
## Prefer Boring Technology
- 优先使用仓库已有技术、标准库、CMake 和成熟工具链。
- 不为小问题引入新框架、新构建系统或新代码生成器。
- 新依赖必须说明用途、替代方案、维护成本、许可证和构建影响。
## Reuse Before Creating
- 优先使用共享工具包、已有模块和标准库能力。
- 实现前至少检查同目录、src/include/tests、已有脚本、CMake target 和测试辅助中是否已有相似逻辑。
- 优先调用、扩展、参数化或轻量抽取现有逻辑;不要平行新增相同职责的类、函数或脚本。
- 新 helper 只能在已有能力不适用时添加,并应放在清晰可复用的位置。
- 新增实现时,在变更摘要中说明为什么不能复用已有逻辑。
- 发现重复 helper 时,登记技术债;修复时一次只合并一小类重复。
## Validate Boundaries
- 不要猜数据格式、文件布局、协议字段或外部输入范围。
- 能用类型、解析器、schema、SDK 或边界检查表达约束时,不要靠字符串拼接和隐式假设。
- 错误路径必须可观测:返回错误、抛异常或记录上下文,不要静默吞掉。
## Keep Changes Small
- 一次 PR 只偿还一个明确债务点。
- 不把风格重排、重命名和行为修复混在一起。
- 未跑验证必须写入 verification.md,不得声称完成。
## Improve The Pattern
- 如果仓库里已有坏模式,不要继续模仿;先在 debt-register.md 记录。
- 修改局部代码时,顺手让附近代码向黄金原则靠近,但不要扩大到无关模块。
"
safe_write "docs/ai/testing.md" "# Testing Rules
## Framework
- 当前选择:${TEST_FW_NAME}
## Commands
${TEST_COMMANDS}
## Rules
${TEST_RULE}
- 覆盖正常路径、边界条件、异常/错误路径。
- 每个测试只验证一个行为。
- 测试之间必须独立,不依赖执行顺序。
- 不要在测试中使用 sleep;用条件变量、虚拟时钟或可控同步点。
- 不要 mock 能直接测试的纯逻辑。
"
safe_write "docs/ai/evaluation.md" "# Evaluation Rules
## Principle
生产和验收必须分离。实现者容易偏乐观,因此最终验收必须由 Evaluator 按真实命令和可观察证据完成。
## Roles
- Planner:把模糊需求整理成 spec.md,写清目标、非目标、验收标准、风险和测试计划;不改业务代码。
- Generator:按 spec.md 实现,记录改动和自检结果;不写最终通过结论。
- Evaluator:像 QA 一样从干净状态阅读 spec.md 和 diff,运行真实命令,把证据写入 evaluation.md。
## Evaluator Must Touch Reality
- 必须运行能证明行为的命令:构建、测试、脚本、可执行程序或最小复现。
- 不能只阅读代码后说看起来没问题。
- 如果命令无法运行,必须记录阻塞原因、缺失工具和剩余风险。
- 验收结论只能是 Pass、Fail 或 Blocked。
## Evidence Standard
- 每个通过项都要对应命令或文件证据。
- 每个失败项都要给出复现步骤。
- 未验证项必须留在 evaluation.md 和 verification.md。
"
safe_write "docs/ai/tooling.md" "# AI Tooling
## Project Rule Entrypoints
- Claude Code:读取 CLAUDE.md,使用 .claude/settings.json 的权限和 hooks,并可通过 .claude/skills/full-code-review/SKILL.md 运行全项目代码 review。
- GPT/Codex:读取 AGENTS.md,并复用 docs/ai/、prompts/、spec.md、evaluation.md 等同一套 harness 文件。
- Codex Skill:脚本会生成 .codex/skills/full-code-review,用于项目完成后的全仓库代码 review。
- Cursor:读取 .cursorrules;详细规则仍以 docs/ai/ 为准。
- GitHub Copilot:由 .vscode/settings.json 启用,项目规范仍以 CLAUDE.md / AGENTS.md / docs/ai/ 为准。
## Model And Credential Policy
- 不要把 API key、token、cookie 或本机 auth 文件提交到项目仓库。
- GPT/Codex 的模型和 provider 通常在用户级配置中,例如 ~/.codex/config.toml。
- GPT/Codex 的 API key 通常在用户级认证文件中,例如 ~/.codex/auth.json。
- Claude Code 的认证通常由 Claude CLI 或应用自己的登录态管理,不应写入本项目。
- 如果团队需要示例配置,只提交不含密钥的 example 文件,并在文档里说明本机配置位置。
## Shared Harness
- 两个 Agent 都使用同一套状态文件:claude-progress.txt、session-state.md、todo.md、verification.md。
- 两个 Agent 都使用同一套 Planner / Generator / Evaluator 流程:spec.md、evaluation.md、prompts/*.md。
- 两个 Agent 在开发前都必须先查找已有实现、公共 helper、测试 fixture、脚本和 CMake 逻辑;能复用就复用。
- 两个 Agent 都必须遵守生产和验收分离;最终完成以 evaluation.md 的独立证据为准。
- 项目完成后需要额外做一次全仓库 review 时,让 Claude 使用项目 Skill \`/full-code-review\` 或 prompts/full-code-review.md,让 Codex 使用 \`\$full-code-review\`,重点检查真实 bug、风险和有效优化点,不要把输出变成重复补测试清单。
"
safe_write "docs/ai/build.md" "# Build Rules
## Baseline
- CMake 版本:3.20+
- C++ 标准:C++${CPP_STD}
- 编译器:GCC 12+ / Clang 15+
## Commands
- Debug 配置:\`cmake -B build -DCMAKE_BUILD_TYPE=Debug\`
- Debug 编译:\`cmake --build build -j\$(nproc)\`
- Release 配置:\`cmake -B build -DCMAKE_BUILD_TYPE=Release\`
## Dependency Policy
- 不要在未说明理由时新增第三方依赖。
- 新增依赖必须写清用途、替代方案、构建影响和许可证风险。
- 优先选择成熟、无聊、团队熟悉、Agent 容易稳定使用的技术。
- 测试框架选择只写入规范,不代表 CMake 已完成依赖接入。
## Build Directory
- build/ 是生成目录,禁止手动编辑。
- 修改源码、CMake 或配置后重新运行构建命令验证。
"
safe_write "docs/ai/workflow.md" "# Agent Workflow Rules
## Principle
规则文件宁缺毋滥。CLAUDE.md 和 AGENTS.md 只做短索引,细节文件只在相关任务中读取。
重启胜过修补。上下文开始变浑浊时,不要靠更长总结硬撑;把状态写回文件系统,然后用干净上下文接力。
## Start of Each Round
1. 优先运行 scripts/resume_from_snapshot.sh;如果快照缺失,再运行 scripts/context_reset_check.sh。
2. Claude Code 读取 CLAUDE.md;GPT/Codex 读取 AGENTS.md。
3. 读取 ai_snapshot.json、claude-progress.txt、session-state.md、todo.md、verification.md。
4. 根据任务类型读取 docs/ai/ 下最相关的一个或两个文件。
5. 读取长文件时先看 Quick Brief;只有需要细节时再读正文。
6. 用几行话确认当前目标、下一步和未验证事项。
## During Work
- 按开发文档中的有序队列连续推进:取下一项、实现、验证、记录,然后继续下一项。
- 每个子项仍必须小而可验证;不要把多个无关目标揉成一次大改。
- 模糊需求先走 Planner;实现只走 Generator;最终验收只走 Evaluator。
- 写新函数、脚本、CMake 逻辑或测试 fixture 前,先查找并复用已有同类实现;找不到或不适用时再新增。
- 复杂需求先拆成 tasks/TASK-*/ 子任务,每个 Task 有自己的 task.md、ai_snapshot.json、verification.md 和 defect-rca.md。
- 每完成 3 个子项或修改 3 个文件后做一次检查点记录:已做什么、验证什么、接下来继续哪一项;不需要等待人类确认,除非触发停止条件。
- 不要在修 bug 时顺便重构无关代码。
- 修改范围超出计划时先报告,不要自行扩大。
- 同一问题连续失败两次、Evaluator 判 Fail、或人类指出缺陷时,进入 RCA 流程并更新 docs/ai/check-rules.md。
## Continue Until
- spec.md、todo.md 或当前 Task 中没有下一个可执行项。
- 验证失败、工具不可用或无法触达真实环境。
- 需求、接口、验收标准不清,需要人类确认。
- 下一项会明显扩大范围、跨越非目标、或引入新依赖。
- 上下文变浑浊,开始猜测、重复读错状态或想跳过验证。
## End of Each Round
- 更新 claude-progress.txt:当前状态、已完成、下一步、风险。
- 更新 session-state.md:本轮目标、上下文健康、交接摘要、下一轮第一步。
- 更新 todo.md:勾掉完成项,补充新发现但必要的后续项。
- 更新 verification.md:记录已跑验证、失败验证、未跑原因。
- 更新 evaluation.md:记录 Evaluator 的独立验收结论和真实命令证据。
- 运行 scripts/snapshot_update.sh,把下一轮最小读取集合写入 ai_snapshot.json。
- 未完成验证时不要宣布任务完成。
## Context Reset
- 新会话使用 prompts/resume.md 接力。
- 不依赖聊天历史保存状态;跨轮事实必须落到文件系统。
- 出现以下信号时使用 prompts/handoff.md 停止并交接:上下文接近上限、开始忘记约束、方案突然变粗、想跳过验证、文件改动超过计划、连续失败两次。
- 交接后下一轮从 scripts/context_reset_check.sh 和 prompts/resume.md 开始。
## Technical Debt Cadence
- 定期使用 prompts/debt-scan.md 做小范围巡检。
- 债务先登记到 debt-register.md,再用 prompts/debt-fix.md 一次修一个点。
- 适合后台 Agent 的任务应当 boring、小、可验证,方便人类快速 review。
"
safe_write "docs/ai/quick-brief.md" "# Quick Brief And Layered Reading
## Goal
降低长上下文噪声。Agent 续做时先读短摘要,再按需读取正文,避免每轮重复吞入整篇长文档。
## File Layers
- Frozen:稳定协议,例如 CLAUDE.md、AGENTS.md、docs/ai/*.md。初始化或规则相关任务才读。
- Active:当前阶段指南,例如 spec.md、task.md、evaluation.md。进入阶段时读一次。
- Hot:快照和状态,例如 ai_snapshot.json、session-state.md、todo.md、verification.md。每轮都读。
## Quick Brief Format
超过 80 行、且会被 Agent 多次读取的 Markdown 文件,建议在文件头部放 15 行以内的 YAML 摘要:
\`\`\`yaml
quick_brief:
purpose: 这个文件解决什么问题
current_state: 当前状态
must_read:
- 真正需要继续读的章节或文件
next_step: 下一步
last_verified: 最近一次验证命令或日期
\`\`\`
## Reading Rule
1. 先读 ai_snapshot.json。
2. 对长 Markdown 先读 Quick Brief。
3. 只有 Quick Brief 指向的章节、当前任务相关章节、或验证需要时,才读正文。
4. 如果正文状态改变,更新 Quick Brief;不要让摘要和正文互相矛盾。
## Check
运行 scripts/quick_brief_check.sh 查看哪些长 Markdown 缺少 Quick Brief。该脚本只提示,不替代人工判断。
"
safe_write "docs/ai/rca.md" "# Defect RCA And Rule Self-Healing
## Goal
修 Bug 不只改代码,还要沉淀防护规则,减少下一轮 Agent 重复犯错。
## When To Use
- Evaluator 给出 Fail。
- 人类指出明显缺陷或遗漏。
- 同一问题连续失败两次。
- 修复暴露出缺失的测试、规约或检查项。
## RCA Steps
1. 记录缺陷现象:输入、命令、错误输出、影响范围。
2. 追溯根因:是需求理解、上下文缺失、测试不足、边界遗漏、还是工具使用问题。
3. 修复代码或文档,只处理和缺陷直接相关的范围。
4. 增加回归验证:测试、脚本、最小复现或手工检查步骤。
5. 更新 defect-rca.md 或 tasks/TASK-*/defect-rca.md。
6. 把可复用的防护规则写入 docs/ai/check-rules.md。
7. 更新 ai_snapshot.json,让下一轮能看到这条新规则。
## Rule Quality
- 规则必须具体、可执行、可检查。
- 不写空泛结论,例如“以后更小心”。
- 优先写触发条件和检查动作,例如“修改解析逻辑后必须运行 X 命令”。
- 如果只是一次性事故,不要污染全局规约;只记录在当前 Task RCA。
"
safe_write "docs/ai/check-rules.md" "# Learned Check Rules
这个文件记录从缺陷 RCA 中沉淀出来的可复用防护规则。它不是编码风格大全,只收录真实踩坑后的检查项。
## Active Rules
| ID | Trigger | Check | Source |
| --- | --- | --- | --- |
| CR-0001 | 初始化 harness 后 | 运行 scripts/context_reset_check.sh 和 scripts/quick_brief_check.sh,确认恢复入口可用 | setup_ai_harness.sh |
## How To Add A Rule
1. 先在 defect-rca.md 记录缺陷和根因。
2. 只把可复用、可检查的规则提升到这里。
3. 每条规则必须有 Trigger、Check 和 Source。
4. 新规则加入后,更新 ai_snapshot.json 的 must_read 或 risks。
"
safe_write "docs/ai/task-sandbox.md" "# Task Sandbox
## Goal
把复杂需求拆成可独立接力、独立验证、独立复盘的小任务,避免一个 spec.md 装下所有上下文。
## When To Create A Task
- 需求横跨多个模块、多个接口或多天开发。
- 需要并行或分波次推进。
- 当前任务包含明显不同的设计、实现、验收阶段。
- 一个会话无法稳定承载全部上下文。
## Directory Shape
\`\`\`text
tasks/TASK-YYYYMMDDHHMMSS-name/
task.md
ai_snapshot.json
verification.md
defect-rca.md
\`\`\`
## Task Rules
- 每个 Task 只承载一个可验收目标。
- task.md 写 Goals、Non-Goals、Acceptance Criteria、Plan、Files、Risks。
- Task 内的 ai_snapshot.json 只保存该 Task 的最小恢复集。
- verification.md 只记录该 Task 的真实命令证据。
- defect-rca.md 只记录该 Task 内发生的缺陷复盘。
- Task 完成后,把关键结论同步回根目录 evaluation.md、verification.md 和 ai_snapshot.json。
## Commands
- 新建任务:scripts/task_new.sh short-name
- 续做任务:先读根 ai_snapshot.json,再读对应 Task 的 ai_snapshot.json 和 task.md。
"
# ============================================================================
# 2. Codex Skill — 项目完成后的全代码 Review
# ============================================================================
safe_write ".codex/skills/full-code-review/SKILL.md" '---
name: full-code-review
description: Whole-project code review for a completed or nearly completed software project. Use when the user asks Codex to deeply read the entire repository after development, perform a full-code/full-repo review, check for bugs, regressions, security issues, architectural risks, or meaningful optimization opportunities, especially when they explicitly do not want piecemeal review or repeated generic test suggestions.
---
# Full Code Review
## Purpose
Perform a full-repository review after project development. Prioritize real defects, behavioral risks, security/data-integrity issues, maintainability problems, and worthwhile optimizations. Do not turn the review into a repeated request to add tests.
## Operating Rules
- Review the whole first-party project, not only the latest diff, unless the user explicitly narrows scope.
- Do not ask the user to approve each review slice. Build a repo map, inspect systematically, and continue until the full pass is complete or a hard blocker prevents progress.
- Do not edit code during the review unless the user explicitly asks for fixes. The output is findings and recommendations.
- Respect dirty worktrees. Treat existing local changes as user work; do not revert or overwrite them.
- Use source evidence. A finding should cite file and line references whenever possible and explain the failure mode.
- Avoid generic test advice. Mention tests only when tied to a concrete defect/regression path, or once in a short residual-risk note.
- If the repository is too large to inspect every generated or vendored file, explicitly exclude generated/vendor/build artifacts and list any first-party areas that could not be reviewed.
## Review Workflow
1. Establish the repo root and state.
- Run `git rev-parse --show-toplevel` when available.
- Run `git status --short` to notice user changes.
- Build the inventory with `git ls-files`; fall back to `rg --files`.
2. Create a project map before judging code.
- Read `README`, package manifests, dependency files, build configs, framework configs, CI/deploy files, environment examples, schema/migration files, and main entry points.
- If `.zread/wiki/current` exists, read the relevant generated pages for orientation, but verify important claims against source.
- Classify files into app source, API/backend, frontend/UI, data/schema, scripts/jobs, infrastructure/config, tests, docs, generated/vendor/build artifacts.
3. Inspect all first-party implementation areas systematically.
- Walk directory by directory rather than sampling only suspicious files.
- Trace important user flows end to end: input validation, auth/permission checks, persistence, background jobs, external calls, error handling, retries, cancellation, and UI state transitions.
- Check shared contracts: API schemas, database models, environment variables, serialization formats, route names, feature flags, and build/runtime assumptions.
- Use targeted searches to find risk patterns: `TODO`, `FIXME`, `HACK`, `XXX`, `debugger`, `console.log`, broad catches, ignored lint/type errors, unsafe casts, unchecked `any`, raw SQL, shell execution, eval-like behavior, secrets, auth bypasses, hard-coded URLs, and duplicated business rules.
4. Run low-risk verification commands when discoverable.
- Prefer existing scripts from package manifests, Makefiles, task runners, or CI configs.
- Run static checks, type checks, linters, builds, or focused smoke commands when practical.
- Do not make test coverage the center of the review. Use command results to support or disprove concrete concerns.
5. Triage findings.
- Lead with high-confidence issues that can cause wrong behavior, data loss, security exposure, production failures, or broken user workflows.
- Include optimization opportunities only when they are meaningful: clear performance wins, simpler architecture, reduced duplication, less fragile state handling, or easier operational debugging.
- Do not report style preferences as findings unless they create real maintenance risk.
## Output Format
Start with findings, ordered by severity. Use this structure:
```text
Findings
- High/Medium/Low: <short title> - <file:line>
Impact: <what can go wrong>
Evidence: <why the code behaves that way>
Recommendation: <specific fix direction>
```
Then include:
- `Optimization Opportunities`: only concrete, worthwhile improvements.
- `Coverage`: directories or subsystems reviewed, commands run, and any exclusions.
- `Residual Risk`: short note for areas that could not be verified. Mention test gaps here only once, and only if relevant.
If no high-confidence problems are found, say so clearly and still include coverage and residual risk.'
safe_write ".codex/skills/full-code-review/agents/openai.yaml" 'interface:
display_name: "Full Code Review"
short_description: "全项目深度代码审查,聚焦真实 bug、风险与有效优化点"
default_prompt: "Use $full-code-review to review the entire project after development and report bugs, risks, and meaningful optimization opportunities."'
# ============================================================================
# 3. 全代码 Review Skill/Prompt — Claude 与通用入口
# ============================================================================
safe_write ".claude/skills/full-code-review/SKILL.md" '---
name: full-code-review
description: Whole-project code review for a completed or nearly completed software project. Use when the user asks Claude to deeply read the entire repository after development, perform a full-code/full-repo review, check for bugs, regressions, security issues, architectural risks, or meaningful optimization opportunities, especially when they explicitly do not want piecemeal review or repeated generic test suggestions.
---
'"$FULL_CODE_REVIEW_PROMPT"
safe_write "prompts/full-code-review.md" "$FULL_CODE_REVIEW_PROMPT"
# ============================================================================
# 4. .claude/settings.json — 权限 + Hooks
# ============================================================================
safe_write ".claude/settings.json" '{
"permissions": {
"allow": [
"Read",
"Edit",
"Write",
"Bash(cmake *)",
"Bash(make *)",
"Bash(ninja *)",
"Bash(g++ *)",
"Bash(clang++ *)",
"Bash(c++ *)",
"Bash(gcc *)",
"Bash(clang *)",
"Bash(gdb *)",
"Bash(lldb *)",
"Bash(ctest *)",
"Bash(cpack *)",
"Bash(clang-format *)",
"Bash(clang-tidy *)",
"Bash(git status*)",
"Bash(git diff*)",
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git log*)",
"Bash(git branch*)",
"Bash(git checkout *)",
"Bash(git switch *)",
"Bash(git stash*)",
"Bash(ls *)",
"Bash(cat *)",
"Bash(grep *)",
"Bash(find *)",
"Bash(wc *)",
"Bash(head *)",
"Bash(tail *)",
"Bash(bash scripts/context_reset_check.sh *)",
"Bash(./scripts/context_reset_check.sh *)",
"Bash(bash scripts/resume_from_snapshot.sh *)",
"Bash(./scripts/resume_from_snapshot.sh *)",
"Bash(bash scripts/snapshot_update.sh *)",
"Bash(./scripts/snapshot_update.sh *)",
"Bash(bash scripts/quick_brief_check.sh *)",
"Bash(./scripts/quick_brief_check.sh *)",
"Bash(bash scripts/task_new.sh *)",
"Bash(./scripts/task_new.sh *)",
"Bash(bash scripts/rca_new.sh *)",
"Bash(./scripts/rca_new.sh *)",
"Bash(bash scripts/ai_debt_scan.sh *)",
"Bash(./scripts/ai_debt_scan.sh *)",
"Bash(bash scripts/evaluator_check.sh *)",
"Bash(./scripts/evaluator_check.sh *)"
],
"deny": [
"Bash(rm -rf *)",
"Bash(git push --force *)",
"Bash(git push -f *)",
"Bash(git reset --hard *)",
"Bash(sudo *)"
]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if printf \"%s\\n\" \"$CLAUDE_FILE_PATH\" | grep -qE \"\\.(cpp|cc|cxx|h|hpp|hxx)$\"; then if command -v clang-format >/dev/null 2>&1; then clang-format -i \"$CLAUDE_FILE_PATH\" || echo \"WARN: clang-format failed for $CLAUDE_FILE_PATH\" >&2; else echo \"WARN: clang-format not found\" >&2; fi; fi"
}
]
}
],
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if printf \"%s\\n\" \"$CLAUDE_FILE_PATH\" | grep -qE \"(^|/)build/\"; then echo \"BLOCK: 不要直接编辑 build/ 目录,请修改源码后重新构建\" >&2; exit 1; fi"
}
]
}
]
}
}'
# ============================================================================
# 5. .cursorrules — Cursor 配置
# ============================================================================
safe_write ".cursorrules" "你是一位资深 C++ 工程师,精通现代 C++${CPP_STD} 和 CMake。
项目:${PROJECT_NAME}
构建系统:CMake 3.20+
C++ 标准:C++${CPP_STD}
测试框架:${TEST_FW_NAME}
## 核心规则
- 优先使用智能指针,避免裸 new/delete
- RAII 管理所有资源
- const 正确性:不修改的参数用 const&,不修改的方法标 const
- 头文件使用 #pragma once
- 函数不超过 40 行
- 命名:类型 PascalCase,函数/变量 snake_case,常量 kPascalCase
- 优先使用成熟、无聊、仓库已有的技术和模式
## 构建命令
- 配置:cmake -B build -DCMAKE_BUILD_TYPE=Debug
- 编译:cmake --build build -j\$(nproc)
- 测试:cd build && ctest --output-on-failure
## 禁止
- C 风格内存管理(malloc/free)除非 C 互操作
- 未定义行为(越界访问、空指针解引用、悬挂引用)
- 手动 lock/unlock,使用 lock_guard/scoped_lock
- 不说明理由就引入新第三方依赖
- 复制明显坏模式;发现坏模式先登记到 debt-register.md"
# ============================================================================
# 6. .vscode/settings.json — VS Code + Copilot 配置
# ============================================================================
safe_write ".vscode/settings.json" '{
"editor.formatOnSave": true,
"editor.defaultFormatter": "xaver.clang-format",
"C_Cpp.default.cppStandard": "c++'"${CPP_STD}"'",
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
"cmake.buildDirectory": "${workspaceFolder}/build",
"cmake.configureOnOpen": true,
"files.associations": {
"*.h": "cpp",
"*.hpp": "cpp"
},
"github.copilot.enable": {
"*": true,
"markdown": true,
"cmake": true,
"plaintext": false
},
"[cpp]": {
"editor.defaultFormatter": "xaver.clang-format",
"editor.formatOnSave": true
}
}'
safe_write ".vscode/extensions.json" '{
"recommendations": [
"xaver.clang-format",
"ms-vscode.cmake-tools",
"ms-vscode.cpptools",
"github.copilot",
"github.copilot-chat"
]
}'
# ============================================================================
# 7. .clang-format — 被 Hook 引用,必须存在
# ============================================================================
safe_write ".clang-format" "---
Language: Cpp
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100