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
@@ -2,91 +2,179 @@
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
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
11
13
  *
12
- * Only files that will be modified/deleted are backed up (minimal footprint).
13
- * Keeps the 5 most recent backups; auto-cleans older ones.
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.
19
+ *
20
+ * Only the paths a step will touch are backed up (minimal footprint). Keeps the 5 most recent
21
+ * backups; auto-cleans older ones.
22
+ *
23
+ * What a backup has to be able to undo (XSPEC-454 R1). A rollback that restores "the files that were
24
+ * overwritten" and nothing else leaves a state that neither version describes:
25
+ * - files the step CREATED (a new skill folder) have no earlier copy, so the backup has to name them
26
+ * (`createdFiles`, filled in by `finalizeBackup` once the step is done) or nothing can remove them;
27
+ * - `.standards/manifest.json` records hashes of everything else, so restoring files without it
28
+ * makes `uds check` call every restored file modified;
29
+ * - a directory has to be restored by walking it, not with `copyFileSync` (which throws on one);
30
+ * - `uds update --skills` / `--commands` write outside the reconciler, so they take a backup of
31
+ * their own (`createStepBackup`), and consecutive steps are chained: each backup records the hash
32
+ * of the manifest before and after, and `rollback` walks back through every backup whose "before"
33
+ * is the previous backup's "after" — i.e. through one unbroken series of UDS updates.
14
34
  */
15
35
 
16
36
  import {
17
37
  existsSync,
18
38
  mkdirSync,
19
- copyFileSync,
20
39
  cpSync,
21
- statSync,
40
+ lstatSync,
41
+ readlinkSync,
22
42
  readFileSync,
23
43
  writeFileSync,
24
44
  readdirSync,
25
- rmSync
45
+ rmSync,
46
+ rmdirSync
26
47
  } from 'fs';
27
- import { join, dirname } from 'path';
48
+ import { createHash } from 'crypto';
49
+ import { join, dirname, isAbsolute, sep } from 'path';
50
+ import { newBackupId, ensureBackupsDir, sharedBackupIds, addLegacyBackupIds } from './backup-locations.js';
28
51
 
29
52
  const MAX_BACKUPS = 5;
