kld-sdd 2.7.8-2 → 2.7.8-4

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 (41) hide show
  1. package/README.md +2 -0
  2. package/USABILITY.md +52 -0
  3. package/bin/kld-sdd-init.js +700 -34
  4. package/lib/command-bridge.js +26 -17
  5. package/lib/deploy-codebuddy-hooks.js +19 -26
  6. package/lib/deploy-strategy.js +293 -0
  7. package/lib/hook-gate-core.js +7 -8
  8. package/lib/hook-install.js +75 -0
  9. package/lib/init.js +450 -711
  10. package/lib/managed-hook-hashes.json +24 -0
  11. package/lib/settings-merge.js +102 -25
  12. package/lib/skills-bundle.js +2 -4
  13. package/lib/spec-choice.js +85 -0
  14. package/lib/tool-profiles.js +2 -2
  15. package/lib/uninstall.js +764 -0
  16. package/package.json +3 -3
  17. package/skywalk-sdd/index.cjs +1 -1
  18. package/skywalk-sdd/kb-upload.cjs +64 -49
  19. package/skywalk-sdd/lib/shared.cjs +62 -41
  20. package/skywalk-sdd/lib/test-execution.cjs +20 -0
  21. package/skywalk-sdd/lib/usage-reporter.cjs +17 -8
  22. package/skywalk-sdd/ontology/resolve-spec-root.cjs +49 -0
  23. package/skywalk-sdd/ontology/sdd-config.cjs +33 -5
  24. package/skywalk-sdd/ontology/spec-detect.cjs +421 -0
  25. package/skywalk-sdd/ontology/workspace-layout.cjs +46 -16
  26. package/templates/git-hooks/commit-msg +17 -99
  27. package/templates/git-hooks/commit-msg-runner.cjs +44 -0
  28. package/templates/git-hooks/commit-msg-sdd-trailer.cjs +60 -69
  29. package/templates/git-hooks/consistency-check-core.cjs +61 -240
  30. package/templates/git-hooks/delivery-check.cjs +231 -0
  31. package/templates/git-hooks/delivery-snapshot.cjs +181 -0
  32. package/templates/git-hooks/hooks.config +8 -6
  33. package/templates/git-hooks/pre-commit-consistency-check.cjs +13 -31
  34. package/templates/git-hooks/pre-push-consistency-check.cjs +36 -83
  35. package/templates/hooks/codebuddy/hooks/hook-gate-core.cjs +7 -8
  36. package/templates/openspec/proposal.md +1 -1
  37. package/templates/skills/kld-sdd/opsx-apply/SKILL.md +24 -22
  38. package/templates/skills/kld-sdd/opsx-consistency-check/SKILL.md +34 -112
  39. package/templates/skills/kld-sdd/opsx-consistency-check/scripts/scripts.cjs +15 -14
  40. package/templates/skills/kld-sdd/opsx-kb-config/SKILL.md +157 -11
  41. package/index.js +0 -13
@@ -1,19 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- /**
5
- * commit-msg hook,两种布局:
6
- *
7
- * - 多仓(代码仓有 .sdd.yaml,spec 是另一个 clone):
8
- * 写 Spec-Revision(spec 干净 HEAD 的完整 SHA)+ Spec-Change(活动 change,可多条)。
9
- * - 单仓(openspec 与代码同仓):
10
- * spec 与代码在同一次 commit 里,指针自指无意义 → 只写 Spec-Change,不写 Spec-Revision,
11
- * 且不做「spec 工作区干净」检查(提交进行中必然是脏的)。
12
- *
13
- * Spec-Change 来源:KLD_SDD_CHANGE(显式覆盖)> sdd.config.yaml active_changes。
14
- * Not from branch name, ever.
15
- *
16
- * Authority: 10-最小化多仓库关联与变更命名方案.md
4
+ /** Local provenance only. Explicit Change or exact reviewed index match; failures are advisory.
5
+ * Spec-Revision is written only for a clean, matching, separate Spec repository.
17
6
  */
18
7
 
19
8
  const fs = require('fs');
