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
@@ -28,6 +28,9 @@ import { scanActualState, legacyDiscovery } from './actual-state-scanner.js';
28
28
  import { computeDiff, createEmptyPlan } from './diff-engine.js';
29
29
  import { executePlan } from './plan-executor.js';
30
30
  import { rollback } from './backup-manager.js';
31
+ import { pruneForeignSkillHashes } from '../utils/skill-hash-ownership.js';
32
+ import { pruneForeignCommandHashes } from '../utils/command-hash-ownership.js';
33
+ import { pruneForeignSkillNames, pruneForeignCommandNames } from '../utils/installed-names-ownership.js';
31
34
 
32
35
  /**
33
36
  * Full reconciliation pipeline.
@@ -72,11 +75,37 @@ function reconcileFileHashes(manifest, verifiedPristine) {
72
75
  (k) => k.startsWith('.claude/skills/') || k.startsWith('.claude/commands/')
73
76
  );
74
77
 
75
- if (!verifiedPristine?.length && stale.length === 0) return null;
78
+ // XSPEC-454 R2 step 1: forget skillHashes records that were never UDS's (see
79
+ // utils/skill-hash-ownership.js). They are not harmless: once `uds check` counts a missing
80
+ // skill file against the verdict, a record for a folder an older update already removed
81
+ // would fail the project for a file nobody can restore. This runs on every apply, plan empty
82
+ // or not, so an existing project is corrected by its next `uds update --apply` with nothing
83
+ // for the adopter to do.
84
+ const skillProbe = { skillHashes: { ...(manifest.skillHashes || {}) } };
85
+ const foreignSkillKeys = pruneForeignSkillHashes(skillProbe);
86
+ // ...and the same for command records that name a command UDS does not ship.
87
+ const commandProbe = { commandHashes: { ...(manifest.commandHashes || {}) } };
88
+ const foreignCommandKeys = pruneForeignCommandHashes(commandProbe);
89
+
90
+ // XSPEC-456 R4: and the NAME lists. The hash records above were cleaned and these were not, so a
91
+ // project could read "56 skills installed, 61 skills named". Ownership test only (no disk test): the
92
+ // plan below is what installs or removes files, and a name is judged against what UDS ships.
93
+ const namesProbe = {
94
+ skills: { names: [...(manifest.skills?.names || [])] },
95
+ commands: { names: [...(manifest.commands?.names || [])] }
96
+ };
97
+ const namesBefore = { skills: namesProbe.skills.names.length, commands: namesProbe.commands.names.length };
98
+ pruneForeignSkillNames(namesProbe, '');
99
+ pruneForeignCommandNames(namesProbe, '');
100
+ const foreignSkillNames = namesBefore.skills - namesProbe.skills.names.length;
101
+ const foreignCommandNames = namesBefore.commands - namesProbe.commands.names.length;
102
+
103
+ if (!verifiedPristine?.length && stale.length === 0 && foreignSkillKeys.length === 0 && foreignCommandKeys.length === 0
104
+ && foreignSkillNames === 0 && foreignCommandNames === 0) return null;
76
105
 
77
106
  const kept = Object.fromEntries(Object.entries(current).filter(([k]) => !stale.includes(k)));
78
107
  const corrected = {};
79
- let count = stale.length;
108
+ let count = stale.length + foreignSkillKeys.length + foreignCommandKeys.length + foreignSkillNames + foreignCommandNames;
80
109
 
81
110
  for (const entry of verifiedPristine || []) {
82
111
  const key = entry.path.replace(/\\/g, '/');
@@ -92,7 +121,14 @@ function reconcileFileHashes(manifest, verifiedPristine) {
92
121
 
93
122
  if (count === 0) return null;
94
123
  return {
95
- manifest: { ...manifest, fileHashes: { ...kept, ...corrected } },
124
+ manifest: {
125
+ ...manifest,
126
+ fileHashes: { ...kept, ...corrected },
127
+ ...(foreignSkillKeys.length > 0 ? { skillHashes: skillProbe.skillHashes } : {}),
128
+ ...(foreignCommandKeys.length > 0 ? { commandHashes: commandProbe.commandHashes } : {}),
129
+ ...(foreignSkillNames > 0 ? { skills: { ...manifest.skills, names: namesProbe.skills.names } } : {}),
130
+ ...(foreignCommandNames > 0 ? { commands: { ...manifest.commands, names: namesProbe.commands.names } } : {})
131
+ },
96
132
  count
97
133
  };
98
134
  }
@@ -133,7 +169,10 @@ export async function reconcile(projectPath, options = {}) {
133
169
  // own binding rather than reassigning it.
134
170
  const hashFix = reconcileFileHashes(manifest, reconciliationPlan.verifiedPristine);
135
171
  const effectiveManifest = hashFix ? hashFix.manifest : manifest;
136
- if (hashFix) writeManifest(effectiveManifest, projectPath);
172
+ // With a non-empty plan the executor writes `effectiveManifest` itself, AFTER it has taken its backup.
173
+ // Writing it here first would put the hash correction into the backup's "before" copy, so a rollback
174
+ // could not give back the manifest byte for byte (XSPEC-454 R1).
175
+ if (hashFix && reconciliationPlan.actions.length === 0) writeManifest(effectiveManifest, projectPath);
137
176
 
138
177
  // Step 5: Execute plan
139
178
  if (reconciliationPlan.actions.length === 0) {
@@ -242,5 +281,5 @@ async function getManifest(projectPath) {
242
281
 
243
282
  // Re-export for convenience
244
283
  export { formatPlan } from './diff-engine.js';
245
- export { listBackups } from './backup-manager.js';
284
+ export { listBackups, createStepBackup, finalizeBackup, cleanupBackups } from './backup-manager.js';
246
285
  export { migrateAndBackfill } from './manifest-migrator.js';
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Where `uds update` writes Skills and Commands, in the terms a backup needs (XSPEC-454 R1):
3
+ * project-relative directories it can copy, and targets outside the project it cannot.
4
+ *
5
+ * A user-level target (`~/.claude/skills`) is shared by every project on the machine. Copying it into
6
+ * one project's backup, and writing it back on that project's rollback, would undo other projects'
7
+ * updates — so it is listed as "not backed up" and the rollback says so, rather than touching it.
8
+ *
9
+ * @module reconciler/install-roots
10
+ */
11
+
12
+ import { relative, isAbsolute } from 'path';
13
+ import { getSkillsDirForAgent, getCommandsDirForAgent } from '../config/ai-agent-paths.js';
14
+ import { getAvailableSkillNames, getAvailableCommandNames } from '../utils/skills-installer.js';
15
+
16
+ const normalizeInstallation = (inst) =>
17
+ typeof inst === 'string' ? { agent: inst, level: 'project' } : { agent: inst.agent, level: inst.level || 'project' };
18
+
19
+ /** Project-relative posix path when `abs` is inside the project, else null. */
20
+ function insideProject(projectPath, abs) {
21
+ if (!abs) return null;
22
+ const rel = relative(projectPath, abs).replace(/\\/g, '/');
23
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null;
24
+ return rel;
25
+ }
26
+
27
+ /**
28
+ * @param {string} projectPath
29
+ * @param {Array<string|{agent: string, level?: string}>} installations
30
+ * @param {'skills'|'commands'} kind
31
+ * @returns {{ dirs: string[], outside: Array<{path: string, reason: string}> }}
32
+ */
33
+ export function installRoots(projectPath, installations, kind) {
34
+ const dirs = [];
35
+ const outside = [];
36
+ for (const raw of installations || []) {
37
+ const { agent, level } = normalizeInstallation(raw);
38
+ if (level === 'marketplace') continue; // nothing on disk
39
+ const abs = kind === 'skills'
40
+ ? getSkillsDirForAgent(agent, level, projectPath)
41
+ : getCommandsDirForAgent(agent, level, projectPath);
42
+ if (!abs) continue;
43
+ const rel = insideProject(projectPath, abs);
44
+ if (rel) {
45
+ dirs.push(rel);
46
+ } else {
47
+ outside.push({
48
+ path: abs,
49
+ reason: `${kind} installed at user level for ${agent}; shared by every project on this machine, so it is not backed up and not rolled back`
50
+ });
51
+ }
52
+ }
53
+ return { dirs: [...new Set(dirs)], outside };
54
+ }
55
+
56
+ /**
57
+ * The bookkeeping file every Skills/Commands install rewrites, for each project-level target.
58
+ * A reconciler plan names skill and command files, never these, yet they change on every run.
59
+ */
60
+ export function bookkeepingFiles(projectPath, manifest, { skills, commands }) {
61
+ const out = [];
62
+ if (skills) out.push(...installRoots(projectPath, manifest?.skills?.installations, 'skills').dirs.map((d) => `${d}/.manifest.json`));
63
+ if (commands) out.push(...installRoots(projectPath, manifest?.commands?.installations, 'commands').dirs.map((d) => `${d}/.manifest.json`));
64
+ return out;
65
+ }
66
+
67
+ /**
68
+ * What a `--skills` / `--commands` step is going to write, as paths a backup can copy: the skill folders
69
+ * (or command files) UDS ships, and the bookkeeping file, inside each project-level target.
70
+ *
71
+ * Deliberately not the whole target folder. That folder also holds the adopter's own skills and commands;
72
+ * a backup that copied them would let a rollback write them back — undoing an edit the adopter made
73
+ * after the update, to a file UDS never touched. A shipped name that is not on disk yet is still listed:
74
+ * the backup records it as absent, which is what lets a rollback remove it again.
75
+ *
76
+ * @param {string} projectPath
77
+ * @param {Array<string|{agent: string, level?: string}>} installations
78
+ * @param {'skills'|'commands'} kind
79
+ * @returns {{ paths: string[], outside: Array<{path: string, reason: string}> }}
80
+ */
81
+ export function stepWritePaths(projectPath, installations, kind) {
82
+ const { dirs, outside } = installRoots(projectPath, installations, kind);
83
+ const names = kind === 'skills' ? getAvailableSkillNames() : getAvailableCommandNames();
84
+ const paths = [];
85
+ for (const dir of dirs) {
86
+ paths.push(`${dir}/.manifest.json`);
87
+ for (const name of names) paths.push(kind === 'skills' ? `${dir}/${name}` : `${dir}/${name}.md`);
88
+ }
89
+ return { paths, outside };
90
+ }
@@ -28,7 +28,8 @@ import { writeManifest } from '../core/manifest.js';
28
28
  import { getRepositoryInfo } from '../utils/registry.js';
