@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.
Files changed (95) hide show
  1. package/README.md +3 -1
  2. package/dist/cli/index.js +6 -1
  3. package/dist/commands/change.js +15 -1
  4. package/dist/commands/schema.js +89 -20
  5. package/dist/commands/spec.js +30 -6
  6. package/dist/commands/validate.js +2 -2
  7. package/dist/commands/workflow/instructions.js +32 -27
  8. package/dist/commands/workflow/status.js +2 -2
  9. package/dist/commands/workflow/templates.js +15 -5
  10. package/dist/core/archive.d.ts +14 -0
  11. package/dist/core/archive.js +1265 -151
  12. package/dist/core/artifact-graph/index.d.ts +1 -1
  13. package/dist/core/artifact-graph/index.js +1 -1
  14. package/dist/core/artifact-graph/instruction-loader.d.ts +3 -1
  15. package/dist/core/artifact-graph/instruction-loader.js +15 -5
  16. package/dist/core/artifact-graph/outputs.d.ts +1 -0
  17. package/dist/core/artifact-graph/outputs.js +67 -5
  18. package/dist/core/artifact-graph/resolver.js +35 -9
  19. package/dist/core/artifact-graph/types.js +21 -3
  20. package/dist/core/available-tools.d.ts +2 -2
  21. package/dist/core/available-tools.js +14 -3
  22. package/dist/core/change-metadata/schema.d.ts +1 -0
  23. package/dist/core/change-metadata/schema.js +7 -0
  24. package/dist/core/change-status-policy.js +2 -2
  25. package/dist/core/completions/command-registry.js +8 -0
  26. package/dist/core/config-schema.d.ts +3 -0
  27. package/dist/core/config-schema.js +28 -1
  28. package/dist/core/config.d.ts +3 -0
  29. package/dist/core/config.js +24 -2
  30. package/dist/core/file-state.js +56 -24
  31. package/dist/core/github-copilot/cloud-agent.d.ts +95 -0
  32. package/dist/core/github-copilot/cloud-agent.js +497 -0
  33. package/dist/core/global-config.d.ts +11 -0
  34. package/dist/core/init.d.ts +23 -0
  35. package/dist/core/init.js +234 -39
  36. package/dist/core/legacy-cleanup.js +4 -2
  37. package/dist/core/migration.d.ts +6 -4
  38. package/dist/core/migration.js +78 -22
  39. package/dist/core/parsers/requirement-blocks.d.ts +10 -0
  40. package/dist/core/parsers/requirement-blocks.js +60 -0
  41. package/dist/core/parsers/spec-structure.d.ts +1 -1
  42. package/dist/core/parsers/spec-structure.js +17 -1
  43. package/dist/core/profile-sync-drift.js +40 -5
  44. package/dist/core/project-config.d.ts +3 -0
  45. package/dist/core/project-config.js +31 -1
  46. package/dist/core/shared/index.d.ts +1 -0
  47. package/dist/core/shared/index.js +1 -0
  48. package/dist/core/shared/skill-content-equivalence.d.ts +7 -0
  49. package/dist/core/shared/skill-content-equivalence.js +41 -0
  50. package/dist/core/shared/skill-paths.d.ts +13 -0
  51. package/dist/core/shared/skill-paths.js +23 -0
  52. package/dist/core/shared/tool-detection.js +66 -35
  53. package/dist/core/shared-skill-target.d.ts +16 -0
  54. package/dist/core/shared-skill-target.js +156 -0
  55. package/dist/core/specs-apply.d.ts +72 -0
  56. package/dist/core/specs-apply.js +448 -55
  57. package/dist/core/templates/skill-templates.d.ts +1 -1
  58. package/dist/core/templates/skill-templates.js +1 -1
  59. package/dist/core/templates/workflows/apply-change.d.ts +10 -0
  60. package/dist/core/templates/workflows/apply-change.js +22 -182
  61. package/dist/core/templates/workflows/archive-change.js +8 -4
  62. package/dist/core/templates/workflows/bulk-archive-change.js +30 -26
  63. package/dist/core/templates/workflows/continue-change.js +6 -6
  64. package/dist/core/templates/workflows/explore.js +42 -18
  65. package/dist/core/templates/workflows/onboard.js +9 -3
  66. package/dist/core/templates/workflows/propose.js +72 -20
  67. package/dist/core/templates/workflows/store-selection.d.ts +1 -1
  68. package/dist/core/templates/workflows/store-selection.js +1 -1
  69. package/dist/core/templates/workflows/sync-specs.js +96 -18
  70. package/dist/core/templates/workflows/update-change.js +10 -8
  71. package/dist/core/update.d.ts +1 -0
  72. package/dist/core/update.js +103 -24
  73. package/dist/core/validation/validator.d.ts +23 -3
  74. package/dist/core/validation/validator.js +134 -18
  75. package/dist/core/version-check.js +6 -11
  76. package/dist/telemetry/config.d.ts +3 -4
  77. package/dist/telemetry/index.d.ts +9 -4
  78. package/dist/telemetry/index.js +20 -8
  79. package/dist/utils/change-metadata.d.ts +17 -4
  80. package/dist/utils/change-metadata.js +26 -4
  81. package/dist/utils/ci.d.ts +12 -0
  82. package/dist/utils/ci.js +16 -0
  83. package/dist/utils/command-references.d.ts +14 -2
  84. package/dist/utils/command-references.js +45 -3
  85. package/dist/utils/file-system.d.ts +10 -0
  86. package/dist/utils/file-system.js +70 -0
  87. package/dist/utils/interactive.d.ts +23 -0
  88. package/dist/utils/interactive.js +32 -0
  89. package/dist/utils/spec-discovery.d.ts +4 -4
  90. package/dist/utils/spec-discovery.js +19 -6
  91. package/dist/utils/task-progress.d.ts +17 -0
  92. package/dist/utils/task-progress.js +41 -13
  93. package/package.json +1 -1
  94. package/schemas/spec-driven/schema.yaml +8 -6
  95. package/schemas/spec-driven/templates/proposal.md +6 -4