30
- const BACKUP_PREFIX = '.uds-backup-';
31
- let _backupCounter = 0;
53
+ const MANIFEST_REL = '.standards/manifest.json';
54
+ const FORMAT_VERSION = 2;
55
+
56
+ const toPosix = (p) => p.split(sep).join('/');
57
+
58
+ /** SHA-256 of a file's bytes, or null when it cannot be read. */
59
+ function hashFileBytes(path) {
60
+ try {
61
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
32
66
 
33
67
  /**
34
- * Create a backup for the files that will be affected by a reconciliation plan.
68
+ * What a leaf IS, for comparing a restored leaf with its backup: the bytes of a file, the target of a
69
+ * symlink. (A symlink is copied as a link, never followed — a skills folder can hold links to
70
+ * directories, and following one would copy somebody else's tree into the backup.)
71
+ */
72
+ function leafSignature(path) {
73
+ try {
74
+ if (lstatSync(path).isSymbolicLink()) return `link:${readlinkSync(path)}`;
75
+ } catch {
76
+ return null;
77
+ }
78
+ return hashFileBytes(path);
79
+ }
80
+
81
+ /** Copy one leaf (file or symlink), overwriting a file or link at the destination — never a directory. */
82
+ function copyLeaf(src, dst) {
83
+ try {
84
+ if (lstatSync(dst).isSymbolicLink()) rmSync(dst, { force: true });
85
+ } catch {
86
+ // dst does not exist
87
+ }
88
+ cpSync(src, dst, { force: true, verbatimSymlinks: true });
89
+ }
90
+
91
+ /** Every file under `rel` (project-relative, posix). A file lists itself; a missing path lists nothing. */
92
+ function listFiles(root, rel) {
93
+ const abs = join(root, rel);
94
+ let st;
95
+ try {
96
+ st = lstatSync(abs);
97
+ } catch {
98
+ return [];
99
+ }
100
+ if (!st.isDirectory()) return [rel];
101
+ const out = [];
102
+ let entries;
103
+ try {
104
+ entries = readdirSync(abs, { withFileTypes: true });
105
+ } catch {
106
+ return [];
107
+ }
108
+ for (const e of entries) out.push(...listFiles(root, `${rel}/${e.name}`));
109
+ return out;
110
+ }
111
+
112
+ /** Every directory under (and including) `rel` that exists now. */
113
+ function listDirs(root, rel) {
114
+ const abs = join(root, rel);
115
+ let st;
116
+ try {
117
+ st = lstatSync(abs);
118
+ } catch {
119
+ return [];
120
+ }
121
+ if (!st.isDirectory()) return [];
122
+ const out = [rel];
123
+ for (const e of readdirSync(abs, { withFileTypes: true })) {
124
+ if (e.isDirectory()) out.push(...listDirs(root, `${rel}/${e.name}`));
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /** Ancestor directories of a project-relative path, nearest last, project root excluded. */
130
+ function ancestorsOf(rel) {
131
+ const parts = rel.split('/');
132
+ const out = [];
133
+ for (let i = 1; i < parts.length; i++) out.push(parts.slice(0, i).join('/'));
134
+ return out;
135
+ }
136
+
137
+ /**
138
+ * Snapshot `paths` into a new backup directory.
35
139
  *
36
- * @param {string} projectPath - Project root
37
- * @param {import('./diff-engine.js').ReconciliationPlan} plan - The reconciliation plan
38
- * @returns {{ backupId: string, backupDir: string, backedUp: string[], errors: string[] }}
140
+ * @param {string} projectPath
141
+ * @param {Object} spec
142
+ * @param {string} spec.label - What step this backs up ('reconcile', 'skills', 'commands')
143
+ * @param {string[]} spec.mustBackUp - Paths whose absence/copy failure counts against `coverage`
144
+ * @param {string[]} spec.alsoWatch - Extra project-relative paths: backed up when present, recorded as absent otherwise
145
+ * @param {Object} spec.plan - Plan summary stored in the backup manifest (optional)
146
+ * @param {Array<{path: string, reason: string}>} spec.notBackedUp - Things outside the project this step also writes
39
147
  */
40
- export function createBackup(projectPath, plan) {
41
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
42
- const counter = String(++_backupCounter).padStart(4, '0');
43
- const backupId = `${BACKUP_PREFIX}${timestamp}-${counter}`;
148
+ function snapshot(projectPath, spec) {
149
+ const backupId = newBackupId();
44
150
  const backupDir = join(projectPath, backupId);
45
151
  const backedUp = [];
46
152
  const errors = [];
47
153
 
48
- // Only backup files that will be updated or deleted
49
- const filesToBackup = plan.actions
50
- .filter(a => a.type === 'update' || a.type === 'delete' || a.type === 'migrate_block')
51
- .map(a => a.path);
52
-
53
- if (filesToBackup.length === 0) {
54
- return { backupId, backupDir, backedUp, errors };
55
- }
56
-
57
- // Create backup directory
154
+ // The shared folder first (with its .gitignore), then this backup inside it.
155
+ ensureBackupsDir(projectPath, errors);
58
156
  try {
59
157
  mkdirSync(backupDir, { recursive: true });
60
158
  } catch (err) {
61
- return {
62
- backupId,
63
- backupDir,
64
- backedUp,
65
- errors: [`Failed to create backup directory: ${err.message}`]
66
- };
159
+ return { backupId, backupDir, backedUp, errors: [`Failed to create backup directory: ${err.message}`] };
67
160
  }
68
161
 
69
- // Make the backup invisible to git, from inside itself.
70
- //
71
- // WHY THIS IS NOT A LINE IN THE ADOPTER'S .gitignore. We create this directory
72
- // in someone else's repository; making it disappear is our job, but editing
73
- // their .gitignore to do it is not — that file is theirs, it may be generated,
74
- // and a tool appending to it on every update is a worse trade than the problem.
75
- // A `*` here ignores everything in this directory (this file included, which is
76
- // fine: git reads .gitignore whether or not it is tracked), so `git status` and
77
- // `git add -A` never see the backup at all, and nothing outside is touched.
78
- //
79
- // WHY IT EXISTS. Nothing ignored these directories, so `git add -A` in two
80
- // sibling repos committed them: EngramGraph's 0.8.0 release commit took in 5
81
- // backups — 360 files, 73,992 lines — and dev-platform took one. Both were
82
- // public. The adopter is not the right place to put this responsibility: they
83
- // did not create the directory and have no reason to expect it.
84
- try {
85
- writeFileSync(join(backupDir, '.gitignore'), '*\n', 'utf8');
86
- } catch (err) {
87
- // A backup that git can see still beats no backup — record and carry on.
88
- errors.push(`Failed to write backup .gitignore: ${err.message}`);
162
+ const notBackedUp = [...(spec.notBackedUp || [])];
163
+ const mustBackUp = [];
164
+ for (const p of spec.mustBackUp || []) {
165
+ if (isAbsolute(p)) {
166
+ // `join(projectPath, '/abs/path')` would silently point somewhere else entirely. A path outside
167
+ // the project (a user-level skills folder) is shared by every project; it is reported, not copied.
168
+ notBackedUp.push({ path: p, reason: 'outside this project (user-level); shared by every project, so it is not backed up or rolled back' });
169
+ } else {
170
+ mustBackUp.push(toPosix(p));
171
+ }
89
172
  }
173
+ const extra = (spec.alsoWatch || []).map(toPosix);
174
+
175
+ // The manifest first: every other record in the project is a hash that only means something next to it.
176
+ const watched = [...new Set([...mustBackUp, ...extra, MANIFEST_REL])];
177
+ const preexistingDirs = new Set();
90
178
 
91
179
  // Backup each entry.
92
180
  //
@@ -97,17 +185,25 @@ export function createBackup(projectPath, plan) {
97
185
  // recorded 74 files for a plan of 129 actions, with **0 of the 55 skill
98
186
  // directories** among them — a rollback point that did not cover the largest
99
187
  // part of what was about to be overwritten. (XSPEC-382 R6)
100
- for (const relativePath of filesToBackup) {
188
+ for (const relativePath of watched) {
189
+ for (const a of ancestorsOf(relativePath)) {
190
+ if (existsSync(join(projectPath, a))) preexistingDirs.add(a);
191
+ }
101
192
  const sourcePath = join(projectPath, relativePath);
102
193
  if (!existsSync(sourcePath)) continue;
103
194
 
104
195
  const targetPath = join(backupDir, relativePath);
105
196
  try {
106
197
  mkdirSync(dirname(targetPath), { recursive: true });
107
- if (statSync(sourcePath).isDirectory()) {
108
- cpSync(sourcePath, targetPath, { recursive: true });
198
+ if (lstatSync(sourcePath).isDirectory()) {
199
+ for (const d of listDirs(projectPath, relativePath)) preexistingDirs.add(d);
200
+ mkdirSync(targetPath, { recursive: true });
201
+ for (const f of listFiles(projectPath, relativePath)) {
202
+ mkdirSync(dirname(join(backupDir, f)), { recursive: true });
203
+ copyLeaf(join(projectPath, f), join(backupDir, f));
204
+ }
109
205
  } else {
110
- copyFileSync(sourcePath, targetPath);
206
+ copyLeaf(sourcePath, targetPath);
111
207
  }
112
208
  backedUp.push(relativePath);
113
209
  } catch (err) {
@@ -115,20 +211,12 @@ export function createBackup(projectPath, plan) {
115
211
  }
116
212
  }
117
213
 
118
- // Write backup manifest
119
214
  const backupManifest = {
215
+ format: FORMAT_VERSION,
120
216
  backupId,
217
+ label: spec.label || 'update',
121
218
  createdAt: new Date().toISOString(),
122
- plan: {
123
- summary: plan.summary,
124
- actionCount: plan.actions.length,
125
- actions: plan.actions.map(a => ({
126
- type: a.type,
127
- category: a.category,
128
- path: a.path,
129
- reason: a.reason
130
- }))
131
- },
219
+ plan: spec.plan || { summary: null, actionCount: 0, actions: [] },
132
220
  backedUpFiles: backedUp,
133
221
  // What could NOT be backed up, and the resulting gap.
134
222
  //
@@ -139,18 +227,24 @@ export function createBackup(projectPath, plan) {
139
227
  // does not contain. (XSPEC-382 R6)
140
228
  failedToBackUp: errors.slice(),
141
229
  coverage: {
142
- planned: filesToBackup.length,
143
- backedUp: backedUp.length,
144
- failed: filesToBackup.length - backedUp.length
230
+ planned: mustBackUp.length,
231
+ backedUp: mustBackUp.filter((p) => backedUp.includes(p)).length,
232
+ failed: mustBackUp.length - mustBackUp.filter((p) => backedUp.includes(p)).length
145
233
  },
234
+ // XSPEC-454 R1: the parts a "copy what is about to change" backup cannot know on its own.
235
+ watched,
236
+ preexistingDirs: [...preexistingDirs].sort(),
237
+ createdFiles: [],
238
+ createdDirs: [],
239
+ notBackedUp,
240
+ preManifestHash: hashFileBytes(join(projectPath, MANIFEST_REL)),
241
+ postManifestHash: null,
242
+ finalized: false,
146
243
  projectPath
147
244
  };
148
245
 
149
246
  try {
150
- writeFileSync(
151
- join(backupDir, 'backup-manifest.json'),
152
- JSON.stringify(backupManifest, null, 2)
153
- );
247
+ writeFileSync(join(backupDir, 'backup-manifest.json'), JSON.stringify(backupManifest, null, 2));
154
248
  } catch (err) {
155
249
  errors.push(`Failed to write backup manifest: ${err.message}`);
156
250
  }
@@ -159,84 +253,307 @@ export function createBackup(projectPath, plan) {
159
253
  }
160
254
 
161
255
  /**
162
- * Rollback to a specific backup.
256
+ * Create a backup for the files that will be affected by a reconciliation plan.
163
257
  *
164
258
  * @param {string} projectPath - Project root
165
- * @param {string} [backupId] - Specific backup ID (defaults to most recent)
166
- * @returns {{ success: boolean, restored: string[], errors: string[] }}
259
+ * @param {import('./diff-engine.js').ReconciliationPlan} plan - The reconciliation plan
260
+ * @param {Object} [options]
261
+ * @param {string[]} [options.alsoWatch] - Extra project-relative paths the step writes outside its plan
262
+ * (the skills/commands bookkeeping files the installers rewrite)
263
+ * @returns {{ backupId: string, backupDir: string, backedUp: string[], errors: string[] }}
167
264
  */
168
- export function rollback(projectPath, backupId = null) {
169
- const restored = [];
170
- const errors = [];
265
+ export function createBackup(projectPath, plan, options = {}) {
266
+ // Only backup files that will be updated or deleted
267
+ const mustBackUp = plan.actions
268
+ .filter(a => a.type === 'update' || a.type === 'delete' || a.type === 'migrate_block')
269
+ .map(a => a.path);
270
+ // A `create` has no earlier copy to save, but it must be watched: the backup is what lets a rollback
271
+ // know that file did not exist before.
272
+ const created = plan.actions.filter(a => a.type === 'create').map(a => a.path).filter((p) => !isAbsolute(p));
273
+
274
+ return snapshot(projectPath, {
275
+ label: 'reconcile',
276
+ mustBackUp,
277
+ alsoWatch: [...created, ...(options.alsoWatch || [])],
278
+ plan: {
279
+ summary: plan.summary,
280
+ actionCount: plan.actions.length,
281
+ actions: plan.actions.map(a => ({
282
+ type: a.type,
283
+ category: a.category,
284
+ path: a.path,
285
+ reason: a.reason
286
+ }))
287
+ }
288
+ });
289
+ }
171
290
 
172
- // Find backup
173
- if (!backupId) {
174
- const backups = listBackups(projectPath);
175
- if (backups.length === 0) {
176
- return { success: false, restored, errors: ['No backups found'] };
291
+ /**
292
+ * Backup for a step that writes outside the reconciler: `uds update --skills`, `--commands`.
293
+ *
294
+ * @param {string} projectPath
295
+ * @param {Object} spec
296
+ * @param {string} spec.label - 'skills' | 'commands'
297
+ * @param {string[]} spec.paths - Project-relative directories the step writes into
298
+ * @param {Array<{path: string, reason: string}>} [spec.notBackedUp] - Targets outside the project
299
+ */
300
+ export function createStepBackup(projectPath, spec) {
301
+ return snapshot(projectPath, {
302
+ label: spec.label,
303
+ mustBackUp: [],
304
+ alsoWatch: spec.paths || [],
305
+ notBackedUp: spec.notBackedUp || [],
306
+ plan: { summary: null, actionCount: 0, actions: [] }
307
+ });
308
+ }
309
+
310
+ function readBackupManifest(projectPath, backupId) {
311
+ const manifestPath = join(projectPath, backupId, 'backup-manifest.json');
312
+ return JSON.parse(readFileSync(manifestPath, 'utf-8'));
313
+ }
314
+
315
+ /**
316
+ * Record what the step did, once it is done: the files it created, and the manifest it left behind.
317
+ *
318
+ * Call after the step's last write to `.standards/manifest.json`. A later write that is not followed by
319
+ * another call leaves `postManifestHash` stale, which only ever breaks the chain (the rollback then
320
+ * undoes this one step and says so) — it can never make a rollback restore the wrong thing.
321
+ * Never throws: a backup that cannot be finalized is still a backup.
322
+ *
323
+ * @param {string} projectPath
324
+ * @param {string|null} backupId
325
+ * @returns {{ createdFiles: string[], errors: string[] }}
326
+ */
327
+ export function finalizeBackup(projectPath, backupId) {
328
+ const errors = [];
329
+ if (!backupId) return { createdFiles: [], errors };
330
+ try {
331
+ const backupDir = join(projectPath, backupId);
332
+ const bm = readBackupManifest(projectPath, backupId);
333
+ const created = new Set();
334
+ for (const rel of bm.watched || []) {
335
+ const before = new Set(listFiles(backupDir, rel));
336
+ for (const f of listFiles(projectPath, rel)) {
337
+ if (!before.has(f)) created.add(f);
338
+ }
339
+ }
340
+ const pre = new Set(bm.preexistingDirs || []);
341
+ const createdDirs = new Set();
342
+ for (const f of created) {
343
+ for (const a of ancestorsOf(f)) if (!pre.has(a)) createdDirs.add(a);
177
344
  }
178
- backupId = backups[0].backupId; // Most recent
345
+ bm.createdFiles = [...created].sort();
346
+ bm.createdDirs = [...createdDirs].sort((a, b) => b.length - a.length);
347
+ bm.postManifestHash = hashFileBytes(join(projectPath, MANIFEST_REL));
348
+ bm.finalized = true;
349
+ bm.finalizedAt = new Date().toISOString();
350
+ writeFileSync(join(backupDir, 'backup-manifest.json'), JSON.stringify(bm, null, 2));
351
+ return { createdFiles: bm.createdFiles, errors };
352
+ } catch (err) {
353
+ errors.push(`Failed to finalize ${backupId}: ${err.message}`);
354
+ return { createdFiles: [], errors };
179
355
  }
356
+ }
357
+
358
+ /** Undo one backup. Never throws. */
359
+ function restoreOne(projectPath, backupId) {
360
+ const restored = [];
361
+ const removed = [];
362
+ const errors = [];
363
+ const notRestored = [];
180
364
 
181
365
  const backupDir = join(projectPath, backupId);
182
366
  if (!existsSync(backupDir)) {
183
- return { success: false, restored, errors: [`Backup not found: ${backupId}`] };
367
+ return { restored, removed, errors: [`Backup not found: ${backupId}`], notRestored, label: null };
184
368
  }
185
369
 
186
370
  // Read backup manifest
187
- const manifestPath = join(backupDir, 'backup-manifest.json');
188
- let backupManifest;
371
+ let bm;
189
372
  try {
190
- backupManifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
373
+ bm = readBackupManifest(projectPath, backupId);
191
374
  } catch (err) {
192
- return { success: false, restored, errors: [`Failed to read backup manifest: ${err.message}`] };
375
+ return { restored, removed, errors: [`Failed to read backup manifest: ${err.message}`], notRestored, label: null };
193
376
  }
194
377
 
195
- // Restore each backed-up file
196
- for (const relativePath of backupManifest.backedUpFiles) {
197
- const sourcePath = join(backupDir, relativePath);
198
- const targetPath = join(projectPath, relativePath);
378
+ // 1. Remove what the step created. This comes first so that a path that is a file in the backup and was
379
+ // replaced by a directory since (or the reverse) is clear before it is restored.
380
+ for (const rel of bm.createdFiles || []) {
381
+ const abs = join(projectPath, rel);
382
+ try {
383
+ if (existsSync(abs)) {
384
+ rmSync(abs, { force: true });
385
+ removed.push(rel);
386
+ }
387
+ } catch (err) {
388
+ errors.push(`Failed to remove ${rel}: ${err.message}`);
389
+ }
390
+ }
199
391
 
392
+ // 2. Restore each backed-up entry. A directory is restored file by file: `copyFileSync` throws on one.
393
+ for (const relativePath of bm.backedUpFiles || []) {
394
+ const sourcePath = join(backupDir, relativePath);
200
395
  if (!existsSync(sourcePath)) {
201
396
  errors.push(`Backup file missing: ${relativePath}`);
202
397
  continue;
203
398
  }
204
-
205
399
  try {
206
- mkdirSync(dirname(targetPath), { recursive: true });
207
- copyFileSync(sourcePath, targetPath);
208
- restored.push(relativePath);
400
+ if (lstatSync(sourcePath).isDirectory()) {
401
+ mkdirSync(join(projectPath, relativePath), { recursive: true });
402
+ for (const f of listFiles(backupDir, relativePath)) {
403
+ mkdirSync(dirname(join(projectPath, f)), { recursive: true });
404
+ copyLeaf(join(backupDir, f), join(projectPath, f));
405
+ restored.push(f);
406
+ }
407
+ } else {
408
+ mkdirSync(dirname(join(projectPath, relativePath)), { recursive: true });
409
+ copyLeaf(sourcePath, join(projectPath, relativePath));
410
+ restored.push(relativePath);
411
+ }
209
412
  } catch (err) {
210
413
  errors.push(`Failed to restore ${relativePath}: ${err.message}`);
211
414
  }
212
415
  }
213
416
 
214
- return { success: errors.length === 0, restored, errors };
417
+ // 3. Directories the step created, now empty. Only empty ones: rmdir refuses anything else, which is
418
+ // what keeps a file the user added afterwards from being swept away.
419
+ for (const rel of bm.createdDirs || []) {
420
+ try {
421
+ rmdirSync(join(projectPath, rel));
422
+ } catch {
423
+ // not empty, or already gone — leave it
424
+ }
425
+ }
426
+
427
+ // 4. Read back. "Restored" is a claim; this is what makes it a fact.
428
+ for (const rel of new Set(restored)) {
429
+ const a = leafSignature(join(projectPath, rel));
430
+ const b = leafSignature(join(backupDir, rel));
431
+ if (a === null || a !== b) errors.push(`Restored file differs from the backup: ${rel}`);
432
+ }
433
+ for (const rel of removed) {
434
+ if (existsSync(join(projectPath, rel))) errors.push(`Created file is still there after rollback: ${rel}`);
435
+ }
436
+
437
+ for (const item of bm.notBackedUp || []) {
438
+ notRestored.push(`${item.path} — ${item.reason}`);
439
+ }
440
+ if (bm.format !== FORMAT_VERSION) {
441
+ notRestored.push(
442
+ `${backupId} was made by an older UDS: files that update created, and .standards/manifest.json, ` +
443
+ 'were not recorded and are not restored from it.'
444
+ );
445
+ } else if (!bm.finalized) {
446
+ notRestored.push(
447
+ `${backupId} was never finalized (the update that made it did not finish): files it created are not known, so none were removed.`
448
+ );
449
+ }
450
+ if ((bm.failedToBackUp || []).length > 0) {
451
+ notRestored.push(`${backupId} is incomplete: ${bm.failedToBackUp.join('; ')}`);
452
+ }
453
+
454
+ return { restored, removed, errors, notRestored, label: bm.label || null };
455
+ }
456
+
457
+ /**
458
+ * Rollback.
459
+ *
460
+ * With no `backupId`, undoes the newest backup AND every earlier one that belongs to the same unbroken
461
+ * series of UDS updates (see the file header) — so `update --apply`, `--apply --skills`, `--apply --commands`
462
+ * followed by one `--rollback` returns to where the first of them started. With an explicit `backupId`,
463
+ * undoes only that backup.
464
+ *
465
+ * @param {string} projectPath - Project root
466
+ * @param {string} [backupId] - Specific backup ID (defaults to the most recent series)
467
+ * @returns {{ success: boolean, restored: string[], removed: string[], errors: string[],
468
+ * notRestored: string[], steps: Array<Object>, olderBackups: number }}
469
+ */
470
+ export function rollback(projectPath, backupId = null) {
471
+ const restored = [];
472
+ const removed = [];
473
+ const errors = [];
474
+ const notRestored = [];
475
+ const steps = [];
476
+
477
+ const all = listBackups(projectPath);
478
+ let chain;
479
+ if (backupId) {
480
+ if (!existsSync(join(projectPath, backupId))) {
481
+ return { success: false, restored, removed, errors: [`Backup not found: ${backupId}`], notRestored, steps, olderBackups: 0 };
482
+ }
483
+ chain = [backupId];
484
+ } else {
485
+ if (all.length === 0) {
486
+ return { success: false, restored, removed, errors: ['No backups found'], notRestored, steps, olderBackups: 0 };
487
+ }
488
+ chain = [all[0].backupId];
489
+ // Walk back while "the manifest before this step" is "the manifest the previous step left".
490
+ for (let i = 1; i < all.length; i++) {
491
+ const newer = all[i - 1];
492
+ const older = all[i];
493
+ if (newer.preManifestHash && older.postManifestHash && newer.preManifestHash === older.postManifestHash) {
494
+ chain.push(older.backupId);
495
+ } else {
496
+ break;
497
+ }
498
+ }
499
+ }
500
+
501
+ for (const id of chain) {
502
+ const one = restoreOne(projectPath, id);
503
+ steps.push({ backupId: id, label: one.label, restored: one.restored, removed: one.removed, errors: one.errors, notRestored: one.notRestored });
504
+ restored.push(...one.restored);
505
+ removed.push(...one.removed);
506
+ errors.push(...one.errors);
507
+ notRestored.push(...one.notRestored);
508
+ }
509
+
510
+ const olderBackups = backupId ? 0 : all.length - chain.length;
511
+ return {
512
+ success: errors.length === 0,
513
+ restored: [...new Set(restored)],
514
+ removed: [...new Set(removed)],
515
+ errors,
516
+ notRestored,
517
+ steps,
518
+ olderBackups
519
+ };
215
520
  }
216
521
 
217
522
  /**
218
523
  * List all backups for a project, sorted by creation time (newest first).
219
524
  *
220
525
  * @param {string} projectPath
221
- * @returns {Array<{ backupId: string, createdAt: string, actionCount: number }>}
526
+ * @returns {Array<{ backupId: string, createdAt: string, actionCount: number, label: string|null,
527
+ * preManifestHash: string|null, postManifestHash: string|null }>}
222
528
  */
223
529
  export function listBackups(projectPath) {
224
530
  try {
225
- const entries = readdirSync(projectPath, { withFileTypes: true });
226
531
  const backups = [];
227
532
 
228
- for (const entry of entries) {
229
- 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);
230
537
 
231
- const backupDir = join(projectPath, entry.name);
232
- const manifestPath = join(backupDir, 'backup-manifest.json');
538
+ for (const backupId of places) {
539
+ const manifestPath = join(projectPath, backupId, 'backup-manifest.json');
233
540
 
234
- let info = { backupId: entry.name, createdAt: '', actionCount: 0 };
541
+ const info = {
542
+ backupId,
543
+ createdAt: '',
544
+ actionCount: 0,
545
+ label: null,
546
+ preManifestHash: null,
547
+ postManifestHash: null
548
+ };
235
549
  if (existsSync(manifestPath)) {
236
550
  try {
237
551
  const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
238
552
  info.createdAt = manifest.createdAt || '';
239
553
  info.actionCount = manifest.plan?.actionCount || 0;
554
+ info.label = manifest.label || null;
555
+ info.preManifestHash = manifest.preManifestHash || null;
556
+ info.postManifestHash = manifest.postManifestHash || null;
240
557
  } catch {
241
558
  // Use defaults
242
559
  }
@@ -245,8 +562,11 @@ export function listBackups(projectPath) {
245
562
  backups.push(info);
246
563
  }
247
564
 
248
- // Sort newest first
249
- backups.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
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)));
250
570
  return backups;
251
571
  } catch {
252
572
  return [];