@polymorphism-tech/morph-spec 11.1.1 → 11.3.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 (166) hide show
  1. package/README.md +3 -2
  2. package/bin/morph-spec.js +13 -23
  3. package/docs/CHEATSHEET.md +3 -3
  4. package/docs/QUICKSTART.md +1 -1
  5. package/framework/CLAUDE.md +3 -1
  6. package/framework/MORPH.md +8 -3
  7. package/framework/agents.json +4 -4
  8. package/framework/docs/CLI.md +28 -18
  9. package/framework/evals/review-checklist.md +35 -18
  10. package/framework/hooks/README.md +18 -11
  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 +6 -6
  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 +16 -32
  30. package/framework/rules/ai-agents-standards.md +9 -1
  31. package/framework/rules/dotnet-templates.md +32 -33
  32. package/framework/rules/gsap-standards.md +8 -0
  33. package/framework/rules/infrastructure-standards.md +9 -9
  34. package/framework/rules/mcp-standards.md +10 -0
  35. package/framework/rules/neon-standards.md +4 -4
  36. package/framework/rules/nextjs-templates.md +10 -11
  37. package/framework/rules/ui-design.md +2 -2
  38. package/framework/schemas/config.schema.json +11 -0
  39. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  40. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  41. package/framework/skills/core/morph-apply/SKILL.md +6 -4
  42. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  43. package/framework/skills/core/morph-uiux/SKILL.md +5 -5
  44. package/framework/standards/STANDARDS.json +8 -4
  45. package/framework/standards/STANDARDS.meta.json +1 -1
  46. package/framework/standards/ai-agents/agent-archetypes.md +1 -1
  47. package/framework/standards/ai-agents/middleware-patterns.md +0 -2
  48. package/framework/standards/ai-agents/prompt-sources.md +2 -2
  49. package/framework/standards/ai-agents/providers/model-registry.md +9 -12
  50. package/framework/standards/ai-agents/rag-custom-pgvector.md +2 -9
  51. package/framework/standards/frontend/design-system/ai-image-generation.md +1 -1
  52. package/framework/standards/infrastructure/docker/local-compose-isolation.md +2 -2
  53. package/framework/standards/integration/mcp/mcp-tools.md +125 -267
  54. package/framework/templates/README.md +52 -82
  55. package/framework/templates/REGISTRY.json +1 -281
  56. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +3 -4
  57. package/framework/templates/context/design-system.md +1 -1
  58. package/framework/templates/docs/plan.md +2 -2
  59. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Providers/model-registry.v2.json +1 -1
  60. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/MediaDisclosureTests.cs +1 -1
  61. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/Morph.AiKit.Tests.csproj +3 -5
  62. package/framework/templates/frontend/nextjs/gsap-scroll-section.tsx.hbs +13 -17
  63. package/framework/templates/infrastructure/docker/docker-compose.template.yml +15 -16
  64. package/framework/templates/infrastructure/github/README.md +10 -13
  65. package/package.json +7 -16
  66. package/src/commands/graph/build.js +2 -2
  67. package/src/commands/mcp/manual-setup.js +95 -0
  68. package/src/commands/mcp/mcp-setup.js +26 -192
  69. package/src/commands/project/doctor.js +48 -142
  70. package/src/commands/project/env.js +2 -1
  71. package/src/commands/project/init-contract.js +2 -2
  72. package/src/commands/project/init.js +34 -294
  73. package/src/commands/project/stack-scan.js +6 -14
  74. package/src/commands/project/stack-set.js +3 -1
  75. package/src/commands/project/standards.js +1 -2
  76. package/src/commands/project/update.js +87 -205
  77. package/src/commands/scaffold/scaffold.js +43 -5
  78. package/src/commands/validation/check.js +12 -10
  79. package/src/commands/validation/prove-red.js +61 -22
  80. package/src/core/paths/output-schema.js +8 -27
  81. package/src/core/templates/template-registry.js +8 -43
  82. package/src/core/templates/template-renderer.js +3 -200
  83. package/src/lib/ai/ai-checks.js +1 -1
  84. package/src/lib/ai/ai-project-scan.js +2 -5
  85. package/src/lib/ai/code-audit.js +3 -8
  86. package/src/lib/ai/registry-audit.js +2 -1
  87. package/src/lib/check/signals.js +25 -7
  88. package/src/lib/config/project-config.js +3 -2
  89. package/src/lib/contract/apply.js +2 -1
  90. package/src/lib/contract/defaults.js +2 -2
  91. package/src/lib/contract/merge.js +1 -0
  92. package/src/lib/contract/scan.js +5 -5
  93. package/src/lib/detectors/claude-config-detector.js +44 -98
  94. package/src/lib/detectors/mcp-config.js +2 -1
  95. package/src/lib/diff/diff-lines.js +4 -9
  96. package/src/lib/generators/scaffold-generator.js +5 -17
  97. package/src/lib/git/default-branch.js +5 -13
  98. package/src/lib/graph/graph-health.js +1 -1
  99. package/src/lib/graph/graph-loader.js +2 -1
  100. package/src/lib/graph/graphifyignore.js +5 -5
  101. package/src/lib/graph/sanitize.js +2 -2
  102. package/src/lib/installers/effects.js +0 -13
  103. package/src/lib/installers/install-manifest.js +56 -0
  104. package/src/lib/installers/mcp-installer.js +16 -19
  105. package/src/lib/installers/memory-installer.js +5 -8
  106. package/src/lib/installers/rules-installer.js +9 -15
  107. package/src/lib/installers/stack-assets.js +54 -7
  108. package/src/lib/installers/stack-sync.js +16 -16
  109. package/src/lib/installers/stack-tooling.js +4 -3
  110. package/src/lib/json-file.js +9 -0
  111. package/src/lib/plan/artifact-vocabulary.js +1 -1
  112. package/src/lib/plan/checks.js +4 -3
  113. package/src/lib/plan/media.js +6 -6
  114. package/src/lib/plan/plan-parser.js +6 -11
  115. package/src/lib/review-reports.js +13 -18
  116. package/src/lib/scan/worktree-dirs.js +1 -3
  117. package/src/lib/specs/adr-index.js +4 -4
  118. package/src/lib/specs/revocations.js +3 -3
  119. package/src/lib/stack/stack-scan.js +4 -4
  120. package/src/lib/standards/registry.js +1 -1
  121. package/src/lib/standards/verified-against.js +3 -3
  122. package/src/lib/tests-audit/audit.js +3 -3
  123. package/src/lib/text.js +5 -0
  124. package/src/scripts/global-install.js +41 -19
  125. package/src/scripts/setup-infra.js +68 -187
  126. package/src/utils/agents-installer.js +21 -60
  127. package/src/utils/claude-md-injector.js +16 -50
  128. package/src/utils/claude-settings-manager.js +29 -27
  129. package/src/utils/file-copier.js +3 -4
  130. package/src/utils/hooks-installer.js +83 -62
  131. package/src/utils/skills-installer.js +18 -78
  132. package/src/utils/version-checker.js +2 -31
  133. package/CLAUDE.md +0 -118
  134. package/framework/commands/create-umbraco-lp.md +0 -37
  135. package/framework/commands/migrate-lp-to-umbraco.md +0 -35
  136. package/framework/commands/morph-apply.md +0 -14
  137. package/framework/hooks/shared/spawn-command.js +0 -23
  138. package/framework/templates/CLAUDE.md.core.guide.md +0 -29
  139. package/framework/templates/CLAUDE.md.core.template +0 -22
  140. package/framework/templates/IDE-SNIPPETS.md +0 -262
  141. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +0 -26
  142. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +0 -28
  143. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +0 -99
  144. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +0 -40
  145. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +0 -54
  146. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +0 -53
  147. package/framework/templates/code/dotnet/contracts/README.md +0 -74
  148. package/framework/templates/code/dotnet/database/vector-entity.cs +0 -49
  149. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +0 -91
  150. package/framework/templates/code/sql/postgresql-migration.template.sql +0 -108
  151. package/framework/templates/code/typescript/contracts.ts +0 -140
  152. package/framework/templates/context/ARCHITECTURE.md +0 -106
  153. package/framework/templates/examples/design-system-examples.md +0 -354
  154. package/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  155. package/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  156. package/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  157. package/framework/templates/integrations/asaas-client.cs +0 -332
  158. package/framework/templates/integrations/asaas-webhook.cs +0 -290
  159. package/framework/templates/integrations/neon-auth-config.cs +0 -170
  160. package/framework/templates/ui/design-system.css +0 -226
  161. package/src/commands/context/context-refresh.js +0 -63
  162. package/src/lib/detectors/index.js +0 -178
  163. package/src/lib/generators/architecture-scanner.js +0 -543
  164. package/src/lib/generators/settings-generator.js +0 -97
  165. package/src/lib/graph/god-nodes.js +0 -65
  166. package/src/lib/installers/templates-reconcile.js +0 -26