@@ -5,14 +5,54 @@
5
5
  * Applies delta specs from a change to main specs without archiving.
6
6
  */
7
7
  import { promises as fs } from 'fs';
8
+ import { randomUUID } from 'crypto';
8
9
  import path from 'path';
9
10
  import chalk from 'chalk';
10
- import { extractRequirementsSection, foldRequirementName, parseDeltaSpec, normalizeRequirementName, } from './parsers/requirement-blocks.js';
11
+ import { extractRequirementsSection, findMissingCurrentScenarios, foldRequirementName, parseDeltaSpec, normalizeRequirementName, } from './parsers/requirement-blocks.js';
11
12
  import { findMainSpecStructureIssues } from './parsers/spec-structure.js';
12
13
  import { buildCodeFenceMask } from './parsers/code-fence.js';
13
14
  import { MarkdownParser } from './parsers/markdown-parser.js';
14
15
  import { MIN_PURPOSE_LENGTH } from './validation/constants.js';
15
16
  import { discoverSpecFiles } from '../utils/spec-discovery.js';
17
+ import { FileSystemUtils } from '../utils/file-system.js';
18
+ function isLexicallyWithin(allowedDirectory, targetPath) {
19
+ const relative = path.relative(path.resolve(allowedDirectory), path.resolve(targetPath));
20
+ return (relative === '' ||
21
+ (relative !== '..' &&
22
+ !relative.startsWith(`..${path.sep}`) &&
23
+ !path.isAbsolute(relative)));
24
+ }
25
+ function resolveTrustedSpecPath(specsRoot, specPath) {
26
+ if (!isLexicallyWithin(specsRoot, specPath)) {
27
+ throw new Error(`Path is outside the allowed directory: ${specPath}`);
28
+ }
29
+ try {
30
+ // Preserve spec.md links that remain inside the overall specs tree.
31
+ FileSystemUtils.assertPathWithin(specsRoot, specPath);
32
+ const root = FileSystemUtils.canonicalizeExistingPath(specsRoot);
33
+ return {
34
+ root,
35
+ // Rebase onto the canonical root so missing targets also work when the
36
+ // project is reached through an OS path alias (for example /var on macOS).
37
+ file: path.join(root, path.relative(path.resolve(specsRoot), path.resolve(specPath))),
38
+ };
39
+ }
40
+ catch {
41
+ // Direct capability directories may intentionally be monorepo symlinks.
42
+ // Freeze their canonical location as the trust root so later swaps are
43
+ // rejected while a nested spec.md link still cannot escape.
44
+ const root = FileSystemUtils.canonicalizeExistingPath(path.dirname(specPath));
45
+ const file = path.join(root, path.basename(specPath));
46
+ FileSystemUtils.assertPathWithin(root, file);
47
+ return { root, file };
48
+ }
49
+ }
50
+ function assertTrustedSpecPath(root, specPath) {
51
+ if (FileSystemUtils.canonicalizeExistingPath(root) !== path.resolve(root)) {
52
+ throw new Error(`Path is outside the allowed directory: ${specPath}`);
53
+ }
54
+ FileSystemUtils.assertPathWithin(root, specPath);
55
+ }
16
56
  // -----------------------------------------------------------------------------
17
57
  // Public API
18
58
  // -----------------------------------------------------------------------------
