@educa-corp/sdd-framework 0.4.2 → 0.6.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 (149) hide show
  1. package/bin/build.js +113 -19
  2. package/bin/gate-trace.js +464 -0
  3. package/bin/index.js +418 -146
  4. package/bin/lint-trace.js +602 -0
  5. package/bin/self-check.js +499 -6
  6. package/bin/trace-schema.json +1449 -692
  7. package/commands/debug.md +123 -510
  8. package/commands/debug.tmpl +3 -0
  9. package/commands/define-product.md +86 -509
  10. package/commands/dev-gen-test.md +120 -516
  11. package/commands/dev-run-test.md +120 -516
  12. package/commands/dev-smoke-test.md +86 -509
  13. package/commands/extend-prd.md +486 -0
  14. package/commands/extend-prd.tmpl +273 -0
  15. package/commands/fix-bug.md +152 -515
  16. package/commands/generate-architecture.md +94 -514
  17. package/commands/generate-architecture.tmpl +3 -0
  18. package/commands/generate-bdd.md +138 -519
  19. package/commands/generate-bdd.tmpl +18 -3
  20. package/commands/generate-code.md +156 -523
  21. package/commands/generate-code.tmpl +36 -7
  22. package/commands/generate-design-spec.md +86 -509
  23. package/commands/generate-prd.md +114 -509
  24. package/commands/generate-prd.tmpl +28 -0
  25. package/commands/generate-spec-manifest.md +86 -509
  26. package/commands/generate-tech-docs.md +86 -509
  27. package/commands/learn.md +172 -495
  28. package/commands/learn.tmpl +70 -3
  29. package/commands/map-testids.md +86 -509
  30. package/commands/propose-scenario.md +136 -508
  31. package/commands/propose-scenario.tmpl +52 -1
  32. package/commands/qc-analyze.md +86 -509
  33. package/commands/qc-design-test.md +87 -509
  34. package/commands/qc-design-test.tmpl +1 -0
  35. package/commands/qc-plan.md +86 -509
  36. package/commands/qc-report.md +86 -509
  37. package/commands/qc-review.md +86 -509
  38. package/commands/qc-run-test.md +133 -517
  39. package/commands/qc-run-test.tmpl +13 -1
  40. package/commands/refine-prd.md +99 -519
  41. package/commands/refine-prd.tmpl +3 -0
  42. package/commands/report-bug.md +86 -509
  43. package/commands/review-code.md +127 -513
  44. package/commands/review-code.tmpl +7 -3
  45. package/commands/review-context.md +96 -515
  46. package/commands/review-context.tmpl +6 -2
  47. package/commands/review-tech-docs.md +90 -510
  48. package/commands/review-tech-docs.tmpl +3 -0
  49. package/commands/setup-ai-first.md +166 -137
  50. package/commands/setup-ai-first.tmpl +72 -0
  51. package/commands/sync.md +86 -118
  52. package/commands/sync.tmpl +84 -16
  53. package/commands/update-framework.md +16 -102
  54. package/commands/update-framework.tmpl +14 -0
  55. package/commands/validate-traces.md +458 -531
  56. package/commands/validate-traces.tmpl +381 -31
  57. package/core/FRAMEWORK_VERSION +1 -1
  58. package/core/README.md +20 -0
  59. package/core/commands/debug.md +123 -510
  60. package/core/commands/define-product.md +86 -509
  61. package/core/commands/dev-gen-test.md +120 -516
  62. package/core/commands/dev-run-test.md +120 -516
  63. package/core/commands/dev-smoke-test.md +86 -509
  64. package/core/commands/extend-prd.md +486 -0
  65. package/core/commands/fix-bug.md +152 -515
  66. package/core/commands/generate-architecture.md +94 -514
  67. package/core/commands/generate-bdd.md +138 -519
  68. package/core/commands/generate-code.md +156 -523
  69. package/core/commands/generate-design-spec.md +86 -509
  70. package/core/commands/generate-prd.md +114 -509
  71. package/core/commands/generate-spec-manifest.md +86 -509
  72. package/core/commands/generate-tech-docs.md +86 -509
  73. package/core/commands/learn.md +172 -495
  74. package/core/commands/map-testids.md +86 -509
  75. package/core/commands/propose-scenario.md +136 -508
  76. package/core/commands/qc-analyze.md +86 -509
  77. package/core/commands/qc-design-test.md +87 -509
  78. package/core/commands/qc-plan.md +86 -509
  79. package/core/commands/qc-report.md +86 -509
  80. package/core/commands/qc-review.md +86 -509
  81. package/core/commands/qc-run-test.md +133 -517
  82. package/core/commands/refine-prd.md +99 -519
  83. package/core/commands/report-bug.md +86 -509
  84. package/core/commands/review-code.md +127 -513
  85. package/core/commands/review-context.md +96 -515
  86. package/core/commands/review-tech-docs.md +90 -510
  87. package/core/commands/setup-ai-first.md +166 -137
  88. package/core/commands/sync.md +86 -118
  89. package/core/commands/update-framework.md +16 -102
  90. package/core/commands/validate-traces.md +458 -531
  91. package/core/hooks/data-guard.js +174 -83
  92. package/core/hooks/settings.json +2 -1
  93. package/core/rules/workflow.md +48 -4
  94. package/core/steps/capture-lesson.md +34 -1
  95. package/core/steps/context-loader.md +24 -3
  96. package/core/steps/gate.md +92 -35
  97. package/core/steps/report-footer.md +26 -2
  98. package/core/steps/trace-mirror.md +34 -7
  99. package/core/templates/README.md +24 -1
  100. package/core/templates/ci/trace-gate.yml +146 -0
  101. package/core/templates/feature.template +1 -1
  102. package/core/templates/hooks/pre-push +61 -0
  103. package/docs/01-getting-started/installation.md +18 -1
  104. package/docs/01-getting-started/what-is-sdd.md +4 -2
  105. package/docs/02-concepts/architecture.md +48 -5
  106. package/docs/02-concepts/pipeline-steps/02-specification.md +39 -3
  107. package/docs/02-concepts/pipeline-steps/04-bdd.md +24 -2
  108. package/docs/02-concepts/pipeline-steps/05-tech-docs.md +18 -1
  109. package/docs/02-concepts/pipeline-steps/06-code.md +35 -4
  110. package/docs/02-concepts/pipeline-steps/09-validate-traces.md +137 -12
  111. package/docs/02-concepts/pipeline-steps/10-feedback-loop.md +59 -3
  112. package/docs/02-concepts/roles-and-hitl.md +1 -1
  113. package/docs/02-concepts/traceability.md +183 -117
  114. package/docs/03-guides/architect.md +63 -0
  115. package/docs/03-guides/developer.md +20 -4
  116. package/docs/03-guides/product-owner.md +72 -68
  117. package/docs/03-guides/tester-qa.md +81 -70
  118. package/docs/04-reference/commands.md +134 -105
  119. package/docs/04-reference/configuration.md +146 -94
  120. package/docs/04-reference/model-selection.md +32 -19
  121. package/docs/04-reference/trace-schema.md +26 -9
  122. package/docs/explain/02-generate-prd.md +80 -78
  123. package/docs/explain/02b-extend-prd.md +125 -0
  124. package/docs/explain/03-refine-prd.md +86 -86
  125. package/docs/explain/04-review-context.md +18 -1
  126. package/docs/explain/06-generate-bdd.md +23 -0
  127. package/docs/explain/08-review-tech-docs.md +20 -5
  128. package/docs/explain/10-review-code.md +36 -2
  129. package/docs/explain/19-qc-run-test.md +87 -67
  130. package/docs/explain/21-validate-traces.md +75 -68
  131. package/docs/explain/23-fix-bug.md +19 -3
  132. package/docs/explain/26-propose-scenario.md +70 -63
  133. package/docs/explain/27-learn.md +5 -3
  134. package/docs/explain/README.md +135 -134
  135. package/hooks/data-guard.js +174 -83
  136. package/hooks/settings.json +2 -1
  137. package/package.json +53 -50
  138. package/rules/workflow.md +48 -4
  139. package/steps/capture-lesson.md +34 -1
  140. package/steps/context-loader.md +24 -3
  141. package/steps/gate.md +92 -35
  142. package/steps/report-footer.md +26 -2
  143. package/steps/trace-mirror.md +34 -7
  144. package/templates/README.md +24 -1
  145. package/templates/ci/trace-gate.yml +146 -0
  146. package/templates/feature.template +1 -1
  147. package/templates/hooks/pre-push +61 -0
  148. package/scripts/init.sh +0 -49
  149. package/scripts/upgrade.sh +0 -94
