universal-dev-standards 6.14.0-beta.5 → 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 (99) hide show
  1. package/README.md +13 -3
  2. package/bin/uds.js +32 -7
  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/commit-message.ai.yaml +6 -2
  6. package/bundled/ai/standards/developer-memory.ai.yaml +12 -2
  7. package/bundled/ai/standards/full-coverage-testing.ai.yaml +44 -6
  8. package/bundled/ai/standards/open-work-tracking.ai.yaml +191 -11
  9. package/bundled/ai/standards/pipeline-security-gates.ai.yaml +48 -3
  10. package/bundled/ai/standards/project-context-memory.ai.yaml +12 -2
  11. package/bundled/core/code-review-checklist.md +20 -2
  12. package/bundled/core/developer-memory.md +12 -2
  13. package/bundled/core/full-coverage-testing.md +44 -4
  14. package/bundled/core/open-work-tracking.md +156 -16
  15. package/bundled/core/pipeline-security-gates.md +63 -0
  16. package/bundled/core/project-context-memory.md +10 -2
  17. package/bundled/locales/zh-CN/CHANGELOG.md +75 -3
  18. package/bundled/locales/zh-CN/README.md +1 -1
  19. package/bundled/locales/zh-CN/SECURITY.md +1 -1
  20. package/bundled/locales/zh-CN/adoption/ADOPTION-GUIDE.md +13 -4
  21. package/bundled/locales/zh-CN/adoption/STATIC-DYNAMIC-GUIDE.md +7 -1
  22. package/bundled/locales/zh-CN/adoption/checklists/enterprise.md +7 -1
  23. package/bundled/locales/zh-CN/adoption/checklists/minimal.md +13 -3
  24. package/bundled/locales/zh-CN/adoption/checklists/recommended.md +7 -1
  25. package/bundled/locales/zh-CN/core/code-review-checklist.md +17 -0
  26. package/bundled/locales/zh-CN/core/developer-memory.md +9 -0
  27. package/bundled/locales/zh-CN/core/full-coverage-testing.md +48 -8
  28. package/bundled/locales/zh-CN/core/pipeline-security-gates.md +64 -4
  29. package/bundled/locales/zh-CN/core/project-context-memory.md +5 -0
  30. package/bundled/locales/zh-CN/docs/AVAILABLE-STANDARDS.md +70 -0
  31. package/bundled/locales/zh-CN/docs/CHEATSHEET.md +5 -4
  32. package/bundled/locales/zh-CN/docs/CLI-INIT-OPTIONS.md +25 -23
  33. package/bundled/locales/zh-CN/docs/FEATURE-REFERENCE.md +15 -12
  34. package/bundled/locales/zh-CN/docs/USAGE-MODES-COMPARISON.md +6 -6
  35. package/bundled/locales/zh-CN/docs/WINDOWS-GUIDE.md +7 -1
  36. package/bundled/locales/zh-CN/docs/user/GETTING-STARTED.md +44 -0
  37. package/bundled/locales/zh-CN/options/code-review/pr-review.md +13 -2
  38. package/bundled/locales/zh-TW/CHANGELOG.md +75 -3
  39. package/bundled/locales/zh-TW/README.md +1 -1
  40. package/bundled/locales/zh-TW/SECURITY.md +1 -1
  41. package/bundled/locales/zh-TW/adoption/ADOPTION-GUIDE.md +13 -4
  42. package/bundled/locales/zh-TW/adoption/STATIC-DYNAMIC-GUIDE.md +7 -1
  43. package/bundled/locales/zh-TW/adoption/checklists/enterprise.md +7 -1
  44. package/bundled/locales/zh-TW/adoption/checklists/minimal.md +13 -3
  45. package/bundled/locales/zh-TW/adoption/checklists/recommended.md +7 -1
  46. package/bundled/locales/zh-TW/core/code-review-checklist.md +17 -0
  47. package/bundled/locales/zh-TW/core/developer-memory.md +9 -0
  48. package/bundled/locales/zh-TW/core/full-coverage-testing.md +48 -8
  49. package/bundled/locales/zh-TW/core/open-work-tracking.md +90 -14
  50. package/bundled/locales/zh-TW/core/pipeline-security-gates.md +64 -4
  51. package/bundled/locales/zh-TW/core/project-context-memory.md +5 -0
  52. package/bundled/locales/zh-TW/docs/AVAILABLE-STANDARDS.md +70 -0
  53. package/bundled/locales/zh-TW/docs/CHEATSHEET.md +5 -4
  54. package/bundled/locales/zh-TW/docs/CLI-INIT-OPTIONS.md +25 -23
  55. package/bundled/locales/zh-TW/docs/FEATURE-REFERENCE.md +15 -12
  56. package/bundled/locales/zh-TW/docs/USAGE-MODES-COMPARISON.md +6 -6
  57. package/bundled/locales/zh-TW/docs/WINDOWS-GUIDE.md +7 -1
  58. package/bundled/locales/zh-TW/docs/user/GETTING-STARTED.md +44 -0
  59. package/bundled/locales/zh-TW/options/code-review/pr-review.md +13 -2
  60. package/bundled/skills/SKILL_NAMING.md +9 -0
  61. package/bundled/templates/gates/check-anti-fake-tests.mjs +305 -5
  62. package/package.json +3 -1
  63. package/src/commands/audit.js +9 -2
  64. package/src/commands/check.js +17 -0
  65. package/src/commands/deps.js +31 -1
  66. package/src/commands/init.js +41 -21
  67. package/src/commands/open-work.js +65 -6
  68. package/src/commands/simulate.js +20 -8
  69. package/src/commands/skills.js +59 -33
  70. package/src/commands/spec.js +14 -8
  71. package/src/commands/update.js +106 -66
  72. package/src/core/manifest.js +12 -10
  73. package/src/core/marketplace-sentinel.js +5 -0
  74. package/src/core/open-work-config.js +103 -0
  75. package/src/core/project-config.js +58 -38
  76. package/src/flows/init-flow.js +10 -0
  77. package/src/i18n/messages.js +264 -60
  78. package/src/installers/skills-installer.js +3 -1
  79. package/src/prompts/init.js +148 -13
  80. package/src/reconciler/backup-locations.js +75 -0
  81. package/src/reconciler/backup-manager.js +29 -45
  82. package/src/reconciler/index.js +62 -8
  83. package/src/utils/available-standards-report.js +144 -0
  84. package/src/utils/available-standards.js +216 -0
  85. package/src/utils/commit-message-judge.js +137 -0
  86. package/src/utils/copier.js +5 -4
  87. package/src/utils/deps-applicability.js +25 -0
  88. package/src/utils/friction-detector.js +27 -0
  89. package/src/utils/installed-names-ownership.js +114 -0
  90. package/src/utils/open-work-tracking.mjs +919 -48
  91. package/src/utils/sdd-header.js +65 -0
  92. package/src/utils/skill-frontmatter.js +102 -0
  93. package/src/utils/skill-name-collision.js +169 -0
  94. package/src/utils/skills-install-paths.js +114 -0
  95. package/src/utils/skills-installer.js +63 -105
  96. package/src/utils/standard-validator.js +98 -27
  97. package/src/utils/transient-fs.js +113 -0
  98. package/src/vibe/micro-spec.js +15 -0
  99. 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
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Where UDS update backups live (XSPEC-456 R7).
3
+ *
4
+ * New backups all go into ONE folder, `.uds-backups/`, one subfolder per backup. Backups made before
5
+ * XSPEC-456 R7 are single folders named `.uds-backup-<time>-<NNNN>` directly in the project root; they are
6
+ * not moved and are still backups. A `backupId` is the backup folder's path relative to the project root
7
+ * (`.uds-backups/<time>-<NNNN>` or `.uds-backup-<time>-<NNNN>`), so everything that joins it onto the project
8
+ * root works for both.
9
+ *
10
+ * @module reconciler/backup-locations
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs';
14
+ import { join } from 'path';
15
+
16
+ /** The one folder new backups go into. */
17
+ export const BACKUPS_DIR = '.uds-backups';
18
+ /** Backups made before XSPEC-456 R7: one folder each, directly in the project root. */
19
+ export const LEGACY_BACKUP_PREFIX = '.uds-backup-';
20
+
21
+ let counter = 0;
22
+
23
+ /** A fresh backup id, relative to the project root. The counter orders two backups made in the same millisecond. */
24
+ export function newBackupId() {
25
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
26
+ return `${BACKUPS_DIR}/${timestamp}-${String(++counter).padStart(4, '0')}`;
27
+ }
28
+
29
+ /**
30
+ * Make sure `.uds-backups/` exists and hides itself from git.
31
+ *
32
+ * WHY THIS IS NOT A LINE IN THE ADOPTER'S .gitignore. We create this directory in someone else's repository;
33
+ * making it disappear is our job, but editing their .gitignore to do it is not - that file is theirs, it may
34
+ * be generated, and a tool appending to it on every update is a worse trade than the problem. A `*` inside
35
+ * the folder ignores everything in it (this file included, which is fine: git reads .gitignore whether or
36
+ * not it is tracked), so `git status` and `git add -A` never see a backup, and nothing outside is touched.
37
+ *
38
+ * WHY IT EXISTS. Nothing ignored the backup folders, so `git add -A` in two sibling repos committed them:
39
+ * EngramGraph's 0.8.0 release commit took in 5 backups - 360 files, 73,992 lines - and dev-platform took one.
40
+ * Both were public. (Until XSPEC-456 R7 each backup carried its own copy of this file.)
41
+ *
42
+ * Git is not the only thing that reads a project folder: indexers, IDE search and grep do not look at
43
+ * .gitignore, which is why the backups share ONE folder name that is easy to exclude (the update summary
44
+ * says so).
45
+ *
46
+ * @param {string} projectPath
47
+ * @param {string[]} errors - Receives an error message when it did not work
48
+ */
49
+ export function ensureBackupsDir(projectPath, errors) {
50
+ const dir = join(projectPath, BACKUPS_DIR);
51
+ try {
52
+ mkdirSync(dir, { recursive: true });
53
+ const ignoreFile = join(dir, '.gitignore');
54
+ if (!existsSync(ignoreFile)) writeFileSync(ignoreFile, '*\n', 'utf8');
55
+ } catch (err) {
56
+ // A backup that git can see still beats no backup - the caller records this and carries on.
57
+ errors.push(`Failed to write ${BACKUPS_DIR}/.gitignore: ${err.message}`);
58
+ }
59
+ }
60
+
61
+ /** Ids of the backups in the shared folder. */
62
+ export function sharedBackupIds(projectPath) {
63
+ const dir = join(projectPath, BACKUPS_DIR);
64
+ if (!existsSync(dir)) return [];
65
+ return readdirSync(dir, { withFileTypes: true })
66
+ .filter((entry) => entry.isDirectory())
67
+ .map((entry) => `${BACKUPS_DIR}/${entry.name}`);
68
+ }
69
+
70
+ /** Add the ids of the backups an older UDS left in the project root to `into`. */
71
+ export function addLegacyBackupIds(projectPath, into) {
72
+ for (const entry of readdirSync(projectPath, { withFileTypes: true })) {
73
+ if (entry.isDirectory() && entry.name.startsWith(LEGACY_BACKUP_PREFIX)) into.push(entry.name);
74
+ }
75
+ }
@@ -2,12 +2,20 @@
2
2
  * Backup Manager