@@ -28,10 +68,12 @@ export async function findSpecUpdates(changeDir, mainSpecsDir) {
28
68
  const discovered = await discoverSpecFiles(changeSpecsDir);
29
69
  for (const { id, specFile } of discovered) {
30
70
  const targetFile = path.join(mainSpecsDir, ...id.split('/'), 'spec.md');
71
+ const source = resolveTrustedSpecPath(changeSpecsDir, specFile);
72
+ const target = resolveTrustedSpecPath(mainSpecsDir, targetFile);
31
73
  // Check if target exists
32
74
  let exists = false;
33
75
  try {
34
- await fs.access(targetFile);
76
+ await fs.access(target.file);
35
77
  exists = true;
36
78
  }
37
79
  catch {
@@ -39,8 +81,10 @@ export async function findSpecUpdates(changeDir, mainSpecsDir) {
39
81
  }
40
82
  updates.push({
41
83
  id,
42
- source: specFile,
43
- target: targetFile,
84
+ sourceRoot: source.root,
85
+ source: source.file,
86
+ targetRoot: target.root,
87
+ target: target.file,
44
88
  exists,
45
89
  });
46
90
  }
@@ -61,6 +105,7 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
61
105
  }
62
106
  };
63
107
  // Read change spec content (delta-format expected)
108
+ assertTrustedSpecPath(update.sourceRoot, update.source);
64
109
  const changeContent = await fs.readFile(update.source, 'utf-8');
65
110
  // Parse deltas from the change spec file
66
111
  const plan = parseDeltaSpec(changeContent);
@@ -152,6 +197,7 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
152
197
  const deltaPurpose = extractPurposeSection(changeContent);
153
198
  let targetContent;
154
199
  let isNewSpec = false;
200
+ assertTrustedSpecPath(update.targetRoot, update.target);
155
201
  try {
156
202
  targetContent = await fs.readFile(update.target, 'utf-8');
157
203
  // A delta Purpose only seeds a spec that does not exist yet. Say so rather
@@ -211,6 +257,7 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
211
257
  // Apply operations in order: RENAMED → REMOVED → MODIFIED → ADDED
212
258
  // RENAMED
213
259
  let renamedApplied = 0;
260
+ const renamedTargets = new Map();
214
261
  for (const r of plan.renamed) {
215
262
  const from = normalizeRequirementName(r.from);
216
263
  const to = normalizeRequirementName(r.to);
@@ -244,6 +291,7 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
244
291
  };
245
292
  nameToBlock.delete(from);
246
293
  nameToBlock.set(to, renamedBlock);
294
+ renamedTargets.set(from, to);
247
295
  renamedApplied++;
248
296
  }
249
297
  // REMOVED
@@ -323,6 +371,27 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
323
371
  keptOrder.push(replacement);
324
372
  seen.add(key);
325
373
  }
374
+ // A block's raw runs to the next header the parser RECOGNISES, so a note
375
+ // under an unrecognized heading can be absorbed into the requirement.
376
+ // Warn only when the replacement from this same original block drops the
377
+ // full absorbed suffix. RENAMED carries the original raw content under a
378
+ // new map key, and MODIFIED may repeat the suffix deliberately; neither is
379
+ // data loss.
380
+ const renamedTarget = renamedTargets.get(key);
381
+ const replacementFromOriginal = replacement ?? (renamedTarget ? nameToBlock.get(renamedTarget) : undefined);
382
+ if (replacementFromOriginal !== block) {
383
+ const foreign = firstForeignTail(block.raw);
384
+ const replacementRaw = replacementFromOriginal?.raw;
385
+ const normalizedForeign = foreign ? normalizeBlockRaw(foreign.raw) : '';
386
+ const keepsForeignTail = foreign !== undefined &&
387
+ replacementRaw !== undefined &&
388
+ countOccurrences(normalizeBlockRaw(replacementRaw), normalizedForeign) >=
389
+ countOccurrences(normalizeBlockRaw(block.raw), normalizedForeign);
390
+ if (foreign && !keepsForeignTail) {
391
+ warn(`${specName} - "${foreign.heading}" sits inside requirement "${block.name}" and goes with it. ` +
392
+ 'Move it under its own requirement, or above `## Requirements`, to keep it.');
393
+ }
394
+ }
326
395
  }
327
396
  // Append any newly added that were not in original order
328
397
  for (const [key, block] of nameToBlock.entries()) {
@@ -348,18 +417,393 @@ export async function buildUpdatedSpec(update, changeName, options = {}) {
348
417
  renamed: renamedApplied,
349
418
  },
350
419
  warnings,
420
+ noRequirementBlocks: keptOrder.length === 0,
421
+ // Read off the ORIGINAL requirements section, not the rebuilt one. Anything
422
+ // after the last `### Requirement:` header belongs to that block's raw and
423
+ // is discarded with it, so a rebuilt-body scan only ever sees headings above
424
+ // the first requirement - it would veto `### Notes` written before the
425
+ // requirements and miss the identical heading written after them.
426
+ unaccountedContent: contentTheMergeCannotName(parts),
351
427
  };