@@ -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
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,20 +16,18 @@ 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
27
23
  } from '../../utils/version-checker.js';
28
24
  import { installClaudeHooks, installGlobalStatusline } from '../../utils/claude-settings-manager.js';
29
- import { installSkills } from '../../utils/skills-installer.js';
30
- import { installAgents } from '../../utils/agents-installer.js';
31
- import { injectMorphImport } from '../../utils/claude-md-injector.js';
25
+ import { removeMorphImport } from '../../utils/claude-md-injector.js';
32
26
  import { getProjectTags } from '../../lib/stack-filter.js';
33
27
  import { detectStackTags, mergeDetectedTags } from '../../lib/installers/stack-sync.js';
34
- import { updateClaudeMdAgentsBlock, installRulesForStack, installCommandsForStack } from '../../scripts/setup-infra.js';
35
- import { reconcileLegacyTemplatesCopy } from '../../lib/installers/templates-reconcile.js';
28
+ import { CONFIG_SCHEMA_REF, hooksPayloadFilter, updateClaudeMdAgentsBlock } from '../../scripts/setup-infra.js';
29
+ import { installAssetsForTags } from '../../lib/installers/stack-assets.js';
30
+ import { ASSET_DIRS, readManifest } from '../../lib/installers/install-manifest.js';
36
31
  import { createEffects } from '../../lib/installers/effects.js';