@@ -30,7 +19,7 @@ function resolveOntologyDir() {
30
19
  const ontologyDir = resolveOntologyDir();
31
20
  const changeKey = require(path.join(ontologyDir, 'change-key.cjs'));
32
21
  const sddConfig = require(path.join(ontologyDir, 'sdd-config.cjs'));
33
- const activeChanges = require(path.join(ontologyDir, 'active-changes.cjs'));
22
+ const snap = require('./delivery-snapshot.cjs');
34
23
  const { parseFrontmatter } = require(path.join(ontologyDir, 'artifact-parser.cjs'));
35
24
 
36
25
  function projectRootFromHook() {
@@ -40,8 +29,7 @@ function projectRootFromHook() {
40
29
  }
41
30
 
42
31
  function fail(message) {
43
- console.error(`[kld-sdd commit-msg] ${message}`);
44
- process.exit(1);
32
+ throw new Error(message);
45
33
  }
46
34
 
47
35
  function isSddLinkedCodeRepo(codeRepoRoot) {
@@ -67,9 +55,6 @@ function resolveLayout(repoRoot, env = process.env) {
67
55
  if (!context.specPath) {
68
56
  fail(context.message || '无法解析 spec clone 路径。请执行 kld-sdd link-spec --path=<spec>');
69
57
  }
70
- if (context.code === sddConfig.CODES.SPEC_PATH_INVALID) {
71
- fail(context.message);
72
- }
73
58
  // specPath 指回本仓根:等同单仓(兼容旧平铺);若指向仓内包裹包仍按 mono
74
59
  const resolvedSpec = path.resolve(context.specPath);
75
60
  const resolvedRoot = path.resolve(repoRoot);
@@ -79,6 +64,7 @@ function resolveLayout(repoRoot, env = process.env) {
79
64
  if (resolvedSpec.startsWith(`${resolvedRoot}${path.sep}`)) {
80
65
  return { mode: 'mono', specPath: resolvedSpec, context };
81
66
  }
67
+ if (context.code === sddConfig.CODES.SPEC_PATH_INVALID) fail(context.message);
82
68
  return { mode: 'multi', specPath: context.specPath, context };
83
69
  }
84
70
 
@@ -101,24 +87,42 @@ function parseEnvChangeKeys(env = process.env) {
101
87
  }
102
88
 
103
89
  /**
104
- * Spec-Change values: explicit env wins, otherwise every active change
105
- * registered in the spec repo's sdd.config.yaml.
90
+ * Spec-Change values: explicit env wins, otherwise an exact reviewed index match.
106
91
  */
107
- function resolveChangeKeys(specRoot, env = process.env) {
92
+ function resolveChangeKeys(specRoot, env = process.env, repoRoot = projectRootFromHook()) {
108
93
  const fromEnv = parseEnvChangeKeys(env);
109
94
  if (fromEnv) {
110
- for (const key of fromEnv) {
111
- requireChangeDir(specRoot, key, { strict: true });
112
- }
95
+ for (const key of fromEnv) requireChangeDir(specRoot, key, { strict: true });
113
96
  return { keys: fromEnv, source: 'env' };
114
97
  }
115
- const registered = activeChanges.activeChangeKeys(specRoot);
116
- const keys = registered.filter((key) => requireChangeDir(specRoot, key, { strict: false }));
117
- return { keys, source: 'sdd.config.yaml' };
98
+ // The active registry describes ongoing work, not the ownership of this commit.
99
+ const identity = snap.repoIdentity(repoRoot);
100
+ const file = path.join(specRoot, 'skywalk-sdd/state/delivery-associations', `${snap.digest(identity)}.json`);
101
+ if (!fs.existsSync(file)) return { keys: [], source: 'pending' };
102
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
103
+ const staged = snap.git(repoRoot, ['diff', '--cached', '--name-only', '--no-renames', '-z']).split('\0').filter(Boolean);
104
+ if (!staged.length || staged.length > 200 || saved.repository !== identity) return { keys: [], source: 'pending' };
105
+ const knownFiles = new Set(Object.values(saved.changes || {}).flatMap(item => (item.coveredFiles || []).map(f => f.path)));
106
+ if (staged.some(file => !knownFiles.has(file))) return { keys: [], source: 'pending' };
107
+ const candidates = [];
108
+ const entries = snap.entriesAt(repoRoot, 'index').filter(e => staged.includes(e.path));
109
+ const blobs = snap.readBlobs(repoRoot, entries);
110
+ for (const [key, association] of Object.entries(saved.changes || {})) {
111
+ const covered = new Map((association.coveredFiles || []).map(f => [f.path, f]));
112
+ if (staged.every(file => {
113
+ const meta = covered.get(file);
114
+ if (!meta) return false;
115
+ if (meta.deleted) return !entries.some(e => e.path === file);
116
+ const content = blobs.get(file);
117
+ return content && snap.fileMeta(file, content, meta.mode).sha256 === meta.sha256 && entries.find(e => e.path === file)?.mode === meta.mode;
118
+ }) && requireChangeDir(specRoot, key, { strict: false })) candidates.push(key);
119
+ }
120
+ // Multiple matching reviews are ambiguous too; explicit selection supports multi-change commits.
121
+ return { keys: candidates.length === 1 ? candidates : [], source: candidates.length === 1 ? 'review' : 'pending' };
118
122
  }
119
123
 
120
124
  /**
121
- * @param {{ strict: boolean }} options strict=true 阻断提交;false 仅警告并跳过该条
125
+ * @param {{ strict: boolean }} options strict=true 抛出关联错误;false 仅警告并跳过该条(外层均允许保存)
122
126
  */
123
127
  function requireChangeDir(specRoot, key, options = { strict: true }) {
124
128
  const proposalPath = path.join(specRoot, 'openspec', 'changes', key, 'proposal.md');
@@ -181,52 +185,39 @@ function resolveMsgFile(argv = process.argv) {
181
185
 
182
186
  function main(env = process.env) {
183
187
  const msgFile = resolveMsgFile();
184
- if (!msgFile) {
185
- fail('缺少 commit message 文件参数');
186
- }
187
-
188
+ if (!msgFile) fail('缺少 commit message 文件参数');
188
189
  const repoRoot = projectRootFromHook();
189
- const layout = resolveLayout(repoRoot, env);
190
-
191
- // 未接入 SDD 的普通代码仓:不写 Trailer
192
- if (layout.mode === 'unlinked') {
193
- process.exit(0);
194
- }
195
-
196
- const trailers = {
197
- // 多个活动 change 时写多条 Spec-Change
198
- 'Spec-Change': resolveChangeKeys(layout.specPath, env).keys,
199
- };
200
-
201
- if (layout.mode === 'multi') {
202
- const context = layout.context;
203
- // remote mismatch:仍允许写本地 Revision(溯源本地快照);仅警告
204
- if (context.code === sddConfig.CODES.REMOTE_MISMATCH) {
205
- console.error(`[kld-sdd commit-msg] 警告: ${context.message}`);
206
- }
207
-
208
- if (!sddConfig.gitWorkingTreeClean(layout.specPath)) {
209
- fail('spec 工作区不干净。请先提交或暂存 spec 变更后再提交代码。');
210
- }
211
-
212
- const revision = sddConfig.gitHeadSha(layout.specPath);
213
- if (!revision || revision.length < 40) {
214
- fail(`无法读取完整 Spec-Revision(需要完整 SHA): ${revision}`);
190
+ // Keep only the index context for the code repo (git commit -a uses a temporary index).
191
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES']) delete process.env[key];
192
+ const original = fs.readFileSync(msgFile, 'utf8');
193
+ let trailers = { 'Spec-Change': [], 'Spec-Revision': [] };
194
+ try {
195
+ const layout = resolveLayout(repoRoot, env);
196
+ if (layout.mode === 'unlinked') return;
197
+ const association = resolveChangeKeys(layout.specPath, env, repoRoot);
198
+ trailers['Spec-Change'] = association.keys;
199
+ if (!association.keys.length) console.error('[SDD] 本次提交的 Change 待关联;未从活动列表猜测归属');
200
+ if (layout.mode === 'multi' && association.keys.length) {
201
+ if (layout.context.code === sddConfig.CODES.REMOTE_MISMATCH) fail(layout.context.message);
202
+ if (!layout.context.sddYaml?.ok || !layout.context.specRemote || !sddConfig.remotesMatch(layout.context.sddYaml.spec_repository, layout.context.specRemote)) fail('Spec 来源仓库尚未确认,不能写入精确 Revision');
203
+ const dirty = snap.git(layout.specPath, ['status', '--porcelain', '--untracked-files=normal']).trim();
204
+ if (dirty) console.error('[SDD] Spec 尚有未提交内容,Spec-Revision 待绑定;本次提交继续');
205
+ else {
206
+ const revision = snap.git(layout.specPath, ['rev-parse', '--verify', 'HEAD']).trim();
207
+ if (!/^[a-f0-9]{40}$|^[a-f0-9]{64}$/.test(revision)) fail('无法读取完整 Spec-Revision');
208
+ trailers['Spec-Revision'] = revision;
209
+ }
215
210
  }
216
- trailers['Spec-Revision'] = revision;
211
+ } catch (error) {
212
+ trailers = { 'Spec-Change': [], 'Spec-Revision': [] };
213
+ console.error(`[SDD] 关联待补充:${error.message};本次提交继续`);
217
214
  }
218
-
219
- const original = fs.readFileSync(msgFile, 'utf8');
220
- const updated = upsertTrailers(original, trailers);
221
- fs.writeFileSync(msgFile, updated, 'utf8');
215
+ fs.writeFileSync(msgFile, upsertTrailers(original, trailers), 'utf8');
222
216
  }
223
217
 
224
218
  if (require.main === module) {
225
- try {
226
- main();
227
- } catch (error) {
228
- fail(error.message || String(error));
229
- }
219
+ try { main(); }
220
+ catch (error) { console.error(`[SDD] 关联待补充:${error.message};本次提交继续`); }
230
221
  }
231
222
 
232
223
  module.exports = {
@@ -1,26 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- /**
5
- * consistency-check-core.cjs
6
- *
7
- * pre-commit / pre-push 一致性校验 hook 的共享核心(非独立插件,不在 hooks.config 中登记)。
8
- * 两个入口脚本通过 require 引用本模块,注入各自差异配置:
9
- * - diff 采集方式(pre-commit: git diff HEAD;pre-push: 待推送范围 @{push}..HEAD)
10
- * - 是否检查置信度(pre-commit 检查;pre-push 轻量跳过)
11
- * - strict 模式(仅 pre-commit 支持 SDD_STRICT_CONSISTENCY)
12
- * - 过期比对来源(pre-commit: 工作区内容;pre-push: HEAD 已提交内容,staleFromHead)
13
- * - 提示文案(提交 / 推送)
14
- *
15
- * 核心行为(简化版):
16
- * - diff 驱动:仅检查 diff 文件与报告 coveredFiles 有交集的 change,无关 change 跳过
17
- * - 多仓归属过滤:报告 repositories 已声明覆盖仓库且不含当前仓的 change 静默跳过(不输出、不拦截)
18
- * - 纯注释/空行/空格变更过滤:diff 中所有变更行均为注释/空行/空格的文件直接跳过,不参与校验
19
- * - 报告存在性:活跃 change 无报告 → 阻止
20
- * - 报告过期:diff 业务代码与 coveredFiles 交集文件内容变化(size 短路 + SHA-256)→ 阻止
21
- * - 置信度门禁(仅 pre-commit):low → 阻止;strict 时 medium 也阻止
22
- * - 无活跃 change 但 diff 有业务代码 → 阻止(提示先执行 opsx-propose)
23
- * - 变更范围采集失败 → 阻止(避免静默放行的 fail-open)
4
+ /** Shared collection utilities and the optional strict index entry.
5
+ * Delivery readiness uses delivery-check.cjs receipts with complete input fingerprints.
6
+ * Legacy JSON parsing helpers remain available for readers; old confidence-only reports
7
+ * cannot satisfy the strict entry. Daily commit/push do not call this module by default.
24
8
  */
25
9
 
26
10
  const fs = require('fs');
@@ -105,7 +89,7 @@ function parseReport(reportPath) {
105
89
  : raw;
106
90
  const t = new Date(normalized.replace(/-/g, '/')).getTime();
107
91
  if (!isNaN(t)) {
108
- generatedAtMs = t + 1000;
92
+ generatedAtMs = t;
109
93
  } else {
110
94
  generatedAtFormatError = `generatedAt 无法解析(实际: ${raw},应为 YYYY-MM-DD HH:mm:ss 本地时间)`;
111
95
  }
@@ -417,8 +401,7 @@ function getModifiedFiles(projectRoot, diffFn, options = {}) {
417
401
  /**
418
402
  * 解析 INI 风格的 [consistency] 段,返回段内所有 key=value。
419
403
  */
420
- function parseConsistencySection() {
421
- const configPath = path.join(__dirname, 'hooks.config');
404
+ function parseConsistencySection(configPath = path.join(__dirname, 'hooks.config')) {
422
405
  const values = {};
423
406
  try {
424
407
  const content = fs.readFileSync(configPath, 'utf8');
@@ -448,8 +431,8 @@ const CONSISTENCY_CONFIG = parseConsistencySection();
448
431
  * 业务代码扩展名白名单(business_code_exts,唯一来源为 hooks.config,无内置默认值)。
449
432
  * @returns {{exts: Set<string>, source: 'config'|'missing'|'empty', configPath: string|null}}
450
433
  */
451
- function loadBusinessCodeExts() {
452
- const { configPath, values } = CONSISTENCY_CONFIG;
434
+ function loadBusinessCodeExts(file) {
435
+ const { configPath, values } = file ? parseConsistencySection(file) : CONSISTENCY_CONFIG;
453
436
  const rawValue = Object.prototype.hasOwnProperty.call(values, 'business_code_exts')
454
437
  ? values.business_code_exts : null;
455
438
 
@@ -490,14 +473,14 @@ const CONSISTENCY_MODE = loadConsistencyMode();
490
473
  const TOOLCHAIN_CONFIG_RE = /^(?:vite|vitest|next|nuxt|astro|svelte|remix|webpack|rollup|babel|jest|playwright|cypress|eslint|prettier|tailwind|postcss|karma|wrangler|nest-cli|angular|vue|craco|rspack|metro|tsconfig|jsconfig|turbo|nx)\.(?:config|conf)\.[a-z]+$/i;
491
474
  const DOTFILE_CONFIG_RE = /^\.?(?:eslintrc|babelrc|prettierrc|stylelintrc)\.[a-z]+$/i;
492
475
 
493
- function isBusinessCode(file) {
476
+ function isBusinessCode(file, exts = BUSINESS_CODE_EXTS) {
494
477
  const normalized = String(file).replace(/\\/g, '/');
495
478
  const base = normalized.split('/').pop() || '';
496
479
 
497
480
  const dot = base.lastIndexOf('.');
498
481
  if (dot < 0) return false;
499
482
  const ext = base.slice(dot).toLowerCase();
500
- if (!BUSINESS_CODE_EXTS.has(ext)) return false;
483
+ if (!(exts instanceof Set ? exts : BUSINESS_CODE_EXTS).has(ext)) return false;
501
484
 
502
485
  if (/\.d\.tsx?$/i.test(base)) return false;
503
486
  if (/(^|\/)(dist|build|target|out|node_modules)\//.test(normalized)) return false;
@@ -634,25 +617,12 @@ function normalizeEolLf(buf) {
634
617
  return Buffer.from(str.replace(/\r\n/g, '\n'), 'binary');
635
618
  }
636
619
 
637
- /**
638
- * 单文件过期判断(mtime 快速跳过 + size 短路 + SHA-256,行尾归一化)。
639
- * mtime 快速路径:文件修改时间早于报告生成时间 → 报告生成后从未被碰过 → 内容必然未变,
640
- * 跳过读取和哈希(大变更场景省 100-300ms/百文件)。mtime 晚于报告时间才做精确哈希判断,
641
- * 因此 git pull/checkout 重置 mtime(内容未变)只会多算一次哈希,不会误判过期。
642
- */
620
+ /** 内容哈希是有效性依据,mtime 不参与正确性判断。 */
643
621
  function isFileChangedOnDisk(fp, metas, reportTime, readContent = readWorkingFile, relFile = '') {
644
622
  const list = Array.isArray(metas) ? metas : (metas ? [metas] : []);
645
623
  const hashed = list.filter(m => m && m.sha256);
646
624
 
647
625
  if (hashed.length) {
648
- // mtime 快速跳过:仅在能拿到本地文件时(readContent 为工作区读取)且 mtime 可信时启用
649
- if (readContent === readWorkingFile) {
650
- try {
651
- if (fs.statSync(fp).mtimeMs <= reportTime) return false;
652
- } catch {
653
- return true; // 文件不存在 → 过期
654
- }
655
- }
656
626
  const content = readContent(fp, relFile);
657
627
  if (content === null) return true;
658
628
  const normalized = normalizeEolLf(content);
@@ -663,14 +633,8 @@ function isFileChangedOnDisk(fp, metas, reportTime, readContent = readWorkingFil
663
633
  return !candidates.some(m => hash === String(m.sha256).toLowerCase());
664
634
  }
665
635
 
666
- // 无哈希条目:mtime 比较
667
- let stat;
668
- try {
669
- stat = fs.statSync(fp);
670
- } catch {
671
- return true;
672
- }
673
- return stat.mtimeMs > reportTime;
636
+ // mtime cannot prove content equality. Legacy entries without hashes need review.
637
+ return true;
674
638
  }
675
639
 
676
640
  /**
@@ -773,205 +737,62 @@ function generateInstructions(opts, result, warnOnly) {
773
737
  * @param {object} opts 入口差异配置
774
738
  */
775
739
  function runConsistencyCheck(opts) {
776
- const {
777
- label, actionNoun, diffFn,
778
- checkConfidence = false, includeUntracked = true,
779
- staleFromHead = false,
780
- } = opts;
740
+ const { label, actionNoun, diffFn, includeUntracked = false, staleFromHead = false, staleFromIndex = false } = opts;
781
741
  const projectRoot = path.resolve(readArg('project') || process.env.SDD_PROJECT || process.cwd());
782
-
783
- // 模式解析
784
- const envSkip = process.env.SDD_SKIP_CONSISTENCY_CHECK;
785
- const envStrict = process.env.SDD_STRICT_CONSISTENCY;
786
- const envWarnOnly = process.env.SDD_WARN_ONLY;
787
- const skip = envSkip !== undefined ? envSkip === '1' : CONSISTENCY_MODE.skip;
788
- const strict = envStrict !== undefined ? envStrict === '1' : CONSISTENCY_MODE.strict;
789
- const warnOnly = envWarnOnly !== undefined ? envWarnOnly === '1' : CONSISTENCY_MODE.warnOnly;
790
-
791
- // 互斥检查
792
- const activeModes = [skip, strict, warnOnly].filter(Boolean).length;
793
- if (activeModes > 1) {
794
- const names = [
795
- ...(skip ? ['SDD_SKIP_CONSISTENCY_CHECK' + (envSkip === undefined ? '(hooks.config)' : '')] : []),
796
- ...(strict ? ['SDD_STRICT_CONSISTENCY' + (envStrict === undefined ? '(hooks.config)' : '')] : []),
797
- ...(warnOnly ? ['SDD_WARN_ONLY' + (envWarnOnly === undefined ? '(hooks.config)' : '')] : []),
798
- ];
799
- console.error(`${label} 错误:${names.join('、')} 互斥,只能启用一个`);
800
- process.exit(1);
801
- }
802
-
803
- if (skip) {
804
- console.log(`${label} 跳过校验`);
805
- process.exit(0);
806
- }
807
-
808
- if (warnOnly) console.log(`${label} 仅告警模式`);
809
-
810
- // 配置缺失/空清单显式告警
811
- if (BUSINESS_CODE_EXTS_INFO.source !== 'config') {
812
- const reason = BUSINESS_CODE_EXTS_INFO.source === 'missing'
813
- ? '未配置 business_code_exts(hooks.config 缺失或无 [consistency] 段)'
814
- : 'business_code_exts 为空清单';
815
- console.warn(`${label} ⚠️ ${reason},一致性校验不拦截任何业务代码文件(仅保留报告存在性/过期检查)`);
816
- console.warn(`${label} ℹ️ 请在 ${BUSINESS_CODE_EXTS_INFO.configPath || path.join(__dirname, 'hooks.config')} 的 [consistency] 段配置 business_code_exts`);
817
- }
818
-
819
- const specRoot = resolveSpecRoot();
820
-
821
- // 1. 采集 diff 文件
822
- const { files: modifiedFiles, deleted: deletedFiles, failed: diffFailed } =
823
- getModifiedFiles(projectRoot, diffFn, { includeUntracked });
824
-
825
- if (diffFailed) {
826
- console.log(`${label} ❌ 无法确定本次${actionNoun}的变更范围(git diff 采集失败),拒绝${actionNoun}`);
827
- if (warnOnly) {
828
- console.log(`${label} 仅告警模式,放行${actionNoun}`);
829
- process.exit(0);
830
- }
742
+ const mode = loadConsistencyMode();
743
+ const skip = process.env.SDD_SKIP_CONSISTENCY_CHECK === undefined ? mode.skip : process.env.SDD_SKIP_CONSISTENCY_CHECK === '1';
744
+ const strict = process.env.SDD_STRICT_CONSISTENCY === undefined ? mode.strict : process.env.SDD_STRICT_CONSISTENCY === '1';
745
+ const warnOnly = process.env.SDD_WARN_ONLY === undefined ? mode.warnOnly : process.env.SDD_WARN_ONLY === '1';
746
+ if ([skip, strict, warnOnly].filter(Boolean).length > 1) {
747
+ console.error(`${label} skip / strict / warn_only 互斥`);
831
748
  process.exit(1);
832
749
  }
833
-
834
- // 2. 筛选业务代码文件
835
- const diffBusinessFiles = modifiedFiles.filter(isBusinessCode);
836
- const deletedBusinessFiles = deletedFiles.filter(isBusinessCode);
837
-
838
- // 3. 无业务代码文件 → 放行
839
- if (diffBusinessFiles.length === 0 && deletedBusinessFiles.length === 0) {
750
+ if (skip) { console.log(`${label} 跳过校验`); process.exit(0); }
751
+ const problems = [];
752
+ const { files, deleted, failed } = getModifiedFiles(projectRoot, diffFn, { includeUntracked });
753
+ if (failed) problems.push('无法确定变更范围');
754
+ if (BUSINESS_CODE_EXTS_INFO.source !== 'config') problems.push('business_code_exts 未配置,不能证明检查完整');
755
+ const required = [...new Set([...files, ...deleted])].filter(isBusinessCode);
756
+ if (!problems.length && !required.length) {
840
757
  console.log(`${label} 本次${actionNoun}无业务代码文件,跳过一致性校验`);
841
758
  process.exit(0);
842
759
  }
843
-
844
- // 4. 活跃 change 发现
845
- const changes = discoverActiveChanges(specRoot);
846
- if (!changes.length) {
847
- console.log([
848
- '', '==========================================',
849
- `${label} 存在业务代码变更但无活跃 change 可归属,拒绝${actionNoun}:`,
850
- '',
851
- ' 请先执行 opsx-propose 创建变更(登记到 sdd.config.yaml 的 active_changes),',
852
- ' 再执行 opsx-consistency-check 生成一致性报告。',
853
- '==========================================', '',
854
- ].join('\n'));
855
- if (warnOnly) {
856
- console.log(`${label} 仅告警模式,放行${actionNoun}`);
857
- process.exit(0);
858
- }
859
- process.exit(1);
860
- }
861
-
862
- // 5. 逐 change 解析报告
863
- const parseError = [];
864
- const invalid = [];
865
- const lowConfidence = [];
866
- const stale = [];
867
- const missing = [];
868
- const parsedReports = new Map();
869
-
870
- // 当前代码仓目录名(多仓布局下用于报告归属过滤 + normalizeCoveredFiles 兜底前缀剥离)
871
- const currentRepoName = path.basename(projectRoot).toLowerCase();
872
-
873
- for (const cn of changes) {
874
- const rp = findReportJson(specRoot, cn);
875
- if (!rp) {
876
- missing.push(cn);
877
- continue;
878
- }
879
-
880
- const report = parseReport(rp);
881
- if (report.parseError) {
882
- console.warn(`${label} ⚠️ ${cn} 报告解析失败`);
883
- parseError.push(cn);
884
- continue;
885
- }
886
-
887
- // 旧格式报告(无 coveredFiles)
888
- if (!report.coveredFiles) {
889
- console.log(`${label} ⚠️ ${cn}: 报告为旧格式(缺少 coveredFiles),建议重新生成`);
890
- missing.push(cn);
891
- continue;
892
- }
893
-
894
- // 字段合法性校验(仅 confidence + generatedAt)
895
- const fieldErrors = validateReportFields(report);
896
- if (fieldErrors.length) {
897
- console.warn(`${label} ⚠️ ${cn} 报告字段不合法:${fieldErrors.join(';')}`);
898
- invalid.push({ cn, errors: fieldErrors });
899
- continue;
900
- }
901
-
902
- const covered = normalizeCoveredFiles(report, currentRepoName);
903
- parsedReports.set(cn, { report, covered });
904
- }
905
-
906
- // 6. 对 diff(含删除)与 coveredFiles 有交集的 change 检查报告
907
- const checkFiles = [...new Set([...diffBusinessFiles, ...deletedBusinessFiles])];
908
- const checkFilesLower = checkFiles.map(f => f.toLowerCase());
909
-
910
- let headContentCache = null;
911
- const readContent = staleFromHead
912
- ? (fp, relFile) => {
913
- if (headContentCache === null) {
914
- headContentCache = gitShowHeadContentBatch(projectRoot, checkFiles);
915
- }
916
- const fromHead = headContentCache.get(relFile);
917
- return fromHead !== undefined && fromHead !== null ? fromHead : readWorkingFile(fp);
918
- }
919
- : readWorkingFile;
920
-
921
- for (const [cn, { report, covered }] of parsedReports) {
922
- // 多仓归属过滤:报告显式声明了覆盖仓库且不含当前仓 → 与本仓无关,静默跳过
923
- // (repositories 为空视为未声明,保持原交集判断行为,兼容单仓与旧报告)
924
- const declaredRepos = (report.repositories || [])
925
- .map(r => String(r && r.path || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase())
926
- .filter(Boolean);
927
- if (declaredRepos.length && !declaredRepos.includes(currentRepoName)) {
928
- continue;
929
- }
930
-
931
- const hasIntersection = checkFilesLower.some(f => covered.has(f));
932
- if (!hasIntersection) {
933
- console.log(`${label} ⏭️ ${cn}: 与本次${actionNoun}无交集,跳过`);
934
- continue;
935
- }
936
-
937
- if (isReportStale(report, covered, checkFiles, projectRoot, readContent)) {
938
- console.log(`${label} ⚠️ ${cn}: 报告已过期`);
939
- stale.push(cn);
940
- continue;
941
- }
942
-
943
- if (checkConfidence) {
944
- const c = report.confidence;
945
- if (c === 'low' || (c === 'medium' && strict)) {
946
- console.log(`${label} ❌ ${cn}: 置信度 ${c}`);
947
- lowConfidence.push(cn);
760
+ const delivery = require('./delivery-check.cjs');
761
+ const snap = require('./delivery-snapshot.cjs');
762
+ const specRoot = resolveSpecRoot();
763
+ const explicit = String(readArg('change') || process.env.KLD_SDD_CHANGE || '').split(/[,\s]+/).filter(Boolean);
764
+ const changes = explicit.length ? explicit : discoverActiveChanges(specRoot);
765
+ const covered = new Set();
766
+ for (const change of changes) {
767
+ try {
768
+ const identity = snap.repoIdentity(projectRoot);
769
+ const rp = delivery.reviewPath({ specRoot, change, identity });
770
+ if (!fs.existsSync(rp)) {
771
+ // Unrelated active changes do not require a report for this commit.
772
+ if (explicit.includes(change)) problems.push(`${change}: 缺少一致性检查回执,请运行 opsx-consistency-check`);
948
773
  continue;
949
774
  }
950
- console.log(`${label} ✅ ${cn}: 置信度 ${c}`);
951
- } else {
952
- console.log(`${label} ✅ ${cn}: 报告有效`);
953
- }
954
- }
955
-
956
- const result = {
957
- missing, parseError, invalid, lowConfidence, stale,
958
- };
959
-
960
- const hasBlocking = missing.length || parseError.length || invalid.length || lowConfidence.length
961
- || stale.length;
962
-
963
- if (hasBlocking) {
964
- console.log(generateInstructions(opts, result, warnOnly));
965
-
966
- if (warnOnly) {
967
- console.log(`${label} 仅告警模式,放行${actionNoun}`);
968
- process.exit(0);
969
- }
970
-
971
- process.exit(1);
972
- }
973
-
974
- console.log(`\n${label} ✅ 本次${actionNoun}涉及的业务代码均已通过一致性校验,放行${actionNoun}`);
775
+ const report = JSON.parse(fs.readFileSync(rp, 'utf8'));
776
+ if (!explicit.includes(change) && !required.some(f => (report.reviewedFiles || []).includes(f))) continue;
777
+ const ctx = delivery.context({ project: projectRoot, 'spec-root': specRoot, change,
778
+ scope: staleFromHead ? 'commit' : staleFromIndex ? 'index' : 'worktree',
779
+ base: opts.base || report.base, ref: opts.ref || 'HEAD', 'spec-ref': opts.specRef });
780
+ // This report need only cover its own files; union coverage is asserted below.
781
+ ctx.required = required.filter(f => (report.reviewedFiles || []).includes(f));
782
+ const errors = delivery.reviewErrors(ctx, report);
783
+ if (errors.length) problems.push(`${change}: 报告过期或未完成:${errors.join(';')}`);
784
+ else for (const file of ctx.required) covered.add(file);
785
+ } catch (error) { problems.push(`${change}: ${error.message}`); }
786
+ }
787
+ const uncovered = required.filter(file => !covered.has(file));
788
+ if (uncovered.length) problems.push(`缺少有效检查覆盖(UNCOVERED_FILES):${uncovered.join(', ')}`);
789
+ if (problems.length) {
790
+ console.log(`${label} 未通过:\n${problems.map(p => ` - ${p}`).join('\n')}`);
791
+ console.log('请由 opsx-consistency-check 更新回执;日常提交默认不运行此严格入口。');
792
+ if (warnOnly) console.log(`${label} 仅告警模式,放行${actionNoun}(不代表已通过检查)`);
793
+ process.exit(warnOnly ? 0 : 1);
794
+ }
795
+ console.log(`${label} 本次${actionNoun}涉及的业务代码均已通过一致性校验`);
975
796
  process.exit(0);
976
797
  }
977
798