@polymorphism-tech/morph-spec 11.2.0 → 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 (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 +2 -2
  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
@@ -12,12 +12,11 @@ import {
12
12
  } from '../utils/file-copier.js';
13
13
  import { getProjectTags } from '../lib/stack-filter.js';
14
14
  import { readMorphConfig } from '../lib/config/project-config.js';
15
- import { injectMorphImport } from '../utils/claude-md-injector.js';
15
+ import { removeMorphImport } from '../utils/claude-md-injector.js';
16
16
  import { saveProjectMorphVersion, getInstalledCLIVersion, getProjectMorphVersion } from '../utils/version-checker.js';
17
17
  import { installClaudeHooks, installGlobalStatusline } from '../utils/claude-settings-manager.js';
18
- import { reconcileLegacyTemplatesCopy } from '../lib/installers/templates-reconcile.js';
19
18
  import { realEffects } from '../lib/installers/effects.js';
20
- import { installAssetsForTags } from '../lib/installers/stack-assets.js';
19
+ import { installAssetsForTags, refreshAssetsForTags } from '../lib/installers/stack-assets.js';
21
20
 
22
21
  const FRAMEWORK_DIR = join(import.meta.dirname, '..', '..', 'framework');
23
22
 
@@ -25,6 +24,12 @@ const REQUIRED_PLUGINS = [
25
24
  'context7@claude-plugins-official',
26
25
  ];
27
26
 
27
+ // The status line runs from `~/.claude/` and imports only `shared/` from the project: its project copy has no reader.
28
+ export const hooksPayloadFilter = (from) => !['statusline.js', 'README.md'].includes(basename(from));
29
+
30
+ // Relative to `.morph/config/config.json`: the editor validates the contract against the installed schema.
31
+ export const CONFIG_SCHEMA_REF = '../framework/schemas/config.schema.json';
32
+
28
33
  const toolInstallOff = () => process.env.MORPH_NO_TOOL_INSTALL === '1';
29
34
 
30
35
  function installRequiredPlugins(log, exec) {
@@ -43,10 +48,13 @@ function installRequiredPlugins(log, exec) {
43
48
  }
44
49
  }
45
50
 
46
- async function installStackAwareAssets(targetPath, log) {
51
+ // The full install writes the manifest and installs the hooks itself, deny included; `--reinstall` only follows a manifest that exists.
52
+ async function installStackAwareAssets(targetPath, log, { full }) {
47
53
  const projectTags = getProjectTags(readMorphConfig(targetPath));
48
54
  log('Installing stack-filtered rules, commands, skills and agents...');
49
- const agentCounts = await installAssetsForTags(targetPath, projectTags, { frameworkSrc: FRAMEWORK_DIR });
55
+ const { agents: agentCounts } = full
56
+ ? await installAssetsForTags(targetPath, projectTags, { frameworkSrc: FRAMEWORK_DIR, createManifest: true })
57
+ : await refreshAssetsForTags(targetPath, projectTags, { frameworkSrc: FRAMEWORK_DIR });
50
58
  return { agentCounts, projectTags };
51
59
  }
52
60
 
@@ -78,7 +86,7 @@ export async function updateClaudeMdAgentsBlock(claudeMdPath, agents = [], optio
78
86
  * Headless install: no prompts, no stack detection.
79
87
  */
80
88
  export async function setupInfra(targetPath, {
81
- _exec = execSync, _detectGraphifyVersion = null, _log = null, reinstall = false,
89
+ _exec = execSync, _detectGraphifyVersion = null, _detectInstaller = null, _log = null, reinstall = false,
82
90
  } = {}) {
83
91
  const quiet = process.env.MORPH_QUIET === '1';
84
92
 
@@ -89,7 +97,7 @@ export async function setupInfra(targetPath, {
89
97
 
90
98
  if (reinstall) {
91
99
  log('setup-infra (reinstall): re-installing stack-aware assets...');
92
- const { agentCounts } = await installStackAwareAssets(targetPath, log);
100
+ const { agentCounts } = await installStackAwareAssets(targetPath, log, { full: false });
93
101
  await updateClaudeMdAgentsBlock(join(targetPath, '.claude', 'CLAUDE.md'), agentCounts?.agents ?? []);
94
102
  log('setup-infra (reinstall): complete.');
95
103
  return { agents: { installed: agentCounts?.installed ?? 0 } };
@@ -97,10 +105,8 @@ export async function setupInfra(targetPath, {
97
105
 
98
106
  installRequiredPlugins(log, _exec);
99
107
 
100
- log('Setting up CLAUDE.md...');
101
108
  const claudeMdSrc = join(FRAMEWORK_DIR, 'CLAUDE.md');
102
- const importResult = await injectMorphImport(join(targetPath, 'CLAUDE.md'));
103
- log(` ✓ Root CLAUDE.md: ${importResult}`);
109
+ if ((await removeMorphImport(join(targetPath, 'CLAUDE.md'))).startsWith('removed')) log(' ✓ CLAUDE.md da raiz sem o import antigo: o Claude Code carrega .claude/CLAUDE.md sozinho');
104
110
 
105
111
  log('Creating .morph structure...');
106
112
  const morphPath = join(targetPath, '.morph');
@@ -113,37 +119,20 @@ export async function setupInfra(targetPath, {
113
119
  const configPath = join(configDir, 'config.json');
114
120
  if (!(await pathExists(configPath))) {
115
121
  await writeJson(configPath, {
122
+ $schema: CONFIG_SCHEMA_REF,
116
123
  frameworkVersion: getInstalledCLIVersion(),
117
124
  project: { name: basename(resolve(targetPath)) },
118
125
  });
119
126
  }
120
127
 
121
- // A legacy copy shadows the package templates (override-first); the prior version is read here,
122
- // before `.morph/.morphversion` is rewritten below.
123
- const legacyTemplatesDir = join(frameworkDestDir, 'templates');
124
- if (await pathExists(legacyTemplatesDir)) {
125
- const priorVersionInfo = await getProjectMorphVersion(targetPath);
126
- if (priorVersionInfo) {
127
- const result = reconcileLegacyTemplatesCopy(legacyTemplatesDir, priorVersionInfo.morphVersion);
128
- if (result === 'removed-legacy') {
129
- log(' ✓ .morph/framework/templates/ (cópia legada de instalação antiga removida — resolvida do pacote)');
130
- } else {
131
- log(' ⚠ .morph/framework/templates/ (override local presente — preservado, não reconciliado)');
132
- }
133
- } else {
134
- log(' ⚠ .morph/framework/templates/ existe (instalação antiga) e tem precedência sobre os templates do pacote — sem versão anterior registrada em .morph/.morphversion para decidir com segurança; rode `morph-spec update` para reconciliar, ou apague se não for customização sua.');
135
- }
136
- }
137
-
138
- log('Copying standards, hooks, review checklist, schemas, agents.json, MORPH.md and CLI.md...');
128
+ log('Copying standards, hooks, review checklist, schemas, agents.json, ai-pin.json, MORPH.md and CLI.md...');
139
129
  for (const dir of ['standards', 'hooks', 'evals', 'schemas']) {
140
- await copyDirectory(join(FRAMEWORK_DIR, dir), join(frameworkDestDir, dir));
130
+ await copyDirectory(join(FRAMEWORK_DIR, dir), join(frameworkDestDir, dir), dir === 'hooks' ? { filter: hooksPayloadFilter } : {});
141
131
  }
142
- await copyFile(join(FRAMEWORK_DIR, 'agents.json'), join(frameworkDestDir, 'agents.json'));
143
- await copyFile(join(FRAMEWORK_DIR, 'MORPH.md'), join(frameworkDestDir, 'MORPH.md'));
132
+ for (const file of ['agents.json', 'ai-pin.json', 'MORPH.md']) await copyFile(join(FRAMEWORK_DIR, file), join(frameworkDestDir, file));
144
133
  await copyFile(join(FRAMEWORK_DIR, 'docs', 'CLI.md'), join(frameworkDestDir, 'CLI.md'));
145
134
 
146
- const { agentCounts, projectTags } = await installStackAwareAssets(targetPath, log);
135
+ const { agentCounts, projectTags } = await installStackAwareAssets(targetPath, log, { full: true });
147
136
 
148
137
  log('Installing .claude/CLAUDE.md...');
149
138
  const runtimeClaudeMdDest = join(targetPath, '.claude', 'CLAUDE.md');
@@ -194,7 +183,7 @@ export async function setupInfra(targetPath, {
194
183
  if (installed === GRAPHIFY_VERSION) {
195
184
  log(` ✓ graphify ${installed} já instalado`);
196
185
  } else {
197
- const { kind } = detectInstaller();
186
+ const kind = toolInstallOff() ? null : (_detectInstaller ?? detectInstaller)().kind;
198
187
  if (toolInstallOff()) {
199
188
  log(` ○ graphify não instalado (MORPH_NO_TOOL_INSTALL=1). Depois: uv tool install ${GRAPHIFY_PACKAGE}==${GRAPHIFY_VERSION}`);
200
189
  } else if (!kind) {
@@ -2,6 +2,7 @@ import { readFileSync, existsSync, readdirSync } from 'node:fs';
2
2
  import { join } from 'path';
3
3
  import { shouldInstall } from '../lib/stack-filter.js';
4
4
  import { realEffects } from '../lib/installers/effects.js';
5
+ import { pruneOwned } from '../lib/installers/install-manifest.js';
5
6
  import { REVIEW_ROLES, VERDICT_TOKEN, REVIEWED_SHA_TOKEN, VERDICTS } from '../lib/review-reports.js';
6
7
 
7
8
  const DEFAULT_AGENT_TOOLS = 'Read, Glob, Grep, Bash';
@@ -94,10 +95,9 @@ const MANAGED_HEADER =
94
95
  ' Do NOT edit by hand: changes are overwritten on `morph-spec update` / `setup-infra --reinstall`.\n' +
95
96
  ' Drift is flagged by `morph-spec doctor`. -->';
96
97
 
97
- const MANAGED_HEADER_MARKER = MANAGED_HEADER.split('\n')[0];
98
-
98
+ /** `previous`: the agents the manifest records. `prune: false` when the caller already emptied `.claude/agents/`. */
99
99
  export async function installAgents(projectDir, frameworkDir = 'framework', options = {}) {
100
- const { projectTags = [], fx = realEffects() } = options;
100
+ const { projectTags = [], fx = realEffects(), previous = [], prune = true } = options;
101
101
 
102
102
  const agentsJsonPath = join(frameworkDir, 'agents.json');
103
103
  const agentsJson = JSON.parse(readFileSync(agentsJsonPath, 'utf-8'));
@@ -120,10 +120,9 @@ export async function installAgents(projectDir, frameworkDir = 'framework', opti
120
120
 
121
121
  const eligible = agents.filter(a => agentEligible(a, projectTags));
122
122
 
123
- const allPossible = new Set(agents.map(a => `morph-${a.id}.md`));
123
+ const shipped = agents.map(a => `morph-${a.id}.md`);
124
124
 
125
- let installed = 0;
126
- const installedFilenames = new Set();
125
+ const names = [];
127
126
  const installedAgents = [];
128
127
 
129
128
  for (const agent of eligible) {
@@ -131,36 +130,19 @@ export async function installAgents(projectDir, frameworkDir = 'framework', opti
131
130
  const targetPath = join(targetDir, filename);
132
131
 
133
132
  fx.writeFile(targetPath, renderAgentMd(agent, knownMcpIds));
134
- installedFilenames.add(filename);
133
+ names.push(filename);
135
134
  installedAgents.push({
136
135
  id: agent.id,
137
136
  name: `morph-${agent.id}`,
138
137
  title: agent.title ?? agent.id,
139
138
  domains: agent.domains ?? [],
140
139
  });
141
- installed++;
142
140
  }
143
141
 
144
- // Silent in dryRun: the real update's cleanFrameworkDirs() already emptied the dir.
145
- if (!fx.dryRun) {
146
- for (const file of readdirSync(targetDir)) {
147
- if (installedFilenames.has(file)) continue;
148
- const path = join(targetDir, file);
149
- if (allPossible.has(file) || isManagedOrphan(file, path)) fx.remove(path);
150
- }
151
- }
142
+ // A persona dropped from agents.json is in `previous` (the manifest); a hand-written morph-*.md is in neither list.
143
+ if (prune) pruneOwned(targetDir, { previous, shipped, installed: names, fx });
152
144
 
153
- return { installed, agents: installedAgents };
154
- }
155
-
156
- // Only the managed header proves the file is ours: a hand-written morph-*.md is never deleted.
157
- function isManagedOrphan(file, path) {
158
- if (!file.startsWith('morph-') || !file.endsWith('.md')) return false;
159
- try {
160
- return readFileSync(path, 'utf-8').includes(MANAGED_HEADER_MARKER);
161
- } catch {
162
- return false;
163
- }
145
+ return { installed: names.length, names, agents: installedAgents };
164
146
  }
165
147
 
166
148
  // Deterministic: the doctor drift check compares files byte-for-byte against this output.
@@ -210,12 +192,13 @@ export const REVIEW_REPORT_CONTRACT = [
210
192
  '## Relatório da revisão',
211
193
  '',
212
194
  'Grave o relatório que o dispatch nomeia antes de encerrar — o arquivo é o retorno, não a mensagem final. ' +
213
- 'Se ele já existir quando você começar, é resíduo de outra rodada: não o leia antes de escrever o seu (ancoragem no veredito alheio), ' +
214
- 'e não leia os relatórios dos outros papéis.',
195
+ 'Se ele já existir quando você começar e o dispatch não trouxer `confirma:`, é resíduo de outra revisão: não o leia antes de escrever o seu (ancoragem no veredito alheio). ' +
196
+ 'Com `confirma: <sha>` o arquivo é o seu relatório: leia-o e acrescente `## Confirmação` ao fim, sem reescrever o que está acima. ' +
197
+ 'Nunca leia os relatórios dos outros papéis.',
215
198
  '',
216
199
  `Primeira linha \`${VERDICT_TOKEN} ${VERDICTS.join('|')}\`, depois \`${REVIEWED_SHA_TOKEN} {sha}\`, ` +
217
200
  'tabela `## Bloqueadores` (`| id | tipo | onde | evidência |`; vazia = `Nenhum.`) e `## Notas`. ' +
218
- 'Bloqueador só com evidência e tipo; o resto é nota, e nota nunca pede rodada nova.',
201
+ 'Bloqueador só com evidência e tipo; o resto é nota, com `arquivo:linha` e o que mudar.',
219
202
  ];
220
203
 
221
204
  function buildBody(agent, maxTurns) {
@@ -2,58 +2,24 @@ import { pathExists, readFile } from './file-copier.js';
2
2
  import { realEffects } from '../lib/installers/effects.js';
3
3
 
4
4
  const MORPH_IMPORT = '@.claude/CLAUDE.md';
5
- const MORPH_MARKER = 'MORPH-SPEC';
5
+ const CREATED_BY_MORPH = `# Project\n\n${MORPH_IMPORT}`;
6
+ const INJECTED_BLOCK = /\n*## MORPH-SPEC\s*\n+@\.claude\/CLAUDE\.md[ \t]*\n?/;
7
+ const IMPORT_LINE = /^@\.claude\/CLAUDE\.md[ \t]*\r?\n?/m;
6
8
 
7
9
  /**
8
- * Leaves the user's root CLAUDE.md in place and only adds the morph-spec @import.
9
- * @returns {Promise<'created'|'migrated'|'injected'|'already-present'>}
10
+ * Claude Code loads `.claude/CLAUDE.md` by itself, so the import older versions wrote into the root
11
+ * CLAUDE.md is removed; a root file that held nothing else was created by morph-spec and goes too.
12
+ * @returns {Promise<'absent'|'clean'|'removed-file'|'removed-import'>}
10
13
  */
11
- export async function injectMorphImport(claudeMdPath, fx = realEffects()) {
12
- if (!await pathExists(claudeMdPath)) {
13
- fx.writeFile(claudeMdPath, `# Project\n\n${MORPH_IMPORT}\n`);
14
- return 'created';
14
+ export async function removeMorphImport(claudeMdPath, fx = realEffects()) {
15
+ if (!await pathExists(claudeMdPath)) return 'absent';
16
+ const content = (await readFile(claudeMdPath)).replace(/\r\n/g, '\n');
17
+ if (!content.includes(MORPH_IMPORT)) return 'clean';
18
+ if (content.trim() === CREATED_BY_MORPH) {
19
+ fx.remove(claudeMdPath);
20
+ return 'removed-file';
15
21
  }
16
-
17
- const content = await readFile(claudeMdPath);
18
-
19
- if (content.includes(MORPH_IMPORT)) {
20
- return 'already-present';
21
- }
22
-
23
- if (isMorphOnly(content)) {
24
- fx.writeFile(claudeMdPath, `# Project\n\n${MORPH_IMPORT}\n`);
25
- return 'migrated';
26
- }
27
-
28
- const separator = content.endsWith('\n') ? '\n' : '\n\n';
29
- fx.writeFile(claudeMdPath, `${content}${separator}## MORPH-SPEC\n\n${MORPH_IMPORT}\n`);
30
- return 'injected';
31
- }
32
-
33
- function isMorphOnly(content) {
34
- if (!content.includes(MORPH_MARKER)) return false;
35
-
36
- const stripped = content
37
- .replace(/# MORPH-SPEC Runtime Instructions/g, '')
38
- .replace(/by Polymorphism Tech[^\n]*/g, '')
39
- .replace(/\*MORPH-SPEC by Polymorphism Tech\*/g, '')
40
- .replace(/@\.morph\/context\/README\.md/g, '')
41
- .replace(/@\.claude\/CLAUDE\.md/g, '')
42
- .replace(/## Critical Rules[\s\S]*?(?=##|$)/g, '')
43
- .replace(/## Quick Reference[\s\S]*?(?=##|$)/g, '')
44
- .replace(/## State & Outputs[\s\S]*?(?=##|$)/g, '')
45
- .replace(/## Phase Sequence[\s\S]*?(?=##|$)/g, '')
46
- .replace(/## Agents[\s\S]*?(?=##|$)/g, '')
47
- .replace(/## Context Window Tip[\s\S]*?(?=##|$)/g, '')
48
- .replace(/## Project Context[\s\S]*?(?=##|$)/g, '')
49
- .replace(/[#\-|>*`\s]/g, '');
50
-
51
- return stripped.length < 50;
52
- }
53
-
54
- export async function checkClaudeMdImport(claudeMdPath) {
55
- if (!await pathExists(claudeMdPath)) return 'missing';
56
- const content = await readFile(claudeMdPath);
57
- if (content.includes(MORPH_IMPORT)) return 'ok';
58
- return 'missing-import';
22
+ const stripped = INJECTED_BLOCK.test(content) ? content.replace(INJECTED_BLOCK, '\n') : content.replace(IMPORT_LINE, '');
23
+ fx.writeFile(claudeMdPath, `${stripped.trimEnd()}\n`);
24
+ return 'removed-import';
59
25
  }
@@ -1,7 +1,7 @@
1
1
  import { join } from 'path';
2
2
  import { readFile, writeFile, mkdir, copyFile, unlink } from 'fs/promises';
3
3
  import { existsSync } from 'fs';
4
- import { MORPH_ALLOW, MORPH_DENY } from './hooks-installer.js';
4
+ import { MORPH_ALLOW, managedDeny } from './hooks-installer.js';
5
5
 
6
6
  const MORPH_MANAGED_KEY = '_morph_managed';
7
7
 
@@ -28,7 +28,7 @@ export async function resetMorphSettings(targetPath) {
28
28
  const backupPath = settingsPath + '.backup';
29
29
  await copyFile(settingsPath, backupPath);
30
30
 
31
- const footprint = { deny: MORPH_DENY, allow: MORPH_ALLOW, envKeys: LEGACY_ENV_KEYS };
31
+ const footprint = { deny: managedDeny(settings), allow: MORPH_ALLOW, envKeys: LEGACY_ENV_KEYS };
32
32
  const permissionsRemoved = [];
33
33
  const envRemoved = [];
34
34
 
@@ -4,6 +4,7 @@ import { join, dirname, resolve } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { WORKTREE_DIR_NAMES } from '../lib/scan/worktree-dirs.js';
6
6
  import { realEffects } from '../lib/installers/effects.js';
7
+ import { stripBom } from '../lib/json-file.js';
7
8
 
8
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
10
  const frameworkRoot = join(__dirname, '..', '..');
@@ -40,9 +41,7 @@ export async function pathExists(path) {
40
41
  }
41
42
 
42
43
  export async function readJson(path) {
43
- // PowerShell 5.1's `Out-File -Encoding utf8` writes a BOM that JSON.parse rejects.
44
- const raw = await fs.readFile(path, 'utf-8');
45
- return JSON.parse(raw.replace(/^/, ''));
44
+ return JSON.parse(stripBom(await fs.readFile(path, 'utf-8')));
46
45
  }
47
46
 
48
47
  export async function writeJson(path, data) {
@@ -63,7 +62,7 @@ export async function readFile(path) {
63
62
  return fs.readFile(path, 'utf8');
64
63
  }
65
64
 
66
- export const MORPH_GITIGNORE_ENTRIES = [
65
+ const MORPH_GITIGNORE_ENTRIES = [
67
66
  '.morph/framework/',
68
67
  '.morph/memory/',
69
68
  '.morph/plans/',
@@ -1,11 +1,12 @@
1
1
  import { join } from 'path';
2
2
  import { readFile } from 'fs/promises';
3
- import { existsSync } from 'fs';
3
+ import { existsSync, readFileSync } from 'fs';
4
4
  import { homedir } from 'os';
5
5
  import { realEffects } from '../lib/installers/effects.js';
6
+ import { readManifest } from '../lib/installers/install-manifest.js';
6
7
  import { SHELL_TOOLS } from '../../framework/hooks/shared/payload-utils.js';
7
8
 
8
- const HOOKS_VERSION = '4.1.0';
9
+ export const HOOKS_VERSION = '4.1.0';
9
10
 
10
11
  const SHELL_MATCHER = [...SHELL_TOOLS].join('|');
11
12
 
@@ -14,11 +15,58 @@ const SHELL_MATCHER = [...SHELL_TOOLS].join('|');
14
15
  export const MORPH_DENY = [
15
16
  'Edit(.morph/framework/**)',
16
17
  'Edit(.claude/CLAUDE.md)',
18
+ ];
19
+
20
+ // Whole folders, as written before the manifest: they left the project no rule, skill or `morph-*` agent of its own.
21
+ const LEGACY_DENY = [
17
22
  'Edit(.claude/rules/**)',
18
23
  'Edit(.claude/agents/morph-*)',
19
24
  'Edit(.claude/skills/**)',
20
25
  ];
21
26
 
27
+ /** One entry per rule, agent and skill the manifest records; commands stay editable, as they always were. */
28
+ export function assetDeny(manifest) {
29
+ if (!manifest) return [];
30
+ return [
31
+ ...manifest.rules.map((file) => `Edit(.claude/rules/${file})`),
32
+ ...manifest.agents.map((file) => `Edit(.claude/agents/${file})`),
33
+ ...manifest.skills.map((name) => `Edit(.claude/skills/${name}/**)`),
34
+ ];
35
+ }
36
+
37
+ /** Every deny entry morph-spec may have written into this settings object: the list it recorded, the fixed ones and the legacy ones. */
38
+ export function managedDeny(settings) {
39
+ const recorded = settings?._morph_managed?.deny;
40
+ return [...new Set([...MORPH_DENY, ...LEGACY_DENY, ...(Array.isArray(recorded) ? recorded : [])])];
41
+ }
42
+
43
+ function applyManagedDeny(settings, manifest) {
44
+ const wanted = [...MORPH_DENY, ...assetDeny(manifest)];
45
+ const ours = new Set([...managedDeny(settings), ...wanted]);
46
+ const current = Array.isArray(settings.permissions?.deny) ? settings.permissions.deny : [];
47
+ settings.permissions = settings.permissions || {};
48
+ settings.permissions.deny = [...current.filter((p) => !ours.has(p)), ...wanted];
49
+ settings._morph_managed = settings._morph_managed || {};
50
+ settings._morph_managed.deny = wanted;
51
+ }
52
+
53
+ /**
54
+ * For a path that changes the installed assets without reinstalling the hooks. A settings file
55
+ * the installer never wrote, or a project with no manifest, is left as it is.
56
+ */
57
+ export function syncAssetDeny(targetPath, { fx = realEffects(), manifest = readManifest(targetPath) } = {}) {
58
+ const settingsPath = join(targetPath, '.claude', 'settings.local.json');
59
+ if (!manifest || !existsSync(settingsPath)) return false;
60
+ let settings;
61
+ try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }
62
+ if (!settings?._morph_managed) return false;
63
+ const before = JSON.stringify([settings.permissions?.deny, settings._morph_managed.deny]);
64
+ applyManagedDeny(settings, manifest);
65
+ if (JSON.stringify([settings.permissions.deny, settings._morph_managed.deny]) === before) return false;
66
+ fx.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n');
67
+ return true;
68
+ }
69
+
22
70
  export const MORPH_ALLOW = [
23
71
  'Edit(.morph/features/**)',
24
72
  'Edit(.morph/context/**)',
@@ -29,7 +77,7 @@ export const MORPH_ALLOW = [
29
77
  // A multi-hook group is ONE `core/chain.js` command whose `args` list the hooks in
30
78
  // run order (block-first-wins). `args` stays separate from `command`: getHookSubpath()
31
79
  // would capture inlined args into the quoted path. `timeout` is in SECONDS.
32
- const MORPH_HOOKS = [
80
+ export const MORPH_HOOKS = [
33
81
  {
34
82
  event: 'PreToolUse',
35
83
  matcher: 'Write|Edit',
@@ -81,10 +129,11 @@ const MORPH_HOOKS = [
81
129
  ];
82
130
 
83
131
  /**
84
- * Idempotent merge of the MORPH-SPEC hooks into `.claude/settings.local.json`.
132
+ * Idempotent merge of the MORPH-SPEC hooks into `.claude/settings.local.json`. Runs AFTER the assets:
133
+ * the deny is one entry per asset of the manifest (`manifest` in memory on `--dry-run`, which writes none).
85
134
  * @returns {Promise<{ installed: number }>}
86
135
  */
87
- export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}) {
136
+ export async function installClaudeHooks(targetPath, { fx = realEffects(), manifest = readManifest(targetPath) } = {}) {
88
137
  const claudeDir = join(targetPath, '.claude');
89
138
  const settingsPath = join(claudeDir, 'settings.local.json');
90
139
 
@@ -127,15 +176,9 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
127
176
  installed++;
128
177
  }
129
178
 
130
- settings.permissions = settings.permissions || {};
131
- settings.permissions.deny = settings.permissions.deny || [];
179
+ applyManagedDeny(settings, manifest);
132
180
  settings.permissions.allow = settings.permissions.allow || [];
133
181
 
134
- settings.permissions.deny = settings.permissions.deny.filter(p => !MORPH_DENY.includes(p));
135
- for (const perm of MORPH_DENY) {
136
- settings.permissions.deny.push(perm);
137
- }
138
-
139
182
  // An entry that left MORPH_ALLOW would survive forever in an existing install unless named here.
140
183
  const STALE_ALLOW = ['Edit(.morph/state.json)'];
141
184
  settings.permissions.allow = settings.permissions.allow.filter(
@@ -239,11 +282,3 @@ function getHookSubpath(command) {
239
282
  const match = command.match(/claude-code\/(.+)$/);
240
283
  return match ? match[1] : command;
241
284
  }
242
-
243
- export function getHooksVersion() {
244
- return HOOKS_VERSION;
245
- }
246
-
247
- export function getHookDefinitions() {
248
- return MORPH_HOOKS;
249
- }
@@ -1,96 +1,36 @@
1
- import { existsSync, readdirSync, statSync, readFileSync } from 'fs';
1
+ import { existsSync, readdirSync, readFileSync } from 'fs';
2
2
  import { basename, join } from 'path';
3
- import { fileURLToPath } from 'url';
4
3
  import { parseStacks, shouldInstall } from '../lib/stack-filter.js';
5
4
  import { realEffects } from '../lib/installers/effects.js';
5
+ import { pruneOwned } from '../lib/installers/install-manifest.js';
6
6
 
7
- const __dirname = fileURLToPath(new URL('.', import.meta.url));
8
- const FRAMEWORK_SKILLS_DIR = join(__dirname, '..', '..', 'framework', 'skills');
9
-
10
- const SKILL_LEVELS_TO_INSTALL = ['core'];
7
+ const CORE_SKILLS_DIR = join(import.meta.dirname, '..', '..', 'framework', 'skills', 'core');
11
8
 
12
9
  export function shouldInstallSkill(skillContent, projectTags) {
13
10
  return shouldInstall(parseStacks(skillContent), projectTags);
14
11
  }
15
12
 
16
- function copySkillDirectory(src, dest, fx) {
17
- fx.copyDir(src, dest, { filter: (from) => basename(from) !== 'README.md' });
18
- }
19
-
20
- function installSkillsFromDir(srcDir, destDir, projectTags, installedNow, fx) {
21
- const entries = readdirSync(srcDir);
22
- for (const entry of entries) {
23
- const srcPath = join(srcDir, entry);
24
- const stat = statSync(srcPath);
25
-
26
- if (stat.isDirectory()) {
27
- const skillMdPath = join(srcPath, 'SKILL.md');
28
- if (existsSync(skillMdPath)) {
29
- const content = readFileSync(skillMdPath, 'utf-8');
30
- if (!shouldInstallSkill(content, projectTags)) continue;
31
- const skillDestDir = join(destDir, entry);
32
- copySkillDirectory(srcPath, skillDestDir, fx);
33
- installedNow.add(entry);
34
- } else {
35
- installSkillsFromDir(srcPath, destDir, projectTags, installedNow, fx);
36
- }
37
- } else if (entry.endsWith('.md') && entry !== 'README.md') {
38
- const content = readFileSync(srcPath, 'utf-8');
39
- if (!shouldInstallSkill(content, projectTags)) continue;
40
- const skillName = entry.slice(0, -3);
41
- const skillDir = join(destDir, skillName);
42
- fx.ensureDir(skillDir);
43
- fx.copyFile(srcPath, join(skillDir, 'SKILL.md'));
44
- installedNow.add(skillName);
45
- }
46
- }
47
- }
48
-
49
- function collectSourceSkillNames() {
50
- const names = new Set();
51
- for (const level of SKILL_LEVELS_TO_INSTALL) {
52
- const levelDir = join(FRAMEWORK_SKILLS_DIR, level);
53
- if (!existsSync(levelDir)) continue;
54
- collectNamesFromDir(levelDir, names);
55
- }
56
- return names;
57
- }
58
-
59
- function collectNamesFromDir(dir, names) {
60
- for (const entry of readdirSync(dir)) {
61
- const fullPath = join(dir, entry);
62
- if (!statSync(fullPath).isDirectory()) continue;
63
- if (existsSync(join(fullPath, 'SKILL.md'))) {
64
- names.add(entry);
65
- } else {
66
- collectNamesFromDir(fullPath, names);
67
- }
68
- }
13
+ function sourceSkillNames() {
14
+ return readdirSync(CORE_SKILLS_DIR, { withFileTypes: true })
15
+ .filter((e) => e.isDirectory() && existsSync(join(CORE_SKILLS_DIR, e.name, 'SKILL.md')))
16
+ .map((e) => e.name);
69
17
  }
70
18
 
71
- export async function installSkills(projectDir, { projectTags = [], fx = realEffects() } = {}) {
19
+ /** `previous`: the skills the manifest records. `prune: false` when the caller already emptied `.claude/skills/`. */
20
+ export async function installSkills(projectDir, { projectTags = [], fx = realEffects(), previous = [], prune = true } = {}) {
72
21
  const claudeSkillsDir = join(projectDir, '.claude', 'skills');
73
22
  fx.ensureDir(claudeSkillsDir);
74
23
 
75
- // Tracked as we go: a disk scan can't tell this run's installs from leftovers
76
- // of a run with other projectTags, which a stack change must clean up.
77
- const installedNow = new Set();
78
- for (const level of SKILL_LEVELS_TO_INSTALL) {
79
- const levelDir = join(FRAMEWORK_SKILLS_DIR, level);
80
- if (!existsSync(levelDir)) continue;
81
- installSkillsFromDir(levelDir, claudeSkillsDir, projectTags, installedNow, fx);
24
+ const shipped = sourceSkillNames();
25
+ const names = [];
26
+ for (const name of shipped) {
27
+ const src = join(CORE_SKILLS_DIR, name);
28
+ if (!shouldInstallSkill(readFileSync(join(src, 'SKILL.md'), 'utf-8'), projectTags)) continue;
29
+ fx.copyDir(src, join(claudeSkillsDir, name), { filter: (from) => basename(from) !== 'README.md' });
30
+ names.push(name);
82
31
  }
83
32
 
84
- // Removes known framework skills not reinstalled this run; user skills are never touched.
85
- // Silent in dryRun: the real update's cleanFrameworkDirs() already emptied the dir.
86
- if (!fx.dryRun) {
87
- const allSourceSkills = collectSourceSkillNames();
88
- for (const entry of readdirSync(claudeSkillsDir)) {
89
- if (!installedNow.has(entry) && allSourceSkills.has(entry)) {
90
- fx.remove(join(claudeSkillsDir, entry));
91
- }
92
- }
93
- }
33
+ if (prune) pruneOwned(claudeSkillsDir, { previous, shipped, installed: names, fx });
94
34
 
95
- return { installed: installedNow.size };
35
+ return { installed: names.length, names };
96
36
  }