352
428
  }
429
+ /**
430
+ * The suffix of a requirement block that begins with content the requirement
431
+ * parser did not recognize as a boundary: a `#`, `##`, or `###` heading after
432
+ * the block's own header.
433
+ *
434
+ * `####` is excluded: a requirement's `#### Scenario:` headings are its own.
435
+ * Fenced lines are skipped, so a heading inside an example does not count.
436
+ *
437
+ * Approximate on purpose, and only ever used to WARN. A `#` line inside a
438
+ * scenario looks the same as a note written below the requirement, and no
439
+ * line-based rule separates them; a wrong warning costs a line of output, while
440
+ * acting on a wrong answer would rewrite the spec.
441
+ */
442
+ function firstForeignTail(raw) {
443
+ const lines = raw.replace(/\r\n?/g, '\n').split('\n');
444
+ const fenceMask = buildCodeFenceMask(lines);
445
+ for (let index = 1; index < lines.length; index++) {
446
+ if (fenceMask[index])
447
+ continue;
448
+ if (/^ {0,3}#{1,3}(?:[ \t]|$)/.test(lines[index])) {
449
+ return {
450
+ heading: lines[index].trim(),
451
+ raw: lines.slice(index).join('\n').trimEnd(),
452
+ };
453
+ }
454
+ }
455
+ return undefined;
456
+ }
457
+ /**
458
+ * The non-blank lines of a spec that are not part of what a retirement is able
459
+ * to name: the title, the `## Purpose` section, the `## Requirements` header,
460
+ * and each requirement block's own header, statement and scenario bullets.
461
+ *
462
+ * Deliberately whole-file. Auditing a subset of the slices is what let authored
463
+ * prose inside a removed block, and content above the requirements section, be
464
+ * deleted unmentioned.
465
+ */
466
+ function contentTheMergeCannotName(parts) {
467
+ const leftovers = [];
468
+ // Above the requirements section: the title and the Purpose section are
469
+ // expected; anything else is authored content the deletion would take.
470
+ const beforeLines = parts.before.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').split('\n');
471
+ const beforeMask = buildCodeFenceMask(beforeLines);
472
+ let inPurpose = false;
473
+ let titleSeen = false;
474
+ let previousLine = '';
475
+ for (let index = 0; index < beforeLines.length; index++) {
476
+ const line = beforeLines[index];
477
+ if (!line.trim()) {
478
+ previousLine = '';
479
+ continue;
480
+ }
481
+ if (!beforeMask[index]) {
482
+ const section = line.match(/^ {0,3}##\s+(.+?)\s*$/);
483
+ if (section) {
484
+ inPurpose = /^purpose$/i.test(section[1].trim());
485
+ if (!inPurpose)
486
+ leftovers.push(line.trim());
487
+ previousLine = line;
488
+ continue;
489
+ }
490
+ // `##` is not the only way to open a section. A setext underline turns
491
+ // the line above it into a heading, and raw HTML says so outright - a
492
+ // reader sees a sibling of `## Purpose`, not more of its body. Treating
493
+ // everything up to the next ATX `##` as Purpose swallowed those whole and
494
+ // deleted them, reported as nothing but "Purpose".
495
+ const setext = inPurpose && previousLine.trim() && /^ {0,3}(=+|-+)\s*$/.test(line);
496
+ const htmlHeading = /^ {0,3}<h[1-6]\b/i.test(line);
497
+ if (setext || htmlHeading) {
498
+ leftovers.push((setext ? previousLine : line).trim());
499
+ inPurpose = false;
500
+ previousLine = line;
501
+ continue;
502
+ }
503
+ if (/^ {0,3}#\s+.+$/.test(line)) {
504
+ if (!titleSeen && !inPurpose) {
505
+ titleSeen = true;
506
+ }
507
+ else {
508
+ leftovers.push(line.trim());
509
+ inPurpose = false;
510
+ }
511
+ previousLine = line;
512
+ continue;
513
+ }
514
+ }
515
+ previousLine = line;
516
+ if (inPurpose)
517
+ continue;
518
+ leftovers.push(line.trim());
519
+ }
520
+ // Between the header and the first requirement, and past the section's end.
521
+ for (const slice of [parts.preamble, parts.after]) {
522
+ for (const line of slice.split('\n')) {
523
+ if (line.trim())
524
+ leftovers.push(line.trim());
525
+ }
526
+ }
527
+ // Inside each requirement block, everything the block parser did not treat as
528
+ // a new header rides along in `raw` - tables, fences, comments, prose written
529
+ // below the scenarios. Only a requirement's own parts are expected here.
530
+ for (const block of parts.bodyBlocks) {
531
+ const foreignTail = firstForeignTail(block.raw);
532
+ if (foreignTail)
533
+ leftovers.push(foreignTail.heading);
534
+ const lines = block.raw.replace(/\r\n?/g, '\n').split('\n');
535
+ const mask = buildCodeFenceMask(lines);
536
+ let seenScenario = false;
537
+ // A scenario's bullets run unbroken beneath its header. A blank line after
538
+ // them ends the scenario, so bullets written past that point are a note the
539
+ // author added, not part of the scenario - and deleting the file would take
540
+ // them. Treating every bullet as a scenario's own is what let an
541
+ // operational note below the last scenario be deleted unmentioned.
542
+ let inScenarioBullets = false;
543
+ let bulletsSeen = false;
544
+ for (let index = 0; index < lines.length; index++) {
545
+ const line = lines[index];
546
+ if (!line.trim()) {
547
+ // Only a blank that follows actual bullets closes the run, so a blank
548
+ // between a scenario header and its first bullet is not a boundary.
549
+ if (bulletsSeen)
550
+ inScenarioBullets = false;
551
+ continue;
552
+ }
553
+ if (index === 0)
554
+ continue; // the `### Requirement:` header itself
555
+ // Fenced lines render as a code block inside the requirement, so they are
556
+ // its own content however they are spelled - a `### Requirement:` in an
557
+ // example is not a heading to any reader. Flagging them made a spec that
558
+ // merely documents a command unretirable.
559
+ if (mask[index])
560
+ continue;
561
+ if (index > 1 &&
562
+ /^ {0,3}(?:=+|-+)\s*$/.test(line) &&
563
+ lines[index - 1].trim()) {
564
+ leftovers.push(lines[index - 1].trim());
565
+ continue;
566
+ }
567
+ if (/^ {0,3}####\s+Scenario:/i.test(line)) {
568
+ seenScenario = true;
569
+ inScenarioBullets = true;
570
+ bulletsSeen = false;
571
+ continue;
572
+ }
573
+ if (/^\s*(?:[-*]|\d+[.)])\s/.test(line)) {
574
+ if (inScenarioBullets) {
575
+ bulletsSeen = true;
576
+ continue;
577
+ }
578
+ // A bullet outside a scenario. Before the first scenario it is part of
579
+ // the requirement statement; after one it is the author's own note.
580
+ if (!seenScenario)
581
+ continue;
582
+ leftovers.push(line.trim());
583
+ continue;
584
+ }
585
+ // Free prose above the first scenario is the requirement statement.
586
+ if (!seenScenario && !/^\s*[|<]/.test(line))
587
+ continue;
588
+ leftovers.push(line.trim());
589
+ }
590
+ }
591
+ return [...new Set(leftovers)];
592
+ }
353
593
  function normalizeBlockRaw(raw) {
354
594
  return raw.replace(/\r\n?/g, '\n').trim();
355
595
  }