37
32
  import { syncStackTooling } from '../../lib/installers/stack-tooling.js';
38
33
  import { detectClaudeConfig } from '../../lib/detectors/claude-config-detector.js';
@@ -40,35 +35,31 @@ import {
40
35
  writeGraphifyignore, describeOutdatedIgnore, graphifyignoreTracked,
41
36
  } from '../../lib/graph/graphifyignore.js';
42
37
 
38
+ // Throws on an unreadable file: the clean deletes `.morph/config/`, and a default written over it loses the contract.
43
39
  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;
40
+ const configPath = join(morphPath, 'config', 'config.json');
41
+ return (await pathExists(configPath)) ? readJson(configPath) : null;
53
42
  }
54
43
 
55
- export function frameworkDirsToClean(morphPath, targetPath) {
56
- const claudeDir = join(targetPath, '.claude');
44
+ /** Payload folders only morph-spec writes: wiped whole on every update. `.morph/framework/installed.json` is outside all of them. */
45
+ export function frameworkDirsToClean(morphPath) {
57
46
  return [
58
- // framework/templates is left out on purpose: reconcileLegacyTemplatesCopy() decides whether
59
- // a local copy is a user override to preserve.
60
47
  join(morphPath, 'framework', 'standards'),
61
48
  join(morphPath, 'framework', 'hooks'),
62
49
  join(morphPath, 'framework', 'schemas'),
63
50
  join(morphPath, 'framework', 'evals'),
64
51
  join(morphPath, 'config'),
65
- join(claudeDir, 'commands'),
66
- join(claudeDir, 'rules'),
67
- join(claudeDir, 'skills'),
68
- join(claudeDir, 'agents'),
69
52
  ];
70
53
  }
71
54
 
55
+ /**
56
+ * The four `.claude` folders the project shares with morph-spec. Wiped whole only once, for an install
57
+ * with no manifest; with one, the installers remove file by file what the manifest and the package name.
58
+ */
59
+ export function assetDirsToClean(targetPath) {
60
+ return ASSET_DIRS.map((dir) => join(targetPath, '.claude', dir));
61
+ }
62
+
72
63
  function sweepRemove(dir, fx) {
73
64
  let entries;
74
65
  try {
@@ -91,18 +82,13 @@ function sweepRemove(dir, fx) {
91
82
  }
92
83
 
93
84
  /**
94
- * Os laços de órfão depois varrem estes mesmos destinos já vazios: em dry eles ficam calados,
95
- * senão o relatório preveria remoções que a execução real nunca faz.
85
+ * Com `wipeAssets`, os installers rodam depois com `prune: false`: em dry as pastas ainda estão no disco,
86
+ * e a poda preveria remoções que a execução real, com elas já vazias, nunca faz.
96
87
  */
97
- function cleanFrameworkDirs(morphPath, targetPath, fx) {
88
+ function cleanFrameworkDirs(morphPath, targetPath, fx, { wipeAssets }) {
98
89
  const cleaned = [];
99
- 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
- }
90
+ for (const dir of [...frameworkDirsToClean(morphPath), ...(wipeAssets ? assetDirsToClean(targetPath) : [])]) {
91
+ if (existsSync(dir)) cleaned.push({ dir, files: sweepRemove(dir, fx) });
106
92
  }
107
93
  return cleaned;
108
94
  }
@@ -117,6 +103,7 @@ function restoreUserConfig(morphPath, targetPath, configBackup, currentVersion,
117
103
  fx.writeJson(configPath, configBackup);
118
104
  } else {
119
105
  const defaultConfig = {
106
+ $schema: CONFIG_SCHEMA_REF,
120
107
  frameworkVersion: currentVersion,
121
108
  project: { name: basename(resolve(targetPath)) },
122
109
  };
@@ -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
@@ -397,85 +354,43 @@ export async function updateCommand(options = {}) {
397
354
  logger.dim(' ✓ Created .morph directory structure');
398
355
  }
399
356
 
357
+ // Lido antes de qualquer remoção; em dry o manifesto novo só existe em memória.
358
+ const manifest = readManifest(targetPath);
359
+ const wipeAssets = manifest === null && !needsInitialization;
360
+ if (wipeAssets) {
361
+ notices.push('Instalação anterior ao manifesto (`.morph/framework/installed.json`): '
362
+ + '`.claude/{commands,rules,skills,agents}` são apagadas por inteiro, pela última vez. '
363
+ + 'Até esta versão o `update` sempre limpou essas pastas inteiras e o deny do settings bloqueava edição em rules e skills, '
364
+ + 'então não há como separar o que seria seu. Daqui em diante só sai o que o manifesto registra: arquivo seu nelas fica.');
365
+ }
366
+
400
367
  const updateSpinner = ora(dryRun ? 'Prevendo efeitos...' : 'Updating MORPH-SPEC...').start();
401
368
  let cleaned = [];
402
369
 
403
370
  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
371
  updateSpinner.text = 'Cleaning old framework files...';
411
- cleaned = cleanFrameworkDirs(morphPath, targetPath, fx);
372
+ cleaned = cleanFrameworkDirs(morphPath, targetPath, fx, { wipeAssets });
373
+ // Written back at once: a failure in the installs below must not leave the project without its contract.
374
+ if (configBackup) restoreUserConfig(morphPath, targetPath, configBackup, cliCheck.current, fx);
412
375
  logger.dim(' ✓ Old framework files removed');
413
376
 
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);
377
+ if (existsSync(join(morphPath, 'framework', 'templates'))) {
378
+ notices.push('.morph/framework/templates/ não é lido: os templates vêm do pacote (`morph-spec scaffold show <id>`). Apague a pasta.');
422
379
  }
423
380
 
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);
381
+ updateSpinner.text = 'Updating standards, hooks, charter, schemas and evals...';
382
+ for (const dir of ['standards', 'hooks', 'schemas', 'evals']) {
383
+ fx.copyDir(join(frameworkDir, dir), join(morphPath, 'framework', dir), dir === 'hooks' ? { filter: hooksPayloadFilter } : {});
429
384
  }
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);
385
+ for (const file of ['agents.json', 'ai-pin.json', 'MORPH.md']) {
386
+ fx.copyFile(join(frameworkDir, file), join(morphPath, 'framework', file));
436
387
  }
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
- }
444
-
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
- }
455
- }
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 {
388
+ fx.copyFile(join(frameworkDir, 'docs', 'CLI.md'), join(morphPath, 'framework', 'CLI.md'));
389
+ for (const dead of [join(morphPath, 'framework', 'phases.json'), join(morphPath, 'context', 'README.md')]) {
390
+ if (existsSync(dead)) fx.remove(dead);
475
391
  }
476
392
 
477
393
  updateSpinner.text = 'Setting up Claude Code integration...';
478
- const frameworkDir = join(__dirname, '..', '..', '..', 'framework');
479
394
  const claudeDest = join(targetPath, '.claude');
480
395
 
481
396
  // MUST come from the pre-clean backup: cleanFrameworkDirs() deleted .morph/config/ and re-reading
@@ -485,7 +400,7 @@ export async function updateCommand(options = {}) {
485
400
  if (configBackup) projectTags = getProjectTags(configBackup);
486
401
  } catch {}
487
402
  // The same detection as `syncStackRules`, folded in before the installs: `restoreUserConfig`
488
- // writes `configBackup`, and a dry run sees `.claude/rules/` before the clean, not after.
403
+ // writes `configBackup`, and a dry run sees `.claude/rules/` as it was, not as this run leaves it.
489
404
  if (configBackup) {
490
405
  try {
491
406
  const detected = detectStackTags(targetPath, { config: configBackup });
@@ -495,34 +410,16 @@ export async function updateCommand(options = {}) {
495
410
  logger.dim(` ✓ config.json: + ${merged.added.join(', ')} (detectado nos arquivos)`);
496
411
  }
497
412
  projectTags = [...new Set([...getProjectTags(configBackup), ...detected.tags])];
498
- } catch {}
499
- }
500
-
501
- let commandsCopied = false;
502
- const commandsSrc = join(frameworkDir, 'commands');
503
- if (await pathExists(commandsSrc)) {
504
- const commandsDest = join(claudeDest, 'commands');
505
- fx.ensureDir(commandsDest);
506
- installCommandsForStack(commandsSrc, commandsDest, projectTags, fx);
507
- commandsCopied = true;
508
- } else {
509
- logger.warn(' ⚠ framework/commands/ source missing — commands not updated');
413
+ } catch (err) {
414
+ logger.dim(` ⚠ stack não redetectada nos arquivos (${err.message}): valem as tags do config.json`);
415
+ }
510
416
  }