3
3
  * Creates backups before reconciliation, enables rollback, and auto-cleans old backups.
4
4
  *
5
- * Backup structure:
6
- * .uds-backup-<ISO timestamp>/
7
- * ├── backup-manifest.json # Backup metadata + rollback instructions
8
- * ├── .standards/ # Backed up standard files (and manifest.json)
9
- * ├── CLAUDE.md # Backed up integration files
10
- * └── .claude/skills/... # Backed up skill files
5
+ * Backup structure (XSPEC-456 R7: all backups live under ONE folder in the project root):
6
+ * .uds-backups/
7
+ * ├── .gitignore # `*` - git never sees any backup
8
+ * └── <ISO timestamp>-<NNNN>/ # one backup
9
+ * ├── backup-manifest.json # Backup metadata + rollback instructions
10
+ * ├── .standards/ # Backed up standard files (and manifest.json)
11
+ * ├── CLAUDE.md # Backed up integration files
12
+ * └── .claude/skills/... # Backed up skill files
13
+ *
14
+ * Before 6.14.0 (this change) every backup was its own folder in the project root, `.uds-backup-<ISO timestamp>/`.
15
+ * Those are NOT moved, and they are still backups: `backupId` is the backup folder's path relative to the
16
+ * project root (`.uds-backups/<time>-<NNNN>` or `.uds-backup-<time>-<NNNN>`), so every place that builds a
17
+ * path from it works for both layouts, and listing, chaining, rollback and "keep the 5 most recent" look at
18
+ * both places and order them together by time.
11
19
  *
