@polymorphism-tech/morph-spec 11.1.0 → 11.2.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 (106) hide show
  1. package/README.md +1 -1
  2. package/bin/morph-spec.js +9 -19
  3. package/docs/CHEATSHEET.md +3 -3
  4. package/docs/QUICKSTART.md +1 -1
  5. package/framework/CLAUDE.md +2 -0
  6. package/framework/MORPH.md +7 -2
  7. package/framework/agents.json +3 -3
  8. package/framework/docs/CLI.md +14 -12
  9. package/framework/evals/review-checklist.md +9 -16
  10. package/framework/hooks/README.md +15 -9
  11. package/framework/hooks/claude-code/core/README.md +2 -2
  12. package/framework/hooks/claude-code/core/chain.js +9 -25
  13. package/framework/hooks/claude-code/core/comment-guard.js +3 -9
  14. package/framework/hooks/claude-code/core/conventional-commit.js +3 -3
  15. package/framework/hooks/claude-code/core/graph-refresh-kick.js +4 -4
  16. package/framework/hooks/claude-code/core/masked-exit.js +4 -3
  17. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  18. package/framework/hooks/claude-code/core/protect-spec-files.js +2 -4
  19. package/framework/hooks/claude-code/core/stack-changed.js +5 -4
  20. package/framework/hooks/claude-code/core/validate-completion.js +15 -12
  21. package/framework/hooks/shared/contract.js +22 -1
  22. package/framework/hooks/shared/git-paths.js +6 -0
  23. package/framework/hooks/shared/graph-freshness.js +3 -3
  24. package/framework/hooks/shared/graph-refresh.js +5 -10
  25. package/framework/hooks/shared/hook-response.js +1 -18
  26. package/framework/hooks/shared/payload-utils.js +12 -1
  27. package/framework/hooks/shared/phase-utils.js +4 -52
  28. package/framework/hooks/shared/report-progress.js +1 -1
  29. package/framework/mcp/registry.json +1 -17
  30. package/framework/rules/dotnet-templates.md +32 -33
  31. package/framework/rules/infrastructure-standards.md +9 -9
  32. package/framework/rules/neon-standards.md +4 -4
  33. package/framework/rules/nextjs-templates.md +10 -11
  34. package/framework/rules/ui-design.md +2 -2
  35. package/framework/schemas/config.schema.json +4 -0
  36. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  37. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  38. package/framework/skills/core/morph-apply/SKILL.md +5 -4
  39. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  40. package/framework/skills/core/morph-uiux/SKILL.md +5 -5
  41. package/framework/standards/integration/mcp/mcp-tools.md +2 -2
  42. package/framework/templates/REGISTRY.json +1 -75
  43. package/framework/templates/docs/plan.md +1 -1
  44. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/Morph.AiKit.Tests.csproj +1 -1
  45. package/framework/templates/infrastructure/docker/docker-compose.template.yml +15 -16
  46. package/package.json +6 -15
  47. package/src/commands/graph/build.js +2 -2
  48. package/src/commands/mcp/mcp-setup.js +6 -4
  49. package/src/commands/project/doctor.js +42 -126
  50. package/src/commands/project/env.js +2 -1
  51. package/src/commands/project/init.js +28 -170
  52. package/src/commands/project/stack-set.js +3 -1
  53. package/src/commands/project/update.js +50 -154
  54. package/src/commands/scaffold/scaffold.js +21 -4
  55. package/src/commands/validation/check.js +12 -10
  56. package/src/commands/validation/prove-red.js +61 -22
  57. package/src/core/paths/output-schema.js +8 -37
  58. package/src/core/templates/template-registry.js +8 -43
  59. package/src/core/templates/template-renderer.js +3 -200
  60. package/src/lib/ai/ai-checks.js +1 -1
  61. package/src/lib/ai/ai-project-scan.js +1 -1
  62. package/src/lib/ai/code-audit.js +2 -2
  63. package/src/lib/check/signals.js +25 -7
  64. package/src/lib/contract/defaults.js +2 -2
  65. package/src/lib/detectors/claude-config-detector.js +0 -52
  66. package/src/lib/detectors/index.js +5 -30
  67. package/src/lib/diff/diff-lines.js +3 -3
  68. package/src/lib/generators/scaffold-generator.js +5 -17
  69. package/src/lib/git/default-branch.js +5 -48
  70. package/src/lib/graph/graph-health.js +1 -1
  71. package/src/lib/graph/graphifyignore.js +3 -4
  72. package/src/lib/graph/sanitize.js +2 -2
  73. package/src/lib/installers/effects.js +0 -13
  74. package/src/lib/installers/mcp-installer.js +5 -17
  75. package/src/lib/installers/memory-installer.js +5 -8
  76. package/src/lib/installers/stack-assets.js +33 -7
  77. package/src/lib/installers/stack-sync.js +4 -4
  78. package/src/lib/plan/checks.js +1 -1
  79. package/src/lib/plan/media.js +3 -3
  80. package/src/lib/plan/plan-parser.js +1 -1
  81. package/src/lib/review-reports.js +8 -14
  82. package/src/lib/scan/worktree-dirs.js +1 -3
  83. package/src/lib/specs/adr-index.js +4 -4
  84. package/src/lib/specs/revocations.js +3 -3
  85. package/src/lib/stack/stack-scan.js +3 -3
  86. package/src/lib/standards/registry.js +1 -1
  87. package/src/lib/standards/verified-against.js +2 -2
  88. package/src/lib/tests-audit/audit.js +2 -2
  89. package/src/scripts/global-install.js +41 -19
  90. package/src/scripts/setup-infra.js +57 -165
  91. package/src/utils/agents-installer.js +8 -30
  92. package/src/utils/claude-settings-manager.js +29 -27
  93. package/src/utils/hooks-installer.js +30 -44
  94. package/src/utils/version-checker.js +2 -31
  95. package/CLAUDE.md +0 -118
  96. package/framework/commands/create-umbraco-lp.md +0 -37
  97. package/framework/commands/migrate-lp-to-umbraco.md +0 -35
  98. package/framework/commands/morph-apply.md +0 -14
  99. package/framework/hooks/shared/spawn-command.js +0 -23
  100. package/framework/templates/CLAUDE.md.core.guide.md +0 -29
  101. package/framework/templates/CLAUDE.md.core.template +0 -22
  102. package/framework/templates/context/ARCHITECTURE.md +0 -106
  103. package/src/commands/context/context-refresh.js +0 -63
  104. package/src/lib/generators/architecture-scanner.js +0 -543
  105. package/src/lib/generators/settings-generator.js +0 -97
  106. package/src/lib/graph/god-nodes.js +0 -65