511
417
 
512
- updateSpinner.text = 'Syncing morph skills to .claude/skills/...';
513
- const skillsResult = await installSkills(targetPath, { projectTags, fx });
514
-
515
- updateSpinner.text = 'Syncing agents to .claude/agents/...';
516
- const agentsResult = await installAgents(targetPath, frameworkDir, { projectTags, fx });
517
-
518
- updateSpinner.text = 'Syncing rules to .claude/rules/...';
519
- const rulesSrc = join(frameworkDir, 'rules');
520
- const rulesDest = join(claudeDest, 'rules');
521
- let rulesResult = null;
522
- if (await pathExists(rulesSrc)) {
523
- fx.ensureDir(rulesDest);
524
- rulesResult = installRulesForStack(rulesSrc, rulesDest, projectTags, fx);
525
- }
418
+ updateSpinner.text = 'Syncing commands, rules, skills and agents to .claude/...';
419
+ const assets = await installAssetsForTags(targetPath, projectTags, {
420
+ frameworkSrc: frameworkDir, fx, manifest, prune: !wipeAssets, createManifest: true,
421
+ });
422
+ const agentsResult = assets.agents;
526
423
 
527
424
  updateSpinner.text = 'Syncing .claude/CLAUDE.md...';
528
425
  const runtimeSrc = join(frameworkDir, 'CLAUDE.md');