@@ -2,28 +2,90 @@
2
2
  /**
3
3
  * data-guard.js — Claude Code PreToolUse Hook
4
4
  *
5
- * Blocks AI from reading, writing, or executing commands involving
6
- * sensitive files (credentials, secrets, private keys, .env, etc.)
5
+ * Chặn AI đọc/ghi/thực thi trên file nhạy cảm (credential, secret, private key, .env…).
7
6
  *
8
- * Install: copy to your project and register in .claude/settings.json
9
- * (see hooks/settings.json for registration template)
7
+ * Cài: copy vào project + đăng trong .claude/settings.json
8
+ * (mẫu: hooks/settings.json hoặc dùng `npx @educa-corp/sdd-framework --hooks`)
10
9
  *
11
- * Exit codes:
12
- * 0 = allow the tool call
13
- * 2 = block the tool call (Claude Code interprets this as a hard block)
10
+ * Exit code:
11
+ * 0 = cho phép
12
+ * 2 = chặn cứng (Claude Code hiểu này block)
13
+ *
14
+ * ── VÌ SAO BẢN NÀY KHÁC BẢN ĐẦU (GAPS-v3 G42) ────────────────────────────────
15
+ *
16
+ * Bản đầu có ba lỗi độc lập; hai trong số đó chặn đúng công việc mà framework tồn
17
+ * tại để làm, và cái còn lại làm lời hứa bảo mật không đúng:
18
+ *
19
+ * (a) matcher thiếu `Grep` — `Grep` với output_mode:"content" trên `.env` TRẢ VỀ
20
+ * nội dung file và không đi qua hook. Nên câu "AI will be blocked from reading
21
+ * .env" là sai.
22
+ * (b) pattern soi CẢ PATH, không neo. `/password/i` khớp
23
+ * `specs/auth/forgot-password/UC1.feature` và `src/auth/PasswordResetController.java`
24
+ * ⇒ một framework sinh code từ spec KHÔNG LÀM NỔI feature auth khi bật hook
25
+ * của chính nó.
26
+ * (c) Bash soi cả command string ⇒ `git commit -m "feat: password reset UC1"` bị
27
+ * chặn — đúng câu commit mà các lệnh hướng dẫn chạy ở cuối pipeline.
28
+ *
29
+ * Cả hai đường đều dẫn tới cùng một kết cục: người dùng TẮT HOOK, và mất luôn phần
30
+ * bảo vệ thật. Một guard bị tắt bảo vệ bằng không.
31
+ *
32
+ * ── MÔ HÌNH MỚI ──────────────────────────────────────────────────────────────
33
+ *
34
+ * Secret sống trong file CẤU HÌNH/DỮ LIỆU, không sống trong file MÃ NGUỒN.
35
+ * `secrets.json` là kho bí mật; `PasswordResetController.java` là code.
36
+ * Nên pattern chung (secret/credential/password/token/api-key) chỉ áp cho file
37
+ * KHÔNG phải mã nguồn. Pattern cứng (.env, .pem, .key…) áp cho mọi file.
38
+ * Cộng thêm allowlist thư mục làm việc của framework (specs/, .trace/, docs/…).
14
39
  */
