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

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 (84) hide show
  1. package/README.md +13 -3
  2. package/bin/uds.js +30 -6
  3. package/bundled/ai/options/code-review/pr-review.ai.yaml +20 -1
  4. package/bundled/ai/standards/code-review.ai.yaml +15 -2
  5. package/bundled/ai/standards/developer-memory.ai.yaml +12 -2
  6. package/bundled/ai/standards/full-coverage-testing.ai.yaml +44 -6
  7. package/bundled/ai/standards/open-work-tracking.ai.yaml +191 -11
  8. package/bundled/ai/standards/pipeline-security-gates.ai.yaml +48 -3
  9. package/bundled/ai/standards/project-context-memory.ai.yaml +12 -2
  10. package/bundled/core/code-review-checklist.md +20 -2
  11. package/bundled/core/developer-memory.md +12 -2
  12. package/bundled/core/full-coverage-testing.md +44 -4
  13. package/bundled/core/open-work-tracking.md +156 -16
  14. package/bundled/core/pipeline-security-gates.md +63 -0
  15. package/bundled/core/project-context-memory.md +10 -2
  16. package/bundled/locales/zh-CN/CHANGELOG.md +51 -3
  17. package/bundled/locales/zh-CN/README.md +1 -1
  18. package/bundled/locales/zh-CN/SECURITY.md +1 -1
  19. package/bundled/locales/zh-CN/adoption/ADOPTION-GUIDE.md +13 -4
  20. package/bundled/locales/zh-CN/adoption/STATIC-DYNAMIC-GUIDE.md +7 -1
  21. package/bundled/locales/zh-CN/adoption/checklists/enterprise.md +7 -1
  22. package/bundled/locales/zh-CN/adoption/checklists/minimal.md +13 -3
  23. package/bundled/locales/zh-CN/adoption/checklists/recommended.md +7 -1
  24. package/bundled/locales/zh-CN/core/code-review-checklist.md +17 -0
  25. package/bundled/locales/zh-CN/core/developer-memory.md +9 -0
  26. package/bundled/locales/zh-CN/core/full-coverage-testing.md +48 -8
  27. package/bundled/locales/zh-CN/core/pipeline-security-gates.md +64 -4
  28. package/bundled/locales/zh-CN/core/project-context-memory.md +5 -0
  29. package/bundled/locales/zh-CN/docs/AVAILABLE-STANDARDS.md +70 -0
  30. package/bundled/locales/zh-CN/docs/CHEATSHEET.md +4 -3
  31. package/bundled/locales/zh-CN/docs/CLI-INIT-OPTIONS.md +25 -23
  32. package/bundled/locales/zh-CN/docs/FEATURE-REFERENCE.md +13 -11
  33. package/bundled/locales/zh-CN/docs/USAGE-MODES-COMPARISON.md +6 -6
  34. package/bundled/locales/zh-CN/docs/WINDOWS-GUIDE.md +7 -1
  35. package/bundled/locales/zh-CN/docs/user/GETTING-STARTED.md +44 -0
  36. package/bundled/locales/zh-CN/options/code-review/pr-review.md +13 -2
  37. package/bundled/locales/zh-TW/CHANGELOG.md +51 -3
  38. package/bundled/locales/zh-TW/README.md +1 -1
  39. package/bundled/locales/zh-TW/SECURITY.md +1 -1
  40. package/bundled/locales/zh-TW/adoption/ADOPTION-GUIDE.md +13 -4
  41. package/bundled/locales/zh-TW/adoption/STATIC-DYNAMIC-GUIDE.md +7 -1
  42. package/bundled/locales/zh-TW/adoption/checklists/enterprise.md +7 -1
  43. package/bundled/locales/zh-TW/adoption/checklists/minimal.md +13 -3
  44. package/bundled/locales/zh-TW/adoption/checklists/recommended.md +7 -1
  45. package/bundled/locales/zh-TW/core/code-review-checklist.md +17 -0
  46. package/bundled/locales/zh-TW/core/developer-memory.md +9 -0
  47. package/bundled/locales/zh-TW/core/full-coverage-testing.md +48 -8
  48. package/bundled/locales/zh-TW/core/open-work-tracking.md +90 -14
  49. package/bundled/locales/zh-TW/core/pipeline-security-gates.md +64 -4
  50. package/bundled/locales/zh-TW/core/project-context-memory.md +5 -0
  51. package/bundled/locales/zh-TW/docs/AVAILABLE-STANDARDS.md +70 -0
  52. package/bundled/locales/zh-TW/docs/CHEATSHEET.md +4 -3
  53. package/bundled/locales/zh-TW/docs/CLI-INIT-OPTIONS.md +25 -23
  54. package/bundled/locales/zh-TW/docs/FEATURE-REFERENCE.md +13 -11
  55. package/bundled/locales/zh-TW/docs/USAGE-MODES-COMPARISON.md +6 -6
  56. package/bundled/locales/zh-TW/docs/WINDOWS-GUIDE.md +7 -1
  57. package/bundled/locales/zh-TW/docs/user/GETTING-STARTED.md +44 -0
  58. package/bundled/locales/zh-TW/options/code-review/pr-review.md +13 -2
  59. package/bundled/skills/SKILL_NAMING.md +9 -0
  60. package/bundled/templates/gates/check-anti-fake-tests.mjs +305 -5
  61. package/package.json +3 -1
  62. package/src/commands/audit.js +9 -2
  63. package/src/commands/check.js +17 -0
  64. package/src/commands/init.js +41 -21
  65. package/src/commands/open-work.js +65 -6
  66. package/src/commands/skills.js +19 -33
  67. package/src/commands/update.js +61 -61
  68. package/src/core/open-work-config.js +103 -0
  69. package/src/flows/init-flow.js +10 -0
  70. package/src/i18n/messages.js +237 -60
  71. package/src/installers/skills-installer.js +3 -1
  72. package/src/prompts/init.js +148 -13
  73. package/src/reconciler/index.js +42 -5
  74. package/src/utils/available-standards-report.js +144 -0
  75. package/src/utils/available-standards.js +216 -0
  76. package/src/utils/copier.js +5 -4
  77. package/src/utils/friction-detector.js +27 -0
  78. package/src/utils/open-work-tracking.mjs +919 -48
  79. package/src/utils/skill-frontmatter.js +102 -0
  80. package/src/utils/skill-name-collision.js +169 -0
  81. package/src/utils/skills-install-paths.js +114 -0
  82. package/src/utils/skills-installer.js +63 -105
  83. package/src/utils/transient-fs.js +113 -0
  84. package/standards-registry.json +9 -9
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, writeFileSync, readdirSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import chalk from 'chalk';
5
5
  import os from 'os';