@@ -537,15 +434,14 @@ export async function updateCommand(options = {}) {
537
434
  }
538
435
 
539
436
  updateSpinner.text = 'Syncing statusline to ~/.claude/...';
540
- const HOOKS_SRC = join(__dirname, '..', '..', '..', 'framework', 'hooks', 'claude-code');
541
437
  try {
542
- await installGlobalStatusline(HOOKS_SRC, null, { fx });
438
+ await installGlobalStatusline(join(frameworkDir, 'hooks', 'claude-code'), null, { fx });
543
439
  } catch {
544
440
  logger.dim(' ⚠ Could not install statusline globally (non-critical)');
545
441
  }
546
442
 
547
443
  updateSpinner.text = 'Updating Claude Code hooks...';
548
- const hooksResult = await installClaudeHooks(targetPath, { fx });
444
+ const hooksResult = await installClaudeHooks(targetPath, { fx, manifest: assets.manifest });
549
445
 
550
446
  updateSpinner.text = 'Syncing stack MCPs, skills and registries...';
551
447
  let tooling = null;
@@ -562,9 +458,7 @@ export async function updateCommand(options = {}) {
562
458
  logger.dim(` ⚠ MCPs do stack não sincronizados (${err.message})`);
563
459
  }
564
460
 
565
- updateSpinner.text = 'Checking CLAUDE.md import...';
566
- const claudeMdDest = join(targetPath, 'CLAUDE.md');
567
- await injectMorphImport(claudeMdDest, fx);
461
+ await removeMorphImport(join(targetPath, 'CLAUDE.md'), fx);
568
462
 