29
29
  import { displayLanguageToLocale } from '../utils/locale.js';
30
30
  import { computeFileHash, pruneIntegrationFileHashes } from '../utils/hasher.js';
31
- import { createBackup, cleanupBackups } from './backup-manager.js';
31
+ import { createBackup, cleanupBackups, finalizeBackup } from './backup-manager.js';
32
+ import { bookkeepingFiles } from './install-roots.js';
32
33
 
33
34
  /**
34
35
  * @typedef {Object} ExecutionResult
@@ -75,7 +76,13 @@ export async function executePlan(projectPath, plan, manifest, options = {}) {
75
76
 
76
77
  // Create backup
77
78
  if (backup && !dryRun) {
78
- const backupResult = createBackup(projectPath, plan);
79
+ // XSPEC-454 R1: the Skills and Commands installers also rewrite `.manifest.json` in each target
80
+ // folder. No plan action names it, so it has to be watched explicitly or a rollback leaves the new one.
81
+ const bookkeeping = bookkeepingFiles(projectPath, manifest, {
82
+ skills: plan.actions.some((a) => a.category === 'skill'),
83
+ commands: plan.actions.some((a) => a.category === 'command')
84
+ });
85
+ const backupResult = createBackup(projectPath, plan, { alsoWatch: bookkeeping });
79
86
  // Abort if ANY planned path could not be backed up — not only if every one
80
87
  // failed.
81
88
  //
@@ -197,6 +204,10 @@ export async function executePlan(projectPath, plan, manifest, options = {}) {
197
204
  error: `Failed to write manifest: ${err.message}`
198
205
  });
199
206
  }
207
+ // XSPEC-454 R1: now that the step is over — whether or not that last write worked — record what it
208
+ // created and what the manifest became. This has to stay after the manifest write: the chain between
209
+ // consecutive backups is "the manifest this step left == the manifest the next step started from".
210
+ finalizeBackup(projectPath, backupId);
200
211
  }
201
212
 
202
213
  const summary = {
@@ -422,6 +433,16 @@ async function executeSkillBatch(projectPath, skillActions, manifest) {
422
433
  if (existsSync(targetPath)) {
423
434
  rmSync(targetPath, { recursive: true, force: true });
424
435
  }
436
+ // XSPEC-454 R2: a deleted skill folder must also lose its hash records. Commands already
437
+ // do this (see executeCommandBatch); skills did not, so each folder removed here stayed in
438
+ // `skillHashes` and `uds check` later called every file in it missing — 26 of them for one project.
439
+ const meta = action.details?.metadata;
440
+ if (meta?.agent && meta?.level && meta?.skillName && manifest.skillHashes) {
441
+ const prefix = `${meta.agent}/${meta.level}/${meta.skillName}/`;
442
+ for (const key of Object.keys(manifest.skillHashes)) {
443
+ if (key.startsWith(prefix)) delete manifest.skillHashes[key];
444
+ }
445
+ }
425
446
  results.push({ action, success: true });
426
447
  } catch (err) {
427
448
  results.push({ action, success: false, error: err.message });
@@ -303,7 +303,8 @@ export function uninstallHookScripts(projectPath, manifest, { dryRun = false, bl
303
303
  const result = { removed: [], skipped: [], errors: [], deletedPaths: [] };
304
304
  const files = manifest?.[RECORDS_KEY]?.files || {};
305
305
  const recorded = Object.entries(files)
306
- .filter(([, rec]) => rec && rec.kind === RECORD_KINDS.HOOK_SCRIPT)
306
+ // gate-script: the scanners `uds init` writes to scripts/ (XSPEC-444 R5) — same proof rule as a hook script
307
+ .filter(([, rec]) => rec && (rec.kind === RECORD_KINDS.HOOK_SCRIPT || rec.kind === RECORD_KINDS.GATE_SCRIPT))
307
308
  .map(([rel]) => rel)
308
309
  .sort();
309
310
 
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Which `manifest.commandHashes` records `uds check` may hold this project to (XSPEC-454 R2, the
3
+ * Commands half).
4
+ *
5
+ * A record is `<agent>/<file>` (`opencode/commit.md`, `gemini-cli/commit.toml`) with no level in it.
6
+ * Two kinds of record do not describe a file this project's check can vouch for:
7
+ *
8
+ * - FOREIGN: the name is not a command UDS ships (any more). A retired command whose file is gone is
9
+ * a "missing" nobody can restore. These are dropped for good by `uds update`.
10
+ * - ELSEWHERE: the command was installed at user level (`~/.config/opencode/command`), shared by every
11
+ * project on the machine. The check looks inside the project, so every one of them would read
12
+ * "missing" — and another project's `uds update` can rewrite them at any time, so "modified" would
13
+ * be noise too. They are ignored by the check and left in the manifest (user-level update still
14
+ * refreshes them).
15
+ *
16
+ * Both exist for the same reason the skills ones do: once a missing or changed command file counts toward
17
+ * the verdict, a record that points at nothing this project owns would fail the project for a file
18
+ * nobody can fix.
19
+ *
20
+ * @module utils/command-hash-ownership
21
+ */
22
+
23
+ import { getAvailableCommandNames } from './skills-installer.js';
24
+ import { getCommandFileExtension } from '../config/ai-agent-paths.js';
25
+
26
+ /** Below this many shipped commands the source tree did not load; never treat that as "UDS ships none". */
27
+ const MIN_SHIPPED_COMMANDS = 10;
28
+
29
+ /**
30
+ * @param {string} key - A commandHashes key
31
+ * @param {Set<string>} shipped - Names of the commands UDS ships (no extension)
32
+ * @returns {boolean}
33
+ */
34
+ export function isUdsCommandHashKey(key, shipped) {
35
+ const parts = String(key).split('/');
36
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return false;
37
+ const [agent, file] = parts;
38
+ const ext = getCommandFileExtension(agent);
39
+ return file.endsWith(ext) && shipped.has(file.slice(0, -ext.length));
40
+ }
41
+
42
+ /**
43
+ * Drop the commandHashes records for commands UDS does not ship. Mutates `manifest`.
44
+ * @param {Object} manifest
45
+ * @param {Set<string>} [shipped] - Injection point for tests
46
+ * @returns {string[]} The keys dropped, sorted
47
+ */
48
+ export function pruneForeignCommandHashes(manifest, shipped = new Set(getAvailableCommandNames())) {
49
+ const hashes = manifest?.commandHashes;
50
+ if (!hashes || shipped.size < MIN_SHIPPED_COMMANDS) return [];
51
+ const dropped = [];
52
+ for (const key of Object.keys(hashes)) {
53
+ if (isUdsCommandHashKey(key, shipped)) continue;
54
+ delete hashes[key];
55
+ dropped.push(key);
56
+ }
57
+ return dropped.sort();
58
+ }
59
+
60
+ /**
61
+ * Agents whose commands are installed, but only outside this project (user level or marketplace).
62
+ * An agent with no recorded installation at all is a legacy manifest and counts as project-level.
63
+ * @param {Object} manifest
64
+ * @returns {Set<string>}
65
+ */
66
+ export function agentsWithCommandsOutsideProject(manifest) {
67
+ const levels = new Map(); // agent -> Set of levels
68
+ for (const entry of manifest?.commands?.installations || []) {
69
+ const agent = typeof entry === 'string' ? entry : entry?.agent;
70
+ const level = typeof entry === 'string' ? 'project' : (entry?.level || 'project');
71
+ if (!agent) continue;
72
+ if (!levels.has(agent)) levels.set(agent, new Set());
73
+ levels.get(agent).add(level);
74
+ }
75
+ return new Set([...levels].filter(([, set]) => !set.has('project')).map(([agent]) => agent));
76
+ }
77
+
78
+ /**
79
+ * The part of `manifest.commandHashes` this project's check is responsible for.
80
+ * @param {Object} manifest
81
+ * @returns {{ hashes: Object, ignored: string[] }} `ignored` are the keys set aside as ELSEWHERE
82
+ */
83
+ export function projectCommandHashes(manifest) {
84
+ const all = manifest?.commandHashes || {};
85
+ const outside = agentsWithCommandsOutsideProject(manifest);
86
+ const hashes = {};
87
+ const ignored = [];
88
+ for (const [key, info] of Object.entries(all)) {
89
+ if (outside.has(key.split('/')[0])) ignored.push(key);
90
+ else hashes[key] = info;
91
+ }
92
+ return { hashes, ignored };
93
+ }
94
+
95
+ /**
96
+ * The command files `uds check` has to report: missing and modified, as one list. Its result is what the
97
+ * verdict is built from — it used to be discarded, like the Skills one.
98
+ * @param {{ missing?: string[], modified?: string[] }} status
99
+ * @returns {string[]}
100
+ */
101
+ export function commandIssuesOf(status) {
102
+ return [...(status?.missing || []), ...(status?.modified || [])];
103
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Judge a commit message against the commit-message standard, in this process.
3
+ * // implements XSPEC-456 R2
4
+ *
5
+ * `uds simulate -s commit-message` used to pipe the message into `npx commitlint`. That needs the
6
+ * network the first time (npx downloads the tool), needs a commitlint config in the project, and
7
+ * interpolates the message into a shell string. In a project with no commitlint config the tool refuses
8
+ * to run at all, and the old code printed that refusal as "Simulation Failed" - the same answer for a
9
+ * compliant message and a non-compliant one, which is the one thing a simulator must not do.
10
+ *
11
+ * Here the verdict comes from the standard's own rules, read from the installed standard file
12
+ * (`.standards/commit-message.ai.yaml`):
13
+ *
14
+ * - the header shape `<type>(<scope>): <subject>` from `format.template` (scope optional, as the
15
+ * standard's component list says);
16
+ * - the allowed types, from the commit-message option files installed next to the standard
17
+ * (`.standards/options/`, files whose `meta.parent` is `commit-message`); the Conventional Commits
18
+ * set when none are installed;
19
+ * - rule `scope-lowercase` and rule `subject-max-length`, using the `validator` pattern the standard gives.
20
+ *
21
+ * What it does NOT judge is returned in `notChecked`, so a pass never reads as more than it is: rules
22
+ * with no machine-checkable pattern (imperative mood, one logical change per commit) and the language
23
+ * option.
24
+ *
25
+ * @module utils/commit-message-judge
26
+ */
27
+
28
+ import fs from 'fs';
29
+ import path from 'path';
30
+ import * as yaml from 'js-yaml';
31
+
32
+ /** Used only when no commit-message option file is installed. The Conventional Commits type set. */
33
+ export const FALLBACK_TYPES = ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert'];
34
+
35
+ /** `type(scope)!: subject` - scope and the breaking-change mark are optional. */
36
+ const HEADER = /^(?<type>[A-Za-z][A-Za-z0-9-]*)(?:\((?<scope>[^()]*)\))?(?<bang>!)?: (?<subject>\S.*)$/;
37
+
38
+ /**
39
+ * The commit types the project's installed option files allow. An option file belongs to this standard when
40
+ * its `meta.parent` is `commit-message`. Installed projects keep option files flat in `.standards/options/`
41
+ * (`english.ai.yaml`); a checkout of UDS itself nests them (`.standards/options/commit-message/`). Both are read.
42
+ * @param {string} standardsDir - `<project>/.standards`
43
+ * @returns {{ types: string[], source: string }}
44
+ */
45
+ export function allowedCommitTypes(standardsDir) {
46
+ const found = new Set();
47
+ const optionsDir = path.join(standardsDir, 'options');
48
+ for (const dir of [optionsDir, path.join(optionsDir, 'commit-message')]) {
49
+ let names = [];
50
+ try {
51
+ names = fs.readdirSync(dir).filter((n) => n.endsWith('.ai.yaml'));
52
+ } catch {
53
+ continue; // this layout is not present
54
+ }
55
+ for (const name of names) {
56
+ try {
57
+ const doc = yaml.load(fs.readFileSync(path.join(dir, name), 'utf-8'));
58
+ if (doc?.meta?.parent !== 'commit-message') continue;
59
+ for (const entry of doc.types || []) {
60
+ if (entry && typeof entry.type === 'string') found.add(entry.type);
61
+ }
62
+ } catch {
63
+ // an unreadable option file contributes nothing
64
+ }
65
+ }
66
+ }
67
+ if (found.size === 0) return { types: FALLBACK_TYPES, source: 'the Conventional Commits set, because no commit-message option file is installed' };
68
+ return { types: [...found], source: '.standards/options' };
69
+ }
70
+
71
+ /** The `validator` pattern of a rule in the standard, as a RegExp, or null when there is none. */
72
+ function ruleValidator(standardConfig, ruleId) {
73
+ const rule = (standardConfig?.standard?.rules || []).find((r) => r && r.id === ruleId);
74
+ if (!rule || typeof rule.validator !== 'string') return null;
75
+ try {
76
+ return new RegExp(rule.validator);
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * @param {Object} standardConfig - the parsed commit-message standard
84
+ * @param {string} input - the commit message (only the first line is the header)
85
+ * @param {{ standardsDir: string }} context
86
+ * @returns {{ verdict: 'pass' | 'fail', findings: string[], checked: string[], notChecked: string[] }}
87
+ */
88
+ export function judgeCommitMessage(standardConfig, input, { standardsDir }) {
89
+ const findings = [];
90
+ const checked = [];
91
+ const notChecked = [];
92
+
93
+ const header = String(input).replace(/\r\n/g, '\n').split('\n')[0];
94
+ const match = HEADER.exec(header);
95
+
96
+ checked.push('header format <type>(<scope>): <subject>');
97
+ if (!match) {
98
+ findings.push('The first line is not in the form <type>(<scope>): <subject> (scope is optional).');
99
+ } else {
100
+ const { type, scope, subject } = match.groups;
101
+ const { types, source } = allowedCommitTypes(standardsDir);
102
+
103
+ checked.push(`type is one of: ${types.join(', ')} (from ${source})`);
104
+ if (!types.includes(type)) {
105
+ findings.push(`Type "${type}" is not one of: ${types.join(', ')}.`);
106
+ }
107
+
108
+ if (scope !== undefined) {
109
+ const scopeRule = ruleValidator(standardConfig, 'scope-lowercase');
110
+ if (scopeRule) {
111
+ checked.push('rule scope-lowercase');
112
+ if (scope === '' || !scopeRule.test(scope)) {
113
+ findings.push(`Scope "${scope}" breaks rule scope-lowercase (use lowercase letters, digits and dashes, starting with a letter).`);
114
+ }
115
+ } else {
116
+ notChecked.push('rule scope-lowercase (this copy of the standard gives no pattern for it)');
117
+ }
118
+ }
119
+
120
+ if (subject.trim() === '') findings.push('The subject is empty.');
121
+ }
122
+
123
+ const lengthRule = ruleValidator(standardConfig, 'subject-max-length');
124
+ if (lengthRule) {
125
+ checked.push('rule subject-max-length');
126
+ if (!lengthRule.test(header)) {
127
+ findings.push(`The subject line is ${header.length} characters, which breaks rule subject-max-length.`);
128
+ }
129
+ } else {
130
+ notChecked.push('rule subject-max-length (this copy of the standard gives no pattern for it)');
131
+ }
132
+
133
+ notChecked.push('rule imperative-mood (the standard gives no machine-checkable pattern)');
134
+ notChecked.push('rule no-mixed-changes and the commit language option');
135
+
136
+ return { verdict: findings.length === 0 ? 'pass' : 'fail', findings, checked, notChecked };
137
+ }
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, copyFileSync } from 'fs';
1
+ import { existsSync, mkdirSync, copyFileSync, readFileSync } from 'fs';
2
2
  import { dirname, join, basename } from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { downloadStandard, downloadIntegration } from './github.js';
@@ -78,6 +78,26 @@ export async function copyExtension(sourcePath, targetDir, projectPath) {
78
78
  }
79
79
  }
80
80
 
81
+ /**
82
+ * Read the original of a source path from the installed package — never from the network.
83
+ *
84
+ * This is what `uds check --diff` compares an adopter's file against (XSPEC-453 R1). The original
85
+ * used to be downloaded from GitHub `main`: offline it failed, and whatever UDS had changed on `main`
86
+ * since the adopter installed was listed as a difference the adopter had made. The package's own copy
87
+ * is the version that was installed, so a difference against it is the adopter's.
88
+ *
89
+ * Returns `null` when the installed package has no such file; the caller says so by name. There is
90
+ * deliberately no fallback to a download here.
91
+ *
92
+ * @param {string} sourcePath - Relative path from repo root (e.g., 'ai/standards/x.ai.yaml', 'extensions/locales/zh-tw.md')
93
+ * @returns {string|null} File content, or null if the installed package does not contain it
94
+ */
95
+ export function readPackagedSource(sourcePath) {
96
+ const source = getSourcePath(sourcePath);
97
+ if (!source) return null;
98
+ return readFileSync(source, 'utf-8');
99
+ }
100
+
81
101
  /**
82
102
  * Copy a standard file to target project
83
103
  * Falls back to downloading from GitHub if local file not found
@@ -0,0 +1,25 @@
1
+ /**
2
+ * When `uds deps --if-present` is allowed to say "not applicable" instead of failing.
3
+ * // implements XSPEC-456 R6
4
+ *
5
+ * `uds deps` exits 1 when there is no package.json, on purpose: a check that examined nothing must not
6
+ * be able to show a pass (the same rule as `clean` in utils/dependency-resolution.js). That makes it
7
+ * awkward in a shared script that also runs in .NET, Python or Go projects, where callers ended up
8
+ * writing `if [ -f package.json ]` around it. `--if-present` is that guard made part of the command
9
+ * AND visible: the run says nothing was checked, in words, and exits 0.
10
+ *
11
+ * @module utils/deps-applicability
12
+ */
13
+
14
+ import { existsSync } from 'fs';
15
+ import { join } from 'path';
16
+
17
+ /**
18
+ * @param {string} root - Directory `uds deps` would examine
19
+ * @param {boolean} ifPresent - Whether `--if-present` was given
20
+ * @returns {'no-package-json' | null} Why the run is not applicable, or null when it must be run
21
+ */
22
+ export function notApplicableReason(root, ifPresent) {
23
+ if (ifPresent && !existsSync(join(root, 'package.json'))) return 'no-package-json';
24
+ return null;
25
+ }