12
20
  * Only the paths a step will touch are backed up (minimal footprint). Keeps the 5 most recent
13
21
  * backups; auto-cleans older ones.
@@ -39,12 +47,11 @@ import {
39
47
  } from 'fs';
40
48
  import { createHash } from 'crypto';
41
49
  import { join, dirname, isAbsolute, sep } from 'path';
50
+ import { newBackupId, ensureBackupsDir, sharedBackupIds, addLegacyBackupIds } from './backup-locations.js';
42
51
 
43
52
  const MAX_BACKUPS = 5;
44
- const BACKUP_PREFIX = '.uds-backup-';
45
53
  const MANIFEST_REL = '.standards/manifest.json';
46
54
  const FORMAT_VERSION = 2;
47
- let _backupCounter = 0;
48
55
 
49
56
  const toPosix = (p) => p.split(sep).join('/');
50
57
 
@@ -127,12 +134,6 @@ function ancestorsOf(rel) {
127
134
  return out;
128
135
  }
129
136
 
130
- function newBackupId() {
131
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
132
- const counter = String(++_backupCounter).padStart(4, '0');
133
- return `${BACKUP_PREFIX}${timestamp}-${counter}`;
134
- }
135
-
136
137
  /**
137
138
  * Snapshot `paths` into a new backup directory.
138
139
  *
@@ -150,34 +151,14 @@ function snapshot(projectPath, spec) {
150
151
  const backedUp = [];
151
152
  const errors = [];
152
153
 
154
+ // The shared folder first (with its .gitignore), then this backup inside it.
155
+ ensureBackupsDir(projectPath, errors);
153
156
  try {
154
157
  mkdirSync(backupDir, { recursive: true });
155
158
  } catch (err) {
156
159
  return { backupId, backupDir, backedUp, errors: [`Failed to create backup directory: ${err.message}`] };
157
160
  }
158
161
 
159
- // Make the backup invisible to git, from inside itself.
160
- //
161
- // WHY THIS IS NOT A LINE IN THE ADOPTER'S .gitignore. We create this directory
162
- // in someone else's repository; making it disappear is our job, but editing
163
- // their .gitignore to do it is not — that file is theirs, it may be generated,
164
- // and a tool appending to it on every update is a worse trade than the problem.
165
- // A `*` here ignores everything in this directory (this file included, which is
166
- // fine: git reads .gitignore whether or not it is tracked), so `git status` and
167
- // `git add -A` never see the backup at all, and nothing outside is touched.
168
- //
169
- // WHY IT EXISTS. Nothing ignored these directories, so `git add -A` in two
170
- // sibling repos committed them: EngramGraph's 0.8.0 release commit took in 5
171
- // backups — 360 files, 73,992 lines — and dev-platform took one. Both were
172
- // public. The adopter is not the right place to put this responsibility: they
173
- // did not create the directory and have no reason to expect it.
174
- try {
175
- writeFileSync(join(backupDir, '.gitignore'), '*\n', 'utf8');
176
- } catch (err) {
177
- // A backup that git can see still beats no backup — record and carry on.
178
- errors.push(`Failed to write backup .gitignore: ${err.message}`);
179
- }
180
-
181
162
  const notBackedUp = [...(spec.notBackedUp || [])];
182
163
  const mustBackUp = [];
183
164
  for (const p of spec.mustBackUp || []) {
@@ -547,17 +528,18 @@ export function rollback(projectPath, backupId = null) {
547
528
  */