569
463
  updateSpinner.text = 'Restoring user configuration...';
570
464
  restoreUserConfig(morphPath, targetPath, configBackup, cliCheck.current, fx);
@@ -606,44 +500,32 @@ export async function updateCommand(options = {}) {
606
500
 
607
501
  logger.blank();
608
502
  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
- }
617
- }
618
-
619
503
  // Counts make a silent stack-filter downgrade visible (a dotnet project with "1 persona");
620
504
  // only compact tags, since integrations are long free text.
621
505
  const compactTags = projectTags.filter(t => !t.includes(' '));
622
506
  const tagsLabel = compactTags.length > 0 ? compactTags.join('+') : 'universal only';
623
507
  logger.dim(` ✓ .claude/settings.local.json (${hooksResult.installed} hooks installed)`);
624
- logger.dim(` ✓ .claude/skills/ (${skillsResult?.installed ?? '?'} skills — stack: ${tagsLabel})`);
625
- logger.dim(` ✓ .claude/agents/ (${agentsResult?.agents?.length ?? '?'} personas — stack: ${tagsLabel})`);
626
- logger.dim(` ✓ .claude/rules/ (${rulesResult?.installed ?? '?'} stack-filtered rules)`);
627
- if (commandsCopied) logger.dim(' ✓ .claude/commands/');
508
+ logger.dim(` ✓ .claude/skills/ (${assets.skills.installed} skills — stack: ${tagsLabel})`);
509
+ logger.dim(` ✓ .claude/agents/ (${assets.agents.installed} personas — stack: ${tagsLabel})`);
510
+ logger.dim(` ✓ .claude/rules/ (${assets.rules.installed} stack-filtered rules)`);
511
+ logger.dim(` ✓ .claude/commands/ (${assets.commands.installed} commands)`);
628
512
  if (tooling?.mcps.length) logger.dim(` ✓ .mcp.json (+ ${tooling.mcps.join(', ')})`);
