@polymorphism-tech/morph-spec 11.2.0 → 11.3.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 (109) hide show
  1. package/README.md +3 -2
  2. package/bin/morph-spec.js +7 -7
  3. package/docs/CHEATSHEET.md +1 -1
  4. package/docs/QUICKSTART.md +1 -1
  5. package/framework/CLAUDE.md +1 -1
  6. package/framework/MORPH.md +2 -2
  7. package/framework/agents.json +4 -4
  8. package/framework/docs/CLI.md +19 -11
  9. package/framework/evals/review-checklist.md +26 -2
  10. package/framework/hooks/README.md +3 -2
  11. package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
  12. package/framework/mcp/registry.json +15 -15
  13. package/framework/rules/ai-agents-standards.md +9 -1
  14. package/framework/rules/gsap-standards.md +8 -0
  15. package/framework/rules/mcp-standards.md +10 -0
  16. package/framework/schemas/config.schema.json +7 -0
  17. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  18. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  19. package/framework/skills/core/morph-apply/SKILL.md +4 -3
  20. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  21. package/framework/skills/core/morph-uiux/SKILL.md +1 -1
  22. package/framework/standards/STANDARDS.json +8 -4
  23. package/framework/standards/STANDARDS.meta.json +1 -1
  24. package/framework/standards/ai-agents/agent-archetypes.md +1 -1
  25. package/framework/standards/ai-agents/middleware-patterns.md +0 -2
  26. package/framework/standards/ai-agents/prompt-sources.md +2 -2
  27. package/framework/standards/ai-agents/providers/model-registry.md +9 -12
  28. package/framework/standards/ai-agents/rag-custom-pgvector.md +2 -9
  29. package/framework/standards/frontend/design-system/ai-image-generation.md +1 -1
  30. package/framework/standards/infrastructure/docker/local-compose-isolation.md +2 -2
  31. package/framework/standards/integration/mcp/mcp-tools.md +124 -266
  32. package/framework/templates/README.md +52 -82
  33. package/framework/templates/REGISTRY.json +0 -206
  34. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +3 -4
  35. package/framework/templates/context/design-system.md +1 -1
  36. package/framework/templates/docs/plan.md +1 -1
  37. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Providers/model-registry.v2.json +1 -1
  38. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/MediaDisclosureTests.cs +1 -1
  39. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/Morph.AiKit.Tests.csproj +2 -4
  40. package/framework/templates/frontend/nextjs/gsap-scroll-section.tsx.hbs +13 -17
  41. package/framework/templates/infrastructure/github/README.md +10 -13
  42. package/package.json +9 -3
  43. package/src/commands/mcp/manual-setup.js +95 -0
  44. package/src/commands/mcp/mcp-setup.js +23 -191
  45. package/src/commands/project/doctor.js +6 -16
  46. package/src/commands/project/init-contract.js +2 -2
  47. package/src/commands/project/init.js +15 -133
  48. package/src/commands/project/stack-scan.js +6 -14
  49. package/src/commands/project/stack-set.js +1 -1
  50. package/src/commands/project/standards.js +1 -2
  51. package/src/commands/project/update.js +52 -66
  52. package/src/commands/scaffold/scaffold.js +28 -7
  53. package/src/lib/ai/ai-project-scan.js +1 -4
  54. package/src/lib/ai/code-audit.js +1 -6
  55. package/src/lib/ai/registry-audit.js +2 -1
  56. package/src/lib/config/project-config.js +3 -2
  57. package/src/lib/contract/apply.js +2 -1
  58. package/src/lib/contract/merge.js +1 -0
  59. package/src/lib/contract/scan.js +5 -5
  60. package/src/lib/detectors/claude-config-detector.js +45 -47
  61. package/src/lib/detectors/mcp-config.js +2 -1
  62. package/src/lib/diff/diff-lines.js +2 -7
  63. package/src/lib/graph/graph-loader.js +2 -1
  64. package/src/lib/graph/graphifyignore.js +2 -1
  65. package/src/lib/installers/install-manifest.js +56 -0
  66. package/src/lib/installers/mcp-installer.js +14 -5
  67. package/src/lib/installers/rules-installer.js +9 -15
  68. package/src/lib/installers/stack-assets.js +42 -21
  69. package/src/lib/installers/stack-sync.js +12 -12
  70. package/src/lib/installers/stack-tooling.js +4 -3
  71. package/src/lib/json-file.js +9 -0
  72. package/src/lib/plan/artifact-vocabulary.js +1 -1
  73. package/src/lib/plan/checks.js +3 -2
  74. package/src/lib/plan/media.js +3 -3
  75. package/src/lib/plan/plan-parser.js +5 -10
  76. package/src/lib/review-reports.js +5 -4
  77. package/src/lib/stack/stack-scan.js +1 -1
  78. package/src/lib/standards/verified-against.js +1 -1
  79. package/src/lib/tests-audit/audit.js +1 -1
  80. package/src/lib/text.js +5 -0
  81. package/src/scripts/setup-infra.js +22 -33
  82. package/src/utils/agents-installer.js +13 -30
  83. package/src/utils/claude-md-injector.js +16 -50
  84. package/src/utils/claude-settings-manager.js +2 -2
  85. package/src/utils/file-copier.js +3 -4
  86. package/src/utils/hooks-installer.js +55 -20
  87. package/src/utils/skills-installer.js +18 -78
  88. package/framework/templates/IDE-SNIPPETS.md +0 -262
  89. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +0 -26
  90. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +0 -28
  91. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +0 -99
  92. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +0 -40
  93. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +0 -54
  94. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +0 -53
  95. package/framework/templates/code/dotnet/contracts/README.md +0 -74
  96. package/framework/templates/code/dotnet/database/vector-entity.cs +0 -49
  97. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +0 -91
  98. package/framework/templates/code/sql/postgresql-migration.template.sql +0 -108
  99. package/framework/templates/code/typescript/contracts.ts +0 -140
  100. package/framework/templates/examples/design-system-examples.md +0 -354
  101. package/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  102. package/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  103. package/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  104. package/framework/templates/integrations/asaas-client.cs +0 -332
  105. package/framework/templates/integrations/asaas-webhook.cs +0 -290
  106. package/framework/templates/integrations/neon-auth-config.cs +0 -170
  107. package/framework/templates/ui/design-system.css +0 -226
  108. package/src/lib/detectors/index.js +0 -153
  109. package/src/lib/installers/templates-reconcile.js +0 -26
