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