@fission-ai/openspec 1.7.0 → 1.9.0

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 (113) hide show
  1. package/README.md +3 -1
  2. package/dist/cli/index.d.ts +15 -0
  3. package/dist/cli/index.js +39 -5
  4. package/dist/commands/change.js +16 -1
  5. package/dist/commands/config.d.ts +5 -0
  6. package/dist/commands/config.js +5 -1
  7. package/dist/commands/schema.js +281 -47
  8. package/dist/commands/spec.js +30 -6
  9. package/dist/commands/validate.d.ts +23 -0
  10. package/dist/commands/validate.js +148 -4
  11. package/dist/commands/workflow/instructions.js +32 -27
  12. package/dist/commands/workflow/schemas.d.ts +2 -0
  13. package/dist/commands/workflow/schemas.js +9 -2
  14. package/dist/commands/workflow/status.js +2 -2
  15. package/dist/commands/workflow/templates.js +15 -5
  16. package/dist/core/archive.d.ts +14 -0
  17. package/dist/core/archive.js +1272 -151
  18. package/dist/core/artifact-graph/index.d.ts +1 -1
  19. package/dist/core/artifact-graph/index.js +1 -1
  20. package/dist/core/artifact-graph/instruction-loader.d.ts +3 -1
  21. package/dist/core/artifact-graph/instruction-loader.js +15 -5
  22. package/dist/core/artifact-graph/outputs.d.ts +1 -0
  23. package/dist/core/artifact-graph/outputs.js +67 -5
  24. package/dist/core/artifact-graph/resolver.d.ts +0 -12
  25. package/dist/core/artifact-graph/resolver.js +49 -9
  26. package/dist/core/artifact-graph/types.js +21 -3
  27. package/dist/core/available-tools.d.ts +2 -2
  28. package/dist/core/available-tools.js +14 -3
  29. package/dist/core/change-metadata/schema.d.ts +1 -0
  30. package/dist/core/change-metadata/schema.js +7 -0
  31. package/dist/core/change-status-policy.js +2 -2
  32. package/dist/core/command-generation/adapters/command-code.d.ts +19 -0
  33. package/dist/core/command-generation/adapters/command-code.js +34 -0
  34. package/dist/core/command-generation/adapters/index.d.ts +1 -0
  35. package/dist/core/command-generation/adapters/index.js +1 -0
  36. package/dist/core/command-generation/registry.js +2 -0
  37. package/dist/core/completions/command-registry.js +13 -0
  38. package/dist/core/config-schema.d.ts +3 -0
  39. package/dist/core/config-schema.js +28 -1
  40. package/dist/core/config.d.ts +4 -0
  41. package/dist/core/config.js +40 -17
  42. package/dist/core/file-state.js +56 -24
  43. package/dist/core/github-copilot/cloud-agent.d.ts +95 -0
  44. package/dist/core/github-copilot/cloud-agent.js +497 -0
  45. package/dist/core/global-config.d.ts +11 -0
  46. package/dist/core/init.d.ts +23 -0
  47. package/dist/core/init.js +253 -46
  48. package/dist/core/legacy-cleanup.d.ts +10 -0
  49. package/dist/core/legacy-cleanup.js +52 -28
  50. package/dist/core/migration.d.ts +6 -4
  51. package/dist/core/migration.js +78 -22
  52. package/dist/core/parsers/requirement-blocks.d.ts +10 -0
  53. package/dist/core/parsers/requirement-blocks.js +93 -1
  54. package/dist/core/parsers/requirement-text.d.ts +8 -0
  55. package/dist/core/parsers/requirement-text.js +4 -3
  56. package/dist/core/parsers/spec-structure.d.ts +1 -1
  57. package/dist/core/parsers/spec-structure.js +17 -1
  58. package/dist/core/profile-sync-drift.js +40 -5
  59. package/dist/core/project-config.d.ts +3 -0
  60. package/dist/core/project-config.js +31 -1
  61. package/dist/core/root-selection.d.ts +1 -1
  62. package/dist/core/shared/index.d.ts +1 -0
  63. package/dist/core/shared/index.js +1 -0
  64. package/dist/core/shared/skill-content-equivalence.d.ts +7 -0
  65. package/dist/core/shared/skill-content-equivalence.js +41 -0
  66. package/dist/core/shared/skill-paths.d.ts +13 -0
  67. package/dist/core/shared/skill-paths.js +23 -0
  68. package/dist/core/shared/tool-detection.js +66 -35
  69. package/dist/core/shared-skill-target.d.ts +31 -0
  70. package/dist/core/shared-skill-target.js +186 -0
  71. package/dist/core/specs-apply.d.ts +72 -0
  72. package/dist/core/specs-apply.js +459 -59
  73. package/dist/core/templates/skill-templates.d.ts +1 -1
  74. package/dist/core/templates/skill-templates.js +1 -1
  75. package/dist/core/templates/workflows/apply-change.d.ts +10 -0
  76. package/dist/core/templates/workflows/apply-change.js +25 -182
  77. package/dist/core/templates/workflows/archive-change.js +8 -4
  78. package/dist/core/templates/workflows/bulk-archive-change.js +30 -26
  79. package/dist/core/templates/workflows/continue-change.js +6 -6
  80. package/dist/core/templates/workflows/explore.js +42 -18
  81. package/dist/core/templates/workflows/onboard.js +9 -3
  82. package/dist/core/templates/workflows/propose.js +72 -20
  83. package/dist/core/templates/workflows/store-selection.d.ts +1 -1
  84. package/dist/core/templates/workflows/store-selection.js +1 -1
  85. package/dist/core/templates/workflows/sync-specs.js +96 -18
  86. package/dist/core/templates/workflows/update-change.js +10 -8
  87. package/dist/core/update.d.ts +1 -0
  88. package/dist/core/update.js +136 -30
  89. package/dist/core/validation/task-numbering.d.ts +16 -0
  90. package/dist/core/validation/task-numbering.js +57 -0
  91. package/dist/core/validation/validator.d.ts +26 -3
  92. package/dist/core/validation/validator.js +189 -19
  93. package/dist/core/version-check.js +6 -11
  94. package/dist/telemetry/config.d.ts +3 -4
  95. package/dist/telemetry/index.d.ts +12 -5
  96. package/dist/telemetry/index.js +27 -9
  97. package/dist/utils/change-metadata.d.ts +17 -4
  98. package/dist/utils/change-metadata.js +26 -4
  99. package/dist/utils/ci.d.ts +12 -0
  100. package/dist/utils/ci.js +16 -0
  101. package/dist/utils/command-references.d.ts +14 -2
  102. package/dist/utils/command-references.js +45 -3
  103. package/dist/utils/file-system.d.ts +10 -0
  104. package/dist/utils/file-system.js +70 -0
  105. package/dist/utils/interactive.d.ts +52 -0
  106. package/dist/utils/interactive.js +135 -0
  107. package/dist/utils/spec-discovery.d.ts +4 -4
  108. package/dist/utils/spec-discovery.js +19 -6
  109. package/dist/utils/task-progress.d.ts +51 -1
  110. package/dist/utils/task-progress.js +93 -41
  111. package/package.json +1 -1
  112. package/schemas/spec-driven/schema.yaml +8 -6
  113. package/schemas/spec-driven/templates/proposal.md +6 -4
@@ -1,13 +1,18 @@
1
- import { promises as fs } from 'fs';
1
+ import { constants, createReadStream, promises as fs } from 'fs';
2
+ import { createHash, randomUUID } from 'crypto';
2
3
  import path from 'path';
3
4
  import { formatLocalDate } from '../utils/date.js';
4
5
  import { getTaskProgressForChange, formatTaskStatus } from '../utils/task-progress.js';
5
6
  import { Validator } from './validation/validator.js';
7
+ import { VALIDATION_MESSAGES } from './validation/constants.js';
6
8
  import chalk from 'chalk';
7
9
  import { emitStoreRootBanner, isRootSelectionError, resolveOpenSpecRoot, toRootOutput, withStoreFlag, isStoreSelectedRoot, } from './root-selection.js';
8
- import { findSpecUpdates, buildUpdatedSpec, writeUpdatedSpec, } from './specs-apply.js';
10
+ import { findSpecUpdates, buildUpdatedSpec, writeUpdatedSpec, retireSpec, finalizeRetiredSpec, } from './specs-apply.js';
9
11
  import { discoverSpecFiles, hasAnyFileUnder } from '../utils/spec-discovery.js';