596
+ /** Count non-overlapping copies so one retained duplicate cannot mask another copy's loss. */
597
+ function countOccurrences(haystack, needle) {
598
+ if (!needle)
599
+ return 0;
600
+ let count = 0;
601
+ let start = 0;
602
+ while ((start = haystack.indexOf(needle, start)) !== -1) {
603
+ count++;
604
+ start += needle.length;
605
+ }
606
+ return count;
607
+ }
608
+ /**
609
+ * Retire a capability whose last requirement a delta removed: delete its main
610
+ * spec and prune any directories the deletion leaves empty. Returns false when
611
+ * there was nothing to delete.
612
+ *
613
+ * Gated by the caller on the change's `retire_capabilities` marker, so the one
614
+ * archive action that removes a file from `openspec/specs/` is always something
615
+ * the author asked for rather than something inferred from a delta's shape. The
616
+ * file is recoverable from git, which the report names; applying REMOVED already
617
+ * deletes requirement content from a main spec, so deleting the spec once
618
+ * nothing is left is the same operation carried to its end rather than a new
619
+ * kind of act.
620
+ *
621
+ * Only the generated `spec.md` is removed - a directory holding anything else (a
622
+ * nested capability, a hand-kept note) is left in place.
623
+ *
624
+ * The target must resolve inside the selected specs root. A capability-directory
625
+ * symlink must not turn a retirement marker into authorization to delete an
626
+ * unrelated external file. A symlinked `spec.md` itself is safe: unlink removes
627
+ * the link and leaves its target alone.
628
+ *
629
+ * Directory pruning IS bounded, by REAL paths rather than string prefixes:
630
+ * `path.resolve` collapses `..` but does not resolve symlinks, and `readdir` and
631
+ * `rmdir` both follow them, so a symlinked capability directory would otherwise
632
+ * let the walk delete directories outside the specs root entirely.
633
+ */
634
+ export async function retireSpec(update, mainSpecsDir, options = {}) {
635
+ if (options.deferDelete && options.verifyDisplaced === undefined) {
636
+ throw new Error('Deferred retirement requires displaced-file verification.');
637
+ }
638
+ // Resolved before the unlink, while the link still exists, so the report can
639
+ // name the file that actually goes when a symlink points out of the tree.
640
+ // A symlinked `spec.md` is excluded: `realpath` would follow it, but `unlink`
641
+ // removes the link and leaves the target alone, so naming the target would
642
+ // claim a file was deleted that is still there.
643
+ let realSource;
644
+ try {
645
+ const link = await fs.lstat(update.target);
646
+ realSource = link.isSymbolicLink() ? undefined : await fs.realpath(update.target);
647
+ }
648
+ catch (error) {
649
+ if (error.code === 'ENOENT')
650
+ return { retired: false };
651
+ throw new Error(`Could not retire capability '${update.id}': could not verify ${update.target} ` +
652
+ `before deletion (${error instanceof Error ? error.message : String(error)}).`);
653
+ }
654
+ if (realSource !== undefined) {
655
+ let inside;
656
+ try {
657
+ inside = await isInsideRealDir(realSource, mainSpecsDir);
658
+ }
659
+ catch (error) {
660
+ throw new Error(`Could not retire capability '${update.id}': could not verify that ${update.target} ` +
661
+ `is inside ${mainSpecsDir} (${error instanceof Error ? error.message : String(error)}).`);
662
+ }
663
+ if (!inside) {
664
+ throw new Error(`Could not retire capability '${update.id}': ${update.target} resolves outside ` +
665
+ `${mainSpecsDir}. Remove the external file by hand, or replace the symlink and rerun.`);
666
+ }
667
+ }
668
+ let displacedPath;
669
+ try {
670
+ await options.beforeMutate?.();
671
+ if (options.verifyDisplaced) {
672
+ const displaced = `${update.target}.openspec-retire-${randomUUID()}`;
673
+ displacedPath = displaced;
674
+ await fs.rename(update.target, displaced);
675
+ try {
676
+ await options.verifyDisplaced(displaced);
677
+ try {
678
+ await fs.lstat(update.target);
679
+ throw new Error(`A concurrent file appeared at ${update.target} while archive was retiring it.`);
680
+ }
681
+ catch (targetError) {
682
+ if (targetError.code !== 'ENOENT')
683
+ throw targetError;
684
+ }
685
+ if (!options.deferDelete)
686
+ await fs.unlink(displaced);
687
+ }
688
+ catch (error) {
689
+ try {
690
+ await fs.lstat(update.target);
691
+ throw new Error(`${error instanceof Error ? error.message : String(error)} ` +
692
+ `A concurrent file now occupies ${update.target}; the displaced spec was retained at ${displaced}.`);
693
+ }
694
+ catch (targetError) {
695
+ if (targetError.code !== 'ENOENT')
696
+ throw targetError;
697
+ }
698
+ await fs.rename(displaced, update.target);
699
+ throw error;
700
+ }
701
+ }
702
+ else {
703
+ await fs.unlink(update.target);
704
+ }
705
+ }
706
+ catch (error) {
707
+ if (error.code === 'ENOENT')
708
+ return { retired: false };
709
+ // A bare errno here reads as an internal failure; say what was being
710
+ // attempted so the message is actionable on its own.
711
+ throw new Error(`Could not retire capability '${update.id}': failed to delete ${update.target} ` +
712
+ `(${error.message}). Remove it by hand, then rerun the archive.`);
713
+ }
714
+ if (!options.deferDelete) {
715
+ await pruneEmptyDirs(path.dirname(update.target), mainSpecsDir);
716
+ }
717
+ const nominal = options.displayPath ?? `openspec/specs/${update.id}/spec.md`;
718
+ if (!options.silent) {
719
+ console.log(`Retiring ${nominal}: all requirements removed.`);
720
+ }
721
+ // `resolvedPath` is always the file that was actually unlinked - callers need
722
+ // it to report a path git will accept, since the nominal one is built from
723
+ // the capability id and can differ in case, or point through a symlink.
724
+ return {
725
+ retired: true,
726
+ ...(realSource ? { resolvedPath: realSource } : {}),
727
+ ...(options.deferDelete && displacedPath ? { displacedPath } : {}),
728
+ };
729
+ }
730
+ export async function finalizeRetiredSpec(target, displacedPath, mainSpecsDir) {
731
+ await fs.unlink(displacedPath);
732
+ await pruneEmptyDirs(path.dirname(target), mainSpecsDir);
733
+ }
734
+ /** Whether `realPath` (already canonical) sits under the real `dir`. */
735
+ async function isInsideRealDir(realPath, dir) {
736
+ const realDir = await fs.realpath(dir);
737
+ return realPath.startsWith(realDir + path.sep);
738
+ }
739
+ /**
740
+ * Remove now-empty directories from `startDir` upward, never leaving the real
741
+ * `boundaryDir` and never removing that directory itself.
742
+ *
743
+ * The boundary is a parameter rather than the specs root directly so the walk's
744
+ * containment is stated at the call site, where the root it must not escape is
745
+ * the thing being reasoned about.
746
+ *
747
+ * The guard re-runs every iteration, so stepping to the LEXICAL parent is safe:
748
+ * a parent that is not the real one is simply re-resolved and rejected. Errors
749
+ * are swallowed and end the walk - ENOTEMPTY and ENOENT are correct outcomes (a
750
+ * file arriving mid-walk must win), and a permissions failure leaves an empty
751
+ * directory behind, which the next successful archive clears.
752
+ *
753
+ * Not race-free: an attacker who can swap an ancestor between the check and the
754
+ * `rmdir` could get an empty directory outside the root removed. Closing that
755
+ * needs fd-relative syscalls Node does not expose, and it requires local write
756
+ * access to `openspec/specs` during an archive.
757
+ */
758
+ async function pruneEmptyDirs(startDir, boundaryDir) {
759
+ let boundary;
760
+ try {
761
+ boundary = await fs.realpath(boundaryDir);
762
+ }
763
+ catch {
764
+ return;
765
+ }
766
+ let dir = startDir;
767
+ for (;;) {
768
+ let realDir;
769
+ try {
770
+ // lstat first: rmdir on a symlink fails anyway, but resolving one would
771
+ // walk us out of the tree, and the parent we then step to would be wrong.
772
+ const link = await fs.lstat(dir);
773
+ if (link.isSymbolicLink())
774
+ return;
775
+ realDir = await fs.realpath(dir);
776
+ }
777
+ catch {
778
+ return;
779
+ }
780
+ // Strictly inside the real boundary - the boundary itself is never pruned.
781
+ if (realDir === boundary || !realDir.startsWith(boundary + path.sep))
782
+ return;
783
+ try {
784
+ const entries = await fs.readdir(dir);
785
+ if (entries.length > 0)
786
+ return;
787
+ await fs.rmdir(dir);
788
+ }
789
+ catch {
790
+ return;
791
+ }
792
+ dir = path.dirname(dir);
793
+ }
794
+ }
356
795
  /**
357
796
  * Write an updated spec to disk.
358
797
  */