548
529
  export function listBackups(projectPath) {
549
530
  try {
550
- const entries = readdirSync(projectPath, { withFileTypes: true });
551
531
  const backups = [];
552
532
 
553
- for (const entry of entries) {
554
- if (!entry.isDirectory() || !entry.name.startsWith(BACKUP_PREFIX)) continue;
533
+ // Where backups can be: the shared folder (new), and the project root (backups from before R7).
534
+ const places = [];
535
+ places.push(...sharedBackupIds(projectPath));
536
+ addLegacyBackupIds(projectPath, places);
555
537
 
556
- const backupDir = join(projectPath, entry.name);
557
- const manifestPath = join(backupDir, 'backup-manifest.json');
538
+ for (const backupId of places) {
539
+ const manifestPath = join(projectPath, backupId, 'backup-manifest.json');
558
540
 
559
541
  const info = {
560
- backupId: entry.name,
542
+ backupId,
561
543
  createdAt: '',
562
544
  actionCount: 0,
563
545
  label: null,
@@ -580,9 +562,11 @@ export function listBackups(projectPath) {
580
562
  backups.push(info);
581
563
  }
582
564
 
583
- // Sort newest first. The id carries a per-process counter after the timestamp, so ties on
584
- // `createdAt` (two steps in the same millisecond) still order by creation.
585
- backups.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.backupId.localeCompare(a.backupId));
565
+ // Sort newest first, both places together. The id carries a per-process counter after the timestamp, so
566
+ // ties on `createdAt` (two steps in the same millisecond) still order by creation - compared on the
567
+ // folder name, not the whole id, so the two layouts compare with each other.
568
+ const leaf = (id) => id.slice(id.lastIndexOf('/') + 1).replace(/^\.uds-backup-/, '');
569
+ backups.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || leaf(b.backupId).localeCompare(leaf(a.backupId)));
586
570
  return backups;
587
571
  } catch {
588
572
  return [];
@@ -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';
@@ -30,6 +30,7 @@ import { executePlan } from './plan-executor.js';
30
30
  import { rollback } from './backup-manager.js';
31
31
  import { pruneForeignSkillHashes } from '../utils/skill-hash-ownership.js';
32
32
  import { pruneForeignCommandHashes } from '../utils/command-hash-ownership.js';
33
+ import { pruneForeignSkillNames, pruneForeignCommandNames } from '../utils/installed-names-ownership.js';
33
34
 
34
35
  /**
35
36
  * Full reconciliation pipeline.
@@ -86,11 +87,25 @@ function reconcileFileHashes(manifest, verifiedPristine) {
86
87
  const commandProbe = { commandHashes: { ...(manifest.commandHashes || {}) } };
87
88
  const foreignCommandKeys = pruneForeignCommandHashes(commandProbe);
88
89
 
89
- if (!verifiedPristine?.length && stale.length === 0 && foreignSkillKeys.length === 0 && foreignCommandKeys.length === 0) return null;
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;
90
105
 
91
106
  const kept = Object.fromEntries(Object.entries(current).filter(([k]) => !stale.includes(k)));
92
107
  const corrected = {};
93
- let count = stale.length + foreignSkillKeys.length + foreignCommandKeys.length;
108
+ let count = stale.length + foreignSkillKeys.length + foreignCommandKeys.length + foreignSkillNames + foreignCommandNames;
94
109
 
95
110
  for (const entry of verifiedPristine || []) {
96
111
  const key = entry.path.replace(/\\/g, '/');
@@ -110,18 +125,48 @@ function reconcileFileHashes(manifest, verifiedPristine) {
110
125
  ...manifest,
111
126
  fileHashes: { ...kept, ...corrected },
112
127
  ...(foreignSkillKeys.length > 0 ? { skillHashes: skillProbe.skillHashes } : {}),
113
- ...(foreignCommandKeys.length > 0 ? { commandHashes: commandProbe.commandHashes } : {})
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 } } : {})
114
131
  },
115
132
  count
116
133
  };
117
134
  }
118
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
+
119
163
  export async function reconcile(projectPath, options = {}) {
120
- const { force = false, backup = true, onAction } = options;
164
+ const { force = false, backup = true, onAction, addStandards = [] } = options;
121
165
  const errors = [];
122
166
 
123
167
  // Step 1: Get manifest (migrate if needed, or discover from legacy)
124
- const { manifest, migrationErrors } = await getManifest(projectPath);
168
+ const { manifest: diskManifest, migrationErrors } = await getManifest(projectPath);
169
+ const manifest = withAddedStandards(diskManifest, addStandards);
125
170
  if (migrationErrors.length > 0) errors.push(...migrationErrors);
126
171
  if (!manifest) {
127
172
  return {
@@ -156,6 +201,13 @@ export async function reconcile(projectPath, options = {}) {
156
201
  // Writing it here first would put the hash correction into the backup's "before" copy, so a rollback
157
202
  // could not give back the manifest byte for byte (XSPEC-454 R1).
158
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
+ }
159
211
 
160
212
  // Step 5: Execute plan
161
213
  if (reconciliationPlan.actions.length === 0) {
@@ -200,10 +252,12 @@ export async function reconcile(projectPath, options = {}) {
200
252
  * }>}
201
253
  */
202
254
  export async function plan(projectPath, options = {}) {
203
- const { force = false } = options;
255
+ const { force = false, addStandards = [] } = options;
204
256
  const errors = [];
205
257
 
206
- 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);
207
261
  if (migrationErrors.length > 0) errors.push(...migrationErrors);
208
262
  if (!manifest) {
209
263
  return {