@polymorphism-tech/morph-spec 8.22.0 → 8.24.1

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 (42) hide show
  1. package/README.md +2 -2
  2. package/bin/morph-spec.js +27 -1
  3. package/claude-plugin.json +1 -1
  4. package/docs/CHEATSHEET.md +1 -1
  5. package/docs/QUICKSTART.md +1 -1
  6. package/framework/CLAUDE.md +1 -1
  7. package/framework/MORPH.md +2 -2
  8. package/framework/agents.json +1 -0
  9. package/framework/docs/CLI.md +5 -3
  10. package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +118 -0
  11. package/framework/hooks/shared/reparse-scan.js +100 -0
  12. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  13. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  14. package/framework/skills/core/morph-apply/SKILL.md +2 -2
  15. package/framework/skills/core/morph-brainstorming/SKILL.md +1 -1
  16. package/framework/skills/core/morph-eval/SKILL.md +1 -1
  17. package/framework/skills/core/morph-hotfix/SKILL.md +1 -1
  18. package/framework/skills/core/morph-implement/SKILL.md +14 -2
  19. package/framework/skills/core/morph-plan/SKILL.md +6 -4
  20. package/framework/skills/core/morph-proposal/SKILL.md +1 -1
  21. package/framework/skills/core/morph-review/SKILL.md +29 -3
  22. package/framework/skills/core/morph-stack-scan/SKILL.md +1 -1
  23. package/framework/skills/core/morph-standards/SKILL.md +1 -1
  24. package/framework/skills/core/morph-uiux/SKILL.md +1 -1
  25. package/framework/standards/STANDARDS.json +28 -0
  26. package/framework/standards/backend/dotnet/fluent-validation-vsa.md +5 -2
  27. package/framework/standards/backend/dotnet/testing.md +127 -0
  28. package/package.json +1 -1
  29. package/src/commands/project/worktree.js +250 -86
  30. package/src/commands/state/approve.js +11 -0
  31. package/src/commands/state/archive.js +12 -3
  32. package/src/commands/state/finish.js +30 -16
  33. package/src/commands/state/handoff.js +3 -2
  34. package/src/commands/state/usecase.js +77 -0
  35. package/src/commands/validation/verify.js +6 -0
  36. package/src/lib/generators/handoff-generator.js +2 -2
  37. package/src/lib/specs/usecase-promoter.js +135 -19
  38. package/src/lib/specs/usecase-registry.js +237 -0
  39. package/src/lib/validators/traceability-check.js +198 -0
  40. package/src/lib/validators/verify-runner.js +14 -0
  41. package/src/lib/worktree/worktree-audit.js +6 -2
  42. package/src/utils/hooks-installer.js +12 -8
@@ -63,7 +63,8 @@ function readReviewApproved(fjPath) {
63
63
  * @param {string} feature
64
64
  * @param {{ cwd?: string, force?: boolean, git?: boolean }} [opts]
65
65
  * @returns {{ ok: boolean, error?: string, archived?: boolean, alreadyArchived?: boolean,
66
- * committed?: boolean, staged?: boolean, archivePath?: string, promotedUseCases?: string[] }}
66
+ * committed?: boolean, staged?: boolean, archivePath?: string, promotedUseCases?: string[],
67
+ * refusedUseCases?: Array<{id: string, incoming: string, existing: string, existingFeature: string, message: string}> }}
67
68
  */