6
+ import * as yaml from 'js-yaml';
6
7
  import { t, setLanguage, detectLanguage } from '../i18n/messages.js';
7
8
  import {
8
9
  getAgentConfig,
@@ -169,7 +170,7 @@ export async function promptSkillsInstallLocation(selectedTools = []) {
169
170
  // Show Marketplace info for Claude Code (not as a selectable option)
170
171
  if (hasClaudeCode) {
171
172
  console.log();
172
- console.log(chalk.yellow(` 💡 ${marketplaceMsg.claudeCodeTip || 'Claude Code can be installed via Marketplace:'}`));
173
+ console.log(chalk.yellow(` 💡 ${marketplaceMsg.claudeCodeTip}`));
173
174
  console.log(chalk.white(' /plugin install universal-dev-standards@asia-ostrich'));
174
175
  console.log(chalk.gray(` → ${msg.choices.marketplace}`));
175
176
  }
@@ -195,10 +196,12 @@ export async function promptSkillsInstallLocation(selectedTools = []) {
195
196
  value: `${tool}:user`
196
197
  });
197
198
 
198
- // Project level option
199
+ // Project level option. Pre-selected (XSPEC-468 R1): the project way is the main path, so pressing Enter
200
+ // installs the skills into the project. Deselect everything to skip them (for example, to use the plugin).
199
201
  choices.push({
200
202
  name: `${chalk.blue(displayName)} - ${msg.choices.projectLevel} ${chalk.gray(`(${config.skills.project})`)}`,
201
- value: `${tool}:project`
203
+ value: `${tool}:project`,
204
+ checked: true
202
205
  });
203
206
  }
204
207
 
@@ -1427,8 +1430,22 @@ export function suggestCommands(projectPath) {
1427
1430
  return { test: '', lint: '', build: '', security: '' };
1428
1431
  }
1429
1432
 