@@ -1,27 +1,22 @@
1
1
  import { existsSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import ora from 'ora';
4
- import { execSync } from 'child_process';
5
4
  import { logger } from '../../utils/logger.js';
6
- import { pathExists, readJson, writeJson } from '../../utils/file-copier.js';
5
+ import { pathExists, readJson } from '../../utils/file-copier.js';
7
6
  import { getInstalledCLIVersion, checkProjectOutdated } from '../../utils/version-checker.js';
8
7
  import inquirer from 'inquirer';
9
- import { detectProject } from '../../lib/detectors/index.js';
10
8
  import { detectClaudeConfig, formatConfigSummary } from '../../lib/detectors/claude-config-detector.js';
11
9
  import {
12
10
  orchestrateMcpSetup,
13
11
  installAutoMcps,
14
12
  installCompanionSkills,
15
- installMcpWithCredentials,
16
- generateSetupInstructions,
17
13
  formatMcpStatusTable,
18
- isRemoteMcp
19
14
  } from '../../lib/installers/mcp-installer.js';
15
+ import { printMcpStatusTable, setupManualMcp } from '../mcp/manual-setup.js';
20
16
  import { setupInfra } from '../../scripts/setup-infra.js';
21
17
  import { getProjectTags } from '../../lib/stack-filter.js';
22
18
  import { updateCommand } from './update.js';
23
19
  import { setProjectStack } from '../../lib/installers/stack-sync.js';
24
- import { installStackAssets } from '../../lib/installers/stack-assets.js';
25
20
  import { scanRepo } from '../../lib/contract/scan.js';
26
21
  import { initDryRun, refreshContract } from './init-contract.js';
27
22
  import { isSecondaryWorktree } from '../../../framework/hooks/shared/git-paths.js';
@@ -53,13 +48,6 @@ export async function chooseGreenfieldStack(options = {}, { isTTY = process.stdi
53
48
  return stackChoice;
54
49
  }
55
50
 
56
- async function reinstallForStack(targetPath, stackTags, spinner) {
57
- if (stackTags.length === 0) return;
58
- spinner.start('Re-installing stack-filtered assets...');
59
- await installStackAssets(targetPath, stackTags);
60
- spinner.succeed(`Stack-filtered assets reinstalled for [${stackTags.join(', ')}]`);
61
- }
62
-
63
51
  // A fresh worktree carries the committed contract but not the gitignored harness: that is an install, not a refresh.
64
52
  function harnessInstalled(targetPath) {
65
53
  return ['.morph/framework/hooks', '.claude/skills/morph-plan'].every((p) => existsSync(join(targetPath, p)));
@@ -80,7 +68,7 @@ export async function initCommand(options) {
80
68
  if (projectCheck.isOutdated) {
81
69
  logger.info(`MORPH already initialized (v${projectCheck.current}). Framework update available (v${projectCheck.cliVersion}).`);
82
70
  logger.blank();
83
- const updated = await updateCommand(options);
71
+ const updated = await updateCommand({ path: options.path });
84
72
  return updated?.refused ? undefined : refreshContract(targetPath);
85
73
  }
86
74
  logger.info('MORPH já instalado e em dia: atualizando o contrato pelo repo.');
@@ -100,12 +88,6 @@ export async function initCommand(options) {
100
88
 
101
89
  const cliVersion = getInstalledCLIVersion();
102
90
 
103
- const configDir = join(morphPath, 'config');
104
- const configPath = join(configDir, 'config.json');
105
-
106
- let config = (await pathExists(configPath)) ? await readJson(configPath) : { project: {} };
107
- if (!config.project) config.project = {};
108
-
109
91
  let claudeConfigDetected = null;
110
92
  try {
111
93
  claudeConfigDetected = await detectClaudeConfig(targetPath);
@@ -118,43 +100,20 @@ export async function initCommand(options) {
118
100
  logger.dim(` Claude config detection skipped: ${error.message}`);
119
101
  }
120
102
 
121
- const hasProjectFiles = scanRepo(targetPath).stack !== null;
122
-
123
- if (hasProjectFiles) {
124
- try {
125
- const { structure } = detectProject(targetPath);
126
- if (structure.stack !== 'unknown') {
127
- config.project.stack = structure.stack;
128
- if (structure.integrations.length > 0) config.project.integrations = structure.integrations;
129
- await writeJson(configPath, config);
130
-
131
- logger.blank();
132
- logger.header('Existing Project Detected');
133
- logger.info(`Stack detected: ${structure.stack}`);
134
- if (structure.integrations.length > 0) logger.dim(`Integrations: ${structure.integrations.join(', ')}`);
135
-
136
- await reinstallForStack(targetPath, getProjectTags(config), spinner);
137
- }
138
- } catch (error) {
139
- logger.dim(` Stack detection skipped: ${error.message}`);
140
- }
141
- } else {
103
+ // A repo with manifests gets its stack from `refreshContract` alone: a value written here first
104
+ // would reach the merge without a fingerprint and freeze as a hand edit.
105
+ if (scanRepo(targetPath).stack === null) {
142
106
  const choice = await chooseGreenfieldStack(options);
143
107
  if (choice) {
144
108
  const result = setProjectStack(targetPath, choice.stack, { integrations: choice.integrations, log: (line) => logger.dim(line) });
145
- if (result.error) {
146
- logger.warn(`Stack não declarada: ${result.error}`);
147
- } else {
148
- config = await readJson(configPath);
149
- await reinstallForStack(targetPath, getProjectTags(config), spinner);
150
- }
109
+ if (result.error) logger.warn(`Stack não declarada: ${result.error}`);
151
110
  } else {
152
111
  logger.dim(' Stack: não declarada — o /morph-plan pergunta antes de planejar (recomendada: a do Morph)');
153
112
  }
154
113
  }
155
114
 
156
115
  await refreshContract(targetPath);
157
- config = await readJson(configPath);
116
+ const config = await readJson(join(morphPath, 'config', 'config.json'));
158
117
 
159
118
  let mcpSetupResult = null;
160
119
  if (options.skipMcp) {
@@ -165,7 +124,7 @@ export async function initCommand(options) {
165
124
  try {
166
125
  const existingMcps = claudeConfigDetected?.mcpServers || [];
167
126
  const orchestration = orchestrateMcpSetup(targetPath, config.project?.stack ?? 'unknown', existingMcps,
168
- { integrations: config.project?.integrations ?? [], enabledPlugins: claudeConfigDetected?.enabledPlugins ?? [] });
127
+ { integrations: getProjectTags(config), enabledPlugins: claudeConfigDetected?.enabledPlugins ?? [] });
169
128
 
170
129
  const autoNames = Object.keys(orchestration.autoInstallable);
171
130
  const manualNames = Object.keys(orchestration.needsManualSetup);
@@ -205,94 +164,17 @@ export async function initCommand(options) {
205
164
  }
206
165
 
207
166
  const manualInstalled = {};
208
- if (hasManualMcps) {
209
- for (const [name, entry] of Object.entries(orchestration.needsManualSetup)) {
210
- logger.blank();
211
-
212
- for (const warning of entry.install.warnings || []) {
213
- logger.warn(` ${warning}`);
214
- }
215
-
216
- const capitalizedName = name.charAt(0).toUpperCase() + name.slice(1);
217
- const { setupNow } = await inquirer.prompt([{
218
- type: 'confirm',
219
- name: 'setupNow',
220
- message: `Set up ${capitalizedName} MCP now? (${entry.usage})`,
221
- default: false
222
- }]);
223
-
224
- if (setupNow) {
225
- if (isRemoteMcp(entry.install.config)) {
226
- const url = entry.install.config.url;
227
- logger.info(` Launching ${capitalizedName} OAuth authentication...`);
228
- try {
229
- execSync(`claude mcp add --transport http ${name} ${url}`, {
230
- stdio: 'inherit',
231
- timeout: 120000
232
- });
233
- logger.success(` ${capitalizedName} MCP configured`);
234
- manualInstalled[name] = entry;
235
- } catch {
236
- logger.warn(` ${capitalizedName} setup cancelled. Run later: claude mcp add --transport http ${name} ${url}`);
237
- }
238
- continue;
239
- }
240
-
241
- const credentialValues = {};
242
- for (const cred of entry.install.credentials) {
243
- const { value } = await inquirer.prompt([{
244
- type: cred.secret ? 'password' : 'input',
245
- name: 'value',
246
- message: `${cred.name}:`,
247
- mask: cred.secret ? '*' : undefined
248
- }]);
249
- credentialValues[cred.envVar] = value;
250
- }
251
-
252
- spinner.start(`Configuring ${name}...`);
253
- await installMcpWithCredentials(targetPath, name, entry, credentialValues);
254
- spinner.succeed(`${capitalizedName} MCP configured`);
255
- manualInstalled[name] = entry;
256
- } else {
257
- const instructions = generateSetupInstructions(name, entry);
258
- logger.blank();
259
- logger.dim(' Add to .mcp.json → mcpServers:');
260
- logger.dim(' ' + '─'.repeat(55));
261
- for (const line of instructions.configSnippet.split('\n')) {
262
- logger.dim(` ${line}`);
263
- }
264
- logger.dim(' ' + '─'.repeat(55));
265
-
266
- for (const cred of instructions.credentialUrls) {
267
- logger.dim(` Get ${cred.name}: ${cred.helpUrl}`);
268
- }
269
- logger.dim(` Or run later: ${instructions.cliCommand}`);
270
- }
271
- }
167
+ for (const [name, entry] of Object.entries(orchestration.needsManualSetup)) {
168
+ logger.blank();
169
+ if (await setupManualMcp(targetPath, name, entry)) manualInstalled[name] = entry;
272
170
  }
273
171
 
274
- const justInstalled = { ...autoInstalled, ...manualInstalled };
275
- const statusRows = formatMcpStatusTable(orchestration, justInstalled);
276
-
172
+ const statusRows = formatMcpStatusTable(orchestration, { ...autoInstalled, ...manualInstalled });
277
173
  if (statusRows.length > 0) {
278
174
  logger.blank();
279
175
  logger.info('MCP Servers');
280
176
  logger.dim('─'.repeat(60));
281
-
282
- const STATUS_ICONS = {
283
- installed: '✓',
284
- available: '○',
285
- already_configured: '✓',
286
- needs_setup: '⚠',
287
- prereq_missing: '✗',
288
- not_relevant: '─'
289
- };
290
-
291
- for (const row of statusRows) {
292
- const icon = STATUS_ICONS[row.status] || '?';
293
- const statusLabel = row.status.replace(/_/g, ' ');
294
- logger.dim(` ${icon} ${row.name.padEnd(15)} ${statusLabel.padEnd(20)} ${row.detail}`);
295
- }
177
+ printMcpStatusTable(statusRows);
296
178
  }
297
179
 
298
180
  mcpSetupResult = { autoInstalled, manualInstalled, orchestration };
@@ -313,7 +195,7 @@ export async function initCommand(options) {
313
195
  logger.blank();
314
196
 
315
197
  logger.info('Files installed:');
316
- logger.dim(' ✓ CLAUDE.md (import de .claude/CLAUDE.md)');
198
+ logger.dim(' ✓ .claude/CLAUDE.md (o Claude Code carrega sozinho; o CLAUDE.md da raiz é seu)');
317
199
  logger.dim(' ✓ .morph/config/config.json (o contrato)');
318
200
  logger.dim(' ✓ .morph/framework/ (MORPH.md, CLI.md, agents.json, standards/, hooks/)');
319
201
  logger.dim(' ✓ .claude/{commands,rules,skills}/ (filtrados pela stack)');
@@ -1,19 +1,11 @@
1
1
  import { readMorphConfig } from '../../lib/config/project-config.js';
2
2
  import { scanStack, renderStackScan } from '../../lib/stack/stack-scan.js';
3
3
 
4
- /** Scan the tree at `cwd`; prints, never writes — the plan reads stdout. */
5
- export function runStackScan(featureName, cwd = process.cwd()) {
4
+ /** Prints, never writes: the plan reads stdout. */
5
+ export function stackScanCommand(options = {}) {
6
+ const cwd = process.cwd();
6
7
  const result = scanStack(cwd, readMorphConfig(cwd));
7
- return { ...result, markdown: renderStackScan(result, featureName ?? 'projeto'), exit: 0 };
8
- }
9
-
10
- export function stackScanCommand(featureName, options = {}) {
11
- const result = runStackScan(featureName);
12
- if (options.json) {
13
- const { markdown, ...rest } = result;
14
- console.log(JSON.stringify(rest, null, 2));
15
- } else {
16
- process.stdout.write(result.markdown);
17
- }
18
- process.exit(result.exit);
8
+ if (options.json) console.log(JSON.stringify(result, null, 2));
9
+ else process.stdout.write(renderStackScan(result, 'projeto'));
10
+ process.exit(0);
19
11
  }
@@ -16,7 +16,7 @@ export async function stackSetCommand(stack, options = {}) {
16
16
  process.exit(1);
17
17
  }
18
18
  const { stack: declared, integrations: declaredIntegrations, sync } = result;
19
- // The whole tag set, not only what was declared now: the install removes every rule and command outside it.
19
+ // The whole tag set, not only what was declared now: the install removes every framework asset outside it.
20
20
  await installStackAssets(process.cwd(), [...new Set([...getProjectTags(readMorphConfig(process.cwd())), ...sync.tags])]);
21
21
  if (options.json) {
22
22
  console.log(JSON.stringify({ stack: declared, integrations: declaredIntegrations, rulesAdded: sync.added, rulesUpdated: sync.updated }, null, 2));
@@ -140,8 +140,7 @@ function parseTagsOption(raw) {
140
140
  }
141
141
 
142
142
  export function standardsCommand(options = {}) {
143
- const cwd = options.cwd || process.cwd();
144
- const standardsJsonPath = resolveStandardsJsonPath(cwd);
143
+ const standardsJsonPath = resolveStandardsJsonPath(process.cwd());
145
144
 
146
145
  if (!standardsJsonPath) {
147
146
  console.error(chalk.red('\n❌ STANDARDS.json não encontrado — nem em .morph/framework/standards/ nem no pacote.'));
@@ -22,15 +22,12 @@ import {
22
22
  MAJOR_JUMP_LIMIT
23
23
  } from '../../utils/version-checker.js';
24
24
  import { installClaudeHooks, installGlobalStatusline } from '../../utils/claude-settings-manager.js';
25
- import { installSkills } from '../../utils/skills-installer.js';
26
- import { installAgents } from '../../utils/agents-installer.js';
27
- import { injectMorphImport } from '../../utils/claude-md-injector.js';
25
+ import { removeMorphImport } from '../../utils/claude-md-injector.js';
28
26
  import { getProjectTags } from '../../lib/stack-filter.js';
29
27
  import { detectStackTags, mergeDetectedTags } from '../../lib/installers/stack-sync.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';
33
- 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';
34
31
  import { createEffects } from '../../lib/installers/effects.js';
35
32
  import { syncStackTooling } from '../../lib/installers/stack-tooling.js';
36
33
  import { detectClaudeConfig } from '../../lib/detectors/claude-config-detector.js';
@@ -44,23 +41,25 @@ async function backupUserConfig(morphPath) {
44
41
  return (await pathExists(configPath)) ? readJson(configPath) : null;
45
42
  }
46
43
 
47
- export function frameworkDirsToClean(morphPath, targetPath) {
48
- 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) {
49
46
  return [
50
- // framework/templates is left out on purpose: reconcileLegacyTemplatesCopy() decides whether
51
- // a local copy is a user override to preserve.
52
47
  join(morphPath, 'framework', 'standards'),
53
48
  join(morphPath, 'framework', 'hooks'),
54
49
  join(morphPath, 'framework', 'schemas'),
55
50
  join(morphPath, 'framework', 'evals'),
56
51
  join(morphPath, 'config'),
57
- join(claudeDir, 'commands'),
58
- join(claudeDir, 'rules'),
59
- join(claudeDir, 'skills'),
60
- join(claudeDir, 'agents'),
61
52
  ];
62
53
  }
63
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
+
64
63
  function sweepRemove(dir, fx) {
65
64
  let entries;
66
65
  try {
@@ -83,12 +82,12 @@ function sweepRemove(dir, fx) {
83
82
  }
84
83
 
85
84
  /**
86
- * Os laços de órfão depois varrem estes mesmos destinos já vazios: em dry eles ficam calados,
87
- * 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.
88
87
  */
89
- function cleanFrameworkDirs(morphPath, targetPath, fx) {
88
+ function cleanFrameworkDirs(morphPath, targetPath, fx, { wipeAssets }) {
90
89
  const cleaned = [];
91
- for (const dir of frameworkDirsToClean(morphPath, targetPath)) {
90
+ for (const dir of [...frameworkDirsToClean(morphPath), ...(wipeAssets ? assetDirsToClean(targetPath) : [])]) {
92
91
  if (existsSync(dir)) cleaned.push({ dir, files: sweepRemove(dir, fx) });
93
92
  }
94
93
  return cleaned;
@@ -104,6 +103,7 @@ function restoreUserConfig(morphPath, targetPath, configBackup, currentVersion,
104
103
  fx.writeJson(configPath, configBackup);
105
104
  } else {
106
105
  const defaultConfig = {
106
+ $schema: CONFIG_SCHEMA_REF,
107
107
  frameworkVersion: currentVersion,
108
108
  project: { name: basename(resolve(targetPath)) },
109
109
  };
@@ -354,25 +354,37 @@ export async function updateCommand(options = {}) {
354
354
  logger.dim(' ✓ Created .morph directory structure');
355
355
  }
356
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
+
357
367
  const updateSpinner = ora(dryRun ? 'Prevendo efeitos...' : 'Updating MORPH-SPEC...').start();
358
368
  let cleaned = [];
359
369
 
360
370
  try {
361
371
  updateSpinner.text = 'Cleaning old framework files...';
362
- cleaned = cleanFrameworkDirs(morphPath, targetPath, fx);
372
+ cleaned = cleanFrameworkDirs(morphPath, targetPath, fx, { wipeAssets });
363
373
  // Written back at once: a failure in the installs below must not leave the project without its contract.
364
374
  if (configBackup) restoreUserConfig(morphPath, targetPath, configBackup, cliCheck.current, fx);
365
375
  logger.dim(' ✓ Old framework files removed');
366
376
 
367
- updateSpinner.text = 'Checking for a legacy templates copy...';
368
- const templatesReconcile = reconcileLegacyTemplatesCopy(join(morphPath, 'framework', 'templates'), 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.');
379
+ }
369
380
 
370
381
  updateSpinner.text = 'Updating standards, hooks, charter, schemas and evals...';
371
382
  for (const dir of ['standards', 'hooks', 'schemas', 'evals']) {
372
- fx.copyDir(join(frameworkDir, dir), join(morphPath, 'framework', dir));
383
+ fx.copyDir(join(frameworkDir, dir), join(morphPath, 'framework', dir), dir === 'hooks' ? { filter: hooksPayloadFilter } : {});
384
+ }
385
+ for (const file of ['agents.json', 'ai-pin.json', 'MORPH.md']) {
386
+ fx.copyFile(join(frameworkDir, file), join(morphPath, 'framework', file));
373
387
  }
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
388
  fx.copyFile(join(frameworkDir, 'docs', 'CLI.md'), join(morphPath, 'framework', 'CLI.md'));
377
389
  for (const dead of [join(morphPath, 'framework', 'phases.json'), join(morphPath, 'context', 'README.md')]) {
378
390
  if (existsSync(dead)) fx.remove(dead);
@@ -388,7 +400,7 @@ export async function updateCommand(options = {}) {
388
400
  if (configBackup) projectTags = getProjectTags(configBackup);
389
401
  } catch {}
390
402
  // The same detection as `syncStackRules`, folded in before the installs: `restoreUserConfig`
391
- // 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.
392
404
  if (configBackup) {
393
405
  try {
394
406
  const detected = detectStackTags(targetPath, { config: configBackup });
@@ -398,34 +410,16 @@ export async function updateCommand(options = {}) {
398
410
  logger.dim(` ✓ config.json: + ${merged.added.join(', ')} (detectado nos arquivos)`);
399
411
  }
400
412
  projectTags = [...new Set([...getProjectTags(configBackup), ...detected.tags])];
401
- } catch {}
402
- }
403
-
404
- let commandsCopied = false;
405
- const commandsSrc = join(frameworkDir, 'commands');
406
- if (await pathExists(commandsSrc)) {
407
- const commandsDest = join(claudeDest, 'commands');
408
- fx.ensureDir(commandsDest);
409
- installCommandsForStack(commandsSrc, commandsDest, projectTags, fx);
410
- commandsCopied = true;
411
- } else {
412
- 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
+ }
413
416
  }
414
417
 
415
- updateSpinner.text = 'Syncing morph skills to .claude/skills/...';
416
- const skillsResult = await installSkills(targetPath, { projectTags, fx });
417
-
418
- updateSpinner.text = 'Syncing agents to .claude/agents/...';
419
- const agentsResult = await installAgents(targetPath, frameworkDir, { projectTags, fx });
420
-
421
- updateSpinner.text = 'Syncing rules to .claude/rules/...';
422
- const rulesSrc = join(frameworkDir, 'rules');
423
- const rulesDest = join(claudeDest, 'rules');
424
- let rulesResult = null;
425
- if (await pathExists(rulesSrc)) {
426
- fx.ensureDir(rulesDest);
427
- rulesResult = installRulesForStack(rulesSrc, rulesDest, projectTags, fx);
428
- }
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;
429
423
 
430
424
  updateSpinner.text = 'Syncing .claude/CLAUDE.md...';
431
425
  const runtimeSrc = join(frameworkDir, 'CLAUDE.md');
@@ -447,7 +441,7 @@ export async function updateCommand(options = {}) {
447
441
  }
448
442
 
449
443
  updateSpinner.text = 'Updating Claude Code hooks...';
450
- const hooksResult = await installClaudeHooks(targetPath, { fx });
444
+ const hooksResult = await installClaudeHooks(targetPath, { fx, manifest: assets.manifest });
451
445
 
452
446
  updateSpinner.text = 'Syncing stack MCPs, skills and registries...';
453
447
  let tooling = null;
@@ -464,9 +458,7 @@ export async function updateCommand(options = {}) {
464
458
  logger.dim(` ⚠ MCPs do stack não sincronizados (${err.message})`);
465
459
  }
466
460
 
467
- updateSpinner.text = 'Checking CLAUDE.md import...';
468
- const claudeMdDest = join(targetPath, 'CLAUDE.md');
469
- await injectMorphImport(claudeMdDest, fx);
461
+ await removeMorphImport(join(targetPath, 'CLAUDE.md'), fx);
470
462
 
471
463
  updateSpinner.text = 'Restoring user configuration...';
472
464
  restoreUserConfig(morphPath, targetPath, configBackup, cliCheck.current, fx);
@@ -508,21 +500,15 @@ export async function updateCommand(options = {}) {
508
500
 
509
501
  logger.blank();
510
502
  logger.info('Updated files:');
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)');
515
- }
516
-
517
503
  // Counts make a silent stack-filter downgrade visible (a dotnet project with "1 persona");
518
504
  // only compact tags, since integrations are long free text.
519
505
  const compactTags = projectTags.filter(t => !t.includes(' '));
520
506
  const tagsLabel = compactTags.length > 0 ? compactTags.join('+') : 'universal only';
521
507
  logger.dim(` ✓ .claude/settings.local.json (${hooksResult.installed} hooks installed)`);
522
- logger.dim(` ✓ .claude/skills/ (${skillsResult?.installed ?? '?'} skills — stack: ${tagsLabel})`);
523
- logger.dim(` ✓ .claude/agents/ (${agentsResult?.agents?.length ?? '?'} personas — stack: ${tagsLabel})`);
524
- logger.dim(` ✓ .claude/rules/ (${rulesResult?.installed ?? '?'} stack-filtered rules)`);
525
- 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)`);
526
512
  if (tooling?.mcps.length) logger.dim(` ✓ .mcp.json (+ ${tooling.mcps.join(', ')})`);
527
513
  if (tooling?.skills.length) logger.dim(` ✓ .claude/skills/ (+ skill de ${tooling.skills.join(', ')})`);
528
514
  if (tooling?.registries.length) logger.dim(` ✓ components.json (+ ${tooling.registries.join(', ')})`);
@@ -1,6 +1,6 @@
1
1
  import chalk from 'chalk';
2
- import { readFileSync, statSync } from 'fs';
3
- import { relative } from 'path';
2
+ import { readFileSync, readdirSync, statSync } from 'fs';
3
+ import { join, relative } from 'path';
4
4
  import { logger } from '../../utils/logger.js';
5
5
  import {
6
6
  scaffoldDotnetSlice,
@@ -108,16 +108,37 @@ export async function scaffoldNextjsCommand(feature, options) {
108
108
  }
109
109
  }
110
110
 
111
- /** Prints a package template verbatim: templates are never copied into the project. */
112
- export function scaffoldShowCommand(templateId) {
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) {
113
124
  if (!getTemplateById(templateId)) {
114
125
  logger.error(`Template "${templateId}" not found in the package registry`);
115
126
  process.exit(1);
116
127
  }
117
128
  const path = resolveFrameworkTemplatePath(templateId);
118
- if (statSync(path).isDirectory()) {
119
- logger.error(`Template "${templateId}" is a whole project, not a single file`);
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`);
120
141
  process.exit(1);
121
142
  }
122
- process.stdout.write(readFileSync(path, 'utf-8'));
143
+ process.stdout.write(readFileSync(join(path, wanted), 'utf-8'));
123
144
  }
@@ -4,6 +4,7 @@
4
4
  import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
7
+ import { stripBom } from '../json-file.js';
7
8
 
8
9
  export const SCAN_IGNORED_DIRS = new Set([
9
10
  'node_modules',
@@ -33,10 +34,6 @@ export function isAiPackage(name) {
33
34
  );
34
35
  }
35
36
 
36
- function stripBom(text) {
37
- return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
38
- }
39
-
40
37
  /** Tags fecham na ordem e todo `<` tem `>`: um `.csproj` truncado vira `unreadable`, não "sem drift". */
41
38
  export function isWellFormedXml(xml) {
42
39
  const stack = [];
@@ -5,6 +5,7 @@
5
5
  import { readFileSync } from 'node:fs';
6
6
  import { relative } from 'node:path';
7
7
  import { collectProjectFiles } from './ai-project-scan.js';
8
+ import { lineOf } from '../text.js';
8
9
  import { stripComments } from '../../../framework/hooks/shared/comment-stripper.js';
9
10
 
10
11
  /** Símbolos renomeados antes do 1.0 GA, e o nome vivo de cada um. */
@@ -14,12 +15,6 @@ const RENAMED_SYMBOLS = {
14
15
  ChatMessageStore: 'a conversa persistida do projeto (ver ai-agents/agent-session.md)',
15
16
  };
16
17
 
17
- function lineOf(text, index) {
18
- let line = 1;
19
- for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line += 1;
20
- return line;
21
- }
22
-
23
18
  function collectCsharpFiles(root) {
24
19
  return collectProjectFiles(root, (name) => name.toLowerCase().endsWith('.cs'));
25
20
  }
@@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { isAbsolute, join, basename } from 'node:path';
7
7
  import { collectProjectFiles } from './ai-project-scan.js';
8
+ import { stripBom } from '../json-file.js';
8
9
  import { jsoncToJson } from '../../../framework/hooks/shared/comment-stripper.js';
9
10
 
10
11
  const MAX_JSON_CHARS = 512 * 1024;
@@ -15,7 +16,7 @@ function readJsonSafe(file) {
15
16
  try {
16
17
  const raw = readFileSync(file, 'utf8');
17
18
  if (raw.length > MAX_JSON_CHARS) return null;
18
- const text = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
19
+ const text = stripBom(raw);
19
20
  try {
20
21
  return JSON.parse(text);
21
22
  } catch {
@@ -1,12 +1,13 @@
1
- import { existsSync, readFileSync } from 'fs';
1
+ import { existsSync } from 'fs';
2
2
  import { join } from 'path';
3
+ import { readJsonFile } from '../json-file.js';
3
4
  import { CONTRACT_FILE } from '../../../framework/hooks/shared/contract.js';
4
5
 
5
6
  export function readMorphConfig(projectPath) {
6
7
  const configPath = join(projectPath, CONTRACT_FILE);
7
8
  if (!existsSync(configPath)) return null;
8
9
  try {
9
- return JSON.parse(readFileSync(configPath, 'utf8').replace(/^/, ''));
10
+ return readJsonFile(configPath);
10
11
  } catch {
11
12
  return null;
12
13
  }
@@ -3,6 +3,7 @@ import { dirname, join } from 'path';
3
3
  import { atomicWriteJson } from '../../utils/atomic-json.js';
4
4
  import { CONTRACT_FILE } from '../../../framework/hooks/shared/contract.js';
5
5
  import { readMorphConfig } from '../config/project-config.js';
6
+ import { readJsonFile } from '../json-file.js';
6
7
  import { getProjectTags, parseStacks, shouldInstall } from '../stack-filter.js';
7
8
  import { scanRepo } from './scan.js';
8
9
  import { contractFromScan } from './defaults.js';
@@ -12,7 +13,7 @@ const FRAMEWORK_SRC = join(import.meta.dirname, '..', '..', '..', 'framework');
12
13
  // Inside config.json, not beside it: `update` wipes .morph/config/ and restores only that file.
13
14
  export const PRINTS_KEY = '_generated';
14
15
 
15
- const readJson = (path) => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
16
+ const readJson = (path) => { try { return readJsonFile(path); } catch { return null; } };
16
17
 
17
18
  /** What `init` would write, without writing: the dry run and the real run share it. */
18
19
  export function planContract(root) {
@@ -63,6 +63,7 @@ export function mergeContract(config, contract, previousPrints = {}) {
63
63
  out.project ??= {};
64
64
  const p = out.project;
65
65
 
66
+ out.$schema ??= '../framework/schemas/config.schema.json';
66
67
  out.contractVersion = contract.contractVersion;
67
68
  p.stack = mergeValue('project.stack', p.stack, contract.stack, prints, report);
68
69
  p.tags = mergeValue('project.tags', p.tags, contract.tags, prints, report);