@@ -1,10 +1,7 @@
1
- import { basename, join, dirname, relative, isAbsolute, resolve } from 'path';
2
- import { fileURLToPath } from 'url';
1
+ import { basename, join, relative, isAbsolute, resolve } from 'path';
3
2
  import { spawnSync } from 'child_process';
4
- import { existsSync, readdirSync, readFileSync } from 'fs';
3
+ import { existsSync, readdirSync } from 'fs';
5
4
  import { homedir } from 'os';
6
-
7
- const __dirname = dirname(fileURLToPath(import.meta.url));
8
5
  import ora from 'ora';
9
6
  import chalk from 'chalk';
10
7
  import { logger } from '../../utils/logger.js';
@@ -19,8 +16,7 @@ import {
19
16
  checkCLIOutdated,
20
17
  checkProjectOutdated,
21
18
  saveProjectMorphVersion,
22
- getUpdateInstructions,
23
- detectInstallMethod,
19
+ CLI_UPDATE_COMMAND,
24
20
  getInstalledCLIVersion,
25
21
  majorJump,
26
22
  MAJOR_JUMP_LIMIT
@@ -31,7 +27,9 @@ import { installAgents } from '../../utils/agents-installer.js';
31
27
  import { injectMorphImport } from '../../utils/claude-md-injector.js';
32
28
  import { getProjectTags } from '../../lib/stack-filter.js';
33
29
  import { detectStackTags, mergeDetectedTags } from '../../lib/installers/stack-sync.js';
34
- import { updateClaudeMdAgentsBlock, installRulesForStack, installCommandsForStack } from '../../scripts/setup-infra.js';
30
+ import { updateClaudeMdAgentsBlock } from '../../scripts/setup-infra.js';
31
+ import { installRulesForStack } from '../../lib/installers/rules-installer.js';
32
+ import { installCommandsForStack } from '../../lib/installers/stack-assets.js';
35
33
  import { reconcileLegacyTemplatesCopy } from '../../lib/installers/templates-reconcile.js';
36
34
  import { createEffects } from '../../lib/installers/effects.js';
37
35
  import { syncStackTooling } from '../../lib/installers/stack-tooling.js';
@@ -40,16 +38,10 @@ import {
40
38
  writeGraphifyignore, describeOutdatedIgnore, graphifyignoreTracked,
41
39
  } from '../../lib/graph/graphifyignore.js';
42
40
 
41
+ // Throws on an unreadable file: the clean deletes `.morph/config/`, and a default written over it loses the contract.
43
42
  async function backupUserConfig(morphPath) {
44
- try {
45
- const configPath = join(morphPath, 'config', 'config.json');
46
- if (await pathExists(configPath)) {
47
- const config = await readJson(configPath);
48
- return config;
49
- }
50
- } catch (error) {
51
- }
52
- return null;
43
+ const configPath = join(morphPath, 'config', 'config.json');
44
+ return (await pathExists(configPath)) ? readJson(configPath) : null;
53
45
  }
54
46
 
55
47
  export function frameworkDirsToClean(morphPath, targetPath) {
@@ -97,12 +89,7 @@ function sweepRemove(dir, fx) {
97
89
  function cleanFrameworkDirs(morphPath, targetPath, fx) {
98
90
  const cleaned = [];
99
91
  for (const dir of frameworkDirsToClean(morphPath, targetPath)) {
100
- try {
101
- if (existsSync(dir)) {
102
- cleaned.push({ dir, files: sweepRemove(dir, fx) });
103
- }
104
- } catch (error) {
105
- }
92
+ if (existsSync(dir)) cleaned.push({ dir, files: sweepRemove(dir, fx) });
106
93
  }
107
94
  return cleaned;
108
95
  }
@@ -125,7 +112,7 @@ function restoreUserConfig(morphPath, targetPath, configBackup, currentVersion,
125
112
  }
126
113
 
127
114
  /** Sonda separada da mutação: ler acontece nos dois modos, e é o que faz previsão e execução concordarem. */
128
- export function stateJsonIsTracked(targetPath) {
115
+ function stateJsonIsTracked(targetPath) {
129
116
  try {
130
117
  const isRepo = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], {
131
118
  cwd: targetPath, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore']
@@ -200,7 +187,6 @@ const VERB_GROUPS = {
200
187
  writeFile: 'Escrever',
201
188
  writeJson: 'Escrever (JSON)',
202
189
  mergeJson: 'Mesclar (JSON)',
203
- spawn: 'Executar',
204
190
  gitIndex: 'Índice do git',
205
191
  };
206
192
 
@@ -210,25 +196,12 @@ function isUnder(path, root) {
210
196
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
211
197
  }
212
198
 
213
- // O `target` de um spawn é o binário (`node`): classifica pelo script em `effect.args`, o array —
214
- // um split do `detail` por espaço quebra em caminho com espaço.
215
- function effectLocation(effect) {
216
- if (effect.verb !== 'spawn') return effect.target;
217
- const args = Array.isArray(effect.args) ? effect.args : [];
218
- const script = args.find((a) => /\.(js|mjs|cjs)$/.test(String(a)));
219
- return script || effect.target;
220
- }
221
-
222
199
  export function renderEffectsReport(effects, context) {
223
- const { targetPath, packageRoot, dryRun, cleaned = [], notices = [] } = context;
200
+ const { targetPath, dryRun, cleaned = [], notices = [] } = context;
224
201
  const globalClaudeDir = join(homedir(), '.claude');
225
202
 
226
203
  logger.blank();
227
- // Não diz "nem executado": em dry o spawn de `generate-refs.js --check` roda.
228
- logger.info(dryRun
229
- ? 'Relatório do --dry-run — nada foi escrito, apagado nem removido '
230
- + '(o único processo executado é a variante `--check` do gerador, que só verifica):'
231
- : 'Efeitos desta execução:');
204
+ logger.info(dryRun ? 'Relatório do --dry-run — nada foi escrito, apagado nem executado:' : 'Efeitos desta execução:');
232
205
  logger.blank();
233
206
 
234
207
  for (const notice of notices) logger.warn(notice);
@@ -247,13 +220,10 @@ export function renderEffectsReport(effects, context) {
247
220
  && cleanedRoots.some((root) => e.target === root || isUnder(e.target, root));
248
221
 
249
222
  const outside = [];
250
- const inPackage = [];
251
223
  const rest = [];
252
224
  for (const e of effects) {
253
225
  if (insideCleaned(e)) continue; // já contabilizado acima, e são centenas
254
- const where = effectLocation(e);
255
- if (isUnder(where, globalClaudeDir) || where === globalClaudeDir) outside.push(e);
256
- else if (isUnder(where, packageRoot) && !isUnder(where, targetPath)) inPackage.push(e);
226
+ if (isUnder(e.target, globalClaudeDir) || e.target === globalClaudeDir) outside.push(e);
257
227
  else rest.push(e);
258
228
  }
259
229
 
@@ -276,26 +246,14 @@ export function renderEffectsReport(effects, context) {
276
246
  logger.blank();
277
247
  }
278
248
 
279
- if (inPackage.length) {
280
- logger.info('DENTRO do pacote da CLI (num `npm link` isto é o repositório do framework):');
281
- for (const e of inPackage) logger.dim(line(e));
282
- logger.blank();
283
- }
284
-
285
249
  logger.dim(`Total: ${effects.length} efeito(s) — ${cleaned.length} diretório(s) apagado(s) por inteiro, `
286
- + `${outside.length} fora do projeto, ${inPackage.length} dentro do pacote da CLI.`);
287
- logger.blank();
288
-
289
- // Risco conhecido, reportado em vez de escondido: o backup
290
- // de `config.json` só existe em memória durante a execução.
291
- logger.dim('Nota: durante uma execução real o backup de `.morph/config/config.json` existe apenas '
292
- + 'em memória — uma falha no meio do caminho deixa o arquivo apagado. Follow-up nomeado.');
250
+ + `${outside.length} fora do projeto.`);
293
251
  logger.blank();
294
252
  }
295
253
 
296
254
  export async function updateCommand(options = {}) {
297
- const targetPath = process.cwd();
298
- const contentDir = getContentDir();
255
+ const targetPath = options.path || process.cwd();
256
+ const frameworkDir = join(getContentDir(), 'framework');
299
257
  const morphPath = join(targetPath, '.morph');
300
258
  const dryRun = Boolean(options.dryRun);
301
259
  const force = Boolean(options.force);
@@ -340,25 +298,24 @@ export async function updateCommand(options = {}) {
340
298
  logger.info('Please update the CLI first:');
341
299
  logger.blank();
342
300
 
343
- const method = detectInstallMethod();
344
- const instructions = getUpdateInstructions(method);
345
-
346
- instructions.forEach(line => {
347
- if (line === '') {
348
- logger.blank();
349
- } else if (line.startsWith('Or ')) {
350
- logger.dim(line);
351
- } else {
352
- logger.box([line]);
353
- }
354
- });
355
-
301
+ logger.box([CLI_UPDATE_COMMAND]);
356
302
  logger.blank();
357
303
  logger.dim('Then run "morph-spec update" again.');
358
- process.exit(0);
304
+ process.exitCode = 1;
305
+ return { refused: true, reason: 'cli-outdated', effects: fx.list() };
359
306
  }
360
307
  }
361
308
 
309
+ let configBackup;
310
+ try {
311
+ configBackup = await backupUserConfig(morphPath);
312
+ } catch (error) {
313
+ logger.error(`Recusado: \`.morph/config/config.json\` não é JSON legível (${error.message}).`);
314
+ logger.dim(' O update apaga `.morph/config/` e regrava o contrato a partir dele: conserte o arquivo e rode de novo.');
315
+ process.exitCode = 1;
316
+ return { refused: true, reason: 'config-unreadable', effects: fx.list() };
317
+ }
318
+
362
319
  const needsInitialization = !(await pathExists(morphPath));
363
320
  const targetVersion = cliCheck.current ?? getInstalledCLIVersion();
364
321
  const verdict = needsInitialization
@@ -401,81 +358,27 @@ export async function updateCommand(options = {}) {
401
358
  let cleaned = [];
402
359
 
403
360
  try {
404
- updateSpinner.text = 'Backing up user configuration...';
405
- const configBackup = await backupUserConfig(morphPath);
406
- if (configBackup) {
407
- logger.dim(' ✓ User config backed up');
408
- }
409
-
410
361
  updateSpinner.text = 'Cleaning old framework files...';
411
362
  cleaned = cleanFrameworkDirs(morphPath, targetPath, fx);
363
+ // Written back at once: a failure in the installs below must not leave the project without its contract.
364
+ if (configBackup) restoreUserConfig(morphPath, targetPath, configBackup, cliCheck.current, fx);
412
365
  logger.dim(' ✓ Old framework files removed');
413
366
 
414
- const updateTemplates = !options.standards || options.templates;
415
- const updateStandards = !options.templates || options.standards;
416
-
417
- let templatesReconcile = 'absent';
418
- if (updateTemplates) {
419
- updateSpinner.text = 'Checking for a legacy templates copy...';
420
- const templatesDest = join(morphPath, 'framework', 'templates');
421
- templatesReconcile = reconcileLegacyTemplatesCopy(templatesDest, projectCheck.current, fx);
422
- }
423
-
424
- if (updateStandards) {
425
- updateSpinner.text = 'Updating standards...';
426
- const standardsSrc = join(contentDir, 'framework', 'standards');
427
- const standardsDest = join(morphPath, 'framework', 'standards');
428
- fx.copyDir(standardsSrc, standardsDest);
429
- }
430
-
431
- updateSpinner.text = 'Updating hooks...';
432
- const hooksSrc = join(__dirname, '..', '..', '..', 'framework', 'hooks');
433
- const hooksDest = join(morphPath, 'framework', 'hooks');
434
- if (await pathExists(hooksSrc)) {
435
- fx.copyDir(hooksSrc, hooksDest);
436
- }
437
-
438
- updateSpinner.text = 'Updating agents configuration...';
439
- const agentsSrc = join(__dirname, '..', '..', '..', 'framework', 'agents.json');
440
- const agentsDest = join(morphPath, 'framework', 'agents.json');
441
- if (await pathExists(agentsSrc)) {
442
- fx.copyFile(agentsSrc, agentsDest);
443
- }
367
+ updateSpinner.text = 'Checking for a legacy templates copy...';
368
+ const templatesReconcile = reconcileLegacyTemplatesCopy(join(morphPath, 'framework', 'templates'), projectCheck.current, fx);
444
369
 
445
- updateSpinner.text = 'Updating charter, schemas and evals...';
446
- const canonicalFrameworkDir = join(__dirname, '..', '..', '..', 'framework');
447
- fx.copyFile(join(canonicalFrameworkDir, 'MORPH.md'), join(morphPath, 'framework', 'MORPH.md'));
448
- const deadPhases = join(morphPath, 'framework', 'phases.json');
449
- if (existsSync(deadPhases)) fx.remove(deadPhases);
450
- for (const dir of ['schemas', 'evals']) {
451
- const src = join(canonicalFrameworkDir, dir);
452
- if (await pathExists(src)) {
453
- fx.copyDir(src, join(morphPath, 'framework', dir));
454
- }
370
+ updateSpinner.text = 'Updating standards, hooks, charter, schemas and evals...';
371
+ for (const dir of ['standards', 'hooks', 'schemas', 'evals']) {
372
+ fx.copyDir(join(frameworkDir, dir), join(morphPath, 'framework', dir));
455
373
  }
456
- // CLI.md instala achatado em .morph/framework/CLI.md, por isso fica fora do loop acima.
457
- const cliMdSrc = join(canonicalFrameworkDir, 'docs', 'CLI.md');
458
- if (await pathExists(cliMdSrc)) {
459
- fx.copyFile(cliMdSrc, join(morphPath, 'framework', 'CLI.md'));
460
- }
461
-
462
- // Escreve DENTRO do pacote da CLI (o repositório do framework num `npm link`); em dry roda `--check`.
463
- updateSpinner.text = 'Syncing generated refs...';
464
- try {
465
- const generateScript = join(__dirname, '..', '..', '..', 'scripts', 'generate-refs.js');
466
- if (existsSync(generateScript)) {
467
- const result = fx.spawn(process.execPath, [generateScript], {
468
- dryRunArgs: [generateScript, '--check'],
469
- });
470
- if (result && result.status === 0 && !dryRun) {
471
- logger.dim(' ✓ Generated refs synced (phase-utils.js, skill outputs)');
472
- }
473
- }
474
- } catch {
374
+ fx.copyFile(join(frameworkDir, 'agents.json'), join(morphPath, 'framework', 'agents.json'));
375
+ fx.copyFile(join(frameworkDir, 'MORPH.md'), join(morphPath, 'framework', 'MORPH.md'));
376
+ fx.copyFile(join(frameworkDir, 'docs', 'CLI.md'), join(morphPath, 'framework', 'CLI.md'));
377
+ for (const dead of [join(morphPath, 'framework', 'phases.json'), join(morphPath, 'context', 'README.md')]) {
378
+ if (existsSync(dead)) fx.remove(dead);
475
379
  }
476
380
 
477
381
  updateSpinner.text = 'Setting up Claude Code integration...';
478
- const frameworkDir = join(__dirname, '..', '..', '..', 'framework');
479
382
  const claudeDest = join(targetPath, '.claude');
480
383
 
481
384
  // MUST come from the pre-clean backup: cleanFrameworkDirs() deleted .morph/config/ and re-reading
@@ -537,9 +440,8 @@ export async function updateCommand(options = {}) {
537
440
  }
538
441
 
539
442
  updateSpinner.text = 'Syncing statusline to ~/.claude/...';
540
- const HOOKS_SRC = join(__dirname, '..', '..', '..', 'framework', 'hooks', 'claude-code');
541
443
  try {
542
- await installGlobalStatusline(HOOKS_SRC, null, { fx });
444
+ await installGlobalStatusline(join(frameworkDir, 'hooks', 'claude-code'), null, { fx });
543
445
  } catch {
544
446
  logger.dim(' ⚠ Could not install statusline globally (non-critical)');
545
447
  }
@@ -606,14 +508,10 @@ export async function updateCommand(options = {}) {
606
508
 
607
509
  logger.blank();
608
510
  logger.info('Updated files:');
609
- if (updateTemplates) {
610
- if (templatesReconcile === 'removed-legacy') {
611
- logger.dim(' ✓ .morph/framework/templates/ (legacy installer copy removed — resolved from package)');
612
- } else if (templatesReconcile === 'preserved-override') {
613
- logger.dim(' ⚠ .morph/framework/templates/ (local override present — preserved untouched, not updated)');
614
- } else {
615
- logger.dim(' · .morph/framework/templates/ (not present — resolved from package, no local override)');
616
- }
511
+ if (templatesReconcile === 'removed-legacy') {
512
+ logger.dim(' ✓ .morph/framework/templates/ (legacy installer copy removed — resolved from package)');
513
+ } else if (templatesReconcile === 'preserved-override') {
514
+ logger.dim(' ⚠ .morph/framework/templates/ (local override present — preserved untouched, not updated)');
617
515
  }
618
516
 
619
517
  // Counts make a silent stack-filter downgrade visible (a dotnet project with "1 persona");
@@ -630,20 +528,18 @@ export async function updateCommand(options = {}) {
630
528
  if (tooling?.registries.length) logger.dim(` ✓ components.json (+ ${tooling.registries.join(', ')})`);
631
529
  if (graphIgnore?.migrated) {
632
530
  logger.dim(' ✓ .graphifyignore (dublês, fixtures e helpers de teste voltam ao grafo da raiz no próximo refresh');
633
- logger.dim(' em background — início de sessão ou comando git do agente; numa worktree: morph-spec graph refresh)');
531
+ logger.dim(' em background, depois de um comando git do agente; numa worktree: morph-spec graph refresh)');
634
532
  }
635
533
  if (legacyStateRemoved) {
636
534
  logger.dim(' ✓ .morph/state.json removido: a feature agora é a pasta do branch');
637
535
  logger.warn('Commite a remoção do .morph/state.json.');
638
536
  }
639
537
  logger.blank();
640
- logger.info('Your config.json was preserved.');
538
+ if (configBackup) logger.info('Your config.json was preserved.');
641
539
  }
642
540
 
643
541
  // O resumo sai de `list()` NOS DOIS MODOS: um ponto de emissão esquecido some das duas saídas.
644
- renderEffectsReport(fx.list(), {
645
- targetPath, packageRoot: contentDir, dryRun, cleaned, notices,
646
- });
542
+ renderEffectsReport(fx.list(), { targetPath, dryRun, cleaned, notices });
647
543
 
648
544
  return { refused: false, dryRun, effects: fx.list() };
649
545
  } catch (error) {
@@ -1,11 +1,14 @@
1
1
  import chalk from 'chalk';
2
+ import { readFileSync, statSync } from 'fs';
2
3
  import { relative } from 'path';
3
4
  import { logger } from '../../utils/logger.js';
4
5
  import {
5
6
  scaffoldDotnetSlice,
6
7
  scaffoldNextjsFeature,
7
8
  detectNamespace,
9
+ toPascalCase,
8
10
  } from '../../lib/generators/scaffold-generator.js';
11
+ import { getTemplateById, resolveFrameworkTemplatePath } from '../../core/templates/template-registry.js';
9
12
 
10
13
  const KEBAB_REGEX = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
11
14
 
@@ -47,12 +50,12 @@ export async function scaffoldDotnetCommand(feature, sliceName, options) {
47
50
  const namespace = options.namespace || detectNamespace(outputDir);
48
51
  if (!namespace) {
49
52
  logger.error('Could not detect namespace');
50
- logger.dim('No .csproj or .morph/config.json found. Use --namespace <ns> to specify.');
53
+ logger.dim('No .csproj and no project.name in .morph/config/config.json. Use --namespace <ns> to specify.');
51
54
  process.exit(1);
52
55
  }
53
56
 
54
- const pascalFeature = feature.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
55
- const pascalSlice = sliceName.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
57
+ const pascalFeature = toPascalCase(feature);
58
+ const pascalSlice = toPascalCase(sliceName);
56
59
 
57
60
  logger.header('Scaffolding .NET VSA Slice');
58
61
  logger.dim(`Feature: ${pascalFeature}`);
@@ -83,7 +86,7 @@ export async function scaffoldNextjsCommand(feature, options) {
83
86
 
84
87
  const outputDir = options.outputDir || process.cwd();
85
88
 
86
- const pascalFeature = feature.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
89
+ const pascalFeature = toPascalCase(feature);
87
90
 
88
91
  logger.header('Scaffolding Next.js Feature');
89
92
  logger.dim(`Feature: ${pascalFeature}`);
@@ -104,3 +107,17 @@ export async function scaffoldNextjsCommand(feature, options) {
104
107
  process.exit(1);
105
108
  }
106
109
  }
110
+
111
+ /** Prints a package template verbatim: templates are never copied into the project. */
112
+ export function scaffoldShowCommand(templateId) {
113
+ if (!getTemplateById(templateId)) {
114
+ logger.error(`Template "${templateId}" not found in the package registry`);
115
+ process.exit(1);
116
+ }
117
+ const path = resolveFrameworkTemplatePath(templateId);
118
+ if (statSync(path).isDirectory()) {
119
+ logger.error(`Template "${templateId}" is a whole project, not a single file`);
120
+ process.exit(1);
121
+ }
122
+ process.stdout.write(readFileSync(path, 'utf-8'));
123
+ }
@@ -6,10 +6,10 @@ import { contractExists, NO_CONTRACT_MESSAGE } from '../../../framework/hooks/sh
6
6
  import { readMorphConfig } from '../../lib/config/project-config.js';
7
7
  import { getAbsoluteOutputPath } from '../../core/paths/output-schema.js';
8
8
  import { featureFromBranch } from '../../../framework/hooks/shared/feature-slug.js';
9
- import { git } from '../../lib/diff/diff-lines.js';
10
9
  import { changedFiles, finalSignals, planSignals, reportSignals, reviewSignals, riskSignals, signalText, sizeSignals, uncommittedSignals } from '../../lib/check/signals.js';
11
10
  import { reviewReports } from '../../lib/review-reports.js';
12
- import { worktreeEnv } from '../project/env.js';
11
+ import { currentBranch, worktreeEnv } from '../project/env.js';
12
+ import { restorePendingProveRed } from './prove-red.js';
13
13
  import { recordAttempt, stuckSignal } from '../../lib/check/attempts.js';
14
14
 
15
15
  const TIERS = ['fast', 'full', 'e2e'];
@@ -46,10 +46,6 @@ function readReport(root, feature) {
46
46
  try { return readFileSync(getAbsoluteOutputPath(root, feature, 'implementReport'), 'utf8'); } catch { return ''; }
47
47
  }
48
48
 
49
- function currentBranch(root) {
50
- try { return git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).trim(); } catch { return null; }
51
- }
52
-
53
49
  /** `## Resultado` is the line the orchestrator reads: it opens the PR as ready or as a draft labelled precisa-humano. */
54
50
  export function writeResult(root, feature, result) {
55
51
  const path = getAbsoluteOutputPath(root, feature, 'implementReport');
@@ -57,7 +53,7 @@ export function writeResult(root, feature, result) {
57
53
  for (const s of result.signals) lines.push(`- ${signalText(s)}`);
58
54
  const section = `${lines.join('\n')}\n`;
59
55
  const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
60
- const rest = text.replace(/\n?## Resultado\n[\s\S]*?(?=\n## |$)/, '').trimEnd();
56
+ const rest = text.replace(/(\r?\n)?## Resultado\r?\n[\s\S]*?(?=\r?\n## |$)/, '').trimEnd();
61
57
  mkdirSync(dirname(path), { recursive: true });
62
58
  writeFileSync(path, `${rest ? `${rest}\n\n` : ''}${section}`);
63
59
  return path;
@@ -79,11 +75,11 @@ export function runCheck(root, { tier = 'fast', feature = null, final = false }
79
75
  ...planSignals(checks, limits),
80
76
  ...reportSignals(reportText),
81
77
  ...(closing ? finalSignals(checks, reportText, runs) : []),
82
- ...(closing && feature ? reviewSignals(reviewReports(root, feature), (checks?.checks ?? []).map((c) => c.id)) : []),
78
+ ...(closing && feature ? reviewSignals(reviewReports(root, feature), (checks?.checks ?? []).map((c) => c.id), root) : []),
83
79
  ...(final ? uncommittedSignals(root) : []),
84
80
  ...(files ? [...riskSignals(files, config.project?.risk), ...sizeSignals(files, limits)] : []),
85
81
  ];
86
- const attempt = recordAttempt(root, currentBranch(root), failures);
82
+ const attempt = recordAttempt(root, currentBranch(root) ?? 'HEAD', failures);
87
83
  const stuck = stuckSignal(attempt, limits);
88
84
  if (stuck) signals.push(stuck);
89
85
  if (failures.length) signals.push({ kind: 'vermelho', onde: failures.map((f) => f.id).join(', ') });
@@ -104,8 +100,14 @@ export function checkCommand(options = {}) {
104
100
  process.exit(2);
105
101
  }
106
102
  const feature = options.feature || featureFromBranch(root);
103
+ if (options.report && !feature) {
104
+ console.error(chalk.red('--report fora de um branch (HEAD solto): não há pasta de feature para gravar o ## Resultado. Passe --feature.'));
105
+ process.exit(2);
106
+ }
107
+ const recovered = restorePendingProveRed(root);
108
+ if (recovered.length) console.log(chalk.yellow(`Restaurado o que um prove-red interrompido deixou revertido: ${recovered.join(', ')}`));
107
109
  const result = runCheck(root, { tier, feature, final: Boolean(options.report) });
108
- if (options.report && feature) result.reportPath = writeResult(root, feature, result);
110
+ if (options.report) result.reportPath = writeResult(root, feature, result);
109
111
 
110
112
  if (options.json) {
111
113
  console.log(JSON.stringify(result, null, 2));
@@ -2,8 +2,13 @@ import chalk from 'chalk';
2
2
  import { execFileSync, spawnSync } from 'child_process';
3
3
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
4
4
  import { dirname, join } from 'path';
5
+ import { contractExists, NO_CONTRACT_MESSAGE } from '../../../framework/hooks/shared/contract.js';
6
+ import { featureFromBranch } from '../../../framework/hooks/shared/feature-slug.js';
5
7
  import { detectDefaultBranch } from '../../lib/git/default-branch.js';
6
8
  import { diffLines, fileClass } from '../../lib/diff/diff-lines.js';
9
+ import { worktreeEnv } from '../project/env.js';
10
+
11
+ const TEST_TIMEOUT_MS = 30 * 60 * 1000;
7
12
 
8
13
  const git = (cwd, args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
9
14
 
@@ -26,16 +31,61 @@ function baseContent(cwd, base, path) {
26
31
  }
27
32
 
28
33
  function runTest(cwd, command) {
29
- const r = spawnSync(command, { cwd, shell: true, stdio: 'pipe', encoding: 'utf8' });
34
+ const r = spawnSync(command, {
35
+ cwd, shell: true, stdio: 'pipe', encoding: 'utf8', timeout: TEST_TIMEOUT_MS, windowsHide: true,
36
+ env: { ...process.env, ...worktreeEnv(cwd) },
37
+ });
30
38
  return r.status === 0 ? 'pass' : 'fail';
31
39
  }
32
40
 
41
+ function writeTree(cwd, path, content) {
42
+ if (content === null) rmSync(join(cwd, path), { force: true });
43
+ else {
44
+ mkdirSync(dirname(join(cwd, path)), { recursive: true });
45
+ writeFileSync(join(cwd, path), content);
46
+ }
47
+ }
48
+
49
+ // Per worktree and outside the tree: a killed run leaves the reverted files with their only copy here.
50
+ function backupDir(cwd) {
51
+ return join(git(cwd, ['rev-parse', '--absolute-git-dir']).trim(), 'morph-prove-red');
52
+ }
53
+
54
+ function saveBackup(dir, cwd, targets) {
55
+ rmSync(dir, { recursive: true, force: true });
56
+ mkdirSync(dir, { recursive: true });
57
+ const files = targets.map((path, i) => {
58
+ const existed = existsSync(join(cwd, path));
59
+ if (existed) writeFileSync(join(dir, String(i)), readFileSync(join(cwd, path)));
60
+ return { path, existed };
61
+ });
62
+ writeFileSync(join(dir, 'manifest.json'), JSON.stringify({ files }));
63
+ }
64
+
65
+ function restoreBackup(dir, cwd) {
66
+ const { files } = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8'));
67
+ files.forEach(({ path, existed }, i) => writeTree(cwd, path, existed ? readFileSync(join(dir, String(i))) : null));
68
+ rmSync(dir, { recursive: true, force: true });
69
+ return files.map((f) => f.path);
70
+ }
71
+
72
+ /** Puts back what a `prove-red` killed mid-run left reverted; the paths restored, `[]` when there was nothing. */
73
+ export function restorePendingProveRed(cwd) {
74
+ try {
75
+ const dir = backupDir(cwd);
76
+ return existsSync(join(dir, 'manifest.json')) ? restoreBackup(dir, cwd) : [];
77
+ } catch {
78
+ return [];
79
+ }
80
+ }
81
+
33
82
  /**
34
83
  * The "see it fail without the change" proof, done by the CLI: run the scenario's test with the change,
35
84
  * put the feature's production code back to the merge-base, run it again, restore. Only `code` files
36
- * are reverted (never tests), and the restore runs in `finally` from an in-memory copy.
85
+ * are reverted (never tests), from a copy on disk that the next run restores if this one is killed.
37
86
  */
38
87
  export function proveRed(cwd, { test, files = null }) {
88
+ const recovered = restorePendingProveRed(cwd);
39
89
  const base = mergeBase(cwd);
40
90
  if (!base) return { code: 2, out: { error: 'no-base', hint: 'sem merge-base com a branch padrão: não há "sem a mudança" para comparar' } };
41
91
  const changed = diffLines(cwd, base).filter((f) => fileClass(f.path) === 'code').map((f) => f.path);
@@ -49,41 +99,30 @@ export function proveRed(cwd, { test, files = null }) {
49
99
  return { code: 2, out: { withChange, withoutChange: null, reverted: [], hint: 'o teste já está vermelho COM a mudança: conserte antes de provar' } };
50
100
  }
51
101
 
52
- const saved = new Map(targets.map((p) => [p, existsSync(join(cwd, p)) ? readFileSync(join(cwd, p)) : null]));
102
+ const dir = backupDir(cwd);
103
+ saveBackup(dir, cwd, targets);
53
104
  let withoutChange;
54
105
  try {
55
- for (const path of targets) {
56
- const old = baseContent(cwd, base, path);
57
- if (old === null) rmSync(join(cwd, path), { force: true });
58
- else {
59
- mkdirSync(dirname(join(cwd, path)), { recursive: true });
60
- writeFileSync(join(cwd, path), old);
61
- }
62
- }
106
+ for (const path of targets) writeTree(cwd, path, baseContent(cwd, base, path));
63
107
  withoutChange = runTest(cwd, test);
64
108
  } finally {
65
- for (const [path, content] of saved) {
66
- if (content === null) rmSync(join(cwd, path), { force: true });
67
- else {
68
- mkdirSync(dirname(join(cwd, path)), { recursive: true });
69
- writeFileSync(join(cwd, path), content);
70
- }
71
- }
109
+ restoreBackup(dir, cwd);
72
110
  }
73
111
 
74
- const out = { base, withChange, withoutChange, reverted: targets };
112
+ const out = { base, withChange, withoutChange, reverted: targets, ...(recovered.length ? { recovered } : {}) };
75
113
  if (withoutChange === 'pass') {
76
114
  return { code: 1, out: { ...out, hint: 'o teste passa SEM a mudança: ele não prova o cenário (filtro errado, ou asserção que já era verdade)' } };
77
115
  }
78
116
  return { code: 0, out };
79
117
  }
80
118
 
81
- export function proveRedCommand(feature, options = {}) {
119
+ export function proveRedCommand(featureArg, options = {}) {
82
120
  const cwd = process.cwd();
83
- if (!options.test) {
84
- console.error(chalk.red('\n❌ --test "<comando do teste do cenário>" é obrigatório\n'));
121
+ if (!contractExists(cwd)) {
122
+ console.error(chalk.red(NO_CONTRACT_MESSAGE));
85
123
  process.exit(2);
86
124
  }
125
+ const feature = featureArg || featureFromBranch(cwd) || 'feature';
87
126
  const files = options.files ? String(options.files).split(',').map((f) => f.trim().replace(/\\/g, '/')).filter(Boolean) : null;
88
127
  const { code, out } = proveRed(cwd, { test: options.test, files });
89
128
  const payload = { feature, ...out };
@@ -1,35 +1,23 @@
1
1
  import { join } from 'path';
2
2
 
3
3
  export const OUTPUT_SCHEMA = {
4
- plan: { filename: 'plan.md', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
5
- checks: { filename: 'checks.json', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
6
- planCritique: { filename: 'critica.md', phaseDir: '2-plan', phase: 'plan', protected: false },
4
+ plan: { filename: 'plan.md', phaseDir: '2-plan' },
5
+ checks: { filename: 'checks.json', phaseDir: '2-plan' },
7
6
 
8
- uiMockups: { filename: 'mockups.md', phaseDir: '1-design', phase: 'uiux', protected: true, approvalGate: 'uiux' },
7
+ uiMockups: { filename: 'mockups.md', phaseDir: '1-design' },
9
8
 
10
- implementReport: { filename: 'report.md', phaseDir: '3-implement', phase: 'implement', protected: false },
11
- evidencias: { dirname: 'evidencias', filenamePattern: '^C\\d+\\.md$', displayFilename: '{Cn}.md',
12
- phaseDir: '3-implement', phase: 'implement', protected: false, multi: true },
9
+ implementReport: { filename: 'report.md', phaseDir: '3-implement' },
10
+ evidencias: { dirname: 'evidencias', phaseDir: '3-implement', multi: true },
13
11
 
14
- verifierReport: { filename: 'verifier.md', phaseDir: '4-review', phase: 'review', protected: false },
15
- reviewerReport: { filename: 'reviewer.md', phaseDir: '4-review', phase: 'review', protected: false },
16
- securityReport: { filename: 'security.md', phaseDir: '4-review', phase: 'review', protected: false },
12
+ verifierReport: { filename: 'verifier.md', phaseDir: '4-review' },
13
+ reviewerReport: { filename: 'reviewer.md', phaseDir: '4-review' },
14
+ securityReport: { filename: 'security.md', phaseDir: '4-review' },
17
15
  };
18
16
 
19
17
  function leafSegment(entry) {
20
18
  return entry.multi ? entry.dirname : entry.filename;
21
19
  }
22
20
 
23
- /** For `multi` types this is the directory holding the N files. */
24
- export function getOutputPath(featureName, outputType) {
25
- const entry = OUTPUT_SCHEMA[outputType];
26
- if (!entry) {
27
- throw new Error(`Unknown output type: "${outputType}". Valid types: ${Object.keys(OUTPUT_SCHEMA).join(', ')}`);
28
- }
29
- return join('.morph', 'features', featureName, entry.phaseDir, leafSegment(entry))
30
- .replace(/\\/g, '/');
31
- }
32
-
33
21
  export function getAbsoluteOutputPath(projectRoot, featureName, outputType) {
34
22
  const entry = OUTPUT_SCHEMA[outputType];
35
23
  if (!entry) {
@@ -37,20 +25,3 @@ export function getAbsoluteOutputPath(projectRoot, featureName, outputType) {
37
25
  }
38
26
  return join(projectRoot, '.morph', 'features', featureName, entry.phaseDir, leafSegment(entry));
39
27
  }
40
-
41
- export const FILENAME_TO_OUTPUT = Object.fromEntries(
42
- Object.entries(OUTPUT_SCHEMA)
43
- .filter(([, entry]) => !entry.multi)
44
- .map(([key, entry]) => [entry.filename, key])
45
- );
46
-
47
- export const OUTPUT_PHASE_MAP = Object.fromEntries(
48
- Object.entries(OUTPUT_SCHEMA).map(([key, entry]) => [key, entry.phase])
49
- );
50
-
51
- export const PROTECTED_SPEC_FILES = Object.fromEntries(
52
- Object.entries(OUTPUT_SCHEMA)
53
- .filter(([, entry]) => entry.protected && entry.approvalGate && !entry.multi)
54
- .map(([, entry]) => [entry.filename, entry.approvalGate])
55
- );
56
-