universal-dev-standards 6.14.0-beta.4 → 6.14.0-beta.6

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 (56) hide show
  1. package/bin/uds.js +9 -2
  2. package/bundled/ai/standards/commit-message.ai.yaml +6 -2
  3. package/bundled/ai/standards/full-coverage-testing.ai.yaml +46 -5
  4. package/bundled/core/full-coverage-testing.md +57 -3
  5. package/bundled/locales/zh-CN/CHANGELOG.md +54 -3
  6. package/bundled/locales/zh-CN/README.md +1 -1
  7. package/bundled/locales/zh-CN/SECURITY.md +1 -1
  8. package/bundled/locales/zh-CN/core/full-coverage-testing.md +61 -7
  9. package/bundled/locales/zh-CN/docs/CHEATSHEET.md +4 -2
  10. package/bundled/locales/zh-CN/docs/FEATURE-REFERENCE.md +10 -6
  11. package/bundled/locales/zh-TW/CHANGELOG.md +54 -3
  12. package/bundled/locales/zh-TW/README.md +1 -1
  13. package/bundled/locales/zh-TW/SECURITY.md +1 -1
  14. package/bundled/locales/zh-TW/core/full-coverage-testing.md +61 -7
  15. package/bundled/locales/zh-TW/docs/CHEATSHEET.md +4 -2
  16. package/bundled/locales/zh-TW/docs/FEATURE-REFERENCE.md +10 -6
  17. package/bundled/templates/gates/check-anti-fake-tests.mjs +991 -0
  18. package/bundled/templates/gates/check-stubs.mjs +644 -0
  19. package/package.json +2 -2
  20. package/src/commands/audit.js +11 -0
  21. package/src/commands/check.js +124 -24
  22. package/src/commands/deps.js +31 -1
  23. package/src/commands/init.js +16 -0
  24. package/src/commands/simulate.js +20 -8
  25. package/src/commands/skills.js +42 -2
  26. package/src/commands/spec.js +14 -8
  27. package/src/commands/update.js +222 -21
  28. package/src/core/install-records.js +2 -1
  29. package/src/core/manifest.js +12 -10
  30. package/src/core/marketplace-sentinel.js +5 -0
  31. package/src/core/project-config.js +58 -38
  32. package/src/i18n/messages.js +77 -9
  33. package/src/reconciler/backup-locations.js +75 -0
  34. package/src/reconciler/backup-manager.js +435 -115
  35. package/src/reconciler/index.js +44 -5
  36. package/src/reconciler/install-roots.js +90 -0
  37. package/src/reconciler/plan-executor.js +23 -2
  38. package/src/uninstallers/hook-uninstaller.js +2 -1
  39. package/src/utils/command-hash-ownership.js +103 -0
  40. package/src/utils/commit-message-judge.js +137 -0
  41. package/src/utils/copier.js +21 -1
  42. package/src/utils/deps-applicability.js +25 -0
  43. package/src/utils/gate-scripts.js +141 -0
  44. package/src/utils/health-scorer.js +10 -7
  45. package/src/utils/installed-names-ownership.js +114 -0
  46. package/src/utils/sdd-header.js +65 -0
  47. package/src/utils/skill-hash-ownership.js +64 -0
  48. package/src/utils/skills-installer.js +12 -1
  49. package/src/utils/standard-validator.js +98 -27
  50. package/src/utils/test-change-check.js +160 -0
  51. package/src/utils/test-policy.js +214 -0
  52. package/src/utils/update-summary.js +29 -0
  53. package/src/vibe/micro-spec.js +15 -0
  54. package/standards-registry.json +7 -7
  55. package/bundled/extensions/languages/php/fat-free-patterns.md +0 -915
  56. package/bundled/extensions/languages/php/php-style.md +0 -693
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The two scanners UDS ships into an adopter's project, and the code that runs them.
3
+ * // implements XSPEC-444 R5
4
+ *
5
+ * `full-coverage-testing` has always told adopters to "add scripts/check-stubs.sh and
6
+ * scripts/check-anti-fake-tests.sh", and its validator checked that those files EXIST —
7
+ * but UDS shipped neither, so the instruction could not be followed and the check could
8
+ * only ever say "missing". This is the missing half:
9
+ *
10
+ * installGateScripts() `uds init` writes the two scanners (templates/gates/*.mjs) to
11
+ * `<project>/scripts/`, records them for `uds uninstall`, and never
12
+ * overwrites a file that is already there.
13
+ * runTestQualityGates() `uds check` (what the pre-commit hook runs) executes the ones that
14
+ * are installed and prints what they found as a WARNING. It does not
15
+ * change the exit code unless the adopter set `"mode": "block"`.
16
+ *
17
+ * Why the scanners are written into the project instead of run from the CLI: they are the
18
+ * adopter's to read, edit and wire into CI (`node scripts/check-stubs.mjs` is a hard gate on
19
+ * its own), and a standard that says "this file must exist" is only honest if the file does.
20
+ */
21
+
22
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
23
+ import { dirname, join } from 'path';
24
+ import { spawnSync } from 'child_process';
25
+ import chalk from 'chalk';
26
+ import { getRepoRoot } from './copier.js';
27
+ import { newRecorder, mkdirTracked, recordFile, RECORD_KINDS } from '../core/install-records.js';
28
+ import { loadPolicy } from './test-policy.js';
29
+ import { readStagedChanges } from './test-change-check.js';
30
+
31
+ /** The standard that asks for these scripts; they are only written when it is installed. */
32
+ export const GATE_STANDARD_FILE = 'full-coverage-testing.ai.yaml';
33
+
34
+ export const GATE_SCRIPTS = Object.freeze([
35
+ { file: 'check-anti-fake-tests.mjs', label: 'anti-fake-test', what: 'tests that cannot fail' },
36
+ { file: 'check-stubs.mjs', label: 'stub', what: 'placeholders and empty shells' }
37
+ ]);
38
+
39
+ const templatePath = (file) => join(getRepoRoot(), 'templates', 'gates', file);
40
+ const destRel = (file) => `scripts/${file}`;
41
+
42
+ export function gateStandardInstalled(projectPath) {
43
+ return existsSync(join(projectPath, '.standards', GATE_STANDARD_FILE));
44
+ }
45
+
46
+ /**
47
+ * Write the scanners into `<project>/scripts/`. Never overwrites: a file that exists is the
48
+ * adopter's (they may have edited it), and is reported as kept.
49
+ * @param {string} projectPath
50
+ * @param {object} recorder an install-records recorder (see core/install-records.js)
51
+ * @returns {{ written: string[], kept: string[], missingTemplate: string[], skipped?: string }}
52
+ */
53
+ export function installGateScripts(projectPath, recorder = newRecorder()) {
54
+ const result = { written: [], kept: [], missingTemplate: [] };
55
+ if (!gateStandardInstalled(projectPath)) {
56
+ result.skipped = `${GATE_STANDARD_FILE} is not installed in this project`;
57
+ return result;
58
+ }
59
+ for (const { file } of GATE_SCRIPTS) {
60
+ const rel = destRel(file);
61
+ const dest = join(projectPath, rel);
62
+ if (existsSync(dest)) { result.kept.push(rel); continue; }
63
+ const src = templatePath(file);
64
+ if (!existsSync(src)) { result.missingTemplate.push(file); continue; }
65
+ mkdirTracked(recorder, projectPath, dirname(dest));
66
+ writeFileSync(dest, readFileSync(src, 'utf-8'), 'utf-8');
67
+ recordFile(recorder, projectPath, rel, RECORD_KINDS.GATE_SCRIPT);
68
+ result.written.push(rel);
69
+ }
70
+ return result;
71
+ }
72
+
73
+ const MAX_SHOWN = 12;
74
+
75
+ /**
76
+ * Run the installed scanners and print the outcome. Never throws.
77
+ * @param {string} projectPath
78
+ * @param {{ staged?: boolean, mode?: 'warn'|'block', log?: Function }} [opts]
79
+ * staged — scan only the files staged for commit (what a pre-commit run wants);
80
+ * otherwise the whole project (a CI or manual run). Default: staged when
81
+ * something is staged, whole project when nothing is.
82
+ * @returns {{ ran: string[], findings: Record<string, number>, couldNotJudge: string[], blocked: boolean, missing: string[] }}
83
+ */
84
+ export function runTestQualityGates(projectPath, { staged, mode, log = console.log } = {}) {
85
+ const result = { ran: [], findings: {}, couldNotJudge: [], blocked: false, missing: [] };
86
+ const effectiveMode = mode || loadPolicy(projectPath).policy.mode;
87
+ const blocking = effectiveMode === 'block';
88
+
89
+ if (!gateStandardInstalled(projectPath)) return result;
90
+ if (staged === undefined) {
91
+ const s = readStagedChanges(projectPath);
92
+ staged = Array.isArray(s.changes) && s.changes.length > 0;
93
+ }
94
+
95
+ for (const { file, label } of GATE_SCRIPTS) {
96
+ const rel = destRel(file);
97
+ const abs = join(projectPath, rel);
98
+ if (!existsSync(abs)) { result.missing.push(file); continue; }
99
+
100
+ const args = [abs, ...(staged ? ['--staged'] : [])];
101
+ const r = spawnSync(process.execPath, args, { cwd: projectPath, encoding: 'utf-8', timeout: 120000, maxBuffer: 32 * 1024 * 1024 });
102
+ result.ran.push(file);
103
+
104
+ if (r.status === 0) {
105
+ log(chalk.gray(` ✓ [${label}] ${rel}: nothing found${staged ? ' in the staged files' : ''}`));
106
+ // "Nothing found" must not hide what was NOT looked at: the script lists files it could not
107
+ // judge (a language it has no rule for, an unparsable call) on lines that start with `·`.
108
+ for (const l of (r.stdout || '').split('\n').filter((x) => /^\s*·/.test(x))) log((/NOT scanned|could not be parsed/.test(l) ? chalk.yellow : chalk.gray)(` ${l.trim()}`));
109
+ continue;
110
+ }
111
+ if (r.status === 1) {
112
+ const lines = (r.stdout || '').split('\n').filter((l) => l.trim());
113
+ const count = lines.filter((l) => /^\s*✗/.test(l)).length;
114
+ result.findings[label] = count;
115
+ const head = blocking
116
+ ? ` ✗ [${label}] BLOCKED: ${rel} found ${count} finding(s) (mode "block").`
117
+ : ` ⚠ [${label}] ${rel} found ${count} finding(s) — warning only, the commit is not blocked.`;
118
+ log(blocking ? chalk.red(head) : chalk.yellow(head));
119
+ const shown = lines.slice(0, MAX_SHOWN + 4);
120
+ for (const l of shown) log(chalk.gray(` ${l.trim()}`));
121
+ if (lines.length > shown.length) log(chalk.gray(` ... (run \`node ${rel}\` to see everything)`));
122
+ if (blocking) result.blocked = true;
123
+ continue;
124
+ }
125
+ // exit 2, a crash, a timeout, a missing node: the scanner could not judge. Never a pass.
126
+ const why = r.error ? r.error.message : (r.stderr || r.stdout || `exit ${r.status}`).split('\n').find((l) => l.trim()) || `exit ${r.status}`;
127
+ result.couldNotJudge.push(label);
128
+ const head = blocking
129
+ ? ` ✗ [${label}] BLOCKED: ${rel} could not judge (mode "block" treats that as a failure): ${why.trim()}`
130
+ : ` ⚠ [${label}] ${rel} could not judge — this is NOT a pass: ${why.trim()}`;
131
+ log(blocking ? chalk.red(head) : chalk.yellow(head));
132
+ if (blocking) result.blocked = true;
133
+ }
134
+
135
+ if (result.missing.length > 0) {
136
+ log(chalk.gray(` ℹ [test-gates] ${result.missing.map(destRel).join(', ')} not installed (the full-coverage-testing standard asks for them). \`uds update\` offers to install them.`));
137
+ }
138
+ if (result.blocked) process.exitCode = 1;
139
+ if (result.ran.length > 0 || result.missing.length > 0) log();
140
+ return result;
141
+ }
@@ -177,20 +177,26 @@ export function calculateConsistency(projectPath) {
177
177
  }
178
178
 
179
179
  /**
180
- * Calculate coverage score
180
+ * Calculate coverage score — how many of the two check scripts each installed standard can
181
+ * have (`scripts/check-<id>.sh`, `scripts/check-<id>-sync.sh`) are present.
182
+ *
183
+ * XSPEC-444 R5: this used to report `details.has_tests` and add it into the sum, but
184
+ * `hasTests` was declared as 0 and never incremented anywhere — a number that was always 0 and
185
+ * looked like a measurement of whether the standards have tests. It is removed rather than
186
+ * faked. The SCORE is unchanged: the denominator was already two per standard, which is the
187
+ * two script kinds above, so no project's coverage score moves.
181
188
  * @param {string} projectPath
182
189
  * @param {string[]} standardIds
183
190
  * @returns {{ score: number, details: object }}
184
191
  */
185
192
  export function calculateCoverage(projectPath, standardIds) {
186
193
  if (!standardIds || standardIds.length === 0) {
187
- return { score: 0, details: { has_check_script: 0, has_tests: 0, total: 0 } };
194
+ return { score: 0, details: { has_check_script: 0, total: 0 } };
188
195
  }
189
196
 
190
197
  // Check for check scripts matching standard names
191
198
  const scriptsDir = join(projectPath, 'scripts');
192
199
  let hasCheckScript = 0;
193
- let hasTests = 0;
194
200
 
195
201
  for (const id of standardIds) {
196
202
  const scriptName = `check-${id}.sh`;
@@ -204,16 +210,13 @@ export function calculateCoverage(projectPath, standardIds) {
204
210
  }
205
211
  }
206
212
 
207
- const ratio = standardIds.length > 0
208
- ? (hasCheckScript + hasTests) / (standardIds.length * 2)
209
- : 0;
213
+ const ratio = hasCheckScript / (standardIds.length * 2);
210
214
  const score = Math.round(Math.min(ratio * 100, 100));
211
215
 
212
216
  return {
213
217
  score,
214
218
  details: {
215
219
  has_check_script: hasCheckScript,
216
- has_tests: hasTests,
217
220
  total: standardIds.length
218
221
  }
219
222
  };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Which names in `manifest.skills.names` / `manifest.commands.names` UDS can still vouch for.
3
+ * // implements XSPEC-456 R4
4
+ *
5
+ * XSPEC-454 R2 cleaned `skillHashes` and `commandHashes` and left these two lists alone, on the
6
+ * reasoning that an over-long list is harmless. It is not: after `uds update --apply --skills` removed
7
+ * the `_shared`, `agents`, `ai`, `tools` and `workflows` folders an old CLI had copied into the skills
8
+ * folder, the manifest still listed all five as installed skills (61 names for 56 skills), which
9
+ * contradicted both the disk and the release notes' claim that the records were cleaned.
10
+ *
11
+ * The rule is the one XSPEC-454 R2 uses for the hash records: **what UDS can vouch for stays**.
12
+ * - a skill (command) name stays only if UDS ships a skill (command) of that name;
13
+ * - when asked to (`checkDisk`), only if it is also present in one of the places the manifest says
14
+ * it was installed. That second test is skipped when it cannot be made (no install location
15
+ * recorded, or none of the recorded folders exists): a name list is never emptied because the
16
+ * tool could not find where to look.
17
+ *
18
+ * Every manifest field that records skill or command NAMES, and what handles it:
19
+ * skills.names -> this module (skills)
20
+ * commands.names -> this module (commands)
21
+ * skillHashes -> utils/skill-hash-ownership.js (XSPEC-454 R2; the name is the 3rd path segment)
22
+ * commandHashes -> utils/command-hash-ownership.js (XSPEC-454 R2; the name is the file stem)
23
+ * `skills.installations` / `commands.installations` record tools and levels, not names, and
24
+ * `installedArtifacts` records only integration files and created directories.
25
+ *
26
+ * @module utils/installed-names-ownership
27
+ */
28
+
29
+ import { existsSync } from 'fs';
30
+ import { join } from 'path';
31
+ import { getAvailableSkillNames, getAvailableCommandNames } from './skills-installer.js';
32
+ import { MARKETPLACE_NAMES_SENTINEL } from '../core/marketplace-sentinel.js';
33
+ import { getSkillsDirForAgent, getCommandsDirForAgent, getCommandFileExtension } from '../config/ai-agent-paths.js';
34
+
35
+ /** Below these sizes the source tree did not load; never read that as "UDS ships nothing". */
36
+ const MIN_SHIPPED = 10;
37
+
38
+ /** `{ agent, level }` for every recorded installation (strings are legacy project-level entries). */
39
+ function installationsOf(section) {
40
+ return (section?.installations || [])
41
+ .map((entry) => (typeof entry === 'string'
42
+ ? { agent: entry, level: 'project' }
43
+ : { agent: entry?.agent, level: entry?.level || 'project' }))
44
+ .filter((entry) => entry.agent);
45
+ }
46
+
47
+ /** Folders a skill of the recorded installations would live in. Empty when the manifest does not say. */
48
+ function skillFolders(manifest, projectPath) {
49
+ const dirs = installationsOf(manifest.skills)
50
+ .map(({ agent, level }) => getSkillsDirForAgent(agent, level, projectPath))
51
+ .filter(Boolean);
52
+ if (dirs.length > 0) return dirs;
53
+ // A legacy manifest records no installations, only where the skills went.
54
+ const location = manifest.skills?.location;
55
+ if (location === 'project' || location === 'user') {
56
+ const dir = getSkillsDirForAgent('claude-code', location, projectPath);
57
+ return dir ? [dir] : [];
58
+ }
59
+ return [];
60
+ }
61
+
62
+ /** `[folder, extension]` pairs where a command of the recorded installations would live. */
63
+ function commandFolders(manifest, projectPath) {
64
+ return installationsOf(manifest.commands)
65
+ .map(({ agent, level }) => [getCommandsDirForAgent(agent, level, projectPath), getCommandFileExtension(agent)])
66
+ .filter(([dir]) => Boolean(dir));
67
+ }
68
+
69
+ function prune(names, keep) {
70
+ const kept = [];
71
+ const dropped = [];
72
+ for (const name of names) (keep(name) ? kept : dropped).push(name);
73
+ return { kept, dropped: dropped.sort() };
74
+ }
75
+
76
+ /**
77
+ * Drop the names in `manifest.skills.names` that UDS cannot vouch for. Mutates `manifest`.
78
+ *
79
+ * @param {Object} manifest
80
+ * @param {string} projectPath
81
+ * @param {Object} [options]
82
+ * @param {boolean} [options.checkDisk=false] - also require the skill to be present where it was installed
83
+ * @param {Set<string>} [options.shipped] - Injection point for tests; defaults to the skills this CLI ships
84
+ * @returns {string[]} The names dropped, sorted
85
+ */
86
+ export function pruneForeignSkillNames(manifest, projectPath, { checkDisk = false, shipped = new Set(getAvailableSkillNames()) } = {}) {
87
+ const names = manifest?.skills?.names;
88
+ if (!Array.isArray(names) || shipped.size < MIN_SHIPPED) return [];
89
+ // Marketplace installs record a sentinel instead of names; there is nothing to prune.
90
+ if (names.includes(MARKETPLACE_NAMES_SENTINEL)) return [];
91
+
92
+ const dirs = checkDisk ? skillFolders(manifest, projectPath) : [];
93
+ const diskTestPossible = dirs.some((dir) => existsSync(dir));
94
+ const { kept, dropped } = prune(names, (name) =>
95
+ shipped.has(name) && (!diskTestPossible || dirs.some((dir) => existsSync(join(dir, name)))));
96
+ if (dropped.length > 0) manifest.skills.names = kept;
97
+ return dropped;
98
+ }
99
+
100
+ /**
101
+ * Drop the names in `manifest.commands.names` that UDS cannot vouch for. Mutates `manifest`.
102
+ * Same contract as {@link pruneForeignSkillNames}.
103
+ */
104
+ export function pruneForeignCommandNames(manifest, projectPath, { checkDisk = false, shipped = new Set(getAvailableCommandNames()) } = {}) {
105
+ const names = manifest?.commands?.names;
106
+ if (!Array.isArray(names) || shipped.size < MIN_SHIPPED) return [];
107
+
108
+ const places = checkDisk ? commandFolders(manifest, projectPath) : [];
109
+ const diskTestPossible = places.some(([dir]) => existsSync(dir));
110
+ const { kept, dropped } = prune(names, (name) =>
111
+ shipped.has(name) && (!diskTestPossible || places.some(([dir, ext]) => existsSync(join(dir, `${name}${ext}`)))));
112
+ if (dropped.length > 0) manifest.commands.names = kept;
113
+ return dropped;
114
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Read the header of a full SDD spec: title, status and type.
3
+ * // implements XSPEC-456 R5
4
+ *
5
+ * `uds spec list` was built for micro-specs (`## Micro-Spec: ...` with `**Status**: draft`). A full SDD
6
+ * spec states the same facts in its own header - a table (`| Status | Approved (2026-09-30) |`), field
7
+ * lines (`- **Status**: Archived`, `> **Status**: Stable`) or a YAML front matter - and the reader that
8
+ * found none of them filled in `draft` and an empty title. This module reads those layouts and reports
9
+ * what it could not read as `null`, so a caller can say "not parsed" instead of printing a default.
10
+ *
11
+ * @module utils/sdd-header
12
+ */
13
+
14
+ /** Where a status or type can be read in a header table: `| Status | Approved (2026-01-01) |`. */
15
+ const TABLE_FIELD = (name) => new RegExp(`^\\|\\s*\\**\\s*${name}\\s*\\**\\s*\\|\\s*(.+?)\\s*\\|?\\s*$`, 'i');
16
+ /** ...in a field line: `- **Status**: Archived`, `> **Status**: Stable`, `Status: Draft`. */
17
+ const LINE_FIELD = (name) => new RegExp(`^[\\s>*-]*\\**\\s*${name}\\s*\\**\\s*[:\uFF1A]\\s*\\**\\s*(.+?)\\s*$`, 'i');
18
+ const TABLE_SEPARATOR = /^\|[\s:|-]+\|?\s*$/;
19
+
20
+ /** First word of a header value, lower-cased (`Approved (2026-01-01)` -> `approved`); text it cannot split stays as written. */
21
+ function headerWord(value) {
22
+ const cleaned = String(value).replace(/[*`_]/g, '').trim();
23
+ const word = cleaned.match(/^[A-Za-z][A-Za-z-]*/);
24
+ return (word ? word[0].toLowerCase() : cleaned) || null;
25
+ }
26
+
27
+ /**
28
+ * Read title, status and type from the header of an SDD spec: its first 80 lines. Understands the header table, field lines, and a YAML front matter `status:`.
29
+ * Whatever it cannot find is `null` / empty - never a default that looks like a result.
30
+ *
31
+ * @param {string} content - File content
32
+ * @returns {{ title: string, status: string|null, type: string|null }}
33
+ */
34
+ export function readSddHeader(content) {
35
+ const all = content.replace(/\r\n/g, '\n').split('\n');
36
+ let start = 0;
37
+ let frontMatter = [];
38
+ if (all[0]?.trim() === '---') {
39
+ const close = all.findIndex((l, i) => i > 0 && l.trim() === '---');
40
+ if (close > 0) {
41
+ frontMatter = all.slice(1, close);
42
+ start = close + 1;
43
+ }
44
+ }
45
+ const lines = all.slice(start, start + 80);
46
+
47
+ const title = (lines.find((l) => /^#\s+\S/.test(l)) || '').replace(/^#\s+/, '').replace(/\s+#+\s*$/, '').trim();
48
+
49
+ const read = (name) => {
50
+ for (let i = 0; i < lines.length; i++) {
51
+ const row = TABLE_FIELD(name).exec(lines[i]);
52
+ // A header row of a table (`| Status | Description |`) is followed by a separator row; a field row is not.
53
+ if (row && !TABLE_SEPARATOR.test(lines[i + 1] || '')) return headerWord(row[1]);
54
+ const field = LINE_FIELD(name).exec(lines[i]);
55
+ if (field) return headerWord(field[1]);
56
+ }
57
+ for (const line of frontMatter) {
58
+ const fm = new RegExp(`^${name}\\s*:\\s*(.+?)\\s*$`, 'i').exec(line);
59
+ if (fm) return headerWord(fm[1]);
60
+ }
61
+ return null;
62
+ };
63
+
64
+ return { title, status: read('Status'), type: read('Type') };
65
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Which `manifest.skillHashes` records really describe files UDS installed.
3
+ *
4
+ * A record is `<agent>/<level>/<skill>/<file>`. It is UDS's only if `<skill>` is a skill UDS ships.
5
+ * Anything else got there because an older installer hashed the whole skills folder (XSPEC-454 R2):
6
+ * the adopter's own skills, the `agents/` / `workflows/` / `_shared/` folders an old CLI copied in by
7
+ * mistake (which a later `uds update` deletes — leaving the record behind), and UDS's own
8
+ * `.manifest.json` bookkeeping file. None of those are skills UDS can vouch for, so none of them may
9
+ * decide whether `uds check` says the project is compliant.
10
+ *
11
+ * @module utils/skill-hash-ownership
12
+ */
13
+
14
+ import { getAvailableSkillNames } from './skills-installer.js';
15
+
16
+ /**
17
+ * Below this many shipped skills the source tree did not load; it does not mean UDS stopped shipping
18
+ * skills. Without this guard a broken install would classify every record as foreign and empty the
19
+ * manifest (same guard as pruneRetiredHashes' registry-size check).
20
+ */
21
+ const MIN_SHIPPED_SKILLS = 10;
22
+
23
+ /**
24
+ * @param {string} key - A skillHashes key
25
+ * @param {Set<string>} shipped - Names of the skills UDS ships
26
+ * @returns {boolean}
27
+ */
28
+ export function isUdsSkillHashKey(key, shipped) {
29
+ const parts = String(key).split('/');
30
+ // agent / level / skill / at least one file path segment
31
+ return parts.length >= 4 && shipped.has(parts[2]);
32
+ }
33
+
34
+ /**
35
+ * Drop the skillHashes records that do not describe a file UDS installed. Mutates `manifest`.
36
+ *
37
+ * @param {Object} manifest - Project manifest
38
+ * @param {Set<string>} [shipped] - Injection point for tests; defaults to the skills this CLI ships
39
+ * @returns {string[]} The keys that were dropped, sorted
40
+ */
41
+ export function pruneForeignSkillHashes(manifest, shipped = new Set(getAvailableSkillNames())) {
42
+ const hashes = manifest?.skillHashes;
43
+ if (!hashes || shipped.size < MIN_SHIPPED_SKILLS) return [];
44
+ const dropped = [];
45
+ for (const key of Object.keys(hashes)) {
46
+ if (isUdsSkillHashKey(key, shipped)) continue;
47
+ delete hashes[key];
48
+ dropped.push(key);
49
+ }
50
+ return dropped.sort();
51
+ }
52
+
53
+ /**
54
+ * Which skill files `uds check` has to report: the missing and the changed ones, as one list.
55
+ *
56
+ * Its result is what the verdict is built from. `uds check` used to throw the integrity result away, so a
57
+ * deleted skill file printed a red ✗ and the run still ended "compliant", exit 0 (XSPEC-454 R2).
58
+ *
59
+ * @param {{ missing?: string[], modified?: string[] }} status - Result of the Skills integrity check
60
+ * @returns {string[]}
61
+ */
62
+ export function skillIssuesOf(status) {
63
+ return [...(status?.missing || []), ...(status?.modified || [])];
64
+ }
@@ -248,8 +248,19 @@ export async function installSkillsForAgent(agent, level, skillNames = null, pro
248
248
 
249
249
  // Compute file hashes for tracking
250
250
  // Key format: agent/level/skillName/filename (e.g., "opencode/project/commit-standards/SKILL.md")
251
+ //
252
+ // XSPEC-454 R2: only the skills THIS run installed are recorded. This used to hash the whole
253
+ // target directory, so everything that happened to sit in `.claude/skills/` — the adopter's own
254
+ // skills, and the `agents/`, `workflows/`, `_shared/` folders an old CLI copied in by mistake —
255
+ // became "files UDS installed". `uds update` later (rightly) deleted the old strays but kept their
256
+ // records, and `uds check` listed 26 of them as missing. A record has to mean "UDS wrote this".
257
+ // `.manifest.json` is deliberately not recorded either: it is UDS's own bookkeeping, rewritten by
258
+ // every install, and nothing a user edits — a hash of it could only ever raise a false alarm.
251
259
  const baseKey = `${agent}/${level}`;
252
- results.fileHashes = computeDirectoryHashes(targetDir, baseKey);
260
+ results.fileHashes = {};
261
+ for (const name of results.installed) {
262
+ Object.assign(results.fileHashes, computeDirectoryHashes(join(targetDir, name), `${baseKey}/${name}`));
263
+ }
253
264
  }
254
265
 
255
266
  return results;
@@ -5,6 +5,7 @@ import { exec } from 'child_process';
5
5
  import util from 'util';
6
6
  import { pathToFileURL } from 'node:url';
7
7
  import { readManifest } from './copier.js';
8
+ import { judgeCommitMessage } from './commit-message-judge.js';
8
9
 
9
10
  const execAsync = util.promisify(exec);
10
11
 
@@ -395,51 +396,121 @@ export class StandardValidator {
395
396
  }
396
397
 
397
398
  /**
398
- * Run a simulation to predict compliance with a standard
399
+ * Standards in this project that define a `physical_spec.simulator` (the only ones `uds simulate` can run).
400
+ * @returns {string[]} Standard ids, sorted
401
+ */
402
+ listSimulatableStandards() {
403
+ const ids = [];
404
+ let files;
405
+ try {
406
+ files = fs.readdirSync(this.standardsDir).filter(f => f.endsWith('.ai.yaml'));
407
+ } catch {
408
+ return ids;
409
+ }
410
+ for (const file of files) {
411
+ try {
412
+ const doc = yaml.load(fs.readFileSync(path.join(this.standardsDir, file), 'utf-8'));
413
+ if (doc?.physical_spec?.simulator) ids.push(doc?.standard?.id || file.replace(/\.ai\.yaml$/, ''));
414
+ } catch {
415
+ // an unreadable standard is not simulatable
416
+ }
417
+ }
418
+ return ids.sort();
419
+ }
420
+
421
+ /**
422
+ * Run a simulation to predict compliance with a standard.
423
+ *
424
+ * XSPEC-456 R2. Three outcomes, never two:
425
+ * - `pass` - the input complies;
426
+ * - `fail` - the input does not comply (the standard's rules say so);
427
+ * - `cannot-simulate` - no verdict was reached: the standard has no simulator, the standard is not
428
+ * installed, or the tool a simulator delegates to is not usable. Reporting that
429
+ * as `fail` told people their input was non-compliant when nothing had judged it.
430
+ * `success` stays for existing readers and is true only for `pass`.
431
+ *
399
432
  * @param {string} standardId - Standard ID
400
- * @param {string} input - Input to test (e.g. commit message)
401
- * @returns {Promise<Object>} Simulation result
433
+ * @param {string} input - Input to test (e.g. a commit message)
434
+ * @returns {Promise<{ status: 'pass'|'fail'|'cannot-simulate', success: boolean, message: string, details?: string }>}
402
435
  */
403
436
  async simulate(standardId, input) {
437
+ const cannot = (message, details) => ({ status: 'cannot-simulate', success: false, message, ...(details ? { details } : {}) });
438
+
404
439
  const standardFile = this.findStandardFile(standardId);
405
440
  if (!standardFile) {
406
- return { success: false, message: `Standard '${standardId}' not found.` };
441
+ return cannot(`Standard '${standardId}' not found.`, this._simulatableHint());
407
442
  }
408
443
 
409
444
  let standardConfig;
410
445
  try {
411
446
  standardConfig = yaml.load(fs.readFileSync(standardFile, 'utf-8'));
412
447
  } catch (e) {
413
- return { success: false, message: `Failed to parse standard: ${e.message}` };
448
+ return cannot(`Failed to parse standard: ${e.message}`);
414
449
  }
415
450
 
416
- if (!standardConfig.physical_spec || !standardConfig.physical_spec.simulator) {
417
- return {
418
- success: false,
419
- message: `Standard '${standardId}' does not support simulation (no 'simulator' spec defined).`
420
- };
451
+ const simulator = standardConfig?.physical_spec?.simulator;
452
+ if (!simulator) {
453
+ return cannot(
454
+ `Standard '${standardId}' does not support simulation (no 'simulator' spec defined).`,
455
+ this._simulatableHint()
456
+ );
421
457
  }
422
458
 
423
- const { command } = standardConfig.physical_spec.simulator;
424
-
425
- // Sanitization: Escape double quotes to prevent breaking the echo command
426
- // This is a basic implementation. For production, consider using spawn with stdin stream.
427
- const sanitizedInput = input.replace(/"/g, '\\"');
428
- const finalCommand = command.replace('{input}', sanitizedInput);
459
+ // In-process judges. A standard names one with `simulator.judge`; copies installed before that field
460
+ // existed carry `command: echo "{input}" | npx commitlint`, and are routed the same way.
461
+ const judgeName = simulator.judge
462
+ || (standardConfig?.standard?.id === 'commit-message' && /commitlint/.test(simulator.command || '') ? 'commit-message' : null);
463
+ if (judgeName === 'commit-message') {
464
+ const outcome = judgeCommitMessage(standardConfig, input, { standardsDir: this.standardsDir });
465
+ const details = [
466
+ ...outcome.findings.map(f => `- ${f}`),
467
+ `Checked: ${outcome.checked.join('; ')}`,
468
+ `Not checked: ${outcome.notChecked.join('; ')}`
469
+ ].join('\n');
470
+ return outcome.verdict === 'pass'
471
+ ? { status: 'pass', success: true, message: 'Simulation passed', details }
472
+ : { status: 'fail', success: false, message: 'Simulation failed: the input does not comply', details };
473
+ }
474
+ if (simulator.judge) {
475
+ return cannot(`Standard '${standardId}' names an unknown simulator judge '${simulator.judge}'.`);
476
+ }
477
+
478
+ if (typeof simulator.command !== 'string' || simulator.command.trim() === '') {
479
+ return cannot(`Standard '${standardId}' defines a simulator without a command or a judge.`);
480
+ }
481
+ return this._simulateWithCommand(simulator.command, input);
482
+ }
483
+
484
+ /** @private Names the standards that can be simulated, for messages. */
485
+ _simulatableHint() {
486
+ const ids = this.listSimulatableStandards();
487
+ return ids.length > 0
488
+ ? `Standards that can be simulated in this project: ${ids.join(', ')}.`
489
+ : 'No installed standard defines a simulator.';
490
+ }
491
+
492
+ /**
493
+ * @private Delegate to the command a standard gives. The input never becomes part of the shell string:
494
+ * `{input}` is replaced by a reference to an environment variable, which the shell expands without
495
+ * re-reading its value (so quotes, `$` and backticks in the input stay data). A tool that is not usable
496
+ * (not found, not executable) is `cannot-simulate`; a tool that ran and said no is `fail`.
497
+ */
498
+ async _simulateWithCommand(command, input) {
499
+ const ref = process.platform === 'win32' ? '%UDS_SIMULATE_INPUT%' : '$UDS_SIMULATE_INPUT';
500
+ const finalCommand = command.split('{input}').join(ref);
501
+ const env = { ...process.env, UDS_SIMULATE_INPUT: String(input) };
429
502
 
430
503
  try {
431
- const { stdout } = await execAsync(finalCommand, { cwd: this.projectPath });
432
- return {
433
- success: true,
434
- message: 'Simulation passed',
435
- details: stdout.trim()
436
- };
504
+ const { stdout } = await execAsync(finalCommand, { cwd: this.projectPath, env });
505
+ return { status: 'pass', success: true, message: 'Simulation passed', details: stdout.trim() };
437
506
  } catch (e) {
438
- return {
439
- success: false,
440
- message: 'Simulation failed',
441
- details: e.message + (e.stdout ? `\nOutput: ${e.stdout}` : '')
442
- };
507
+ const text = `${e.stderr || ''}`;
508
+ const notUsable = e.code === 126 || e.code === 127 || e.code === 9009
509
+ || /command not found|not recognized as an internal or external command|ENOENT/i.test(text);
510
+ const details = e.message + (e.stdout ? `\nOutput: ${e.stdout}` : '');
511
+ return notUsable
512
+ ? { status: 'cannot-simulate', success: false, message: 'Simulation could not run: the tool the standard delegates to is not usable here', details }
513
+ : { status: 'fail', success: false, message: 'Simulation failed: the input does not comply', details };
443
514
  }
444
515
  }
445
516
  }