68
69
  export function runArchive(feature, opts = {}) {
69
70
  const cwd = opts.cwd || process.cwd();
@@ -156,9 +157,11 @@ export function runArchive(feature, opts = {}) {
156
157
  // (MORPH.md §2.2). Fail-open: any failure degrades to "promoted nothing",
157
158
  // never to a refused close.
158
159
  let promotedUseCases = [];
160
+ let refusedUseCases = [];
159
161
  try {
160
- const { promoted } = promoteUseCases(cwd, archivePath);
162
+ const { promoted, refused } = promoteUseCases(cwd, archivePath);
161
163
  promotedUseCases = promoted;
164
+ refusedUseCases = refused;
162
165
  if (promoted.length && useGit && staged) {
163
166
  // This staging exists for the NEW files: promoted use cases are untracked,
164
167
  // and the scoped `commit -- <pathspec>` below only knows paths git already
@@ -203,7 +206,7 @@ export function runArchive(feature, opts = {}) {
203
206
  } catch { /* index is derivable — non-fatal */ }
204
207
  }
205
208
 
206
- return { ok: true, archived: true, committed, staged, archivePath, promotedUseCases };
209
+ return { ok: true, archived: true, committed, staged, archivePath, promotedUseCases, refusedUseCases };
207
210
  }
208
211
 
209
212
  /**
@@ -244,6 +247,12 @@ export async function archiveCommand(featureName, options = {}) {
244
247
  if (result.promotedUseCases?.length) {
245
248
  console.log(chalk.gray(` ${result.promotedUseCases.length} use case(s) promoted → .morph/specs/usecases/ (status: implemented).`));
246
249
  }
250
+ if (result.refusedUseCases?.length) {
251
+ console.log(chalk.yellow(`\n⚠️ ${result.refusedUseCases.length} use case(s) NOT promoted — numbering collision:`));
252
+ for (const r of result.refusedUseCases) {
253
+ console.log(chalk.yellow(` ${r.message}`));
254
+ }
255
+ }
247
256
  if (result.committed) console.log(chalk.gray(` Move committed on the current branch.\n`));
248
257
  else if (result.staged) console.log(chalk.gray(` Move staged in git; commit it when ready.\n`));
249
258
  else console.log('');
@@ -10,6 +10,7 @@ import {
10
10
  isValidFeatureName,
11
11
  buildBranchName,
12
12
  branchExists,
13
+ cwdIsInsideWorktree,
13
14
  } from '../project/worktree.js';
14
15
  import { detectDefaultBranch, hasOriginRemote } from '../../lib/git/default-branch.js';
15
16
  import { releaseClaim } from '../../../framework/hooks/shared/claim-registry.js';
@@ -162,16 +163,14 @@ export async function finishCommand(feature, options = {}) {
162
163
  // a de-registered worktree, and a `relinkHint` telling the user to repair
163
164
  // by hand. Refuse HERE, before the first mutation — the cost is one
164
165
  // `cd`, and it is the exact failure observed in the ProspectPRO session.
165
- const cwdNorm = resolve(cwd).replace(/\\/g, '/');
166
- const wtNorm = resolve(worktreePath).replace(/\\/g, '/');
167
- if (cwdNorm === wtNorm || cwdNorm.startsWith(`${wtNorm}/`)) {
166
+ if (cwdIsInsideWorktree(cwd, worktreePath)) {
168
167
  emit({
169
168
  finished: false,
170
169
  error: 'cwd-inside-worktree',
171
170
  feature,
172
171
  path: worktreePath,
173
172
  root,
174
- hint: `saia do worktree antes do finish — o \`git worktree remove\` não consegue apagar o diretório de trabalho do próprio processo. Rode de novo a partir de "${root}"`,
173
+ hint: `saia do worktree antes do finish — a remoção não consegue apagar o diretório de trabalho do próprio processo. Rode de novo a partir de "${root}"`,
175
174
  });
176
175
  process.exit(1);
177
176
  }
@@ -405,12 +404,17 @@ async function integratePr({ emit, root, feature, expectedBranch, defaultBranch,
405
404
  // ── output helpers ────────────────────────────────────────────────────────
406
405
 
407
406
  /**
408
- * Report the use cases the archive promoted into `.morph/specs/usecases/`.
409
- * Absent when nothing was promoted, so a feature with no use cases keeps the
410
- * exact output shape it had before this existed.
407
+ * Report the use cases the archive promoted into `.morph/specs/usecases/`, and
408
+ * any that were REFUSED for a numbering collision (`ucCollisions` — see
409
+ * `usecase-promoter.js`'s reservation-backed guard). Both absent when there is
410
+ * nothing to report, so a feature with no use cases keeps the exact output
411
+ * shape it had before either existed.
411
412
  */
412
413
  function promotedNote(arch) {
413
- return arch?.promotedUseCases?.length ? { promotedUseCases: arch.promotedUseCases } : {};
414
+ return {
415
+ ...(arch?.promotedUseCases?.length ? { promotedUseCases: arch.promotedUseCases } : {}),
416
+ ...(arch?.refusedUseCases?.length ? { ucCollisions: arch.refusedUseCases } : {}),
417
+ };
414
418
  }
415
419
 
416
420
  function mergeOutput({ feature, branch, worktreePath, teardown, shedBackup }) {
@@ -436,15 +440,25 @@ function teardownExtras(teardown, worktreePath, branch, deleteBranch) {
436
440
  if (teardown.blockers.length) out.reparsePoints = teardown.blockers;
437
441
  if (teardown.ignoredBlocking.length) out.ignoredFiles = teardown.ignoredBlocking;
438
442
  out.cleanupHint = teardown.declineReason;
439
- // The unlink runs before the removal by design (it is what keeps `git
440
- // worktree remove` from following the junctions out into the primary root),
441
- // so a declined removal always passes through a moment with the infra
442
- // loose. The teardown now re-links on that path — report which of the two
443
- // actually happened instead of always announcing the worse one (A4).
443
+ // The unlink runs before the removal by design (it is what keeps the removal
444
+ // from following the junctions out into the primary root), so every
445
+ // non-removal passes through a moment with the infra loose. What happens
446
+ // next depends on WHY, and the two must not be reported alike:
447
+ // REFUSED — we proved removal unsafe, the user keeps working here, so the
448
+ // teardown re-links (A4).
449
+ // FAILED — removal was the intent and a lock got in the way. The infra
450
+ // stays down ON PURPOSE, so the retry (or anything pasted from an old
451
+ // transcript) has nothing to traverse. Say so explicitly, or the user
452
+ // reads a bare "failed" and reaches for the destructive command.
444
453
  out.relinked = teardown.relinked === true;
445
- out.relinkHint = teardown.relinked
446
- ? 'as junctions de infra foram soltas antes da tentativa e RESTAURADAS após a recusa — o worktree segue utilizável'
447
- : `as junctions de infra foram soltas antes desta recusa e não puderam ser restauradas — para continuar no worktree, rode \`morph-spec worktree link --all --target "${worktreePath}"\``;
454
+ if (!teardown.refused) {
455
+ if (teardown.infraLeftUnlinked?.length) out.infraLeftUnlinked = teardown.infraLeftUnlinked;
456
+ out.relinkHint = `a remoção falhou e as junctions de infra foram deixadas DESMONTADAS de propósito — qualquer nova tentativa é segura. Para voltar a trabalhar no worktree, rode \`morph-spec worktree link --all --target "${worktreePath}"\``;
457
+ } else {
458
+ out.relinkHint = teardown.relinked
459
+ ? 'as junctions de infra foram soltas antes da tentativa e RESTAURADAS após a recusa — o worktree segue utilizável'
460
+ : `as junctions de infra foram soltas antes desta recusa e não puderam ser restauradas — para continuar no worktree, rode \`morph-spec worktree link --all --target "${worktreePath}"\``;
461
+ }
448
462
  }
449
463
  return out;
450
464
  }
@@ -6,8 +6,9 @@
6
6
  * worktree session, a resumed session after a phase transition). The handoff
7
7
  * is the sanctioned way to carry context across: derived, regenerable, and
8
8
  * pointer-based (see handoff-generator.js). This command is also called
9
- * in-process by `worktree setup`, `create --worktree` and `advance` — the CLI
10
- * surface exists for the LLM/user to refresh the document on demand.
9
+ * in-process by `worktree setup`, `create --worktree`, `advance` and
10
+ * `approve` — the CLI surface exists for the LLM/user to refresh the
11
+ * document on demand.
11
12
  */
12
13
 
13
14
  import chalk from 'chalk';
@@ -0,0 +1,77 @@
1
+ /**
2
+ * `morph-spec usecase reserve [--count <n>] [--feature <name>] [--json]` —
3
+ * atomically mint the next N `UC-{nn}` numbers, shared across every worktree
4
+ * of this repo. See `usecase-registry.js` for why this exists (worktrees only
5
+ * ever see their own tree, so an independent max+1 scan collides).
6
+ *
7
+ * `--feature` is more than an audit label: `usecase-promoter.js`'s collision
8
+ * guard uses the reservation record to tell a legitimate cross-feature
9
+ * correction (never reserved — reusing a published number by design) from an
10
+ * accidental collision (both features reserved the same id). Passing it is
11
+ * how `morph-plan` gets that protection; omitting it degrades to "reserved,
12
+ * no owner recorded" — still collision-free, just unable to name the
13
+ * conflicting feature if one ever surfaces.
14
+ */
15
+
16
+ import chalk from 'chalk';
17
+ import { existsSync, readdirSync } from 'fs';
18
+ import { join } from 'path';
19
+ import { resolveGitCommonDir } from '../../../framework/hooks/shared/git-paths.js';
20
+ import { reserveUseCases } from '../../lib/specs/usecase-registry.js';
21
+
22
+ /**
23
+ * Best-effort feature-name inference when `--feature` is omitted: only when
24
+ * exactly one active feature exists is the guess unambiguous. Anything else
25
+ * (zero, or more than one) is left null rather than guessed wrong — a wrong
26
+ * guess would poison the collision guard's provenance record.
27
+ */
28
+ function inferActiveFeature(cwd) {
29
+ const featuresDir = join(cwd, '.morph', 'features');
30
+ try {
31
+ if (!existsSync(featuresDir)) return null;
32
+ const entries = readdirSync(featuresDir, { withFileTypes: true }).filter((e) => e.isDirectory());
33
+ return entries.length === 1 ? entries[0].name : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * @param {{ count?: string, feature?: string, json?: boolean, cwd?: string }} [options]
41
+ */
42
+ export function usecaseReserveCommand(options = {}) {
43
+ const cwd = options.cwd || process.cwd();
44
+ const count = Number.parseInt(options.count, 10);
45
+ const n = Number.isInteger(count) && count > 0 ? count : 1;
46
+ const feature = options.feature || inferActiveFeature(cwd) || null;
47
+
48
+ let gitCommonDir = null;
49
+ try { gitCommonDir = resolveGitCommonDir(cwd); } catch { gitCommonDir = null; }
50
+
51
+ let result;
52
+ try {
53
+ result = reserveUseCases(cwd, { feature, count: n, gitCommonDir });
54
+ } catch (error) {
55
+ if (options.json) {
56
+ console.log(JSON.stringify({ reserved: false, error: error.message }));
57
+ process.exit(1);
58
+ }
59
+ console.error(chalk.red(`\n❌ ${error.message}\n`));
60
+ process.exit(1);
61
+ }
62
+
63
+ const warning = gitCommonDir
64
+ ? null
65
+ : 'projeto fora de um repositório git — numeração protegida só localmente; paralelismo entre worktrees NÃO está garantido.';
66
+
67
+ if (options.json) {
68
+ console.log(JSON.stringify({ reserved: true, ...result, feature, warning }));
69
+ process.exit(0);
70
+ }
71
+
72
+ console.log(chalk.green(`\n✅ Reservado: ${result.numbers.join(' ')}`));
73
+ if (feature) console.log(chalk.gray(` feature: ${feature}`));
74
+ if (warning) console.log(chalk.yellow(`⚠️ ${warning}\n`));
75
+ else console.log('');
76
+ process.exit(0);
77
+ }
@@ -53,6 +53,12 @@ function formatVerifyResult(result) {
53
53
  for (const line of result.feedback) lines.push(` ${line}`);
54
54
  }
55
55
 
56
+ if (result.traceability?.warnings?.length > 0) {
57
+ lines.push('');
58
+ lines.push(chalk.yellow('Traceability warnings (advisory — never fails verify):'));
59
+ for (const w of result.traceability.warnings) lines.push(` ⚠ ${w}`);
60
+ }
61
+
56
62
  lines.push('');
57
63
  return lines.join('\n');
58
64
  }
@@ -9,8 +9,8 @@
9
9
  * Deterministic by construction — everything here is derived from feature.json,
10
10
  * tasks.json, decisions.md and the worktree env manifest. The document is
11
11
  * therefore REGENERABLE (never hand-edited, never merged): `morph-spec handoff`
12
- * rebuilds it, and setup/create/advance regenerate it at the moments a new
13
- * session is most likely to pick the feature up.
12
+ * rebuilds it, and setup/create/advance/approve regenerate it at the moments a
13
+ * new session is most likely to pick the feature up.
14
14
  *
15
15
  * Every section is fail-open: a missing tasks.json or a corrupt decisions.md
16
16
  * degrades that section, never the document.
@@ -12,15 +12,29 @@
12
12
  * as a no-op rather than an error.
13
13
  * - **No-op without the folder.** A feature with no use cases promotes nothing.
14
14
  * - **Idempotent.** Re-promoting the same use case rewrites the same content.
15
- * - **Overwrite by ID, not by filename.** `UC-07-old-slug.md` in the archive is
16
- * REPLACED by an incoming `UC-07-new-slug.md`. Keying on the filename would
17
- * leave two files claiming UC-07 the first time a slug is reworded — and the
18
- * `bug` work type exists precisely to correct an existing use case.
15
+ * - **Overwrite by ID, not by filename — with a collision backstop.**
16
+ * `UC-07-old-slug.md` in the archive is REPLACED by an incoming
17
+ * `UC-07-new-slug.md`. Keying on the filename would leave two files
18
+ * claiming UC-07 the first time a slug is reworded — and the `bug` work
19
+ * type exists precisely to correct an existing use case, from a DIFFERENT
20
+ * feature than the one that first published it, sometimes rewording the
21
+ * slug in the same pass. That legitimate case is INDISTINGUISHABLE, by
22
+ * filename and slug alone, from two worktrees that independently minted
23
+ * the SAME number for two UNRELATED use cases (the numbering-collision bug
24
+ * this backstop exists for) — a user has already lost a use case this way
25
+ * in production. The one signal that tells them apart is `usecase-registry.js`'s
26
+ * reservation record: a feature that REPLACES a number it never reserved is
27
+ * reusing a published UC by design (the bug/update flow); a feature that
28
+ * REPLACES a number it DID reserve, and finds someone ELSE'S feature already
29
+ * sitting on that ID, is the collision — refuse that one specific promotion
30
+ * rather than silently destroy the other feature's use case.
19
31
  */
20
32
 
21
33
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, rmSync } from 'fs';
22
- import { join } from 'path';
34
+ import { basename, join, relative } from 'path';
23
35
  import { OUTPUT_SCHEMA } from '../../core/paths/output-schema.js';
36
+ import { resolveGitCommonDir } from '../../../framework/hooks/shared/git-paths.js';
37
+ import { reservationOwner } from './usecase-registry.js';
24
38
 
25
39
  const UC = OUTPUT_SCHEMA.usecases;
26
40
  const UC_FILENAME_RE = new RegExp(UC.filenamePattern);
@@ -35,38 +49,102 @@ export function useCaseId(filename) {
35
49
  }
36
50
 
37
51
  /**
38
- * Rewrite the frontmatter `status:` to `implemented`.
52
+ * Set (or replace) a single top-level frontmatter field, preserving every
53
+ * other line, the original EOL style, and anything after the closing `---`.
39
54
  *
40
- * A file with no frontmatter is copied verbatim: the use case belongs to the
41
- * author, and inventing a header would be a silent edit of their document.
55
+ * A file with no frontmatter block is returned UNCHANGED: the use case
56
+ * belongs to the author, and inventing a header would be a silent edit of
57
+ * their document.
42
58
  *
43
59
  * @param {string} content
60
+ * @param {string} key
61
+ * @param {string} value
44
62
  * @returns {string}
45
63
  */
46
- export function stampImplemented(content) {
64
+ function setFrontmatterField(content, key, value) {
47
65
  const m = /^(?---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content);
48
66
  if (!m || m.index !== 0) return content;
49
67
 
50
68
  const [full, open, body, close] = m;
51
69
  const eol = full.includes('\r\n') ? '\r\n' : '\n';
52
- const statusLine = /^status:[ \t]*.*$/m;
53
- const next = statusLine.test(body)
54
- ? body.replace(statusLine, 'status: implemented')
55
- : `${body}${eol}status: implemented`;
70
+ const fieldLine = new RegExp(`^${key}:[ \\t]*.*$`, 'm');
71
+ const next = fieldLine.test(body)
72
+ ? body.replace(fieldLine, `${key}: ${value}`)
73
+ : `${body}${eol}${key}: ${value}`;
56
74
 
57
75
  return open + next + close + content.slice(full.length);
58
76
  }
59
77
 
78
+ /** Read a single top-level frontmatter field. `null` when absent or there is no frontmatter block. */
79
+ function readFrontmatterField(content, key) {
80
+ const m = /^(?---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content);
81
+ if (!m || m.index !== 0) return null;
82
+ const line = new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, 'm').exec(m[2]);
83
+ return line ? line[1].trim() : null;
84
+ }
85
+
86
+ /**
87
+ * Rewrite the frontmatter `status:` to `implemented`.
88
+ *
89
+ * A file with no frontmatter is copied verbatim: the use case belongs to the
90
+ * author, and inventing a header would be a silent edit of their document.
91
+ *
92
+ * @param {string} content
93
+ * @returns {string}
94
+ */
95
+ export function stampImplemented(content) {
96
+ return setFrontmatterField(content, 'status', 'implemented');
97
+ }
98
+
99
+ /**
100
+ * Stamp the promoting feature's name into `sourceFeature:` — the provenance
101
+ * record the collision guard (below) compares against a reservation to tell a
102
+ * legitimate cross-feature correction from an accidental numbering collision.
103
+ *
104
+ * @param {string} content
105
+ * @param {string} feature
106
+ * @returns {string}
107
+ */
108
+ export function stampSourceFeature(content, feature) {
109
+ return setFrontmatterField(content, 'sourceFeature', feature);
110
+ }
111
+
112
+ /**
113
+ * Build the message for a refused promotion — named clearly enough that the
114
+ * next session (or human) can actually recover, not just "colisão".
115
+ *
116
+ * The recovery instruction has to be honest about WHERE the file sits: by the
117
+ * time this runs, `runArchive` has already moved the feature folder, and its
118
+ * own idempotent short-circuit (`existsSync(archivePath)`) means re-running
119
+ * `archive`/`finish` on this feature promotes NOTHING a second time — so
120
+ * "renumber and re-run finish" would be a lie. The file is wherever `srcDir`
121
+ * actually is (the feature's `2-plan/usecases/`, wherever that folder lives
122
+ * right now — pre- or post-archive, the caller decides), and recovery is
123
+ * either a fresh reservation + manual copy, or editing the archive in place.
124
+ *
125
+ * @returns {string}
126
+ */
127
+ function collisionMessage({ id, incoming, existing, existingFeature, feature, relIncomingPath }) {
128
+ return `${id}: colisão de numeração — "${incoming}" (feature "${feature}") não pôde substituir "${existing}" ` +
129
+ `já promovido no acervo por "${existingFeature}". O arquivo continua em ${relIncomingPath}. ` +
130
+ 'Se for um use case NOVO: renumere-o com `morph-spec usecase reserve` e promova manualmente para ' +
131
+ '.morph/specs/usecases/ (o finish/archive não reprocessa uma feature já arquivada). ' +
132
+ `Se for uma CORREÇÃO do mesmo UC publicado: edite .morph/specs/usecases/${existing} diretamente em vez de reservar um número novo.`;
133
+ }
134
+
60
135
  /**
61
136
  * Copy every use case of a feature into the project's permanent archive.
62
137
  *
63
138
  * @param {string} cwd - project root that owns `.morph/specs/`
64
139
  * @param {string} featureDir - the feature folder holding `2-plan/usecases/`
65
- * @returns {{ promoted: string[], replaced: string[] }} filenames, always arrays
140
+ * @returns {{ promoted: string[], replaced: string[], refused: Array<{id: string,
141
+ * incoming: string, existing: string, existingFeature: string, message: string}> }}
142
+ * filenames, always arrays
66
143
  */
67
144
  export function promoteUseCases(cwd, featureDir) {
68
- const empty = { promoted: [], replaced: [] };
145
+ const empty = { promoted: [], replaced: [], refused: [] };
69
146
  const srcDir = join(featureDir, UC.phaseDir, UC.dirname);
147
+ const feature = basename(featureDir);
70
148
 
71
149
  let names;
72
150
  try {
@@ -80,6 +158,7 @@ export function promoteUseCases(cwd, featureDir) {
80
158
  const destDir = join(cwd, '.morph', 'specs', 'usecases');
81
159
  const promoted = [];
82
160
  const replaced = [];
161
+ const refused = [];
83
162
 
84
163
  try {
85
164
  mkdirSync(destDir, { recursive: true });
@@ -87,6 +166,11 @@ export function promoteUseCases(cwd, featureDir) {
87
166
  return empty;
88
167
  }
89
168
 
169
+ // Resolved ONCE per call — pure filesystem, no subprocess (git-paths.js) —
170
+ // and reused for every collision check below.
171
+ let gitCommonDir = null;
172
+ try { gitCommonDir = resolveGitCommonDir(cwd); } catch { gitCommonDir = null; }
173
+
90
174
  // Existing archive entries, indexed by use-case ID — the key the overwrite
91
175
  // rule is written against.
92
176
  const existingById = new Map();
@@ -99,22 +183,54 @@ export function promoteUseCases(cwd, featureDir) {
99
183
 
100
184
  for (const name of names) {
101
185
  try {
102
- const content = stampImplemented(readFileSync(join(srcDir, name), 'utf8'));
103
186
  const id = useCaseId(name);
104
187
  const stale = id ? existingById.get(id) : null;
105
188
 
106
- // Same ID under a different filename: drop the old file, or the archive
107
- // would end up with two documents claiming the same UC number.
189
+ // Same ID under a different filename: normally the old file is dropped
190
+ // (a slug reword, or the `bug` flow correcting a published UC), or the
191
+ // archive would end up with two documents claiming the same UC number.
192
+ //
193
+ // Backstop: refuse instead when BOTH are true —
194
+ // (a) THIS feature holds a reservation for `id` in usecase-registry.js
195
+ // (it believes it MINTED a new number), and
196
+ // (b) the archive entry already there was promoted by a DIFFERENT
197
+ // feature (its stamped `sourceFeature` says so).
198
+ // A feature correcting a published UC never reserved that UC's number —
199
+ // it reused one already in the acervo — so that legitimate flow never
200
+ // trips this. Two features that each reserved the SAME number (the
201
+ // collision this exists for) always do. No reservation record at all
202
+ // (no git common dir, or a legacy archive entry predating this stamp) is
203
+ // fail-open: nothing to compare against, so nothing is refused.
108
204
  if (stale && stale !== name) {
205
+ let staleFeature = null;
206
+ try { staleFeature = readFrontmatterField(readFileSync(join(destDir, stale), 'utf8'), 'sourceFeature'); } catch { /* unreadable — no signal */ }
207
+ const incomingOwner = id ? reservationOwner(id, { cwd, gitCommonDir }) : null;
208
+
209
+ if (staleFeature && staleFeature !== feature && incomingOwner === feature) {
210
+ refused.push({
211
+ id,
212
+ incoming: name,
213
+ existing: stale,
214
+ existingFeature: staleFeature,
215
+ message: collisionMessage({
216
+ id, incoming: name, existing: stale, existingFeature: staleFeature, feature,
217
+ relIncomingPath: relative(cwd, join(srcDir, name)).replace(/\\/g, '/'),
218
+ }),
219
+ });
220
+ continue; // leave the existing archive entry untouched
221
+ }
222
+
109
223
  rmSync(join(destDir, stale), { force: true });
110
224
  replaced.push(stale);
111
225
  }
112
226
 
227
+ let content = stampImplemented(readFileSync(join(srcDir, name), 'utf8'));
228
+ content = stampSourceFeature(content, feature);
113
229
  writeFileSync(join(destDir, name), content, 'utf8');
114
230
  promoted.push(name);
115
231
  if (id) existingById.set(id, name);
116
232
  } catch { /* one unreadable use case must not sink the rest */ }
117
233
  }
118
234
 
119
- return { promoted, replaced };
235
+ return { promoted, replaced, refused };
120
236
  }