1433
+ /**
1434
+ * A command as it is written after `key: ` in YAML. Plain when plain is safe; single-quoted (the form that
1435
+ * has no escape sequences, so a Windows path survives) when the text would otherwise change meaning.
1436
+ * @param {string} command
1437
+ * @returns {string}
1438
+ */
1439
+ function yamlCommandScalar(command) {
1440
+ const text = command.trim();
1441
+ const needsQuotes = /^[\s'"[\]{}&*!|>%@`,?#-]|: | #|:$/.test(text);
1442
+ return needsQuotes ? `'${text.replaceAll("'", "''")}'` : text;
1443
+ }
1444
+
1430
1445
  /**
1431
1446
  * Generate uds.project.yaml content from a commands map.
1447
+ * This writes a NEW file. To change the commands of an existing file without losing its other sections,
1448
+ * use `mergeProjectConfigYaml`.
1432
1449
  * @param {{ test?: string, lint?: string, build?: string, security?: string }} commands
1433
1450
  * @returns {string}
1434
1451
  */
@@ -1436,12 +1453,111 @@ export function generateProjectConfigYaml(commands) {
1436
1453
  const lines = ['version: "1"', '', 'commands:'];
1437
1454
  for (const [intent, cmd] of Object.entries(commands)) {
1438
1455
  if (cmd && cmd.trim()) {
1439
- lines.push(` ${intent}: ${cmd.trim()}`);
1456
+ lines.push(` ${intent}: ${yamlCommandScalar(cmd)}`);
1440
1457
  }
1441
1458
  }
1442
1459
  return lines.join('\n') + '\n';
1443
1460
  }
1444
1461
 
1462
+ /**
1463
+ * What an existing uds.project.yaml holds, as far as the wizard needs it: the names of its top-level sections
1464
+ * and the commands it already declares. `readable: false` means the text is not YAML (or not a mapping), so
1465
+ * nothing in it can be kept apart from the whole file.
1466
+ *
1467
+ * @param {string} text
1468
+ * @returns {{ readable: boolean, sections: string[], commands: Record<string, string> }}
1469
+ */
1470
+ export function describeProjectConfig(text) {
1471
+ let doc;
1472
+ try {
1473
+ doc = yaml.load(text);
1474
+ } catch {
1475
+ return { readable: false, sections: [], commands: {} };
1476
+ }
1477
+ if (doc === null || doc === undefined) return { readable: true, sections: [], commands: {} };
1478
+ if (typeof doc !== 'object' || Array.isArray(doc)) return { readable: false, sections: [], commands: {} };
1479
+ const commands = {};
1480
+ if (doc.commands && typeof doc.commands === 'object' && !Array.isArray(doc.commands)) {
1481
+ for (const [k, v] of Object.entries(doc.commands)) commands[k] = v === null || v === undefined ? '' : String(v);
1482
+ }
1483
+ return { readable: true, sections: Object.keys(doc), commands };
1484
+ }
1485
+
1486
+ /**
1487
+ * Change the command keys of an existing uds.project.yaml and leave every other byte of it alone
1488
+ * (XSPEC-468 R5). The wizard used to rewrite the whole file from `generateProjectConfigYaml`, which dropped
1489
+ * `open_work:` (the place an adopter declares what `uds open-work` needs, XSPEC-460/461), `custom:`, comments,
1490
+ * and anything else the wizard does not ask about.
1491
+ *
1492
+ * Works on the text, not on a parsed copy: a parse-and-dump would keep the data and lose the comments, the
1493
+ * order and the quoting. Only lines of the top-level `commands:` block that name one of the given intents
1494
+ * are replaced (with their indented continuation lines); an intent that is not there yet is added at the end
1495
+ * of that block; with no `commands:` block at all one is appended to the end of the file. An intent whose
1496
+ * value already equals the new one is not touched. Blank commands are skipped.
1497
+ *
1498
+ * @param {string} existing - current file text
1499
+ * @param {Record<string, string>} commands - intent -> command
1500
+ * @returns {string} the new file text
1501
+ */
1502
+ export function mergeProjectConfigYaml(existing, commands) {
1503
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
1504
+ const endsWithNewline = /\n$/.test(existing);
1505
+ const lines = existing.split(/\r?\n/);
1506
+ if (endsWithNewline) lines.pop();
1507
+ const current = describeProjectConfig(existing).commands;
1508
+ const wanted = Object.entries(commands)
1509
+ .filter(([, cmd]) => cmd && cmd.trim())
1510
+ .filter(([intent, cmd]) => current[intent] !== cmd.trim());
1511
+ if (wanted.length === 0) return existing;
1512
+
1513
+ const entryLine = (indent, intent, cmd) => `${indent}${intent}: ${yamlCommandScalar(cmd)}`;
1514
+ const headIdx = lines.findIndex(l => /^commands\s*:/.test(l));
1515
+
1516
+ if (headIdx === -1) {
1517
+ if (lines.length > 0 && lines[lines.length - 1].trim() !== '') lines.push('');
1518
+ lines.push('commands:');
1519
+ for (const [intent, cmd] of wanted) lines.push(entryLine(' ', intent, cmd));
1520
+ return lines.join(eol) + eol;
1521
+ }
1522
+
1523
+ const inlineValue = lines[headIdx].replace(/^commands\s*:/, '').replace(/\s+#.*$/, '').trim();
1524
+ if (inlineValue) {
1525
+ // `commands: {test: x}` written on one line: turn it into a block that keeps the keys it had.
1526
+ const merged = { ...current };
1527
+ for (const [intent, cmd] of wanted) merged[intent] = cmd.trim();
1528
+ const block = ['commands:', ...Object.entries(merged).filter(([, c]) => c).map(([i, c]) => entryLine(' ', i, c))];
1529
+ lines.splice(headIdx, 1, ...block);
1530
+ return lines.join(eol) + eol;
1531
+ }
1532
+
1533
+ // The block runs until the next line that starts in column 0 (a section, or a comment about one).
1534
+ let end = headIdx + 1;
1535
+ while (end < lines.length && (lines[end].trim() === '' || /^\s/.test(lines[end]))) end++;
1536
+ while (end > headIdx + 1 && lines[end - 1].trim() === '') end--; // blank lines after the block are not in it
1537
+
1538
+ const firstKey = lines.slice(headIdx + 1, end).find(l => l.trim() !== '' && !l.trim().startsWith('#'));
1539
+ const indent = firstKey ? firstKey.match(/^\s*/)[0] : ' ';
1540
+
1541
+ for (const [intent, cmd] of wanted) {
1542
+ const keyLine = new RegExp(`^${indent}${intent.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:`);
1543
+ let at = -1;
1544
+ for (let i = headIdx + 1; i < end; i++) {
1545
+ if (keyLine.test(lines[i])) { at = i; break; }
1546
+ }
1547
+ if (at === -1) {
1548
+ lines.splice(end, 0, entryLine(indent, intent, cmd));
1549
+ end += 1;
1550
+ continue;
1551
+ }
1552
+ // The old value may continue on deeper-indented lines (a block scalar): they go with it.
1553
+ let stop = at + 1;
1554
+ while (stop < end && (lines[stop].trim() === '' ? false : lines[stop].match(/^\s*/)[0].length > indent.length)) stop++;
1555
+ lines.splice(at, stop - at, entryLine(indent, intent, cmd));
1556
+ end -= (stop - at) - 1;
1557
+ }
1558
+ return lines.join(eol) + eol;
1559
+ }
1560
+
1445
1561
  /**
1446
1562
  * Wraps promptProjectCommandContract with an initial confirm prompt.
1447
1563
  * Used as the optional Step 13 in the init flow so the whole step can be
@@ -1475,15 +1591,28 @@ export async function promptProjectContractStep(projectPath) {
1475
1591
  export async function promptProjectCommandContract(projectPath) {
1476
1592
  const contractPath = join(projectPath, 'uds.project.yaml');
1477
1593
 
1478
- // If already exists, ask whether to overwrite
1594
+ // If it already exists, ask before touching it. XSPEC-468 R5: the question says exactly what will change.
1595
+ // The wizard only manages the command keys; every other section (`open_work:`, `custom:`, ...) stays.
1596
+ let existingText = null;
1597
+ let existing = null;
1479
1598
  if (existsSync(contractPath)) {
1599
+ existingText = readFileSync(contractPath, 'utf-8');
1600
+ existing = describeProjectConfig(existingText);
1601
+
1480
1602
  console.log();
1481
1603
  console.log(chalk.yellow(' uds.project.yaml already exists.'));
1482
1604
 
1483
- const overwrite = await inquirerConfirm({
1484
- message: 'Overwrite existing uds.project.yaml?',
1485
- default: false
1486
- });
1605
+ const kept = existing.sections.filter(name => name !== 'commands');
1606
+ const message = existing.readable
1607
+ ? 'Update the commands (test, lint, build, security) in the existing uds.project.yaml? ' +
1608
+ (kept.length > 0
1609
+ ? `These sections are kept exactly as they are: ${kept.join(', ')}.`
1610
+ : 'It has no other sections.')
1611
+ // Not YAML: nothing in it can be kept, so the question names the loss instead of hiding it.
1612
+ : 'The existing uds.project.yaml cannot be read as YAML, so none of its content can be kept. ' +
1613
+ 'Replace the whole file?';
1614
+
1615
+ const overwrite = await inquirerConfirm({ message, default: false });
1487
1616
 
1488
1617
  if (!overwrite) {
1489
1618
  console.log(chalk.gray(' Skipped — keeping existing uds.project.yaml'));
@@ -1512,7 +1641,8 @@ export async function promptProjectCommandContract(projectPath) {
1512
1641
  const commands = {};
1513
1642
 
1514
1643
  for (const intent of intents) {
1515
- const defaultVal = suggestions[intent] || '';
1644
+ // A command the file already declares is the default, so Enter keeps it; the ecosystem guess only fills gaps.
1645
+ const defaultVal = existing?.commands?.[intent] || suggestions[intent] || '';
1516
1646
  const answer = await input({
1517
1647
  message: ` ${intent} command${defaultVal ? ` (default: ${defaultVal})` : ' (optional)'}:`,
1518
1648
  default: defaultVal
@@ -1526,11 +1656,16 @@ export async function promptProjectCommandContract(projectPath) {
1526
1656
  return false;
1527
1657
  }
1528
1658
 
1529
- const yaml = generateProjectConfigYaml(commands);
1530
- writeFileSync(contractPath, yaml, 'utf-8');
1659
+ // An existing, readable file is edited in place (XSPEC-468 R5); a new file, or one that is not YAML at all
1660
+ // and that the user agreed to replace, is written whole.
1661
+ const merging = existing?.readable === true;
1662
+ const content = merging
1663
+ ? mergeProjectConfigYaml(existingText, commands)
1664
+ : generateProjectConfigYaml(commands);
1665
+ writeFileSync(contractPath, content, 'utf-8');
1531
1666
 
1532
1667
  console.log();
1533
- console.log(chalk.green(' ✔ uds.project.yaml created'));
1668
+ console.log(chalk.green(merging ? ' ✔ uds.project.yaml updated (other sections kept as they were)' : ' ✔ uds.project.yaml created'));
1534
1669
  console.log(chalk.gray(` Path: ${contractPath}`));
1535
1670
  return true;
1536
1671
  }
@@ -21,7 +21,7 @@
21
21
  * const rollbackResult = rollbackLast(projectPath);
22
22
  */
23
23
 
24
- import { readManifest, writeManifest, needsMigration } from '../core/manifest.js';
24
+ import { readManifest, writeManifest, needsMigration, migrateStandardsPathsToIds } from '../core/manifest.js';
25
25
  import { migrateAndBackfill } from './manifest-migrator.js';
26
26
  import { calculateDesiredState } from './desired-state-calculator.js';
27
27
  import { scanActualState, legacyDiscovery } from './actual-state-scanner.js';
@@ -133,12 +133,40 @@ function reconcileFileHashes(manifest, verifiedPristine) {
133
133
  };
134
134
  }
135
135
 
136
+ /**
137
+ * A copy of `manifest` with extra standards listed (XSPEC-458 R3, `uds update --add-standard`).
138
+ *
139
+ * The reconciler treats a file under `.standards/` that the manifest does not list as surplus and
140
+ * deletes it, so a standard the user picks has to be in the manifest the plan is computed from AND
141
+ * in the manifest the executor writes back. Both are this copy. The manifest ON DISK is not touched
142
+ * here: the backup the executor takes holds the old one, which is what lets one `--rollback` take
143
+ * the standard out again.
144
+ *
145
+ * The list is put through the same normalisation `readManifest` applies on every read (registry ids
146
+ * sorted, option paths after them). That is not tidiness: the integration blocks (CLAUDE.md,
147
+ * AGENTS.md) are generated from this list, and their text depends on its order. Generated from an
148
+ * un-normalised copy, the block would differ from what the next run expects of the manifest as
149
+ * written, and `--plan` would still show "migrate block" after a successful `--apply`.
150
+ *
151
+ * @param {Object} manifest
152
+ * @param {string[]} [ids] - Registry ids to add
153
+ * @returns {Object}
154
+ */
155
+ export function withAddedStandards(manifest, ids = []) {
156
+ if (!manifest || ids.length === 0) return manifest;
157
+ const listed = new Set(manifest.standards || []);
158
+ const added = ids.filter(id => !listed.has(id));
159
+ if (added.length === 0) return manifest;
160
+ return { ...manifest, standards: migrateStandardsPathsToIds([...(manifest.standards || []), ...added]) };
161
+ }
162
+
136
163
  export async function reconcile(projectPath, options = {}) {
137
- const { force = false, backup = true, onAction } = options;
164
+ const { force = false, backup = true, onAction, addStandards = [] } = options;
138
165
  const errors = [];
139
166
 
140
167
  // Step 1: Get manifest (migrate if needed, or discover from legacy)
141
- const { manifest, migrationErrors } = await getManifest(projectPath);
168
+ const { manifest: diskManifest, migrationErrors } = await getManifest(projectPath);
169
+ const manifest = withAddedStandards(diskManifest, addStandards);
142
170
  if (migrationErrors.length > 0) errors.push(...migrationErrors);
143
171
  if (!manifest) {
144
172
  return {
@@ -173,6 +201,13 @@ export async function reconcile(projectPath, options = {}) {
173
201
  // Writing it here first would put the hash correction into the backup's "before" copy, so a rollback
174
202
  // could not give back the manifest byte for byte (XSPEC-454 R1).
175
203
  if (hashFix && reconciliationPlan.actions.length === 0) writeManifest(effectiveManifest, projectPath);
204
+ // XSPEC-458 R3: a chosen standard whose file is already on disk, byte for byte, produces no action —
205
+ // and with no action the executor never writes the manifest, so the choice would be lost and the next
206
+ // run would call that file surplus. Record it. (Nothing but the manifest changes, so there is no
207
+ // file for a backup to protect.)
208
+ if (addStandards.length > 0 && !hashFix && manifest !== diskManifest && reconciliationPlan.actions.length === 0) {
209
+ writeManifest(effectiveManifest, projectPath);
210
+ }
176
211
 
177
212
  // Step 5: Execute plan
178
213
  if (reconciliationPlan.actions.length === 0) {
@@ -217,10 +252,12 @@ export async function reconcile(projectPath, options = {}) {
217
252
  * }>}
218
253
  */
219
254
  export async function plan(projectPath, options = {}) {
220
- const { force = false } = options;
255
+ const { force = false, addStandards = [] } = options;
221
256
  const errors = [];
222
257
 
223
- const { manifest, migrationErrors } = await getManifest(projectPath);
258
+ const { manifest: diskManifest, migrationErrors } = await getManifest(projectPath);
259
+ // XSPEC-458 R3: `--plan --add-standard X` plans from the manifest as it would be with X listed.
260
+ const manifest = withAddedStandards(diskManifest, addStandards);
224
261
  if (migrationErrors.length > 0) errors.push(...migrationErrors);
225
262
  if (!manifest) {
226
263
  return {
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Printing for the "available upstream, not installed" findings (XSPEC-458 R2, R3, R5).
3
+ *
4
+ * Everything here reads `getAvailableStandards()` and prints; none of it changes a plan, a verdict,
5
+ * an exit code or a score. (The one exception is `resolveAddStandardRequest`, which sets a non-zero
6
+ * exit code for a bad `--add-standard` id — that is its whole job.)
7
+ *
8
+ * @module utils/available-standards-report
9
+ */
10
+
11
+ import chalk from 'chalk';
12
+ import { t } from '../i18n/messages.js';
13
+ import { getAvailableStandards, judgeAddStandard } from './available-standards.js';
14
+
15
+ const CATEGORY_ORDER = ['reference', 'skill'];
16
+
17
+ function fill(template, values) {
18
+ return Object.entries(values).reduce((text, [key, value]) => text.replaceAll(`{${key}}`, String(value)), template);
19
+ }
20
+
21
+ function breakdown(byCategory) {
22
+ return Object.entries(byCategory)
23
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
24
+ .map(([category, count]) => `${category} ${count}`)
25
+ .join(', ');
26
+ }
27
+
28
+ /**
29
+ * `uds update --plan` / `--apply`: the section itself, or (apply) its count and the commands.
30
+ * Always printed — "none" is said out loud, because silence reads as "this step did not run".
31
+ *
32
+ * @param {Object} manifest - The manifest the plan was computed from (a standard chosen with
33
+ * --add-standard is already in it, so it is not listed as still available)
34
+ * @param {{phase: 'plan'|'apply'}} opts
35
+ */
36
+ export function printAvailableStandardsSection(manifest, { phase }) {
37
+ const msg = t().availableStandards;
38
+ const { offered, notOffered, notOfferedByCategory } = getAvailableStandards(manifest);
39
+
40
+ console.log();
41
+ if (offered.length === 0) {
42
+ console.log(chalk.gray(msg.none));
43
+ } else if (phase === 'apply') {
44
+ console.log(chalk.cyan(fill(msg.applySummary, { count: offered.length })));
45
+ console.log(chalk.gray(` ${msg.applyHint}`));
46
+ } else {
47
+ console.log(chalk.cyan(fill(msg.title, { count: offered.length })));
48
+ const categories = [...new Set([...CATEGORY_ORDER, ...offered.map(s => s.category)])];
49
+ for (const category of categories) {
50
+ const group = offered.filter(s => s.category === category);
51
+ if (group.length === 0) continue;
52
+ console.log(chalk.bold(` ${fill(msg.categoryLine, { category, count: group.length })}`));
53
+ for (const std of group) {
54
+ console.log(` ${chalk.green(std.id)} ${chalk.gray(`— ${std.description}`)}`);
55
+ }
56
+ }
57
+ console.log(chalk.gray(` ${msg.installHint}`));
58
+ }
59
+
60
+ if (notOffered.length > 0) {
61
+ console.log(chalk.gray(fill(msg.othersLine, { count: notOffered.length, breakdown: breakdown(notOfferedByCategory) })));
62
+ }
63
+ }
64
+
65
+ /** `uds check`: one line, never part of the verdict. */
66
+ export function printAvailableStandardsCheckLine(manifest) {
67
+ const msg = t().availableStandards;
68
+ const { offered } = getAvailableStandards(manifest);
69
+ if (offered.length === 0) {
70
+ console.log(chalk.gray(msg.checkNone));
71
+ } else {
72
+ console.log(chalk.cyan(fill(msg.checkLine, { count: offered.length })));
73
+ }
74
+ }
75
+
76
+ /**
77
+ * `--add-standard` belongs to the reconciliation (`--plan` / `--apply`). Any other mode would take the
78
+ * flag and quietly not use it, so those combinations are refused, in words.
79
+ *
80
+ * @param {Object} options - Parsed `uds update` options
81
+ * @returns {string|null} The message to print, or null when the flags are compatible
82
+ */
83
+ export function findAddStandardConflict(options) {
84
+ const msg = t().availableStandards;
85
+ if (!options.plan && !options.apply && !options.force) return msg.addNeedsMode;
86
+ const clashes = [
87
+ ['rollback', '--rollback'], ['claudeTarget', '--claude-target'], ['withHooks', '--with-hooks'],
88
+ ['syncRefs', '--sync-refs'], ['integrationsOnly', '--integrations-only']
89
+ ];
90
+ for (const [key, flag] of clashes) {
91
+ if (options[key]) return fill(msg.addCannotCombine, { flag });
92
+ }
93
+ if (options.plan && options.skills) return fill(msg.addCannotCombine, { flag: '--plan --skills' });
94
+ if (options.plan && options.commands) return fill(msg.addCannotCombine, { flag: '--plan --commands' });
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * Judge every `--add-standard <id>`, say what is wrong with the ones that are, and return what is
100
+ * left to install. A bad id is never ignored: it prints the problem, sets a non-zero exit code and
101
+ * stops the run (`proceed: false`) before anything is planned or written.
102
+ *
103
+ * @param {Object} manifest
104
+ * @param {string[]} ids
105
+ * @returns {{proceed: boolean, ids: string[], alreadyInstalled: string[]}}
106
+ */
107
+ export function resolveAddStandardRequest(manifest, ids) {
108
+ const msg = t().availableStandards;
109
+ const toAdd = [];
110
+ const alreadyInstalled = [];
111
+ let failed = false;
112
+
113
+ for (const id of [...new Set(ids)]) {
114
+ const judged = judgeAddStandard(id, manifest);
115
+ switch (judged.status) {
116
+ case 'add':
117
+ toAdd.push(id);
118
+ break;
119
+ case 'installed':
120
+ alreadyInstalled.push(id);
121
+ console.log(chalk.gray(fill(msg.addAlreadyInstalled, { id })));
122
+ break;
123
+ case 'unknown':
124
+ failed = true;
125
+ console.log(chalk.red(fill(msg.addUnknown, { id })));
126
+ for (const near of judged.closest) console.log(chalk.gray(` ${near}`));
127
+ break;
128
+ case 'other-means':
129
+ failed = true;
130
+ console.log(chalk.red(fill(msg.addOtherMeans, { id, category: judged.entry.category })));
131
+ break;
132
+ default:
133
+ failed = true;
134
+ console.log(chalk.red(fill(msg.addNoSource, { id, format: manifest.format || 'ai' })));
135
+ }
136
+ }
137
+
138
+ if (failed) {
139
+ process.exitCode = 1;
140
+ console.log();
141
+ return { proceed: false, ids: [], alreadyInstalled };
142
+ }
143
+ return { proceed: true, ids: toAdd, alreadyInstalled };
144
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Available-but-not-installed standards (XSPEC-458 R1).
3
+ *
4
+ * ONE definition, used by three commands. `uds update` (the old path's "new standards" list,
5
+ * `--plan`/`--apply`'s "available upstream" section, `--add-standard`), `uds check`'s one-line
6
+ * count and `uds audit --friction` all ask this module and nothing else. Before this existed the
7
+ * old path had its own copy inside update.js and the reconciler path had none: `--apply` printed
8
+ * a green "everything is up to date" for a project that was missing a standard UDS ships.
9
+ *
10
+ * What counts as "available but not installed"
11
+ * --------------------------------------------
12
+ * A registry standard that
13
+ * 1. is in a category `uds init` installs (reference, skill — see OFFERED_CATEGORIES),
14
+ * 2. has a source file in the project's `manifest.format` (a skill-only entry has none), and
15
+ * 3. is not already in `manifest.standards` (matched by file name, so an ID-format entry
16
+ * and a path-format entry such as `ai/standards/x.ai.yaml` both count as installed).
17
+ * That is exactly the set the old `checkNewStandards()` computed; it now calls this.
18
+ *
19
+ * What does NOT count, and is reported instead of being dropped (`notOffered`)
20
+ * ----------------------------------------------------------------------------
21
+ * Every other registry category (core, testing, security, deployment, operations, extension,
22
+ * integration, template). `uds init` has never installed them, so for a project they are not
23
+ * "new upstream" — they were never in the offer. Why, per category, is in CATEGORY_NOTES.
24
+ * They are still returned (with a reason) so no command can silently pretend they do not exist.
25
+ *
26
+ * Manifest fields that look like they should matter, and do not (measured 2026-10-07):
27
+ * - `level` — a manifest written by 6.11.0 carries it only as a leftover snapshot inside
28
+ * `integrationConfigs[<file>].level`; no code reads it to decide what to install, the generator
29
+ * never reads `config.level`, and the registry's level system is a deprecated stub (registry.js).
30
+ * DEAD.
31
+ * - `profile` — appears nowhere in the CLI or in any manifest. DEAD (it does not exist).
32
+ * - `contentMode` — LIVE, but only for how the integration file (CLAUDE.md) is rendered
33
+ * (minimal vs index). It never decides which standards are installed.
34
+ * None of the three enters this computation, on purpose.
35
+ *
36
+ * @module utils/available-standards
37
+ */
38
+
39
+ import { basename } from 'path';
40
+ import { getAllStandards, getStandardSource } from './registry.js';
41
+
42
+ /** Categories `uds init` installs into `.standards/`. Must match installers/standards-installer.js. */
43
+ export const OFFERED_CATEGORIES = Object.freeze(['reference', 'skill']);
44
+
45
+ /**
46
+ * Categories whose registry entry is not a plain standard file under `.standards/`: they are
47
+ * installed by other means (a language/locale option, a per-tool integration file, a template
48
+ * copy), so `--add-standard` does not install them.
49
+ */
50
+ export const INSTALLED_BY_OTHER_MEANS = Object.freeze(['extension', 'integration', 'template']);
51
+
52
+ /**
53
+ * Why each category outside OFFERED_CATEGORIES is not offered. Written down so the exclusion is a
54
+ * visible decision, not a filter nobody can explain. (Rendered in docs/user/CLI-REFERENCE and the
55
+ * R1 section of the update guide; keep in step with them.)
56
+ */
57
+ export const CATEGORY_NOTES = Object.freeze({
58
+ core: 'added to the registry after the installer\'s reference/skill filter was written; never installed by init',
59
+ testing: 'same as core: added later, never installed by init',
60
+ security: 'same as core: added later, never installed by init',
61
+ deployment: 'same as core: added later, never installed by init',
62
+ operations: 'same as core: added later, never installed by init',
63
+ extension: 'installed by a language/framework/locale choice at init, not as a standard',
64
+ integration: 'a per-tool integration file, installed through the AI-tool choice at init',
65
+ template: 'a document template to copy, not a standard file'
66
+ });
67
+
68
+ /**
69
+ * File names (basenames) of the standards a manifest already lists.
70
+ * Handles both legacy path entries ("ai/standards/foo.ai.yaml") and ID entries ("foo").
71
+ * Option paths are skipped: they live under `.standards/options/` and are not standards.
72
+ *
73
+ * @param {Object} manifest
74
+ * @param {Array} [registryStandards]
75
+ * @returns {Set<string>}
76
+ */
77
+ export function installedStandardFileNames(manifest, registryStandards = getAllStandards()) {
78
+ const format = manifest.format || 'ai';
79
+ const names = new Set();
80
+ for (const s of (manifest.standards || [])) {
81
+ if (typeof s !== 'string') continue;
82
+ if (s.includes('/options/') || s.startsWith('options/')) continue;
83
+ if (!s.includes('/') && !s.includes('.')) {
84
+ const entry = registryStandards.find(r => r.id === s);
85
+ if (entry) {
86
+ const sourcePath = getStandardSource(entry, format);
87
+ if (sourcePath) names.add(basename(sourcePath));
88
+ }
89
+ } else {
90
+ names.add(basename(s));
91
+ }
92
+ }
93
+ return names;
94
+ }
95
+
96
+ /**
97
+ * One line of description: the first sentence, cut to `max` characters.
98
+ * @param {string} description
99
+ * @param {number} [max]
100
+ * @returns {string}
101
+ */
102
+ export function oneLineDescription(description, max = 100) {
103
+ const text = String(description || '').replace(/\s+/g, ' ').trim();
104
+ const firstSentence = text.split(/(?<=[.。])\s/)[0] || text;
105
+ const cut = firstSentence.length > max ? `${firstSentence.slice(0, max - 1).trimEnd()}…` : firstSentence;
106
+ return cut;
107
+ }
108
+
109
+ /**
110
+ * @typedef {Object} AvailableStandard
111
+ * @property {string} id
112
+ * @property {string} category
113
+ * @property {string} description One line.
114
+ * @property {string} source Registry source path in the project's format (what the manifest records).
115
+ * @property {string} name File name under `.standards/`.
116
+ */
117
+
118
+ /**
119
+ * The single definition of "available but not installed".
120
+ *
121
+ * @param {Object} manifest
122
+ * @returns {{
123
+ * offered: AvailableStandard[],
124
+ * notOffered: Array<AvailableStandard & {reason: string, addable: boolean}>,
125
+ * notOfferedByCategory: Object<string, number>
126
+ * }}
127
+ */
128
+ export function getAvailableStandards(manifest) {
129
+ const format = manifest.format || 'ai';
130
+ const registryStandards = getAllStandards();
131
+ const installed = installedStandardFileNames(manifest, registryStandards);
132
+
133
+ const offered = [];
134
+ const notOffered = [];
135
+ for (const std of registryStandards) {
136
+ const source = getStandardSource(std, format);
137
+ if (!source) continue; // skill-only entry: no file to install
138
+ const name = basename(source);
139
+ if (installed.has(name)) continue;
140
+
141
+ const item = { id: std.id, category: std.category, description: oneLineDescription(std.description), source, name };
142
+ if (OFFERED_CATEGORIES.includes(std.category)) {
143
+ offered.push(item);
144
+ } else {
145
+ notOffered.push({
146
+ ...item,
147
+ reason: CATEGORY_NOTES[std.category] || 'category not installed by init',
148
+ addable: !INSTALLED_BY_OTHER_MEANS.includes(std.category)
149
+ });
150
+ }
151
+ }
152
+
153
+ const notOfferedByCategory = {};
154
+ for (const n of notOffered) notOfferedByCategory[n.category] = (notOfferedByCategory[n.category] || 0) + 1;
155
+ return { offered, notOffered, notOfferedByCategory };
156
+ }
157
+
158
+ /** Plain edit distance, enough for "did you mean". */
159
+ function editDistance(a, b) {
160
+ const prev = Array.from({ length: b.length + 1 }, (_, j) => j);
161
+ for (let i = 1; i <= a.length; i++) {
162
+ let diagonal = prev[0];
163
+ prev[0] = i;
164
+ for (let j = 1; j <= b.length; j++) {
165
+ const above = prev[j];
166
+ prev[j] = a[i - 1] === b[j - 1] ? diagonal : 1 + Math.min(diagonal, above, prev[j - 1]);
167
+ diagonal = above;
168
+ }
169
+ }
170
+ return prev[b.length];
171
+ }
172
+
173
+ /**
174
+ * The registry ids nearest to `id` (substring matches first, then by edit distance).
175
+ * @param {string} id
176
+ * @param {number} [limit]
177
+ * @returns {string[]}
178
+ */
179
+ export function closestStandardIds(id, limit = 5) {
180
+ const needle = String(id || '').toLowerCase();
181
+ const scored = getAllStandards().map(s => {
182
+ const candidate = s.id.toLowerCase();
183
+ const contains = needle.length >= 3 && (candidate.includes(needle) || needle.includes(candidate));
184
+ return { id: s.id, score: (contains ? 0 : 1000) + editDistance(needle, candidate) };
185
+ });
186
+ scored.sort((x, y) => x.score - y.score || x.id.localeCompare(y.id));
187
+ return scored.slice(0, limit).map(s => s.id);
188
+ }
189
+
190
+ /**
191
+ * Judge one `--add-standard <id>` request against a manifest.
192
+ *
193
+ * status:
194
+ * 'add' installable now; `source` is what goes into manifest.standards
195
+ * 'installed' already in manifest.standards (not an error)
196
+ * 'unknown' not a registry id; `closest` lists the nearest ids
197
+ * 'other-means' a registry id, but installed through language/integration/template choices
198
+ * 'no-source' a registry id with no file in the project's format
199
+ *
200
+ * @param {string} id
201
+ * @param {Object} manifest
202
+ * @returns {{status: string, id: string, entry?: Object, source?: string, closest?: string[]}}
203
+ */
204
+ export function judgeAddStandard(id, manifest) {
205
+ const format = manifest.format || 'ai';
206
+ const registryStandards = getAllStandards();
207
+ const entry = registryStandards.find(s => s.id === id);
208
+ if (!entry) return { status: 'unknown', id, closest: closestStandardIds(id) };
209
+ if (INSTALLED_BY_OTHER_MEANS.includes(entry.category)) return { status: 'other-means', id, entry };
210
+ const source = getStandardSource(entry, format);
211
+ if (!source) return { status: 'no-source', id, entry };
212
+ if (installedStandardFileNames(manifest, registryStandards).has(basename(source))) {
213
+ return { status: 'installed', id, entry, source };
214
+ }
215
+ return { status: 'add', id, entry, source };
216
+ }