629
513
  if (tooling?.skills.length) logger.dim(` ✓ .claude/skills/ (+ skill de ${tooling.skills.join(', ')})`);
630
514
  if (tooling?.registries.length) logger.dim(` ✓ components.json (+ ${tooling.registries.join(', ')})`);
631
515
  if (graphIgnore?.migrated) {
632
516
  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)');
517
+ logger.dim(' em background, depois de um comando git do agente; numa worktree: morph-spec graph refresh)');
634
518
  }
635
519
  if (legacyStateRemoved) {
636
520
  logger.dim(' ✓ .morph/state.json removido: a feature agora é a pasta do branch');
637
521
  logger.warn('Commite a remoção do .morph/state.json.');
638
522
  }
639
523
  logger.blank();
640
- logger.info('Your config.json was preserved.');
524
+ if (configBackup) logger.info('Your config.json was preserved.');
641
525
  }
642
526
 
643
527
  // 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
- });
528
+ renderEffectsReport(fx.list(), { targetPath, dryRun, cleaned, notices });
647
529
 
648
530
  return { refused: false, dryRun, effects: fx.list() };
649
531
  } catch (error) {
@@ -1,11 +1,14 @@
1
1
  import chalk from 'chalk';
2
- import { relative } from 'path';
2
+ import { readFileSync, readdirSync, statSync } from 'fs';
3
+ import { join, 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,38 @@ export async function scaffoldNextjsCommand(feature, options) {
104
107
  process.exit(1);
105
108
  }
106
109
  }
110
+
111
+ function projectFiles(root, rel = '') {
112
+ return readdirSync(join(root, rel), { withFileTypes: true }).flatMap((e) => {
113
+ const child = rel ? `${rel}/${e.name}` : e.name;
114
+ if (e.isDirectory()) return ['bin', 'obj', 'TestResults'].includes(e.name) ? [] : projectFiles(root, child);
115
+ return [child];
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Prints a package template verbatim: templates are never copied into the project. A template that is a
121
+ * whole project lists its files, and prints the one named by `file`.
122
+ */
123
+ export function scaffoldShowCommand(templateId, file) {
124
+ if (!getTemplateById(templateId)) {
125
+ logger.error(`Template "${templateId}" not found in the package registry`);
126
+ process.exit(1);
127
+ }
128
+ const path = resolveFrameworkTemplatePath(templateId);
129
+ if (!statSync(path).isDirectory()) {
130
+ process.stdout.write(readFileSync(path, 'utf-8'));
131
+ return;
132
+ }
133
+ const files = projectFiles(path).sort();
134
+ if (!file) {
135
+ process.stdout.write(`${files.join('\n')}\n`);
136
+ return;
137
+ }
138
+ const wanted = String(file).replace(/\\/g, '/');
139
+ if (!files.includes(wanted)) {
140
+ logger.error(`"${wanted}" is not a file of "${templateId}": morph-spec scaffold show ${templateId} lists them`);
141
+ process.exit(1);
142
+ }
143
+ process.stdout.write(readFileSync(join(path, wanted), 'utf-8'));
144
+ }
@@ -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));