10
- import { readSkipSpecsMarker } from '../utils/change-metadata.js';
12
+ import { METADATA_FILENAME, readRetireCapabilitiesMarker, readSkipSpecsMarker } from '../utils/change-metadata.js';
13
+ import { confirmPrompt, isNonInteractivePromptError } from '../utils/interactive.js';
14
+ import { FileSystemUtils } from '../utils/file-system.js';
15
+ import { folderStyleNameProblem } from './id.js';
11
16
  function isMissingPathError(error) {
12
17
  return (typeof error === 'object' &&
13
18
  error !== null &&
@@ -20,6 +25,66 @@ function isMissingPathError(error) {
20
25
  * is archived under its existing name so the prefix is never stacked (#1309).
21
26
  */
22
27
  const ARCHIVE_DATE_PREFIX_PATTERN = /^\d{4}-\d{2}-\d{2}-/;
28
+ /**
29
+ * True when the ONLY thing wrong with a rebuilt spec is that it has no
30
+ * requirements. That is the exact failure retiring a capability replaces
31
+ * (#1302); anything else means the spec is broken in a way the author still has
32
+ * to fix, so archive must abort exactly as it always did instead of retiring.
33
+ *
34
+ * Asking the validator - rather than counting requirement blocks a second time -
35
+ * is what makes "this spec could not have been written anyway" true by
36
+ * construction. The two counts genuinely disagree: `MarkdownParser` accepts any
37
+ * `###` heading under `## Requirements` as a requirement, while the delta block
38
+ * parser only indexes canonical `### Requirement:` headers and sweeps the rest
39
+ * into the preamble, which survives into the rebuilt spec.
40
+ */
41
+ export async function isRetirableSpec(specName, rebuilt) {
42
+ const report = await new Validator().validateSpecContent(specName, rebuilt);
43
+ if (report.valid)
44
+ return false;
45
+ const errors = report.issues.filter((issue) => issue.level === 'ERROR');
46
+ return (errors.length > 0 &&
47
+ errors.every((issue) => issue.message === VALIDATION_MESSAGES.SPEC_NO_REQUIREMENTS));
48
+ }
49
+ async function isRetirementCandidate(update, built, skipValidation) {
50
+ return (!skipValidation &&
51
+ built.noRequirementBlocks &&
52
+ built.unaccountedContent.length === 0 &&
53
+ (await isRetirableSpec(update.id, built.rebuilt)));
54
+ }
55
+ async function decideSpecOutcome(update, built, skipValidation, retirementDeclared) {
56
+ // The author has to have asked. Without the marker this falls through to the
57
+ // ordinary write, which fails validation exactly as it always did - and the
58
+ // abort names the marker, so the dead end #1302 describes now comes with its
59
+ // own way out instead of just a rejected spec.
60
+ if (!retirementDeclared)
61
+ return 'write';
62
+ // Retirement is decided by the validator, never by a second opinion about
63
+ // what counts as a requirement: the block parser sweeps some shapes the
64
+ // validator accepts into the preamble, so "no blocks left" alone would retire
65
+ // specs that validate fine.
66
+ //
67
+ // Residual `###` headings veto it outright. The validator can be talked out of
68
+ // seeing them - a stray `### Requirements` under Purpose captures its section
69
+ // lookup - but a reader cannot, and deleting the file would take them with it.
70
+ //
71
+ // Under --no-validate there is no verdict to lean on, so nothing is retired:
72
+ // the author opted out of the check that makes this safe, and the old
73
+ // behavior (write the spec) loses nothing.
74
+ // Nothing in the file may sit outside the parts the merge understands. Asked
75
+ // as "did anything land outside the parts I understand" rather than "does
76
+ // anything look like a requirement" - the second question is the one six
77
+ // review rounds each found a new way to answer wrongly.
78
+ const retirable = await isRetirementCandidate(update, built, skipValidation);
79
+ if (!retirable)
80
+ return 'write';
81
+ // Nothing on disk to write or retire: the capability is already retired.
82
+ if (!update.exists)
83
+ return 'skip';
84
+ // A spec that was already requirement-less and lost nothing this run is still
85
+ // the author's to fix, so it takes the same abort it has always produced.
86
+ return built.counts.removed > 0 ? 'retire' : 'write';
87
+ }
23
88
  async function listActiveChangeNames(changesDir) {
24
89
  try {
25
90
  const entries = await fs.readdir(changesDir, { withFileTypes: true });
@@ -35,9 +100,11 @@ async function listActiveChangeNames(changesDir) {
35
100
  }
36
101
  }
37
102
  /**
38
- * JSON mode is non-interactive: any point where the human flow would prompt or
39
- * print prose instead throws this error, which becomes a machine-readable
40
- * status entry with a non-zero exit code.
103
+ * A decision point archive cannot get past on its own. Thrown wherever the
104
+ * flow needs an answer it has no way to obtain: in JSON mode, which never
105
+ * prompts at all, and in human mode when a prompt failed because nothing
106
+ * could answer it (#1479). Either way it carries a machine-readable
107
+ * diagnostic and exits non-zero.
41
108
  */
42
109
  class ArchiveBlockedError extends Error {
43
110
  diagnostic;
@@ -52,6 +119,99 @@ class ArchiveBlockedError extends Error {
52
119
  };
53
120
  }
54
121
  }
122
+ /**
123
+ * Quotes a change name for a `Fix:` line the reader is meant to paste.
124
+ * Archive resolves a change by stat-ing its directory, so the name is
125
+ * whatever the directory is called - including names with spaces or shell
126
+ * metacharacters, which pasted unquoted would run as a second command.
127
+ *
128
+ * Double quotes are the one form bash, zsh, PowerShell and cmd.exe all read
129
+ * the same way, so a POSIX-only `'...'` would be wrong on Windows. Characters
130
+ * that stay inert inside double quotes in every one of those shells are the
131
+ * limit of what can be quoted portably; a name containing anything else has
132
+ * no portable spelling, so the placeholder is named instead of emitting a
133
+ * command that might expand to something the reader did not intend.
134
+ *
135
+ * `%` and `!` are unquotable for the same reason even though POSIX shells
136
+ * leave them alone inside double quotes: cmd.exe expands `%NAME%` inside
137
+ * double quotes, and `!NAME!` expands there too under `setlocal
138
+ * enabledelayedexpansion` (as does `!` under bash's interactive history
139
+ * expansion). A change directory really can be named `%USERNAME%`, and a
140
+ * rerun that silently targets a different change is worse than one the reader
141
+ * has to fill in.
142
+ */
143
+ function quoteChangeName(name) {
144
+ return quoteForShell(name) ?? '<change-name>';
145
+ }
146
+ /**
147
+ * Quotes an argument for a line the reader is meant to paste, or returns
148
+ * undefined when no portable spelling exists.
149
+ *
150
+ * Double quotes are the one form bash, zsh, PowerShell and cmd.exe all read the
151
+ * same way. A value holding a character that stays special INSIDE double quotes
152
+ * in any of them has no portable spelling, so callers say something else rather
153
+ * than emit a command that expands to something the reader did not intend.
154
+ */
155
+ function quoteForShell(value) {
156
+ if (/^[A-Za-z0-9._\/-]+$/.test(value))
157
+ return value;
158
+ if (!/["\\$`\r\n%!]/.test(value))
159
+ return `"${value}"`;
160
+ return undefined;
161
+ }
162
+ /**
163
+ * Renders a change name inside a prose message. The name is a directory name,
164
+ * so it can hold control characters, and human mode prints the message
165
+ * verbatim: a raw CR or LF would let a change directory forge its own `Fix:`
166
+ * line, which is worse here than anywhere else because `quoteChangeName`
167
+ * degrades the real fix to the `<change-name>` placeholder for exactly those
168
+ * names - leaving the forged line as the only pasteable command on screen.
169
+ * An ESC could redraw the terminal. Neither survives.
170
+ */
171
+ function describeChangeName(name) {
172
+ return name.replace(/[\u0000-\u001f\u007f]/g, '?');
173
+ }
174
+ /**
175
+ * Builds the flags a blocked archive's suggested rerun has to reproduce. The
176
+ * caller's own flags are carried, because suggesting a bare `--yes` rerun for
177
+ * `archive x --skip-specs` would merge deltas into the main specs - the exact
178
+ * thing `--skip-specs` was passed to prevent.
179
+ */
180
+ function rerunFlags(options) {
181
+ return [
182
+ ...(options.skipSpecs ? ['--skip-specs'] : []),
183
+ ...(options.validate === false || options.noValidate === true ? ['--no-validate'] : []),
184
+ '--yes',
185
+ ];
186
+ }
187
+ function rerunCommand(root, changeName, options) {
188
+ const flags = rerunFlags(options).join(' ');
189
+ // A name starting with a dash is read as an option wherever it sits, so it
190
+ // goes last, behind the `--` that ends option parsing. The store flag has
191
+ // to stay in front of that `--` to still be read as an option.
192
+ if (changeName.startsWith('-')) {
193
+ return `${withStoreFlag(root, `openspec archive ${flags}`)} -- ${quoteChangeName(changeName)}`;
194
+ }
195
+ return withStoreFlag(root, `openspec archive ${quoteChangeName(changeName)} ${flags}`);
196
+ }
197
+ /**
198
+ * Asks a yes/no question in human mode. When no answer can be read — the
199
+ * usual case for an AI agent or a script that runs the command with stdin
200
+ * closed — the raw @inquirer failure is replaced with guidance for this
201
+ * decision point, so the caller learns which flag to pass instead of reading
202
+ * `User force closed the prompt` (#1479).
203
+ */
204
+ async function confirmOrBlock(prompt, blocked) {
205
+ try {
206
+ return await confirmPrompt(prompt);
207
+ }
208
+ catch (error) {
209
+ if (isNonInteractivePromptError(error)) {
210
+ throw blocked();
211
+ }
212
+ throw error;
213
+ }
214
+ }
55
215
  function toArchiveDiagnostic(error) {
56
216
  if (error instanceof ArchiveBlockedError) {
57
217
  return error.diagnostic;
@@ -68,41 +228,603 @@ function toArchiveDiagnostic(error) {
68
228
  /**
69
229
  * Recursively copy a directory. Used when fs.rename fails (e.g. EPERM on Windows).
70
230
  */
71
- async function copyDirRecursive(src, dest) {
72
- await fs.mkdir(dest, { recursive: true });
231
+ async function copySymbolicLink(src, dest) {
232
+ const target = await fs.readlink(src);
233
+ const isWindowsDirectoryLink = process.platform === 'win32' && (await fs.stat(src)).isDirectory();
234
+ const destinationTarget = isWindowsDirectoryLink && !path.isAbsolute(target)
235
+ ? path.resolve(path.dirname(src), target)
236
+ : target;
237
+ await fs.symlink(destinationTarget, dest, isWindowsDirectoryLink ? 'junction' : undefined);
238
+ }
239
+ async function copyDirContents(src, dest) {
240
+ const sourceStat = await fs.lstat(src);
241
+ // Keep group/other access no broader than the source while ensuring this
242
+ // process can populate even a read-only source directory.
243
+ await fs.chmod(dest, (sourceStat.mode & 0o7777) | 0o700);
73
244
  const entries = await fs.readdir(src, { withFileTypes: true });
74
245
  for (const entry of entries) {
75
246
  const srcPath = path.join(src, entry.name);
76
247
  const destPath = path.join(dest, entry.name);
77
248
  if (entry.isDirectory()) {
78
- await copyDirRecursive(srcPath, destPath);
249
+ await fs.mkdir(destPath, { mode: 0o700 });
250
+ await copyDirContents(srcPath, destPath);
251
+ }
252
+ else if (entry.isSymbolicLink()) {
253
+ await copySymbolicLink(srcPath, destPath);
254
+ }
255
+ else if (entry.isFile()) {
256
+ await fs.copyFile(srcPath, destPath, constants.COPYFILE_EXCL);
79
257
  }
80
258
  else {
81
- await fs.copyFile(srcPath, destPath);
259
+ throw new Error(`Cannot archive unsupported filesystem entry: ${srcPath}`);
260
+ }
261
+ }
262
+ await fs.chmod(dest, sourceStat.mode & 0o7777);
263
+ }
264
+ async function fingerprintDirectoryContents(root) {
265
+ const hash = createHash('sha256');
266
+ const updateHashField = (label, value) => {
267
+ const labelBuffer = Buffer.from(label);
268
+ const valueBuffer = typeof value === 'string' ? Buffer.from(value) : value;
269
+ const lengths = Buffer.allocUnsafe(16);
270
+ lengths.writeBigUInt64BE(BigInt(labelBuffer.length), 0);
271
+ lengths.writeBigUInt64BE(BigInt(valueBuffer.length), 8);
272
+ hash.update(lengths);
273
+ hash.update(labelBuffer);
274
+ hash.update(valueBuffer);
275
+ };
276
+ const fingerprintFile = async (filePath) => {
277
+ const fileHash = createHash('sha256');
278
+ for await (const chunk of createReadStream(filePath)) {
279
+ fileHash.update(chunk);
82
280
  }
281
+ return fileHash.digest();
282
+ };
283
+ const visit = async (dir, relativeDir) => {
284
+ const before = await fs.lstat(dir, { bigint: true });
285
+ if (!before.isDirectory()) {
286
+ throw new Error(`Expected a directory while verifying ${dir}.`);
287
+ }
288
+ updateHashField('directory-mode', (before.mode & 4095n).toString());
289
+ const entries = (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
290
+ for (const entry of entries) {
291
+ const entryPath = path.join(dir, entry.name);
292
+ const relativePath = path.join(relativeDir, entry.name);
293
+ const stat = await fs.lstat(entryPath, { bigint: true });
294
+ updateHashField('path', relativePath);
295
+ if (stat.isDirectory()) {
296
+ updateHashField('type', 'directory');
297
+ await visit(entryPath, relativePath);
298
+ }
299
+ else if (stat.isSymbolicLink()) {
300
+ const target = await fs.readlink(entryPath);
301
+ const after = await fs.lstat(entryPath, { bigint: true });
302
+ if (statIdentity(stat) !== statIdentity(after)) {
303
+ throw new Error(`Path changed while archive was reading ${entryPath}.`);
304
+ }
305
+ updateHashField('type', 'symlink');
306
+ updateHashField('target', target);
307
+ }
308
+ else if (stat.isFile()) {
309
+ const contentFingerprint = await fingerprintFile(entryPath);
310
+ const after = await fs.lstat(entryPath, { bigint: true });
311
+ if (statIdentity(stat) !== statIdentity(after)) {
312
+ throw new Error(`Path changed while archive was reading ${entryPath}.`);
313
+ }
314
+ updateHashField('type', 'file');
315
+ updateHashField('mode', (stat.mode & 4095n).toString());
316
+ updateHashField('content-sha256', contentFingerprint);
317
+ }
318
+ else {
319
+ updateHashField('type', 'other');
320
+ updateHashField('mode', stat.mode.toString());
321
+ updateHashField('size', stat.size.toString());
322
+ }
323
+ }
324
+ const after = await fs.lstat(dir, { bigint: true });
325
+ if (statIdentity(before) !== statIdentity(after)) {
326
+ throw new Error(`Directory changed while archive was reading ${dir}.`);
327
+ }
328
+ };
329
+ await visit(root, '');
330
+ return hash.digest('hex');
331
+ }
332
+ async function assertCopiedDirectoryUnchanged(stagedSource, destination, expectedFingerprint) {
333
+ const sourceFingerprint = await fingerprintDirectoryContents(stagedSource);
334
+ const destinationFingerprint = await fingerprintDirectoryContents(destination);
335
+ if (sourceFingerprint !== expectedFingerprint ||
336
+ destinationFingerprint !== expectedFingerprint) {
337
+ throw new Error(`Change directory contents changed during the fallback copy from ${stagedSource} to ${destination}.`);
83
338
  }
84
339
  }
85
340
  /**
86
- * Move a directory from src to dest. On Windows, fs.rename() often fails with
87
- * EPERM when the directory is non-empty or another process has it open (IDE,
88
- * file watcher, antivirus). Fall back to copy-then-remove when rename fails
89
- * with EPERM or EXDEV.
341
+ * Move a directory from src to dest. On Windows, fs.rename() can fail with
342
+ * EPERM, and cross-device moves fail with EXDEV. When the source can first be
343
+ * renamed to a private sibling, fall back to a verified copy-then-remove. A
344
+ * source that cannot be staged is left untouched rather than copied and deleted
345
+ * through a path another process may still be editing.
90
346
  */
91
- async function moveDirectory(src, dest) {
347
+ class MoveDestinationRetainedError extends Error {
348
+ }
349
+ class RetirementBackupsRetainedError extends Error {
350
+ }
351
+ async function moveDirectory(src, dest, options = {}) {
92
352
  try {
93
353
  await fs.rename(src, dest);
94
354
  }
95
355
  catch (err) {
96
356
  const code = err?.code;
357
+ // rename onto a non-empty directory: the destination was taken while the
358
+ // archive was running. Same condition the pre-flight check reports.
359
+ if (code === 'ENOTEMPTY' || code === 'EEXIST') {
360
+ throw new ArchiveBlockedError('archive_target_exists', `Archive '${path.basename(dest)}' already exists.`);
361
+ }
97
362
  if (code === 'EPERM' || code === 'EXDEV') {
98
- await copyDirRecursive(src, dest);
99
- await fs.rm(src, { recursive: true, force: true });
363
+ const stagedSource = path.join(path.dirname(src), `.openspec-move-${randomUUID()}`);
364
+ try {
365
+ await fs.rename(src, stagedSource);
366
+ }
367
+ catch (stageError) {
368
+ throw new Error(`Could not safely stage ${src} before the fallback archive copy ` +
369
+ `(${stageError instanceof Error ? stageError.message : String(stageError)}). ` +
370
+ 'No fallback copy was attempted.');
371
+ }
372
+ let destIsOurs = false;
373
+ let stagedFingerprint;
374
+ try {
375
+ stagedFingerprint = await fingerprintDirectoryContents(stagedSource);
376
+ await fs.mkdir(dest, { mode: 0o700 });
377
+ destIsOurs = true;
378
+ await copyDirContents(stagedSource, dest);
379
+ await options.verifyCopiedDestination?.(stagedSource);
380
+ await assertCopiedDirectoryUnchanged(stagedSource, dest, stagedFingerprint);
381
+ }
382
+ catch (copyError) {
383
+ if (destIsOurs) {
384
+ await fs.rm(dest, { recursive: true, force: true }).catch(() => undefined);
385
+ }
386
+ try {
387
+ await fs.rename(stagedSource, src);
388
+ }
389
+ catch (restoreError) {
390
+ throw new Error(`${copyError instanceof Error ? copyError.message : String(copyError)} ` +
391
+ `Could not restore the staged source at ${stagedSource} ` +
392
+ `(${restoreError instanceof Error ? restoreError.message : String(restoreError)}).`);
393
+ }
394
+ if (copyError.code === 'EEXIST') {
395
+ throw new ArchiveBlockedError('archive_target_exists', `Archive '${path.basename(dest)}' already exists.`);
396
+ }
397
+ throw copyError;
398
+ }
399
+ try {
400
+ await options.verifyCopiedDestination?.(stagedSource);
401
+ await assertCopiedDirectoryUnchanged(stagedSource, dest, stagedFingerprint);
402
+ }
403
+ catch (verificationError) {
404
+ await fs.rm(dest, { recursive: true, force: true }).catch(() => undefined);
405
+ try {
406
+ await fs.rename(stagedSource, src);
407
+ }
408
+ catch (restoreError) {
409
+ throw new Error(`${verificationError instanceof Error ? verificationError.message : String(verificationError)} ` +
410
+ `Could not restore the staged source at ${stagedSource} ` +
411
+ `(${restoreError instanceof Error ? restoreError.message : String(restoreError)}).`);
412
+ }
413
+ throw verificationError;
414
+ }
415
+ try {
416
+ await fs.rm(stagedSource, { recursive: true, force: true });
417
+ }
418
+ catch (cleanupError) {
419
+ // Recursive removal may already have deleted part of the source. The
420
+ // destination is now the only complete copy, so never erase it while
421
+ // trying to make this failed move look atomic.
422
+ throw new MoveDestinationRetainedError(`Copied ${src} to ${dest}, but could not remove the staged source at ` +
423
+ `${stagedSource} completely ` +
424
+ `(${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}). ` +
425
+ 'The complete destination was retained for recovery.');
426
+ }
100
427
  }
101
428
  else {
102
429
  throw err;
103
430
  }
104
431
  }
105
432
  }
433
+ async function assertArchiveDestinationAvailable(archivePath, archiveName) {
434
+ try {
435
+ await fs.lstat(archivePath);
436
+ throw new ArchiveBlockedError('archive_target_exists', `Archive '${archiveName}' already exists.`);
437
+ }
438
+ catch (error) {
439
+ if (error instanceof ArchiveBlockedError)
440
+ throw error;
441
+ if (error.code !== 'ENOENT')
442
+ throw error;
443
+ }
444
+ }
445
+ function archiveClaimPath(archivePath, _archiveName) {
446
+ return path.join(path.dirname(archivePath), '.openspec-archive.lock');
447
+ }
448
+ async function releaseArchiveClaim(claim, claimPath) {
449
+ const owned = await claim.handle.stat({ bigint: true }).catch(() => undefined);
450
+ await claim.handle.close().catch(() => undefined);
451
+ if (owned === undefined)
452
+ return;
453
+ try {
454
+ // Read between two lstats by design: the identity + content match below
455
+ // proves we still own this claim before unlinking it. This is a concurrent-
456
+ // change detector, not an fd-less race to "fix" (CodeQL js/file-system-race).
457
+ const current = await fs.lstat(claimPath, { bigint: true });
458
+ const contents = await fs.readFile(claimPath, 'utf8');
459
+ const currentAfterRead = await fs.lstat(claimPath, { bigint: true });
460
+ if (current.dev === owned.dev &&
461
+ current.ino === owned.ino &&
462
+ current.dev === currentAfterRead.dev &&
463
+ current.ino === currentAfterRead.ino &&
464
+ contents === claim.contents) {
465
+ await fs.unlink(claimPath);
466
+ }
467
+ }
468
+ catch (error) {
469
+ if (error.code !== 'ENOENT')
470
+ throw error;
471
+ }
472
+ }
473
+ async function claimArchiveDestination(archivePath, archiveName) {
474
+ const claimPath = archiveClaimPath(archivePath, archiveName);
475
+ try {
476
+ const handle = await fs.open(claimPath, 'wx');
477
+ const claim = {
478
+ handle,
479
+ contents: JSON.stringify({ pid: process.pid, nonce: randomUUID() }),
480
+ };
481
+ try {
482
+ await handle.writeFile(claim.contents);
483
+ await handle.sync();
484
+ return claim;
485
+ }
486
+ catch (error) {
487
+ await releaseArchiveClaim(claim, claimPath).catch(() => undefined);
488
+ throw error;
489
+ }
490
+ }
491
+ catch (error) {
492
+ if (error.code === 'EEXIST') {
493
+ throw new ArchiveBlockedError('archive_target_exists', `Archive '${archiveName}' is already being created. If no archive process is running, ` +
494
+ `remove the stale claim at ${claimPath} and rerun.`);
495
+ }
496
+ throw error;
497
+ }
498
+ }
499
+ function statIdentity(value) {
500
+ return `${value.dev}:${value.ino}:${value.mode}:${value.size}:${value.mtimeNs}:${value.ctimeNs}`;
501
+ }
502
+ function movableStatIdentity(value) {
503
+ return `${value.dev}:${value.ino}:${value.mode}:${value.size}`;
504
+ }
505
+ async function fingerprintPath(filePath) {
506
+ try {
507
+ const stat = await fs.lstat(filePath, { bigint: true });
508
+ const digest = async () => createHash('sha256').update(await fs.readFile(filePath)).digest('hex');
509
+ if (stat.isSymbolicLink()) {
510
+ const link = await fs.readlink(filePath);
511
+ try {
512
+ const referentBefore = await fs.stat(filePath, { bigint: true });
513
+ const hash = await digest();
514
+ const referentAfter = await fs.stat(filePath, { bigint: true });
515
+ const entryAfter = await fs.lstat(filePath, { bigint: true });
516
+ if (statIdentity(stat) !== statIdentity(entryAfter) ||
517
+ statIdentity(referentBefore) !== statIdentity(referentAfter) ||
518
+ link !== (await fs.readlink(filePath))) {
519
+ throw new Error(`Path changed while archive was reading ${filePath}.`);
520
+ }
521
+ return `symlink:${statIdentity(stat)}:${link}:${statIdentity(referentAfter)}:${hash}`;
522
+ }
523
+ catch (error) {
524
+ if (error.code === 'ENOENT') {
525
+ return `symlink:${statIdentity(stat)}:${link}:missing`;
526
+ }
527
+ throw error;
528
+ }
529
+ }
530
+ if (stat.isFile()) {
531
+ const hash = await digest();
532
+ const after = await fs.lstat(filePath, { bigint: true });
533
+ if (statIdentity(stat) !== statIdentity(after)) {
534
+ throw new Error(`Path changed while archive was reading ${filePath}.`);
535
+ }
536
+ return `file:${statIdentity(after)}:${hash}`;
537
+ }
538
+ return `other:${statIdentity(stat)}`;
539
+ }
540
+ catch (error) {
541
+ if (error.code === 'ENOENT')
542
+ return 'missing';
543
+ throw error;
544
+ }
545
+ }
546
+ async function fingerprintMovablePath(filePath) {
547
+ try {
548
+ const entry = await fs.lstat(filePath, { bigint: true });
549
+ // Deliberate stat -> read -> re-stat: a concurrent change is DETECTED by the
550
+ // statIdentity comparison below and throws. Do not collapse to fd I/O, which
551
+ // would pin one inode and blind the detector (CodeQL js/file-system-race).
552
+ const hash = createHash('sha256')
553
+ .update(await fs.readFile(filePath))
554
+ .digest('hex');
555
+ if (entry.isSymbolicLink()) {
556
+ const link = await fs.readlink(filePath);
557
+ const referent = await fs.stat(filePath, { bigint: true });
558
+ const entryAfter = await fs.lstat(filePath, { bigint: true });
559
+ const referentAfter = await fs.stat(filePath, { bigint: true });
560
+ const linkAfter = await fs.readlink(filePath);
561
+ if (statIdentity(entry) !== statIdentity(entryAfter) ||
562
+ statIdentity(referent) !== statIdentity(referentAfter) ||
563
+ link !== linkAfter) {
564
+ throw new Error(`Path changed while archive was reading ${filePath}.`);
565
+ }
566
+ return (`symlink:${movableStatIdentity(entry)}:${link}:` +
567
+ `${movableStatIdentity(referentAfter)}:${hash}`);
568
+ }
569
+ const entryAfter = await fs.lstat(filePath, { bigint: true });
570
+ if (statIdentity(entry) !== statIdentity(entryAfter)) {
571
+ throw new Error(`Path changed while archive was reading ${filePath}.`);
572
+ }
573
+ return `file:${movableStatIdentity(entry)}:${hash}`;
574
+ }
575
+ catch (error) {
576
+ if (error.code === 'ENOENT')
577
+ return 'missing';
578
+ throw error;
579
+ }
580
+ }
581
+ async function fingerprintPortableContent(filePath) {
582
+ try {
583
+ const entry = await fs.lstat(filePath);
584
+ // Point-in-time content hash by design (no re-stat): callers compare it
585
+ // against a prior fingerprint of the same bytes, so any concurrent change
586
+ // surfaces as a hash mismatch (CodeQL js/file-system-race is a false positive here).
587
+ const hash = createHash('sha256')
588
+ .update(await fs.readFile(filePath))
589
+ .digest('hex');
590
+ return entry.isSymbolicLink()
591
+ ? `symlink:${await fs.readlink(filePath)}:${hash}`
592
+ : `file:${hash}`;
593
+ }
594
+ catch (error) {
595
+ if (error.code === 'ENOENT')
596
+ return 'missing';
597
+ throw error;
598
+ }
599
+ }
600
+ /** Fail closed if the metadata authorizing a retirement leaves its snapshot. */
601
+ async function assertRetirementAuthorization(changeDir, expectedFingerprint, options = {}) {
602
+ const metadataPath = path.join(changeDir, METADATA_FILENAME);
603
+ const before = await fingerprintPortableContent(metadataPath);
604
+ const markerStillDeclared = options.verifyMarker === false || readRetireCapabilitiesMarker(changeDir).declared;
605
+ const after = await fingerprintPortableContent(metadataPath);
606
+ if (before !== expectedFingerprint ||
607
+ after !== expectedFingerprint ||
608
+ !markerStillDeclared) {
609
+ throw new Error(`The ${METADATA_FILENAME} retirement authorization changed before archive could complete.`);
610
+ }
611
+ }
612
+ async function fingerprintSpecInputs(update) {
613
+ return `${await fingerprintPath(update.source)}\n${await fingerprintPath(update.target)}`;
614
+ }
615
+ async function mutationTargetIdentity(mutation) {
616
+ try {
617
+ const stat = await fs.stat(mutation.update.target, { bigint: true });
618
+ return `${stat.dev}:${stat.ino}`;
619
+ }
620
+ catch (error) {
621
+ if (error.code === 'ENOENT') {
622
+ const parent = path.dirname(mutation.update.target);
623
+ const realParent = await fs.realpath(parent).catch(() => path.resolve(parent));
624
+ return `missing:${path.join(realParent, path.basename(mutation.update.target))}`;
625
+ }
626
+ throw error;
627
+ }
628
+ }
629
+ async function assertDistinctMutationTargets(mutations) {
630
+ const owners = new Map();
631
+ for (const mutation of mutations) {
632
+ const identity = await mutationTargetIdentity(mutation);
633
+ const existing = owners.get(identity);
634
+ if (existing !== undefined) {
635
+ throw new Error(`Spec updates for '${existing}' and '${mutation.update.id}' resolve to the same target ` +
636
+ `${identity}. Replace the capability alias or combine the deltas before archiving.`);
637
+ }
638
+ owners.set(identity, mutation.update.id);
639
+ }
640
+ }
641
+ async function captureSpecSnapshots(mutations) {
642
+ return Promise.all(mutations.map(async ({ update, outcome, rebuilt }) => {
643
+ try {
644
+ const stat = await fs.lstat(update.target);
645
+ if (stat.isSymbolicLink()) {
646
+ let content;
647
+ let contentExisted = false;
648
+ if (outcome === 'write') {
649
+ try {
650
+ // Best-effort rollback snapshot; a concurrent edit is caught later
651
+ // by restoreSpecSnapshots refusing to overwrite non-matching content,
652
+ // not here (CodeQL js/file-system-race).
653
+ content = await fs.readFile(update.target);
654
+ contentExisted = true;
655
+ }
656
+ catch (error) {
657
+ if (error.code !== 'ENOENT')
658
+ throw error;
659
+ }
660
+ }
661
+ return {
662
+ target: update.target,
663
+ existed: true,
664
+ outcome,
665
+ ...(outcome === 'write' ? { expectedContent: Buffer.from(rebuilt) } : {}),
666
+ content,
667
+ contentExisted,
668
+ symlink: await fs.readlink(update.target),
669
+ };
670
+ }
671
+ return {
672
+ target: update.target,
673
+ existed: true,
674
+ outcome,
675
+ ...(outcome === 'write' ? { expectedContent: Buffer.from(rebuilt) } : {}),
676
+ // Snapshot read for rollback; restoreSpecSnapshots re-checks this
677
+ // content before restoring, so a mid-run change aborts instead of
678
+ // clobbering (CodeQL js/file-system-race).
679
+ ...(stat.isFile() ? { content: await fs.readFile(update.target) } : {}),
680
+ ...(stat.isFile() ? { mode: stat.mode } : {}),
681
+ };
682
+ }
683
+ catch (error) {
684
+ if (error.code === 'ENOENT') {
685
+ return {
686
+ target: update.target,
687
+ existed: false,
688
+ outcome,
689
+ ...(outcome === 'write' ? { expectedContent: Buffer.from(rebuilt) } : {}),
690
+ };
691
+ }
692
+ throw error;
693
+ }
694
+ }));
695
+ }
696
+ async function restoreSpecSnapshots(snapshots) {
697
+ const errors = [];
698
+ for (const snapshot of [...snapshots].reverse()) {
699
+ try {
700
+ if (snapshot.outcome === 'retire') {
701
+ if (snapshot.displacedPath !== undefined) {
702
+ try {
703
+ await fs.lstat(snapshot.target);
704
+ throw new Error(`Archive rollback would overwrite a concurrent change at ${snapshot.target}. ` +
705
+ `The displaced spec was retained at ${snapshot.displacedPath}.`);
706
+ }
707
+ catch (error) {
708
+ if (error.code !== 'ENOENT')
709
+ throw error;
710
+ }
711
+ await fs.rename(snapshot.displacedPath, snapshot.target);
712
+ snapshot.displacedPath = undefined;
713
+ continue;
714
+ }
715
+ try {
716
+ const current = await fs.lstat(snapshot.target);
717
+ const unchangedSymlink = snapshot.symlink !== undefined &&
718
+ current.isSymbolicLink() &&
719
+ (await fs.readlink(snapshot.target)) === snapshot.symlink;
720
+ // Re-read to confirm the target still holds the snapshot content; a
721
+ // mismatch means a concurrent edit, and rollback throws below rather
722
+ // than overwrite it (CodeQL js/file-system-race is intentional here).
723
+ const unchangedFile = snapshot.symlink === undefined &&
724
+ snapshot.content !== undefined &&
725
+ current.isFile() &&
726
+ (await fs.readFile(snapshot.target)).equals(snapshot.content);
727
+ if (unchangedSymlink || unchangedFile)
728
+ continue;
729
+ throw new Error(`Archive rollback would overwrite a concurrent change at ${snapshot.target}.`);
730
+ }
731
+ catch (error) {
732
+ if (error.code !== 'ENOENT')
733
+ throw error;
734
+ }
735
+ }
736
+ else {
737
+ let current;
738
+ try {
739
+ current = await fs.lstat(snapshot.target);
740
+ }
741
+ catch (error) {
742
+ if (error.code === 'ENOENT' &&
743
+ !snapshot.existed) {
744
+ continue;
745
+ }
746
+ throw error;
747
+ }
748
+ if ((snapshot.symlink !== undefined &&
749
+ (!current.isSymbolicLink() ||
750
+ (await fs.readlink(snapshot.target)) !== snapshot.symlink)) ||
751
+ (snapshot.symlink === undefined &&
752
+ (!current.isFile() ||
753
+ (snapshot.mode !== undefined && current.mode !== snapshot.mode)))) {
754
+ throw new Error(`Archive rollback would overwrite a concurrent change at ${snapshot.target}.`);
755
+ }
756
+ // Re-read at rollback: only restore when current content matches what
757
+ // archive wrote or snapshotted; otherwise abort to preserve a concurrent
758
+ // change (CodeQL js/file-system-race is intentional here).
759
+ const currentContent = await fs.readFile(snapshot.target);
760
+ const originalContent = snapshot.symlink !== undefined && !snapshot.contentExisted
761
+ ? undefined
762
+ : snapshot.content;
763
+ if (originalContent !== undefined &&
764
+ currentContent.equals(originalContent)) {
765
+ continue;
766
+ }
767
+ if (snapshot.expectedContent === undefined ||
768
+ !currentContent.equals(snapshot.expectedContent)) {
769
+ throw new Error(`Archive rollback would overwrite a concurrent change at ${snapshot.target}.`);
770
+ }
771
+ }
772
+ if (!snapshot.existed) {
773
+ await fs.rm(snapshot.target, { force: true });
774
+ continue;
775
+ }
776
+ if (snapshot.symlink !== undefined) {
777
+ if (snapshot.outcome === 'retire') {
778
+ await fs.mkdir(path.dirname(snapshot.target), { recursive: true });
779
+ await fs.symlink(snapshot.symlink, snapshot.target);
780
+ }
781
+ else if (snapshot.contentExisted) {
782
+ await fs.writeFile(snapshot.target, snapshot.content);
783
+ }
784
+ else {
785
+ const referent = path.resolve(path.dirname(snapshot.target), snapshot.symlink);
786
+ await fs.rm(referent, { force: true });
787
+ }
788
+ continue;
789
+ }
790
+ if (snapshot.content !== undefined) {
791
+ await fs.mkdir(path.dirname(snapshot.target), { recursive: true });
792
+ await fs.writeFile(snapshot.target, snapshot.content);
793
+ if (snapshot.mode !== undefined)
794
+ await fs.chmod(snapshot.target, snapshot.mode);
795
+ }
796
+ }
797
+ catch (error) {
798
+ errors.push(error instanceof Error ? error : new Error(String(error)));
799
+ }
800
+ }
801
+ if (errors.length > 0) {
802
+ throw new Error(errors.map(({ message }) => message).join(' '));
803
+ }
804
+ }
805
+ async function finalizeRetirementBackups(snapshots, mainSpecsDir) {
806
+ const errors = [];
807
+ for (const snapshot of snapshots) {
808
+ if (snapshot.outcome !== 'retire' || snapshot.displacedPath === undefined)
809
+ continue;
810
+ const displacedPath = snapshot.displacedPath;
811
+ try {
812
+ if (snapshot.displacedFingerprint === undefined ||
813
+ (await fingerprintMovablePath(displacedPath)) !== snapshot.displacedFingerprint) {
814
+ throw new Error('the displaced spec changed after retirement verification');
815
+ }
816
+ await finalizeRetiredSpec(snapshot.target, displacedPath, mainSpecsDir);
817
+ snapshot.displacedPath = undefined;
818
+ }
819
+ catch (error) {
820
+ errors.push(`Could not remove the committed retirement backup at ${displacedPath} ` +
821
+ `(${error instanceof Error ? error.message : String(error)}).`);
822
+ }
823
+ }
824
+ if (errors.length > 0) {
825
+ throw new RetirementBackupsRetainedError(`${errors.join(' ')} The change remains archived and each listed backup was retained for recovery.`);
826
+ }
827
+ }
106
828
  export class ArchiveCommand {
107
829
  async execute(changeName, options = {}) {
108
830
  const json = !!options.json;
@@ -153,27 +875,48 @@ export class ArchiveCommand {
153
875
  const changesDir = root.changesDir;
154
876
  const archiveDir = root.archiveDir;
155
877
  const mainSpecsDir = root.specsDir;
878
+ for (const [allowedDirectory, managedDir] of [
879
+ [root.path, changesDir],
880
+ [changesDir, archiveDir],
881
+ [root.path, mainSpecsDir],
882
+ ]) {
883
+ try {
884
+ FileSystemUtils.assertPathWithin(allowedDirectory, managedDir);
885
+ }
886
+ catch {
887
+ throw new ArchiveBlockedError('archive_path_outside_root', `Refusing to archive through a path outside the OpenSpec root: ${managedDir}`);
888
+ }
889
+ }
156
890
  // Get change name interactively if not provided
157
891
  if (!changeName) {
158
892
  if (json) {
159
893
  throw new ArchiveBlockedError('archive_change_name_required', 'A change name is required: archive --json is non-interactive.', withStoreFlag(root, 'openspec archive <change-name> --json'));
160
894
  }
161
- const selectedChange = await this.selectChange(changesDir);
895
+ const selectedChange = await this.selectChange(changesDir, root, options);
162
896
  if (!selectedChange) {
163
897
  console.log('No change selected. Aborting.');
164
898
  return null;
165
899
  }
166
900
  changeName = selectedChange;
167
901
  }
902
+ const changeNameProblem = folderStyleNameProblem(changeName, 'Change name');
903
+ if (changeNameProblem) {
904
+ throw new ArchiveBlockedError('archive_change_name_invalid', changeNameProblem);
905
+ }
168
906
  const changeDir = path.join(changesDir, changeName);
169
907
  // Verify change exists
170
908
  try {
171
- const stat = await fs.stat(changeDir);
909
+ const stat = await fs.lstat(changeDir);
910
+ if (stat.isSymbolicLink()) {
911
+ throw new ArchiveBlockedError('archive_change_symlink', `Change '${changeName}' is a symbolic link. Replace it with a real directory before archiving.`);
912
+ }
172
913
  if (!stat.isDirectory()) {
173
914
  throw new Error(`Change '${changeName}' not found.`);
174
915
  }
175
916
  }
176
- catch {
917
+ catch (error) {
918
+ if (error instanceof ArchiveBlockedError)
919
+ throw error;
177
920
  const available = await listActiveChangeNames(changesDir);
178
921
  throw new ArchiveBlockedError('archive_change_not_found', available.length > 0
179
922
  ? `Change '${changeName}' not found. Available changes: ${available.join(', ')}`
@@ -263,6 +1006,9 @@ export class ArchiveCommand {
263
1006
  catch { }
264
1007
  }
265
1008
  if (hasDeltaSpecs) {
1009
+ // No mainSpecsDir here on purpose: the scenario-loss check standalone
1010
+ // validate runs (#1477) is the same one buildUpdatedSpec enforces a few
1011
+ // steps later, and reporting it here would relabel that failure.
266
1012
  const deltaReport = await validator.validateChangeDeltaSpecs(changeDir);
267
1013
  if (!deltaReport.valid) {
268
1014
  hasValidationErrors = true;
@@ -298,11 +1044,10 @@ export class ArchiveCommand {
298
1044
  // Log warning when validation is skipped
299
1045
  const timestamp = new Date().toISOString();
300
1046
  if (!options.yes) {
301
- const { confirm } = await import('@inquirer/prompts');
302
- const proceed = await confirm({
1047
+ const proceed = await confirmOrBlock({
303
1048
  message: chalk.yellow('⚠️ WARNING: Skipping validation may archive invalid specs. Continue? (y/N)'),
304
1049
  default: false
305
- });
1050
+ }, () => new ArchiveBlockedError('archive_confirmation_required', 'Skipping validation requires confirmation, and no answer could be read from stdin.', rerunCommand(root, changeName, options)));
306
1051
  if (!proceed) {
307
1052
  console.log('Archive cancelled.');
308
1053
  return null;
@@ -328,11 +1073,10 @@ export class ArchiveCommand {
328
1073
  }
329
1074
  }
330
1075
  else if (!options.yes) {
331
- const { confirm } = await import('@inquirer/prompts');
332
- const proceed = await confirm({
1076
+ const proceed = await confirmOrBlock({
333
1077
  message: `Warning: ${incompleteTasks} incomplete task(s) found. Continue?`,
334
1078
  default: false
335
- });
1079
+ }, () => new ArchiveBlockedError('archive_tasks_incomplete', `${incompleteTasks} incomplete task(s) found for change '${describeChangeName(changeName)}', and no answer could be read from stdin.`, `Complete the tasks or rerun with ${rerunCommand(root, changeName, options)}`));
336
1080
  if (!proceed) {
337
1081
  console.log('Archive cancelled.');
338
1082
  return null;
@@ -342,162 +1086,530 @@ export class ArchiveCommand {
342
1086
  console.log(`Warning: ${incompleteTasks} incomplete task(s) found. Continuing due to --yes flag.`);
343
1087
  }
344
1088
  }
345
- // Handle spec updates unless skipSpecs flag is set
346
- let specsUpdated = false;
347
- let totals;
348
- const specWarnings = [];
349
- if (options.skipSpecs) {
350
- if (!json) {
351
- console.log('Skipping spec updates (--skip-specs flag provided).');
352
- }
353
- }
354
- else {
355
- // Find specs to update
356
- const specUpdates = await findSpecUpdates(changeDir, mainSpecsDir);
357
- if (specUpdates.length > 0) {
1089
+ // Settle the archive destination BEFORE touching any spec. The name depends
1090
+ // only on the change, and a collision is routine (archiving twice in a day,
1091
+ // a restored change), so discovering it after the merge would leave specs
1092
+ // rewritten - or a capability retired - for an archive that never happened.
1093
+ //
1094
+ // Names that already carry a date prefix keep it: re-prefixing would stutter
1095
+ // the name, and when the archive runs on a later day the folder would sort
1096
+ // under a day on which the change did not happen (#1309).
1097
+ const archiveName = ARCHIVE_DATE_PREFIX_PATTERN.test(changeName)
1098
+ ? changeName
1099
+ : `${formatLocalDate()}-${changeName}`;
1100
+ const archivePath = path.join(archiveDir, archiveName);
1101
+ // Read once, before any spec is touched: whether this change is allowed to
1102
+ // retire a capability at all. An unhonorable marker counts as undeclared,
1103
+ // exactly as skip_specs treats one, so metadata the rest of the CLI rejects
1104
+ // can never authorise a deletion.
1105
+ const retirementMarker = readRetireCapabilitiesMarker(changeDir);
1106
+ const retirementDeclared = retirementMarker.declared;
1107
+ const retirementAuthorizationFingerprint = retirementDeclared
1108
+ ? await fingerprintPortableContent(path.join(changeDir, METADATA_FILENAME))
1109
+ : undefined;
1110
+ await assertArchiveDestinationAvailable(archivePath, archiveName);
1111
+ await fs.mkdir(archiveDir, { recursive: true });
1112
+ const claimPath = archiveClaimPath(archivePath, archiveName);
1113
+ let archiveClaim;
1114
+ try {
1115
+ // Handle spec updates unless skipSpecs flag is set
1116
+ let specsUpdated = false;
1117
+ let totals;
1118
+ const specWarnings = [];
1119
+ let changeArchived = false;
1120
+ if (options.skipSpecs) {
358
1121
  if (!json) {
359
- console.log('\nSpecs to update:');
360
- for (const update of specUpdates) {
361
- const status = update.exists ? 'update' : 'create';
362
- const capability = update.id;
363
- console.log(` ${capability}: ${status}`);
364
- }
1122
+ console.log('Skipping spec updates (--skip-specs flag provided).');
365
1123
  }
366
- let shouldUpdateSpecs = true;
367
- if (!options.yes) {
368
- if (json) {
369
- throw new ArchiveBlockedError('archive_confirmation_required', `Updating ${specUpdates.length} spec(s) requires confirmation: rerun with --yes.`, withStoreFlag(root, 'openspec archive <change-name> --json --yes'));
370
- }
371
- const { confirm } = await import('@inquirer/prompts');
372
- shouldUpdateSpecs = await confirm({
373
- message: 'Proceed with spec updates?',
374
- default: true
375
- });
376
- if (!shouldUpdateSpecs) {
377
- console.log('Skipping spec updates. Proceeding with archive.');
1124
+ }
1125
+ else {
1126
+ // Find specs to update
1127
+ const specUpdates = await findSpecUpdates(changeDir, mainSpecsDir);
1128
+ if (specUpdates.length > 0) {
1129
+ if (!json) {
1130
+ console.log('\nSpecs to update:');
1131
+ for (const update of specUpdates) {
1132
+ const status = update.exists ? 'update' : 'create';
1133
+ const capability = update.id;
1134
+ console.log(` ${capability}: ${status}`);
1135
+ }
378
1136
  }
379
- }
380
- if (shouldUpdateSpecs) {
381
- // Prepare all updates first (validation pass, no writes)
1137
+ // Build the proposed updates before asking permission to apply them.
1138
+ // buildUpdatedSpec also reports content that the merge would drop, so
1139
+ // the confirmation must come after this preview.
382
1140
  const prepared = [];
1141
+ let prepareError;
383
1142
  try {
384
1143
  for (const update of specUpdates) {
385
- const built = await buildUpdatedSpec(update, changeName, { silent: json });
386
- prepared.push({ update, rebuilt: built.rebuilt, counts: built.counts });
387
- // Carried into the result so JSON mode (where nothing was
388
- // printed) still surfaces them; human mode discards the result.
1144
+ const sourceBeforeBuild = await fingerprintPath(update.source);
1145
+ const targetBeforeBuild = await fingerprintPath(update.target);
1146
+ const built = await buildUpdatedSpec(update, changeName, { silent: true });
1147
+ const sourceAfterBuild = await fingerprintPath(update.source);
1148
+ const targetAfterBuild = await fingerprintPath(update.target);
1149
+ if (sourceBeforeBuild !== sourceAfterBuild ||
1150
+ targetBeforeBuild !== targetAfterBuild) {
1151
+ throw new Error(`Spec inputs for '${update.id}' changed while archive was preparing the preview.`);
1152
+ }
1153
+ prepared.push({
1154
+ update,
1155
+ rebuilt: built.rebuilt,
1156
+ counts: built.counts,
1157
+ outcome: await decideSpecOutcome(update, built, skipValidation, retirementDeclared),
1158
+ noRequirementBlocks: built.noRequirementBlocks,
1159
+ unaccountedContent: built.unaccountedContent,
1160
+ sourceFingerprint: sourceAfterBuild,
1161
+ sourceContentFingerprint: await fingerprintPortableContent(update.source),
1162
+ targetFingerprint: targetAfterBuild,
1163
+ targetMovableFingerprint: await fingerprintMovablePath(update.target),
1164
+ });
389
1165
  specWarnings.push(...built.warnings);
390
1166
  }
391
1167
  }
392
1168
  catch (err) {
1169
+ // A user may still decline spec updates and archive the change, as
1170
+ // before this preview existed. Defer the error until they accept.
1171
+ prepareError = err;
1172
+ }
1173
+ if (prepareError === undefined && !json) {
1174
+ for (const warning of specWarnings) {
1175
+ console.log(chalk.yellow(`⚠️ Warning: ${warning}`));
1176
+ }
1177
+ }
1178
+ let shouldUpdateSpecs = true;
1179
+ if (!options.yes) {
393
1180
  if (json) {
394
- throw new ArchiveBlockedError('archive_spec_update_failed', String(err.message || err), 'Fix the change delta specs and rerun. No files were changed.');
1181
+ throw new ArchiveBlockedError('archive_confirmation_required', `Updating ${specUpdates.length} spec(s) requires confirmation: rerun with --yes.`, withStoreFlag(root, 'openspec archive <change-name> --json --yes'));
1182
+ }
1183
+ shouldUpdateSpecs = await confirmOrBlock({
1184
+ message: 'Proceed with spec updates?',
1185
+ default: true
1186
+ }, () => new ArchiveBlockedError('archive_confirmation_required', `Updating ${specUpdates.length} spec(s) requires confirmation, and no answer could be read from stdin.`, rerunCommand(root, changeName, options)));
1187
+ if (!shouldUpdateSpecs) {
1188
+ console.log('Skipping spec updates. Proceeding with archive.');
395
1189
  }
396
- console.log(String(err.message || err));
397
- console.log('Aborted. No files were changed.');
398
- process.exitCode = 1;
399
- return null;
400
1190
  }
401
- // Validate every rebuilt spec before writing any of them, so a
402
- // late validation failure really does leave all targets unchanged.
403
- if (!skipValidation) {
404
- for (const p of prepared) {
405
- const specName = p.update.id;
406
- const report = await new Validator().validateSpecContent(specName, p.rebuilt);
407
- if (!report.valid) {
408
- if (json) {
409
- throw new ArchiveBlockedError('archive_spec_validation_failed', `Rebuilt spec for '${specName}' failed validation. No files were changed.`, `Run ${withStoreFlag(root, `openspec validate ${specName}`)} after fixing the change deltas.`);
1191
+ if (shouldUpdateSpecs) {
1192
+ // The confirmation may stay open while another editor changes a main
1193
+ // spec. Never apply the proposal built before the prompt to a newer
1194
+ // baseline: in particular, a stale retirement decision must not
1195
+ // delete a requirement added while the prompt was waiting.
1196
+ if (prepareError === undefined) {
1197
+ try {
1198
+ const currentRetirementMarker = readRetireCapabilitiesMarker(changeDir);
1199
+ if (currentRetirementMarker.declared !== retirementMarker.declared ||
1200
+ currentRetirementMarker.invalidReason !== retirementMarker.invalidReason) {
1201
+ throw new Error(`The ${METADATA_FILENAME} retirement authorization changed while archive was awaiting confirmation.`);
1202
+ }
1203
+ const currentUpdates = await findSpecUpdates(changeDir, mainSpecsDir);
1204
+ const currentById = new Map(currentUpdates.map((update) => [update.id, update]));
1205
+ if (currentUpdates.length !== prepared.length) {
1206
+ throw new Error('The change specs changed while archive was awaiting confirmation.');
410
1207
  }
411
- console.log(chalk.red(`\nValidation errors in rebuilt spec for ${specName} (will not write changes):`));
412
- for (const issue of report.issues) {
413
- if (issue.level === 'ERROR')
414
- console.log(chalk.red(` ✗ ${issue.message}`));
415
- else if (issue.level === 'WARNING')
416
- console.log(chalk.yellow(` ⚠ ${issue.message}`));
1208
+ for (const proposed of prepared) {
1209
+ const current = currentById.get(proposed.update.id);
1210
+ if (!current) {
1211
+ throw new Error(`The delta for '${proposed.update.id}' changed while archive was awaiting confirmation.`);
1212
+ }
1213
+ if ((await fingerprintPath(current.source)) !== proposed.sourceFingerprint ||
1214
+ (await fingerprintPath(current.target)) !== proposed.targetFingerprint) {
1215
+ throw new Error(`Spec inputs for '${proposed.update.id}' changed while archive was awaiting confirmation. ` +
1216
+ 'No files were changed; review the new content and rerun.');
1217
+ }
1218
+ const rebuilt = await buildUpdatedSpec(current, changeName, { silent: true });
1219
+ const outcome = await decideSpecOutcome(current, rebuilt, skipValidation, retirementDeclared);
1220
+ if (current.exists !== proposed.update.exists ||
1221
+ rebuilt.rebuilt !== proposed.rebuilt ||
1222
+ JSON.stringify(rebuilt.counts) !== JSON.stringify(proposed.counts) ||
1223
+ outcome !== proposed.outcome) {
1224
+ throw new Error(`Main spec '${proposed.update.id}' changed while archive was awaiting confirmation. ` +
1225
+ 'No files were changed; review the new content and rerun.');
1226
+ }
417
1227
  }
418
- console.log('Aborted. No files were changed.');
419
- process.exitCode = 1;
420
- return null;
1228
+ }
1229
+ catch (error) {
1230
+ prepareError = error;
421
1231
  }
422
1232
  }
423
- }
424
- // All validations passed; write files and display counts
425
- const writeTotals = { added: 0, modified: 0, removed: 0, renamed: 0 };
426
- let wroteAny = false;
427
- for (const p of prepared) {
428
- const { added, modified, removed, renamed } = p.counts;
429
- if (added + modified + removed + renamed === 0) {
430
- // Every operation was already synced: rewriting the file would
431
- // only churn normalization differences into it.
432
- continue;
1233
+ if (prepareError !== undefined) {
1234
+ const message = prepareError instanceof Error ? prepareError.message : String(prepareError);
1235
+ if (json) {
1236
+ throw new ArchiveBlockedError('archive_spec_update_failed', message, 'Fix the change delta specs and rerun. No files were changed.');
1237
+ }
1238
+ console.log(message);
1239
+ console.log('Aborted. No files were changed.');
1240
+ process.exitCode = 1;
1241
+ return null;
1242
+ }
1243
+ // Validate every rebuilt spec before writing any of them, so a
1244
+ // late validation failure really does leave all targets unchanged.
1245
+ if (!skipValidation) {
1246
+ for (const p of prepared) {
1247
+ // A retirement was already put to the validator, and failed on
1248
+ // nothing but "no requirements" - there is no spec left to write,
1249
+ // so re-reporting that one error would just abort the fix (#1302).
1250
+ if (p.outcome !== 'write')
1251
+ continue;
1252
+ const specName = p.update.id;
1253
+ const report = await new Validator().validateSpecContent(specName, p.rebuilt);
1254
+ if (!report.valid) {
1255
+ // The dead end #1302 describes: the rebuilt spec is unwritable
1256
+ // for exactly one reason, and retiring the capability is the
1257
+ // fix - but only the author can authorise deleting the spec, so
1258
+ // the abort names the marker instead of just rejecting. Says so
1259
+ // only when the marker is the ONLY thing missing, so it never
1260
+ // sends someone after a marker that would not have helped.
1261
+ const retirementWouldFix = !retirementDeclared &&
1262
+ p.update.exists &&
1263
+ p.counts.removed > 0 &&
1264
+ (await isRetirementCandidate(p.update, p, false));
1265
+ const retirementHint = retirementWouldFix
1266
+ ? `This change removes the last requirement '${specName}' has. To retire the` +
1267
+ ` capability and delete its spec, add \`retire_capabilities: true\` to the` +
1268
+ ` change's ${METADATA_FILENAME} (alongside its \`schema:\`, which that file` +
1269
+ ` requires), then rerun.` +
1270
+ (retirementMarker.invalidReason
1271
+ ? ` The marker present now cannot be honored (${retirementMarker.invalidReason}).`
1272
+ : '')
1273
+ : undefined;
1274
+ // The marker was set and retirement was still refused. Saying
1275
+ // nothing left the author who did exactly what the docs asked
1276
+ // back in the original dead end with no signal that their
1277
+ // marker had been read at all.
1278
+ // The author asked for a retirement and got the bare
1279
+ // validation abort. Name the lines that stood in the way.
1280
+ const refusalReason = retirementDeclared &&
1281
+ p.unaccountedContent.length > 0 &&
1282
+ (await isRetirableSpec(specName, p.rebuilt))
1283
+ ? `'${specName}' declares retire_capabilities, but the spec holds content the merge ` +
1284
+ `cannot safely account for and deleting the file would take with it: ` +
1285
+ `${p.unaccountedContent.slice(0, 3).map((line) => `"${line}"`).join(', ')}` +
1286
+ `${p.unaccountedContent.length > 3 ? `, and ${p.unaccountedContent.length - 3} more line(s)` : ''}. ` +
1287
+ 'Move it into `## Purpose` or a canonical requirement, or delete the spec by hand.'
1288
+ : undefined;
1289
+ if (json) {
1290
+ throw new ArchiveBlockedError('archive_spec_validation_failed', `Rebuilt spec for '${specName}' failed validation. No files were changed.`, refusalReason ??
1291
+ retirementHint ??
1292
+ `Run ${withStoreFlag(root, `openspec validate ${specName}`)} after fixing the change deltas.`);
1293
+ }
1294
+ console.log(chalk.red(`\nValidation errors in rebuilt spec for ${specName} (will not write changes):`));
1295
+ for (const issue of report.issues) {
1296
+ if (issue.level === 'ERROR')
1297
+ console.log(chalk.red(` ✗ ${issue.message}`));
1298
+ else if (issue.level === 'WARNING')
1299
+ console.log(chalk.yellow(` ⚠ ${issue.message}`));
1300
+ }
1301
+ if (retirementHint)
1302
+ console.log(chalk.yellow(` → ${retirementHint}`));
1303
+ if (refusalReason)
1304
+ console.log(chalk.yellow(` → ${refusalReason}`));
1305
+ console.log('Aborted. No files were changed.');
1306
+ process.exitCode = 1;
1307
+ return null;
1308
+ }
1309
+ }
1310
+ }
1311
+ // A legitimate concurrent archive cannot pass the exclusive claim,
1312
+ // while this catches an external process that created the final
1313
+ // destination during a confirmation prompt. Check before the first
1314
+ // spec mutation so a collision never strands a write or retirement.
1315
+ await assertArchiveDestinationAvailable(archivePath, archiveName);
1316
+ archiveClaim = await claimArchiveDestination(archivePath, archiveName);
1317
+ await assertArchiveDestinationAvailable(archivePath, archiveName);
1318
+ const mutations = prepared
1319
+ .filter(({ outcome, counts }) => outcome === 'retire' ||
1320
+ (outcome === 'write' &&
1321
+ counts.added + counts.modified + counts.removed + counts.renamed > 0))
1322
+ .map(({ update, outcome, rebuilt }) => ({
1323
+ update,
1324
+ outcome: outcome,
1325
+ rebuilt,
1326
+ }));
1327
+ const hasRetirements = mutations.some(({ outcome }) => outcome === 'retire');
1328
+ await assertDistinctMutationTargets(mutations);
1329
+ for (const proposed of prepared) {
1330
+ if ((await fingerprintPath(proposed.update.source)) !== proposed.sourceFingerprint ||
1331
+ (await fingerprintPath(proposed.update.target)) !== proposed.targetFingerprint) {
1332
+ throw new Error(`Spec inputs for '${proposed.update.id}' changed before archive could apply them. ` +
1333
+ 'No files were changed; review the new content and rerun.');
1334
+ }
1335
+ }
1336
+ const specSnapshots = await captureSpecSnapshots(mutations);
1337
+ const specSnapshotsByTarget = new Map(specSnapshots.map((snapshot) => [snapshot.target, snapshot]));
1338
+ const mutationAttempts = new Set();
1339
+ try {
1340
+ // All validations passed; write files and display counts
1341
+ const writeTotals = { added: 0, modified: 0, removed: 0, renamed: 0 };
1342
+ let wroteAny = false;
1343
+ for (const p of prepared) {
1344
+ // Deletions are deferred to the loop below.
1345
+ if (p.outcome !== 'write')
1346
+ continue;
1347
+ const { added, modified, removed, renamed } = p.counts;
1348
+ if (added + modified + removed + renamed === 0) {
1349
+ // Every operation was already synced: rewriting the file would
1350
+ // only churn normalization differences into it.
1351
+ continue;
1352
+ }
1353
+ await writeUpdatedSpec(p.update, p.rebuilt, p.counts, {
1354
+ silent: json,
1355
+ beforeMutate: async () => {
1356
+ if ((await fingerprintSpecInputs(p.update)) !==
1357
+ `${p.sourceFingerprint}\n${p.targetFingerprint}`) {
1358
+ throw new Error(`Spec inputs for '${p.update.id}' changed before archive could write them.`);
1359
+ }
1360
+ mutationAttempts.add(p.update.target);
1361
+ },
1362
+ // Cross-root paths must be absolute when a store is selected.
1363
+ ...(isStoreSelectedRoot(root) ? { displayPath: p.update.target } : {}),
1364
+ });
1365
+ wroteAny = true;
1366
+ writeTotals.added += added;
1367
+ writeTotals.modified += modified;
1368
+ writeTotals.removed += removed;
1369
+ writeTotals.renamed += renamed;
1370
+ }
1371
+ // Retirements run only after every write has succeeded. If any
1372
+ // later mutation fails, the snapshots below restore every target.
1373
+ for (const p of prepared) {
1374
+ if (p.outcome !== 'retire')
1375
+ continue;
1376
+ const { retired, resolvedPath, displacedPath } = await retireSpec(p.update, mainSpecsDir, {
1377
+ silent: json,
1378
+ deferDelete: true,
1379
+ beforeMutate: async () => {
1380
+ if (retirementAuthorizationFingerprint === undefined) {
1381
+ throw new Error(`The ${METADATA_FILENAME} retirement authorization is unavailable.`);
1382
+ }
1383
+ await assertRetirementAuthorization(changeDir, retirementAuthorizationFingerprint);
1384
+ if ((await fingerprintSpecInputs(p.update)) !==
1385
+ `${p.sourceFingerprint}\n${p.targetFingerprint}`) {
1386
+ throw new Error(`Spec inputs for '${p.update.id}' changed before archive could retire them.`);
1387
+ }
1388
+ mutationAttempts.add(p.update.target);
1389
+ },
1390
+ verifyDisplaced: async (displacedPath) => {
1391
+ await assertRetirementAuthorization(changeDir, retirementAuthorizationFingerprint);
1392
+ if ((await fingerprintMovablePath(displacedPath)) !==
1393
+ p.targetMovableFingerprint) {
1394
+ throw new Error(`Main spec '${p.update.id}' changed while archive was securing it for retirement.`);
1395
+ }
1396
+ },
1397
+ ...(isStoreSelectedRoot(root) ? { displayPath: p.update.target } : {}),
1398
+ });
1399
+ if (!retired)
1400
+ continue;
1401
+ const retirementSnapshot = specSnapshotsByTarget.get(p.update.target);
1402
+ if (retirementSnapshot === undefined || displacedPath === undefined) {
1403
+ throw new Error(`Could not track the displaced main spec for '${p.update.id}' during retirement.`);
1404
+ }
1405
+ retirementSnapshot.displacedPath = displacedPath;
1406
+ retirementSnapshot.displacedFingerprint = p.targetMovableFingerprint;
1407
+ wroteAny = true;
1408
+ // A rename applied on the way to the retirement still happened;
1409
+ // folding every count in keeps the totals honest about the whole
1410
+ // delta.
1411
+ writeTotals.added += p.counts.added;
1412
+ writeTotals.modified += p.counts.modified;
1413
+ writeTotals.removed += p.counts.removed;
1414
+ writeTotals.renamed += p.counts.renamed;
1415
+ // Deleting a file is the one archive outcome a JSON consumer cannot
1416
+ // infer from the totals, so it is recorded the way every other
1417
+ // spec-merge divergence is. Purpose always goes with the file, so it
1418
+ // is named too rather than left to the reader to work out, and the
1419
+ // note carries the command that brings the file back.
1420
+ const lost = ['Purpose'];
1421
+ // Derived from the path that was unlinked, never rebuilt from the
1422
+ // capability id: on a case-insensitive filesystem the id and the
1423
+ // real directory can differ in case, and git is case-sensitive, so
1424
+ // an id-derived path is one git rejects.
1425
+ // `update.target` is built from the capability id, so on a
1426
+ // case-insensitive filesystem it can differ in case from the file
1427
+ // that was actually unlinked - and git is case-sensitive, so the
1428
+ // printed command is one git rejects. A capability directory
1429
+ // symlinked to a sibling has the same problem without leaving the
1430
+ // tree. `retiredPath` carries the resolved path, so it wins
1431
+ // whenever it disagrees, not only when it escapes.
1432
+ const unlinkedPath = resolvedPath ?? p.update.target;
1433
+ // Measured against the REAL root, so the platform's own
1434
+ // `/var` -> `/private/var` link does not read as an escape. A path
1435
+ // that genuinely sits outside stays absolute, which is what routes
1436
+ // it to prose guidance instead of a command git would reject.
1437
+ const realRoot = await fs.realpath(root.path).catch(() => root.path);
1438
+ const relativeToRoot = path.relative(realRoot, unlinkedPath);
1439
+ const insideRoot = relativeToRoot !== '' &&
1440
+ !relativeToRoot.startsWith('..') &&
1441
+ !path.isAbsolute(relativeToRoot);
1442
+ const deletedPath = isStoreSelectedRoot(root) || !insideRoot
1443
+ ? unlinkedPath
1444
+ : relativeToRoot.split(path.sep).join('/');
1445
+ // A command is offered only when pasting it where archive was run
1446
+ // would actually work. An absolute path here means the file did not
1447
+ // live under that directory - a selected store, or a symlinked
1448
+ // capability directory - and `git checkout HEAD -- <abs>` is rejected
1449
+ // from a different worktree however it is quoted, so that case gets
1450
+ // guidance instead of a command that cannot run. A path with no
1451
+ // portable shell spelling is handled the same way.
1452
+ //
1453
+ // Conditional on purpose, too: whether the file is in `HEAD` is not
1454
+ // something archive knows - a spec an earlier archive CREATED and
1455
+ // nobody has committed yet is not - and promising recovery is the one
1456
+ // claim this feature must not get wrong.
1457
+ const pasteablePath = path.isAbsolute(deletedPath)
1458
+ ? undefined
1459
+ : quoteForShell(`:(top)${deletedPath}`);
1460
+ const recovery = pasteablePath
1461
+ ? `If it was committed, restore it with: git checkout HEAD -- ${pasteablePath}`
1462
+ : `It was deleted from ${deletedPath}; if it was committed, restore it from that checkout's history.`;
1463
+ const retirementNote = `${p.update.id} - capability retired; deleted the main spec (all requirements removed` +
1464
+ `, declared by retire_capabilities) at ${deletedPath}` +
1465
+ `. Its section(s) went with it: ${lost.join(', ')}. ` +
1466
+ recovery;
1467
+ specWarnings.push(retirementNote);
1468
+ // The "Retiring ..." line already told a human the file is gone; the
1469
+ // sections it took along, and how to get them back, are the parts
1470
+ // they cannot see from the path.
1471
+ if (!json) {
1472
+ console.log(` ${recovery}`);
1473
+ }
1474
+ }
1475
+ specsUpdated = wroteAny;
1476
+ totals = writeTotals;
1477
+ if (!json) {
1478
+ console.log(`Totals: + ${writeTotals.added}, ~ ${writeTotals.modified}, - ${writeTotals.removed}, → ${writeTotals.renamed}`);
1479
+ console.log(wroteAny
1480
+ ? 'Specs updated successfully.'
1481
+ : 'Specs already in sync; no files changed.');
1482
+ }
1483
+ for (const proposed of prepared) {
1484
+ if ((await fingerprintPath(proposed.update.source)) !==
1485
+ proposed.sourceFingerprint) {
1486
+ throw new Error(`The delta for '${proposed.update.id}' changed before the change could be archived.`);
1487
+ }
1488
+ }
1489
+ if (hasRetirements) {
1490
+ await assertRetirementAuthorization(changeDir, retirementAuthorizationFingerprint);
1491
+ }
1492
+ const verifyArchivedDeltas = async (stagedSource) => {
1493
+ if (hasRetirements) {
1494
+ await assertRetirementAuthorization(archivePath, retirementAuthorizationFingerprint,
1495
+ // Archived changes are nested one level deeper than active
1496
+ // changes, so the marker reader cannot resolve their schema.
1497
+ // Exact content equality proves this is the authorization
1498
+ // already validated at the active path.
1499
+ { verifyMarker: false });
1500
+ if (stagedSource) {
1501
+ await assertRetirementAuthorization(stagedSource, retirementAuthorizationFingerprint);
1502
+ }
1503
+ }
1504
+ for (const proposed of prepared) {
1505
+ const archivedSource = path.join(archivePath, path.relative(changeDir, proposed.update.source));
1506
+ if ((await fingerprintPortableContent(archivedSource)) !==
1507
+ proposed.sourceContentFingerprint) {
1508
+ throw new Error(`The archived delta for '${proposed.update.id}' changed during the final move.`);
1509
+ }
1510
+ if (stagedSource) {
1511
+ const stagedDelta = path.join(stagedSource, path.relative(changeDir, proposed.update.source));
1512
+ if ((await fingerprintPortableContent(stagedDelta)) !==
1513
+ proposed.sourceContentFingerprint) {
1514
+ throw new Error(`The active delta for '${proposed.update.id}' changed during the fallback copy.`);
1515
+ }
1516
+ }
1517
+ }
1518
+ };
1519
+ await moveDirectory(changeDir, archivePath, {
1520
+ verifyCopiedDestination: verifyArchivedDeltas,
1521
+ });
1522
+ changeArchived = true;
1523
+ await verifyArchivedDeltas();
1524
+ await finalizeRetirementBackups(specSnapshots, mainSpecsDir);
1525
+ }
1526
+ catch (error) {
1527
+ if (error instanceof MoveDestinationRetainedError) {
1528
+ changeArchived = true;
1529
+ try {
1530
+ await finalizeRetirementBackups(specSnapshots, mainSpecsDir);
1531
+ }
1532
+ catch (cleanupError) {
1533
+ throw new RetirementBackupsRetainedError(`${error.message} ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
1534
+ }
1535
+ throw error;
1536
+ }
1537
+ if (error instanceof RetirementBackupsRetainedError)
1538
+ throw error;
1539
+ const rollbackErrors = [];
1540
+ try {
1541
+ await restoreSpecSnapshots(specSnapshots.filter(({ target }) => mutationAttempts.has(target)));
1542
+ }
1543
+ catch (rollbackError) {
1544
+ rollbackErrors.push(rollbackError instanceof Error
1545
+ ? rollbackError
1546
+ : new Error(String(rollbackError)));
1547
+ }
1548
+ if (changeArchived) {
1549
+ try {
1550
+ await moveDirectory(archivePath, changeDir);
1551
+ changeArchived = false;
1552
+ }
1553
+ catch (rollbackError) {
1554
+ rollbackErrors.push(rollbackError instanceof Error
1555
+ ? rollbackError
1556
+ : new Error(String(rollbackError)));
1557
+ }
1558
+ }
1559
+ if (rollbackErrors.length > 0) {
1560
+ const original = error instanceof Error ? error.message : String(error);
1561
+ throw new Error(`${original} Rollback also failed: ${rollbackErrors.map(({ message }) => message).join(' ')}`);
1562
+ }
1563
+ throw error;
433
1564
  }
434
- await writeUpdatedSpec(p.update, p.rebuilt, p.counts, {
435
- silent: json,
436
- // Cross-root paths must be absolute when a store is selected.
437
- ...(isStoreSelectedRoot(root) ? { displayPath: p.update.target } : {}),
438
- });
439
- wroteAny = true;
440
- writeTotals.added += added;
441
- writeTotals.modified += modified;
442
- writeTotals.removed += removed;
443
- writeTotals.renamed += renamed;
444
- }
445
- specsUpdated = wroteAny;
446
- totals = writeTotals;
447
- if (!json) {
448
- console.log(`Totals: + ${writeTotals.added}, ~ ${writeTotals.modified}, - ${writeTotals.removed}, → ${writeTotals.renamed}`);
449
- console.log(wroteAny
450
- ? 'Specs updated successfully.'
451
- : 'Specs already in sync; no files changed.');
452
1565
  }
453
1566
  }
454
1567
  }
455
- }
456
- // Create archive directory with date prefix. Names that already carry
457
- // one keep it: re-prefixing would stutter the name, and when the archive
458
- // runs on a later day the folder would sort under a day on which the
459
- // change did not happen (#1309).
460
- const archiveName = ARCHIVE_DATE_PREFIX_PATTERN.test(changeName)
461
- ? changeName
462
- : `${formatLocalDate()}-${changeName}`;
463
- const archivePath = path.join(archiveDir, archiveName);
464
- // Check if archive already exists
465
- let archiveExists = false;
466
- try {
467
- await fs.access(archivePath);
468
- archiveExists = true;
469
- }
470
- catch (error) {
471
- if (error.code !== 'ENOENT') {
472
- throw error;
1568
+ // The destination was checked before the merge, so anything claiming it now
1569
+ // appeared while we were working. Report that as the collision it is: a raw
1570
+ // ENOTEMPTY from rename would otherwise degrade to a bare `archive_error`.
1571
+ if (!changeArchived) {
1572
+ await assertArchiveDestinationAvailable(archivePath, archiveName);
1573
+ archiveClaim = await claimArchiveDestination(archivePath, archiveName);
1574
+ await assertArchiveDestinationAvailable(archivePath, archiveName);
1575
+ // Create archive directory if needed
1576
+ await fs.mkdir(archiveDir, { recursive: true });
1577
+ // Move change to archive (uses copy+remove on EPERM/EXDEV, e.g. Windows)
1578
+ await moveDirectory(changeDir, archivePath);
1579
+ changeArchived = true;
1580
+ }
1581
+ if (!json) {
1582
+ console.log(`Change '${changeName}' archived as '${archiveName}'.`);
473
1583
  }
1584
+ return {
1585
+ change: changeName,
1586
+ archivedAs: archiveName,
1587
+ path: archivePath,
1588
+ specsUpdated,
1589
+ ...(totals ? { totals } : {}),
1590
+ ...(specWarnings.length > 0 ? { warnings: specWarnings } : {}),
1591
+ };
474
1592
  }
475
- if (archiveExists) {
476
- throw new ArchiveBlockedError('archive_target_exists', `Archive '${archiveName}' already exists.`);
1593
+ finally {
1594
+ if (archiveClaim)
1595
+ await releaseArchiveClaim(archiveClaim, claimPath).catch(() => undefined);
477
1596
  }
478
- // Create archive directory if needed
479
- await fs.mkdir(archiveDir, { recursive: true });
480
- // Move change to archive (uses copy+remove on EPERM/EXDEV, e.g. Windows)
481
- await moveDirectory(changeDir, archivePath);
482
- if (!json) {
483
- console.log(`Change '${changeName}' archived as '${archiveName}'.`);
484
- }
485
- return {
486
- change: changeName,
487
- archivedAs: archiveName,
488
- path: archivePath,
489
- specsUpdated,
490
- ...(totals ? { totals } : {}),
491
- ...(specWarnings.length > 0 ? { warnings: specWarnings } : {}),
492
- };
493
1597
  }
494
- async selectChange(changesDir) {
1598
+ async selectChange(changesDir, root, options) {
495
1599
  const { select } = await import('@inquirer/prompts');
496
1600
  const changeDirs = await listActiveChangeNames(changesDir);
497
1601
  if (changeDirs.length === 0) {
498
1602
  console.log('No active changes found.');
499
1603
  return null;
500
1604
  }
1605
+ // A picker needs a real terminal, and @inquirer's `select` writes ANSI
1606
+ // cursor escapes to stdout even when it is redirected — the same #1526
1607
+ // mechanism the confirm prompts were fixed for. When either stream is not a
1608
+ // TTY, refuse up front with the guidance the caught ExitPromptError would
1609
+ // give, rather than render an escape-spewing menu into a pipe or file.
1610
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1611
+ throw new ArchiveBlockedError('archive_change_name_required', 'A change name is required: no terminal is available to choose one from a list.', withStoreFlag(root, `openspec archive <change-name> ${rerunFlags(options).join(' ')}`));
1612
+ }
501
1613
  // Build choices with progress inline to avoid duplicate lists
502
1614
  let choices = changeDirs.map(name => ({ name, value: name }));
503
1615
  try {
@@ -525,6 +1637,15 @@ export class ArchiveCommand {
525
1637
  return answer;
526
1638
  }
527
1639
  catch (error) {
1640
+ // Nobody to pick from the list: reporting "No change selected" and
1641
+ // exiting 0 told an agent the archive had succeeded when nothing
1642
+ // happened (#1479). The suggested rerun carries --yes because the same
1643
+ // caller cannot answer the confirmations further down either, and the
1644
+ // caller's own flags because dropping --skip-specs here would suggest a
1645
+ // rerun that merges the specs it was passed to leave alone.
1646
+ if (isNonInteractivePromptError(error)) {
1647
+ throw new ArchiveBlockedError('archive_change_name_required', 'A change name is required: no answer could be read from stdin.', withStoreFlag(root, `openspec archive <change-name> ${rerunFlags(options).join(' ')}`));
1648
+ }
528
1649
  // User cancelled (Ctrl+C)
529
1650
  return null;
530
1651
  }