15
40
 
16
- const readline = require('readline');
17
-
18
- // ── Sensitive file patterns ────────────────────────────────────────────────
41
+ // ── Thư mục làm việc của framework — không bao giờ chứa secret thật ───────────
42
+ // Tên feature ("forgot-password", "api-key-rotation") hay khớp pattern chung, và
43
+ // đây chính chỗ ca (b) nổ. Cho qua TRƯỚC khi soi.
44
+ const SAFE_DIR_PREFIXES = [
45
+ 'specs/', '.trace/', '.trace-mirror/', '.living-docs/',
46
+ 'docs/', '.agent/', 'feedback/', '.claude/',
47
+ ];
19
48
 
20
- const SENSITIVE_PATH_PATTERNS = [
21
- // Environment files
49
+ // ── Đuôi file MÃ NGUỒN — pattern chung không áp ───────────────────────────────
50
+ // Một file .java/.ts/.dart tên gì đi nữa cũng là code, không phải kho secret.
51
+ // (Pattern CỨNG bên dưới vẫn áp — nhưng .pem/.key không nằm trong danh sách này.)
52
+ const CODE_EXT = new Set([
53
+ 'java', 'kt', 'kts', 'scala', 'groovy',
54
+ 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'vue', 'svelte',
55
+ 'py', 'go', 'rs', 'rb', 'php', 'cs', 'fs', 'vb',
56
+ 'swift', 'm', 'mm', 'dart', 'c', 'h', 'cpp', 'hpp', 'cc',
57
+ 'sql', 'graphql', 'proto', 'feature', 'md', 'mdx', 'txt',
58
+ 'html', 'css', 'scss', 'less', 'tsv', 'csv',
59
+ ]);
60
+
61
+ // ── Pattern CỨNG — áp cho mọi file, soi TÊN FILE ─────────────────────────────
62
+ const SENSITIVE_NAME_HARD = [
22
63
  /^\.env$/i,
23
64
  /^\.env\./i,
24
65
  /\.env$/i,
25
66
 
26
- // Secret/credential files
67
+ /\.key$/i,
68
+ /\.pem$/i,
69
+ /\.p12$/i,
70
+ /\.pfx$/i,
71
+ /\.jks$/i,
72
+ /\.keystore$/i,
73
+ /^id_rsa$/i,
74
+ /^id_ed25519$/i,
75
+
76
+ /^application-(prod|production|staging)\.(yml|yaml|properties)$/i,
77
+ /^appsettings\.(Production|Staging)\.json$/i,
78
+ /^database\.yml$/i,
79
+ /^master\.key$/i,
80
+ /^oauth-private\.key$/i,
81
+ /^credentials$/i,
82
+ /^\.npmrc$/i,
83
+ /^\.pypirc$/i,
84
+ /^\.netrc$/i,
85
+ ];
86
+
87
+ // ── Pattern CHUNG — chỉ áp cho file KHÔNG phải mã nguồn, soi TÊN FILE ────────
88
+ const SENSITIVE_NAME_SOFT = [
27
89
  /secret/i,
28
90
  /credential/i,
29
91
  /password/i,
@@ -32,60 +94,84 @@ const SENSITIVE_PATH_PATTERNS = [
32
94
  /api[_-]?key/i,
33
95
  /access[_-]?token/i,
34
96
  /auth[_-]?token/i,
97
+ ];
35
98
 
36
- // Crypto keys and certificates
37
- /\.key$/i,
38
- /\.pem$/i,
39
- /\.p12$/i,
40
- /\.pfx$/i,
41
- /\.jks$/i,
42
- /\.keystore$/i,
43
-
44
- // Framework-specific prod configs
45
- /application-(prod|production|staging)\.(yml|yaml|properties)$/i,
46
- /appsettings\.(Production|Staging)\.json$/i,
47
- /database\.yml$/i,
48
- /config\/master\.key$/i,
49
- /storage\/oauth-private\.key$/i,
50
-
51
- // Secret directories
52
- /^secrets\//i,
53
- /\/secrets\//i,
54
- /^\.secrets\//i,
99
+ // ── Pattern THƯ MỤC — soi cả path ────────────────────────────────────────────
100
+ const SENSITIVE_DIR = [
101
+ /(^|\/)secrets?\//i,
102
+ /(^|\/)\.secrets?\//i,
103
+ /(^|\/)\.ssh\//i,
104
+ /(^|\/)\.aws\//i,
105
+ /(^|\/)\.gnupg\//i,
55
106
  ];
56
107
 
57
- const SENSITIVE_BASH_PATTERNS = [
108
+ // ── Lệnh bash nguy hiểm bất kể path ──────────────────────────────────────────
109
+ const SENSITIVE_BASH = [
58
110
  /\bprintenv\b/i,
59
- /\benv\b.*\|\s*(grep|awk|sed).*secret/i,
60
- /cat\s+\.env/i,
61
- /docker\s+inspect/i,
62
- /kubectl\s+get\s+secret.*-o\s+yaml/i,
111
+ /\benv\b\s*(\||$)/i,
112
+ /kubectl\s+get\s+secrets?\b[^|]*-o\s*(yaml|json)/i,
113
+ /\baws\s+secretsmanager\s+get-secret-value/i,
114
+ /\bgcloud\s+secrets\s+versions\s+access/i,
115
+ /\bvault\s+(read|kv\s+get)\b/i,
116
+ // `docker inspect` KHÔNG chặn cả cụm (lệnh debug thường dùng) — chỉ chặn khi nó
117
+ // thực sự moi Env ra. Bản đầu chặn cả cụm và đó là ma sát không đổi lấy gì.
118
+ /docker\s+inspect[^|]*\.Config\.Env/i,
63
119
  ];
64
120
 
65
- // ── Helpers ────────────────────────────────────────────────────────────────
121
+ // ── Helpers ──────────────────────────────────────────────────────────────────
122
+
123
+ function normalize(p) {
124
+ return String(p).replace(/\\/g, '/').replace(/^\.\//, '');
125
+ }
126
+
127
+ function extOf(base) {
128
+ const i = base.lastIndexOf('.');
129
+ return i > 0 ? base.slice(i + 1).toLowerCase() : '';
130
+ }
66
131
 
67
132
  function isSensitivePath(filePath) {
68
133
  if (!filePath) return false;
69
- const normalized = filePath.replace(/\\/g, '/');
70
- return SENSITIVE_PATH_PATTERNS.some(pattern => pattern.test(normalized));
134
+ const p = normalize(filePath);
135
+
136
+ // Vùng làm việc của framework — spec/trace/doc không chứa secret thật, và tên
137
+ // feature ở đó hay khớp pattern chung. Bỏ cả tiền tố tuyệt đối trước khi so.
138
+ const relish = p.replace(/^([a-zA-Z]:)?\/+/, '');
139
+ if (SAFE_DIR_PREFIXES.some(d => relish.startsWith(d) || relish.includes('/' + d))) return false;
140
+
141
+ if (SENSITIVE_DIR.some(re => re.test(p))) return true;
142
+
143
+ const base = p.split('/').pop() || '';
144
+ if (SENSITIVE_NAME_HARD.some(re => re.test(base))) return true;
145
+
146
+ // Pattern chung: bỏ qua mã nguồn. Đây là chỗ bản đầu chặn PasswordResetController.java.
147
+ if (CODE_EXT.has(extOf(base))) return false;
148
+ return SENSITIVE_NAME_SOFT.some(re => re.test(base));
71
149
  }
72
150
 
73
- function isSensitiveCommand(command) {
74
- if (!command) return false;
75
- return SENSITIVE_BASH_PATTERNS.some(pattern => pattern.test(command));
151
+ /**
152
+ * Tách các token TRÔNG GIỐNG PATH ra khỏi một command line.
153
+ * Bản đầu soi cả chuỗi lệnh nên `git commit -m "feat: password reset"` bị chặn.
154
+ */
155
+ function pathishTokens(command) {
156
+ return String(command)
157
+ .split(/[\s;|&()<>]+/)
158
+ .map(t => t.replace(/^["']|["']$/g, ''))
159
+ .filter(t => t && !t.startsWith('-') && /[\/.]/.test(t) && !/^-{1,2}/.test(t));
76
160
  }
77
161
 
78
- function block(reason) {
79
- console.error(`\n🔒 DATA GUARD — BLOCKED\n${reason}\n`);
80
- console.error('If you need configuration values, describe what you need');
81
- console.error('without sharing actual secrets. Use placeholder values in generated code.\n');
162
+ function block(reason, detail) {
163
+ console.error(`\n🔒 DATA GUARD — BLOCKED\n${reason}`);
164
+ if (detail) console.error(detail);
165
+ console.error('\nCần giá trị cấu hình? tả thứ bạn cần mà KHÔNG đưa secret thật;');
166
+ console.error('dùng placeholder trong code sinh ra.');
167
+ console.error('Nghĩ đây là chặn nhầm? Vùng specs/ .trace/ docs/ .agent/ luôn được cho qua,');
168
+ console.error('và file mã nguồn (.java/.ts/.dart…) không bị pattern chung đụng tới.\n');
82
169
  process.exit(2);
83
170
  }
84
171
 
85
- // ── Main ───────────────────────────────────────────────────────────────────
172
+ // ── Main ─────────────────────────────────────────────────────────────────────
86
173
 
87
174
  let rawInput = '';
88
-
89
175
  process.stdin.setEncoding('utf8');
90
176
  process.stdin.on('data', chunk => { rawInput += chunk; });
91
177
  process.stdin.on('end', () => {
@@ -93,49 +179,54 @@ process.stdin.on('end', () => {
93
179
  try {
94
180
  input = JSON.parse(rawInput);
95
181
  } catch {
96
- // Cannot parse input allow (fail open, not fail closed)
182
+ // Fail-open CÓ CHỦ Ý: hook parse lỗi chặn hết thì làm cả project đứng máy.
183
+ // Nhưng không im lặng — im lặng là cách một guard chết mà không ai biết.
184
+ console.error('⚠️ data-guard: không parse được input hook — CHO QUA (fail-open).');
97
185
  process.exit(0);
98
186
  }
99
187
 
100
- const toolName = input.tool_name || '';
101
- const toolInput = input.tool_input || {};
102
-
103
- // ── Read tool ─────────────────────────────────────────────────────────
104
- if (toolName === 'Read') {
105
- const filePath = toolInput.file_path || '';
106
- if (isSensitivePath(filePath)) {
107
- block(`Attempted to READ sensitive file: ${filePath}`);
108
- }
109
- }
110
-
111
- // ── Write tool ────────────────────────────────────────────────────────
112
- if (toolName === 'Write') {
113
- const filePath = toolInput.file_path || '';
114
- if (isSensitivePath(filePath)) {
115
- block(`Attempted to WRITE to sensitive file: ${filePath}`);
188
+ const tool = input.tool_name || '';
189
+ const arg = input.tool_input || {};
190
+
191
+ switch (tool) {
192
+ case 'Read':
193
+ case 'Write':
194
+ case 'Edit':
195
+ case 'NotebookEdit': {
196
+ const f = arg.file_path || arg.notebook_path || '';
197
+ if (isSensitivePath(f)) block(`Thao tác ${tool} trên file nhạy cảm: ${f}`);
198
+ break;
116
199
  }
117
- }
118
200
 
119
- // ── Edit tool ─────────────────────────────────────────────────────────
120
- if (toolName === 'Edit') {
121
- const filePath = toolInput.file_path || '';
122
- if (isSensitivePath(filePath)) {
123
- block(`Attempted to EDIT sensitive file: ${filePath}`);
201
+ // Grep ĐỌC ĐƯỢC NỘI DUNG (output_mode: "content"). Thiếu nhánh này thì mọi thứ
202
+ // trên chỉ là cửa trước, còn cửa sau mở toang — chính là lỗi (a) của G42.
203
+ case 'Grep': {
204
+ const target = arg.path || '';
205
+ if (target && isSensitivePath(target)) {
206
+ block(`Grep nhắm vào path nhạy cảm: ${target}`);
207
+ }
208
+ if (arg.glob && isSensitivePath(String(arg.glob).replace(/\*/g, 'x'))) {
209
+ block(`Grep dùng glob nhắm vào file nhạy cảm: ${arg.glob}`);
210
+ }
211
+ // Đang đi TÌM chính chuỗi secret — chặn kèm lý do khác hẳn.
212
+ if (arg.pattern && /\b(BEGIN [A-Z ]*PRIVATE KEY|aws_secret_access_key|sk-[A-Za-z0-9]{16,})/i
213
+ .test(String(arg.pattern))) {
214
+ block(`Grep đang tìm chính giá trị bí mật: ${String(arg.pattern).slice(0, 40)}…`);
215
+ }
216
+ break;
124
217
  }
125
- }
126
218
 
127
- // ── Bash tool ─────────────────────────────────────────────────────────
128
- if (toolName === 'Bash') {
129
- const command = toolInput.command || '';
130
- if (isSensitiveCommand(command)) {
131
- block(`Attempted to execute sensitive command: ${command}`);
132
- }
133
- // Also check if the command references a sensitive file path
134
- if (isSensitivePath(command)) {
135
- block(`Bash command references a sensitive file path: ${command}`);
219
+ case 'Bash': {
220
+ const cmd = arg.command || '';
221
+ if (SENSITIVE_BASH.some(re => re.test(cmd))) {
222
+ block(`Lệnh moi secret: ${cmd.slice(0, 120)}`);
223
+ }
224
+ // CHỈ soi token trông giống path — không soi cả chuỗi lệnh (lỗi (c) của G42).
225
+ const hit = pathishTokens(cmd).find(isSensitivePath);
226
+ if (hit) block(`Lệnh bash chạm file nhạy cảm: ${hit}`, ` (trong: ${cmd.slice(0, 120)})`);
227
+ break;
136
228
  }
137
229
  }
138
230
 
139
- // Allow all other tool calls
140
231
  process.exit(0);
141
232
  });
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "_comment": "Claude Code hook registration template. Copy this content into your project's .claude/settings.json",
3
+ "_matcher_note": "Grep BẮT BUỘC có trong matcher: Grep với output_mode:content ĐỌC ĐƯỢC nội dung file, nên thiếu nó thì việc chặn Read chỉ là cửa trước (GAPS-v3 G42a).",
3
4
  "_docs": "https://docs.anthropic.com/claude/claude-code/hooks",
4
5
 
5
6
  "hooks": {
6
7
  "PreToolUse": [
7
8
  {
8
- "matcher": "Read|Write|Edit|Bash",
9
+ "matcher": "Read|Write|Edit|Grep|NotebookEdit|Bash",
9
10
  "hooks": [
10
11
  {
11
12
  "type": "command",
@@ -7,10 +7,26 @@
7
7
 
8
8
  ## Checkpoints
9
9
 
10
- - **Always** show a CHECKPOINT before making significant changes.
11
- - A CHECKPOINT must include: what will be done, which files will be created/modified, estimated scope.
12
- - Wait for explicit "Y" or user confirmation before proceeding.
13
- - Exception: read-only analysis commands (`/review-code`, `/validate-traces`, `/debug`) may skip CHECKPOINT.
10
+ Ba mức, định nghĩa đầy đủ `steps/gate.md` Bước 3a — **đây chỉ là bản tóm tắt, gate là nguồn**:
11
+
12
+ | Mức | Lệnh nào | `--yes` bỏ qua? |
13
+ |---|---|:---:|
14
+ | **Không chặn** | read-only (`/review-code` · `/validate-traces` · `/debug` · `/review-context` · `/review-tech-docs`) | — |
15
+ | **Chặn thường** | mọi lệnh sinh/sửa artifact | ✅ |
16
+ | **Chặn CỨNG** | ghi đè file đã có · `--resume` · migrate · prune | ❌ |
17
+
18
+ - CHECKPOINT phải nêu **target đã phân giải**, và **mọi cờ 🔴/⚠️ mà context-loader đã tính**
19
+ (`active_service = unresolved`, `Status ≠ FULL`, CLAUDE.md thiếu, target resolve bằng wildcard).
20
+ - **KHÔNG lặp lại** những gì `[CTX LOADED]` vừa in ngay phía trên. Sạch hết thì CHECKPOINT
21
+ chỉ hai dòng.
22
+ - `--yes` bỏ qua *chặn thường*, **không** bỏ qua *chặn cứng*, và **không** tắt việc in cờ.
23
+
24
+ > **Vì sao ba mức thay vì "always show" (G41):** bản cũ viết *"**Always** show a CHECKPOINT"*
25
+ > rồi ngay dòng sau lại cấp một ngoại lệ cho lệnh read-only — mà `gate.md` **không hề thực thi**
26
+ > ngoại lệ đó. Hai file cùng được nạp vào mọi lệnh và nói ngược nhau. Cộng thêm: cổng luôn in
27
+ > ra một bảng giống hệt nhau, 20 lần cho một feature, nên `Y` thành phản xạ và cổng hỏng **âm
28
+ > thầm** — vẫn hiện, vẫn được trả lời, chỉ là không ai đọc. Cổng chỉ ồn khi thật sự có chuyện
29
+ > thì mới được đọc.
14
30
 
15
31
  ## Scope Control
16
32
 
@@ -20,14 +36,42 @@
20
36
 
21
37
  ## Trace Contract
22
38
 
39
+ > **Phạm vi:** mục này áp cho **repo framework**. Ở project consumer, `.agent/` là mirror sinh
40
+ > ra và `bin/` không được cài — contract ở đó là **read-only**: thấy lệch thì **báo**, đừng tự
41
+ > sửa (xem `.agent/README.md`). Việc duy nhất chạy được ở project là **kiểm sổ trace**:
42
+ > `npx @educa-corp/sdd-framework --lint-trace`.
43
+
23
44
  - Contract trace (field `@trace.*`, cột `.tsv`, path pattern, giá trị enum) có **một
24
45
  nguồn-sự-thật máy đọc**: `bin/trace-schema.json`. Bản cho người đọc:
25
46
  `docs/04-reference/trace-schema.md` — giữ hai file đồng bộ.
47
+ - **Canh contract ≠ canh dữ liệu.** `bin/self-check.js` đọc **file lệnh** và kiểm *"lệnh có gọi
48
+ đúng tên cột không"* — nó không bao giờ mở một `.tsv` thật. `bin/lint-trace.js` mở sổ thật.
49
+ Cần cả hai: sổ 24 cột được ghi **bằng tay**, hàng chục lần mỗi feature; một dấu tab thiếu ở
50
+ ô 17 dồn mọi ô sau đó sang trái, ô 21 `status` nhận một ngày tháng, và **không cờ nào bật**.
51
+ Thêm cột/vocabulary mới → khai binding cho `lint-trace` **ngay**; R8 fail build nếu quên.
26
52
  - Đổi contract (thêm/bỏ/đổi nghĩa một field, path, hay giá trị enum) → **sửa
27
53
  `bin/trace-schema.json` TRƯỚC**, rồi mới sửa lệnh. `npm run build` chạy
28
54
  `bin/self-check.js` và **fail** nếu lệnh lệch schema.
29
55
  - Field có consumer mà **không có producer** là lỗi chặn build — đó chính là hình dạng
30
56
  của G1 (`@trace.sc_version`: 3 consumer, 0 producer, DRIFT chết mà không ai báo).
57
+ - **Làm mất hiệu lực ≠ ghi đè.** Cột trace có chủ sở hữu rõ ràng — `dev_selftest`/`dev_selftest_at`
58
+ thuộc `/dev-run-test` · `qc_status`/`qc_run_at` thuộc `/qc-run-test` · `test_count`/`test_classes`
59
+ thuộc `/dev-gen-test` — và **chỉ chủ được ghi giá trị KHẲNG ĐỊNH** (`pass`/`fail`/số lượng).
60
+ Nhưng lệnh nào làm giá trị đó **HẾT ĐÚNG** (spec đổi, code đổi) thì **BẮT BUỘC** hạ nó về giá
61
+ trị "chưa biết" (`not_run` / `—`). Giữ một `pass` đã hết hiệu lực là **báo cáo sai**, không phải
62
+ tôn trọng quyền sở hữu.
63
+ *Tiền lệ đúng có sẵn: `/fix-bug` hạ `dev_selftest → not_run` với lý do "code vừa đổi nên tín
64
+ hiệu self-test cũ hết hiệu lực". Cùng lý do đó áp cho MỌI lệnh làm đổi spec hoặc code.*
65
+ **Ngoại lệ có chủ ý:** `qc_owner`/`qc_blocked_by` (con trỏ tới bug — spec đổi không làm bug biến
66
+ mất) và `test_count`/`test_classes` (test vẫn tồn tại trên đĩa; số lượng không sai, chỉ nội dung
67
+ cũ → **cảnh báo**, không hạ số, để tỷ lệ coverage không nhảy loạn).
68
+ - **Mỗi audit flag phải quan sát được ở CẢ BA tầng.** Mọi giá trị trong
69
+ `vocabularies.audit_flags` bắt buộc có đủ: **(1)** một counter `{flag_lowercase}_count`
70
+ trong Step 7 + `summary` của `trace-report.json` · **(2)** một mảng trong `issues` ·
71
+ **(3)** một khối trong report terminal. Thiếu tầng nào = cờ vô hình ở tầng đó.
72
+ `bin/self-check.js` R7 ép tầng (1) — **không có ngoại lệ**. Đây là hình dạng của G33:
73
+ 7/10 cờ có counter, 3 cái không, nên dashboard (chỉ đọc `summary`) không tổng hợp
74
+ được — và bất đối xứng 7/10 là bẫy cho người viết dashboard: đọc `summary` rồi tưởng đủ.
31
75
 
32
76
  ## Code Generation
33
77
 
@@ -47,7 +47,7 @@ Nếu `lessons_path` chưa tồn tại, tạo file với header sau trước:
47
47
  > Các lỗi AI KHÔNG được lặp lại trong dự án này. Được nạp bởi context-loader ở đầu
48
48
  > mỗi lệnh và coi như ràng buộc cứng (cùng mức ưu tiên với coding standards trong CLAUDE.md).
49
49
  > Thêm bằng /learn, hoặc chấp nhận prompt trong /review-code, /fix-bug, /debug.
50
- > Commit file này để cả team dùng chung guardrail.
50
+ > Rà lại định kỳ bằng `/learn --review`. Commit file này để cả team dùng chung guardrail.
51
51
 
52
52
  | Category | Áp dụng cho |
53
53
  |----------|-----------|
@@ -58,6 +58,9 @@ Nếu `lessons_path` chưa tồn tại, tạo file với header sau trước:
58
58
  | prd | output của /generate-prd, /refine-prd |
59
59
  | general | mọi lệnh |
60
60
 
61
+ **Status:** `active` = đang là ràng buộc cứng · `retired` = đã hết đúng, GIỮ LẠI làm lịch sử
62
+ nhưng context-loader **không nạp nữa**. Lesson không ghi `Status` được coi là `active`.
63
+
61
64
  ---
62
65
  ```
63
66
 
@@ -65,6 +68,7 @@ Chèn lesson mới ngay dưới dấu phân cách `---` (**mới nhất lên đ
65
68
 
66
69
  ```markdown
67
70
  ### L-{NNN} — [{category}] {title}
71
+ - **Status**: active
68
72
  - **Date**: {hôm nay YYYY-MM-DD}
69
73
  - **Scope**: {scope}
70
74
  - **Mistake**: {mistake}
@@ -73,6 +77,35 @@ Chèn lesson mới ngay dưới dấu phân cách `---` (**mới nhất lên đ
73
77
 
74
78
  ```
75
79
 
80
+ ### Retire — đường ra của một lesson *(GAPS-v3 G46)*
81
+
82
+ Một lesson là **giả thuyết rằng AI sẽ lặp lại một lỗi**. Giả thuyết đó hết đúng khi code nó canh
83
+ không còn tồn tại, hoặc khi quy ước dự án đã đổi. Lúc đó nó phải bị **hạ xuống**, không được giữ.
84
+
85
+ Retire = đổi `Status` và ghi lý do — **KHÔNG xoá dòng**:
86
+
87
+ ```markdown
88
+ ### L-003 — [code-gen] Dùng WebClient thay RestTemplate
89
+ - **Status**: retired
90
+ - **Retired**: 2027-03-15 — project đổi tầng HTTP, RestTemplate không còn trong repo
91
+ - **Date**: 2026-08-19
92
+ …giữ nguyên phần còn lại…
93
+ ```
94
+
95
+ Giữ lại vì nó là **lịch sử**: người sau đọc được *"vì sao dự án này từng có luật đó"*, thứ mà xoá
96
+ đi là mất vĩnh viễn.
97
+
98
+ > **Vì sao cần đường ra:** trước G46 file này **chỉ có đường vào**. Lesson được nạp làm *"ràng buộc
99
+ > cứng, cùng mức ưu tiên với CLAUDE.md"* — vĩnh viễn, kể cả khi code nó canh đã bị xoá. Không cờ
100
+ > nào nhắc, không lệnh nào gỡ; cách duy nhất là có người tự nhớ ra rồi xoá tay.
101
+ > Đây đúng lớp lỗi của **G28** (*"giữ một `pass` đã hết hiệu lực là báo cáo sai"*) và luật
102
+ > `rules/workflow.md` §Trace Contract — **"làm mất hiệu lực ≠ ghi đè"** — chỉ là ở hàng đợi này
103
+ > chưa ai áp luật đó.
104
+ >
105
+ > **Ba trong bốn lệnh ghi lesson là lệnh phản ứng khi có sự cố** (`/review-code`, `/fix-bug`,
106
+ > `/debug`), nên file phình nhanh nhất đúng lúc dự án đang trục trặc — và lesson sinh ra lúc đó
107
+ > hay gắn với một sự cố cụ thể hơn là một quy tắc bền.
108
+
76
109
  ## L5 — Xác nhận
77
110
 
78
111
  In: `📝 Đã ghi lesson {id} → {lessons_path} ([{category}] {title})`
@@ -334,13 +334,33 @@ Phân giải path file lessons:
334
334
  - Else mặc định `specs/domain-knowledge/lessons-learned.md`
335
335
  - Ở chế độ umbrella/service (khi `service_root` được set), nếu `paths.lessons_file` chưa set, mặc định `{service_root}/.agent/project-lessons.md`
336
336
 
337
- Nếu file tồn tại, đọc lưu TẤT CẢ lesson làm **GUARDRAIL ĐANG HOẠT ĐỘNG** cho phiên:
337
+ Nếu file tồn tại, **LỌC TRƯỚC KHI NẠP** chỉ giữ lesson thoả **cả hai**:
338
+
339
+ 1. **`Status: active`** (hoặc **không có** field `Status` → lesson cũ, coi là `active`)
340
+ 2. **`category` khớp lệnh đang chạy**, hoặc `category: general`
341
+
342
+ Số còn lại mới nạp làm **GUARDRAIL ĐANG HOẠT ĐỘNG** cho phiên:
338
343
  - Coi **Rule** của mỗi lesson là ràng buộc cứng — cùng mức ưu tiên với coding standards trong CLAUDE.md (Bước 3).
339
- - Trước khi sinh hoặc sửa bất kỳ artifact nào (PRD, BDD, tech-doc, code, test), đối chiếu output với mọi lesson `category` khớp lệnh hiện tại VÀ `scope` khớp target (domain / file).
344
+ - Trước khi sinh hoặc sửa bất kỳ artifact nào (PRD, BDD, tech-doc, code, test), đối chiếu output với lesson đã nạp **`scope` khớp target** (domain / file glob).
340
345
  - Nếu output sinh ra vi phạm một lesson → sửa **trước khi** trình bày, và ghi rõ lesson nào (`L-NNN`) đã được áp dụng.
341
346
 
347
+ Ghi lại **hai** con số cho recap Bước 7: `{n_active_for_this_command}` và `{n_total_active}`.
348
+
342
349
  Nếu file không tồn tại → bỏ qua âm thầm (chưa có lesson nào được ghi nhận).
343
350
 
351
+ > **Vì sao lọc ở ĐÂY chứ không phải lúc dùng (GAPS-v3 G46):** bản cũ viết *"đọc và lưu **TẤT CẢ**
352
+ > lesson"* ở dòng trên, rồi *"đối chiếu với mọi lesson có `category` khớp"* ở dòng dưới. Bộ lọc
353
+ > **đã tồn tại** — chỉ là chạy **sau** khi đã nạp hết. Có 6 category, nên `/generate-prd` đang nạp
354
+ > cả đống lesson `code-gen` mà nó không bao giờ dùng tới. Chuyển bộ lọc lên trước là thay đổi thứ
355
+ > tự, không phải thêm logic.
356
+ >
357
+ > **Và vì sao chỉ nạp `active`:** trước G46 file lessons **chỉ có đường vào**. Một lesson viết năm
358
+ > ngoái cho code đã bị xoá vẫn được nạp làm ràng buộc cứng, mãi mãi. Cùng lớp lỗi với G28 — giữ
359
+ > một tín hiệu đã hết đúng. Đường ra: `/learn --review` (xem `capture-lesson.md` §Retire).
360
+ >
361
+ > ⚠️ **Không bao giờ tự bỏ lesson vì file quá dài.** Nạp thiếu một guardrail trong im lặng đúng là
362
+ > thứ framework này tồn tại để chống. Vượt ngưỡng thì **cảnh báo** ở recap, người quyết retire.
363
+
344
364
  ---
345
365
 
346
366
  ## Bước 7 — [RECAP] Working Memory Recap (chống lost-in-middle)
@@ -360,7 +380,8 @@ CLAUDE.md : {root + {service_root} | chỉ {service_root} | chỉ root | ⚠️
360
380
  Ticket : {ticket_prefix}-
361
381
  Dict : {loaded — N canonical terms, M banned terms | missing}
362
382
  Entities : {loaded — EntityA, EntityB, EntityC | missing}
363
- Lessons : {loaded — N guardrails | chưa có}
383
+ Lessons : {loaded — {n} active cho lệnh này ({tổng} tổng) | chưa có}
384
+ {⚠️ CHỈ IN khi tổng ≥ 40: "{tổng} guardrail đang hoạt động — /learn --review để rà"}
364
385
  Platform : {active_platform: system | web | app | — nếu chưa xác định}
365
386
  Service : {active_service} ({active_service_module}) [← domain{/platform}{/prd_slug} nếu route qua by_prd_slug] | multi (map-theo-platform hoặc map-theo-prd_slug, chốt khi target đủ platform/prd_slug) | single-service
366
387
  Svc Root : {service_root} — đã nạp conventions + trace_dir từ config service | —