359
798
  export async function writeUpdatedSpec(update, rebuilt, counts, options = {}) {
799
+ assertTrustedSpecPath(update.targetRoot, update.target);
360
800
  // Create target directory if needed
361
801
  const targetDir = path.dirname(update.target);
362
802
  await fs.mkdir(targetDir, { recursive: true });
803
+ await options.beforeMutate?.();
804
+ // Preserve the established in-place write semantics: symlink referents,
805
+ // hard-linked specs, ACLs, extended attributes, and filesystems without hard
806
+ // links must continue to behave as they did before capability retirement.
363
807
  await fs.writeFile(update.target, rebuilt);
364
808
  if (options.silent)
365
809
  return;
@@ -469,55 +913,4 @@ export function buildSpecSkeleton(specFolderName, changeName, purpose) {
469
913
  const purposeBody = purpose?.trim() || `TBD - created by archiving change ${changeName}. Update Purpose after archive.`;
470
914
  return `# ${titleBase} Specification\n\n## Purpose\n${purposeBody}\n\n## Requirements\n`;
471
915
  }
472
- function findMissingCurrentScenarios(current, incoming) {
473
- // Multiplicity-aware: a name present N times in current and M times in
474
- // incoming means max(0, N - M) instances are missing. Set membership would
475
- // treat N>M as fully covered and let archive silently drop duplicates
476
- // (residual #1246 / duplicate-scenario-name blind spot).
477
- const remainingIncoming = new Map();
478
- for (const scenario of parseScenarioBlocks(incoming.raw)) {
479
- const name = scenario.name;
480
- remainingIncoming.set(name, (remainingIncoming.get(name) ?? 0) + 1);
481
- }
482
- const missing = [];
483
- for (const scenario of parseScenarioBlocks(current.raw)) {
484
- const name = scenario.name;
485
- const remaining = remainingIncoming.get(name) ?? 0;
486
- if (remaining > 0) {
487
- remainingIncoming.set(name, remaining - 1);
488
- }
489
- else {
490
- missing.push(name);
491
- }
492
- }
493
- return missing;
494
- }
495
- function parseScenarioBlocks(requirementRaw) {
496
- const lines = requirementRaw.replace(/\r\n?/g, '\n').split('\n');
497
- // A `#### Scenario:` inside a fenced example is not a real scenario. The
498
- // validator's countScenarios already ignores fenced lines; the drift check
499
- // must agree with it, or a fenced sample can false-abort an archive (or
500
- // mask a genuinely dropped scenario).
501
- const mask = buildCodeFenceMask(lines);
502
- const scenarios = [];
503
- let index = 0;
504
- while (index < lines.length) {
505
- const headerMatch = mask[index] ? null : lines[index].match(/^####\s*Scenario:\s*(.+)\s*$/);
506
- if (!headerMatch) {
507
- index++;
508
- continue;
509
- }
510
- const start = index;
511
- const name = headerMatch[1].trim();
512
- index++;
513
- while (index < lines.length && (mask[index] || !/^####\s*Scenario:\s*(.+)\s*$/.test(lines[index]))) {
514
- index++;
515
- }
516
- scenarios.push({
517
- name,
518
- raw: lines.slice(start, index).join('\n').trimEnd(),
519
- });
520
- }
521
- return scenarios;
522
- }
523
916
  //# sourceMappingURL=specs-apply.js.map
@@ -7,7 +7,7 @@ export type { SkillTemplate, CommandTemplate } from './types.js';
7
7
  export { getExploreSkillTemplate, getOpsxExploreCommandTemplate } from './workflows/explore.js';
8
8
  export { getNewChangeSkillTemplate, getOpsxNewCommandTemplate } from './workflows/new-change.js';
9
9
  export { getContinueChangeSkillTemplate, getOpsxContinueCommandTemplate } from './workflows/continue-change.js';
10
- export { getApplyChangeSkillTemplate, getOpsxApplyCommandTemplate } from './workflows/apply-change.js';
10
+ export { getApplyInstructions, getApplyChangeSkillTemplate, getOpsxApplyCommandTemplate } from './workflows/apply-change.js';
11
11
  export { getUpdateChangeSkillTemplate, getOpsxUpdateCommandTemplate } from './workflows/update-change.js';
12
12
  export { getFfChangeSkillTemplate, getOpsxFfCommandTemplate } from './workflows/ff-change.js';
13
13
  export { getSyncSpecsSkillTemplate, getOpsxSyncCommandTemplate } from './workflows/sync-specs.js';
@@ -6,7 +6,7 @@
6
6
  export { getExploreSkillTemplate, getOpsxExploreCommandTemplate } from './workflows/explore.js';
7
7
  export { getNewChangeSkillTemplate, getOpsxNewCommandTemplate } from './workflows/new-change.js';
8
8
  export { getContinueChangeSkillTemplate, getOpsxContinueCommandTemplate } from './workflows/continue-change.js';
9
- export { getApplyChangeSkillTemplate, getOpsxApplyCommandTemplate } from './workflows/apply-change.js';
9
+ export { getApplyInstructions, getApplyChangeSkillTemplate, getOpsxApplyCommandTemplate } from './workflows/apply-change.js';
10
10
  export { getUpdateChangeSkillTemplate, getOpsxUpdateCommandTemplate } from './workflows/update-change.js';
11
11
  export { getFfChangeSkillTemplate, getOpsxFfCommandTemplate } from './workflows/ff-change.js';
12
12
  export { getSyncSpecsSkillTemplate, getOpsxSyncCommandTemplate } from './workflows/sync-specs.js';
@@ -5,6 +5,16 @@
5
5
  * templates file into workflow-focused modules.
6
6
  */
7
7
  import type { SkillTemplate, CommandTemplate } from '../types.js';
8
+ /**
9
+ * The apply workflow instructions, authored once and rendered by both the
10
+ * skill and command surfaces. The surfaces are intentionally distinct, but
11
+ * they differ only in how they are invoked — the generation transformers
12
+ * rewrite the canonical `/opsx:<id>` tokens per surface downstream (see
13
+ * command-references.ts). The instruction text itself is shared, so the two
14
+ * cannot silently drift. Should a surface ever need genuinely different
15
+ * wording, add a parameter here and pass it from that surface's template.
16
+ */
17
+ export declare function getApplyInstructions(): string;
8
18
  export declare function getApplyChangeSkillTemplate(): SkillTemplate;
9
19
  export declare function getOpsxApplyCommandTemplate(): CommandTemplate;
10
20
  //# sourceMappingURL=apply-change.d.ts.map