@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
@@ -2,9 +2,10 @@ 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
- export const DEFAULT_AGENT_TOOLS = 'Read, Glob, Grep, Bash';
8
+ const DEFAULT_AGENT_TOOLS = 'Read, Glob, Grep, Bash';
8
9
 
9
10
  export const DEFAULT_MAX_TURNS = 20;
10
11
 
@@ -31,7 +32,7 @@ export function maxTurnsError(id, value) {
31
32
  }
32
33
 
33
34
  // Claude Code's subagent `effort` field; an unknown value is ignored there, so it is refused here.
34
- export const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
35
+ const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
35
36
 
36
37
  export function effortError(id, value) {
37
38
  if (value === undefined || EFFORT_LEVELS.includes(value)) return null;
@@ -53,7 +54,7 @@ function personaError(agent) {
53
54
  }
54
55
 
55
56
  // `tools:` is a strict allowlist: without Skill no skill runs, without ToolSearch no deferred MCP tool loads.
56
- export const PLATFORM_TOOLS = ['Skill', 'ToolSearch'];
57
+ const PLATFORM_TOOLS = ['Skill', 'ToolSearch'];
57
58
 
58
59
  // A grant matches only its own spelling (`mcp__context7` vs `mcp__plugin_context7_context7`),
59
60
  // so every spelling becomes a grant; one the project does not configure is inert.
@@ -71,7 +72,7 @@ export function serverNamesProblem(id, value) {
71
72
  }
72
73
 
73
74
  /** @returns {Map<string, string[]>|null} id → server names; null = no registry (grant nothing) */
74
- export function loadKnownMcpIds(frameworkDir) {
75
+ function loadKnownMcpIds(frameworkDir) {
75
76
  try {
76
77
  const registryPath = join(frameworkDir, 'mcp', 'registry.json');
77
78
  if (!existsSync(registryPath)) return null;
@@ -84,20 +85,19 @@ export function loadKnownMcpIds(frameworkDir) {
84
85
 
85
86
  // With no known stack tags every persona is generated: a dispatch of `morph-{id}` must find
86
87
  // its subagent. Deliberately differs from rules/skills filtering.
87
- export function agentEligible(agent, projectTags = []) {
88
+ function agentEligible(agent, projectTags = []) {
88
89
  if (projectTags.length === 0) return true;
89
90
  return shouldInstall(agent.stack ?? ['*'], projectTags);
90
91
  }
91
92
 
92
93
  const MANAGED_HEADER =
93
- '<!-- MANAGED BY morph-spec — generated from .morph/framework/agents.json (single source of truth).\n' +
94
+ '<!-- MANAGED BY morph-spec — generated from the agents.json of the morph-spec package.\n' +
94
95
  ' Do NOT edit by hand: changes are overwritten on `morph-spec update` / `setup-infra --reinstall`.\n' +
95
- ' To change this persona, edit agents.json and regenerate. Drift is flagged by `morph-spec doctor`. -->';
96
-
97
- const MANAGED_HEADER_MARKER = MANAGED_HEADER.split('\n')[0];
96
+ ' Drift is flagged by `morph-spec doctor`. -->';
98
97
 
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,19 +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.',
219
- '',
220
- 'Numa confirmação (um dispatch novo te traz depois da correção, com o `sha` novo) acrescente ao fim uma seção nova com ' +
221
- `\`${VERDICT_TOKEN}\` e \`${REVIEWED_SHA_TOKEN} {sha novo}\`: se você abriu bloqueadores, julgue só eles; ` +
222
- 'se não abriu, julgue só o delta `{sha anterior}..{sha novo}` — o que a correção abriu. ' +
223
- 'O relatório é append-only: vale o último veredito e, na `## Checks`, a última linha de cada Cn.',
224
- '',
225
- 'Um comando por chamada de Bash, sem encadear (`;`, `&&`, pipe): o composto é negado e custa a rodada.',
201
+ 'Bloqueador só com evidência e tipo; o resto é nota, com `arquivo:linha` e o que mudar.',
226
202
  ];
227
203
 
228
204
  function buildBody(agent, maxTurns) {
@@ -249,8 +225,7 @@ function buildBody(agent, maxTurns) {
249
225
  if (Object.hasOwn(REVIEW_ROLES, agent.id)) lines.push(...REVIEW_REPORT_CONTRACT, '');
250
226
 
251
227
  lines.push(
252
- // `PARCIAL` on line 1 is what report-check reads; "no verdict" keeps a partial
253
- // review from carrying a Verdict the gate would read as final.
228
+ // `PARCIAL` on line 1 is what `parseRound` (review-reports.js) reads as an incomplete report.
254
229
  '## Turn budget',
255
230
  '',
256
231
  `You have ${maxTurns} turns (\`maxTurns\`); at the ceiling you are cut off mid-work, without warning. ` +
@@ -382,17 +357,3 @@ function diffAgentMd(onDisk, rendered) {
382
357
  // Bytes differ but no key/value does (a stray blank line between the fences).
383
358
  return fields.length > 0 ? fields : ['frontmatter'];
384
359
  }
385
-
386
- export function collectSkillFiles(dir) {
387
- const results = [];
388
- if (!existsSync(dir)) return results;
389
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
390
- const fullPath = join(dir, entry.name);
391
- if (entry.isDirectory()) {
392
- results.push(...collectSkillFiles(fullPath));
393
- } else if (entry.name.endsWith('.md') && entry.name !== 'README.md') {
394
- results.push(fullPath);
395
- }
396
- }
397
- return results;
398
- }
@@ -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,11 +1,14 @@
1
1
  import { join } from 'path';
2
- import { readFile, writeFile, mkdir, copyFile } from 'fs/promises';
2
+ import { readFile, writeFile, mkdir, copyFile, unlink } from 'fs/promises';
3
3
  import { existsSync } from 'fs';
4
+ import { MORPH_ALLOW, managedDeny } from './hooks-installer.js';
4
5
 
5
6
  const MORPH_MANAGED_KEY = '_morph_managed';
6
7
 
7
- export { installClaudeHooks, installGlobalStatusline, getHooksVersion } from './hooks-installer.js';
8
- export { installAgents } from './agents-installer.js';
8
+ // The installer writes no env var today; these are what older versions left behind.
9
+ const LEGACY_ENV_KEYS = ['MORPH_SPEC_ACTIVE', 'CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS'];
10
+
11
+ export { installClaudeHooks, installGlobalStatusline } from './hooks-installer.js';
9
12
 
10
13
  export async function resetMorphSettings(targetPath) {
11
14
  const claudeDir = join(targetPath, '.claude');
@@ -25,18 +28,30 @@ export async function resetMorphSettings(targetPath) {
25
28
  const backupPath = settingsPath + '.backup';
26
29
  await copyFile(settingsPath, backupPath);
27
30
 
28
- if (managed.permissions_added && Array.isArray(settings.permissions)) {
29
- settings.permissions = settings.permissions.filter(
30
- p => !managed.permissions_added.includes(p)
31
- );
32
- if (settings.permissions.length === 0) {
31
+ const footprint = { deny: managedDeny(settings), allow: MORPH_ALLOW, envKeys: LEGACY_ENV_KEYS };
32
+ const permissionsRemoved = [];
33
+ const envRemoved = [];
34
+
35
+ if (settings.permissions && typeof settings.permissions === 'object') {
36
+ for (const kind of ['deny', 'allow']) {
37
+ const entries = settings.permissions[kind];
38
+ if (!Array.isArray(entries)) continue;
39
+ const kept = entries.filter(p => !footprint[kind].includes(p));
40
+ permissionsRemoved.push(...entries.filter(p => footprint[kind].includes(p)));
41
+ if (kept.length > 0) settings.permissions[kind] = kept;
42
+ else delete settings.permissions[kind];
43
+ }
44
+ if (Object.keys(settings.permissions).length === 0) {
33
45
  delete settings.permissions;
34
46
  }
35
47
  }
36
48
 
37
- if (managed.env_added && settings.env) {
38
- for (const key of managed.env_added) {
39
- delete settings.env[key];
49
+ if (settings.env) {
50
+ for (const key of footprint.envKeys) {
51
+ if (key in settings.env) {
52
+ delete settings.env[key];
53
+ envRemoved.push(key);
54
+ }
40
55
  }
41
56
  if (Object.keys(settings.env).length === 0) {
42
57
  delete settings.env;
@@ -45,18 +60,14 @@ export async function resetMorphSettings(targetPath) {
45
60
 
46
61
  if (settings.hooks) {
47
62
  const morphPattern = /framework\/hooks\/claude-code\//;
48
- const oldPattern = /agent-teams\/dispatch\.js/;
49
63
 
50
64
  for (const [event, entries] of Object.entries(settings.hooks)) {
51
65
  if (!Array.isArray(entries)) continue;
52
66
 
53
67
  settings.hooks[event] = entries.filter(entry => {
68
+ if (entry._morph === true) return false;
54
69
  if (!Array.isArray(entry.hooks)) return true;
55
- const nonMorphHooks = entry.hooks.filter(h =>
56
- typeof h.command !== 'string' ||
57
- (!morphPattern.test(h.command) && !oldPattern.test(h.command))
58
- );
59
- return nonMorphHooks.length > 0;
70
+ return entry.hooks.some(h => typeof h.command !== 'string' || !morphPattern.test(h.command));
60
71
  });
61
72
 
62
73
  if (settings.hooks[event].length === 0) {
@@ -80,7 +91,6 @@ export async function resetMorphSettings(targetPath) {
80
91
  if (Object.keys(mcpJson).length === 0) {
81
92
  const mcpJsonPath = join(targetPath, '.mcp.json');
82
93
  if (existsSync(mcpJsonPath)) {
83
- const { unlink } = await import('fs/promises');
84
94
  await unlink(mcpJsonPath);
85
95
  }
86
96
  } else {
@@ -102,15 +112,7 @@ export async function resetMorphSettings(targetPath) {
102
112
 
103
113
  await saveSettings(targetPath, settings);
104
114
 
105
- return {
106
- removed: true,
107
- backupPath,
108
- permissionsRemoved: managed.permissions_added || [],
109
- envRemoved: managed.env_added || [],
110
- hooksRemoved: managed.hooks_added || [],
111
- mcpsRemoved: managed.mcps_installed || [],
112
- previouslyGenerated: managed.generated_at
113
- };
115
+ return { removed: true, backupPath, permissionsRemoved, envRemoved };
114
116
  }
115
117
 
116
118
  // Claude Code reads MCP servers from .mcp.json, not settings.local.json.
@@ -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,35 +1,83 @@
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';
7
+ import { SHELL_TOOLS } from '../../framework/hooks/shared/payload-utils.js';
6
8
 
7
- const HOOKS_VERSION = '4.0.0';
9
+ export const HOOKS_VERSION = '4.1.0';
8
10
 
11
+ const SHELL_MATCHER = [...SHELL_TOOLS].join('|');
9
12
 
10
13
  // `Edit(path)` only: an Edit rule also covers Write, while a `Write(path)` rule
11
14
  // matches nothing and makes Claude Code warn on every session start.
12
- const MORPH_DENY = [
15
+ export const MORPH_DENY = [
13
16
  'Edit(.morph/framework/**)',
14
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 = [
15
22
  'Edit(.claude/rules/**)',
16
23
  'Edit(.claude/agents/morph-*)',
17
24
  'Edit(.claude/skills/**)',
18
25
  ];
19
26
 
20
- const MORPH_ALLOW = [
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
+
70
+ export const MORPH_ALLOW = [
21
71
  'Edit(.morph/features/**)',
22
72
  'Edit(.morph/context/**)',
23
73
  'Bash(mkdir:.morph/**)',
24
74
  'Bash(ls:.morph/**)',
25
75
  ];
26
76
 
27
- const MORPH_PERMISSIONS = MORPH_DENY;
28
-
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',
@@ -41,7 +89,7 @@ const MORPH_HOOKS = [
41
89
 
42
90
  {
43
91
  event: 'PreToolUse',
44
- matcher: 'Bash',
92
+ matcher: SHELL_MATCHER,
45
93
  hooks: [{
46
94
  type: 'command',
47
95
  command: 'node framework/hooks/claude-code/core/chain.js',
@@ -49,7 +97,6 @@ const MORPH_HOOKS = [
49
97
  }]
50
98
  },
51
99
 
52
- // comment-guard must be the last Write|Edit link: a block ends the chain.
53
100
  {
54
101
  event: 'PostToolUse',
55
102
  matcher: 'Write|Edit',
@@ -62,7 +109,7 @@ const MORPH_HOOKS = [
62
109
  // masked-exit last: it reads the command every other link already let through.
63
110
  {
64
111
  event: 'PostToolUse',
65
- matcher: 'Bash',
112
+ matcher: SHELL_MATCHER,
66
113
  hooks: [{
67
114
  type: 'command',
68
115
  command: 'node framework/hooks/claude-code/core/chain.js',
@@ -82,10 +129,11 @@ const MORPH_HOOKS = [
82
129
  ];
83
130
 
84
131
  /**
85
- * Idempotent merge of the MORPH-SPEC hooks into `.claude/settings.local.json`.
86
- * @returns {Promise<{ installed: number, updated: boolean }>}
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).
134
+ * @returns {Promise<{ installed: number }>}
87
135
  */
88
- export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}) {
136
+ export async function installClaudeHooks(targetPath, { fx = realEffects(), manifest = readManifest(targetPath) } = {}) {
89
137
  const claudeDir = join(targetPath, '.claude');
90
138
  const settingsPath = join(claudeDir, 'settings.local.json');
91
139
 
@@ -100,9 +148,6 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
100
148
 
101
149
  settings.hooks = settings.hooks || {};
102
150
 
103
- const managed = settings._morph_managed || {};
104
- const alreadyCurrent = managed.hooks_version === HOOKS_VERSION;
105
-
106
151
  removeMorphHooks(settings);
107
152
 
108
153
  let installed = 0;
@@ -123,8 +168,7 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
123
168
  return {
124
169
  type: h.type,
125
170
  command,
126
- ...(h.timeout !== undefined ? { timeout: h.timeout } : {}),
127
- ...(h.async ? { async: true } : {})
171
+ ...(h.timeout !== undefined ? { timeout: h.timeout } : {})
128
172
  };
129
173
  });
130
174
 
@@ -132,33 +176,11 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
132
176
  installed++;
133
177
  }
134
178
 
135
- settings.permissions = settings.permissions || {};
136
- settings.permissions.deny = settings.permissions.deny || [];
179
+ applyManagedDeny(settings, manifest);
137
180
  settings.permissions.allow = settings.permissions.allow || [];
138
181
 
139
- // An entry that left MORPH_* would survive forever in an existing install
140
- // unless named here.
141
- const STALE_DENY = [
142
- 'Write(.morph/state.json)',
143
- 'Edit(.morph/state.json)',
144
- 'Write(.morph/framework/**)',
145
- 'Write(.claude/CLAUDE.md)',
146
- 'Write(.claude/rules/**)',
147
- 'Write(.claude/agents/morph-*)',
148
- 'Write(.claude/skills/**)',
149
- ];
150
- settings.permissions.deny = settings.permissions.deny.filter(
151
- p => !MORPH_DENY.includes(p) && !STALE_DENY.includes(p)
152
- );
153
- for (const perm of MORPH_DENY) {
154
- settings.permissions.deny.push(perm);
155
- }
156
-
157
- const STALE_ALLOW = [
158
- 'Edit(.morph/state.json)',
159
- 'Write(.morph/features/**)',
160
- 'Write(.morph/context/**)',
161
- ];
182
+ // An entry that left MORPH_ALLOW would survive forever in an existing install unless named here.
183
+ const STALE_ALLOW = ['Edit(.morph/state.json)'];
162
184
  settings.permissions.allow = settings.permissions.allow.filter(
163
185
  p => !MORPH_ALLOW.includes(p) && !STALE_ALLOW.includes(p)
164
186
  );
@@ -168,11 +190,7 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
168
190
 
169
191
  settings['$schema'] = 'https://json.schemastore.org/claude-code-settings.json';
170
192
 
171
- settings.env = {
172
- ...settings.env,
173
- MORPH_SPEC_ACTIVE: 'true',
174
- CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1',
175
- };
193
+ dropLegacySettings(settings);
176
194
 
177
195
  if (!settings.attribution) {
178
196
  settings.attribution = {
@@ -181,19 +199,30 @@ export async function installClaudeHooks(targetPath, { fx = realEffects() } = {}
181
199
  };
182
200
  }
183
201
 
184
- if (!settings.plansDirectory) {
185
- settings.plansDirectory = '.morph/plans';
186
- }
187
-
188
202
  settings._morph_managed = settings._morph_managed || {};
189
203
  settings._morph_managed.hooks_version = HOOKS_VERSION;
190
- settings._morph_managed.hooks_installed = [...new Set(MORPH_HOOKS.map(h => h.event))];
191
204
  settings._morph_managed.generated_at = new Date().toISOString();
192
205
 
193
206
  fx.ensureDir(claudeDir);
194
207
 
195
208
  fx.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n');
196
- return { installed, updated: !alreadyCurrent };
209
+ return { installed };
210
+ }
211
+
212
+ const LEGACY_ENV = { MORPH_SPEC_ACTIVE: 'true', CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1' };
213
+ const LEGACY_PLANS_DIRECTORY = '.morph/plans';
214
+
215
+ // Only the exact values an older install wrote: the same key with another value is the user's.
216
+ function dropLegacySettings(settings) {
217
+ const env = settings.env;
218
+ if (env && typeof env === 'object') {
219
+ for (const [name, value] of Object.entries(LEGACY_ENV)) {
220
+ if (env[name] === value) delete env[name];
221
+ }
222
+ if (Object.keys(env).length === 0) delete settings.env;
223
+ }
224
+ if (settings.plansDirectory === LEGACY_PLANS_DIRECTORY) delete settings.plansDirectory;
225
+ delete settings._morph_managed?.hooks_installed;
197
226
  }
198
227
 
199
228
  /**
@@ -253,11 +282,3 @@ function getHookSubpath(command) {
253
282
  const match = command.match(/claude-code\/(.+)$/);
254
283
  return match ? match[1] : command;
255
284
  }
256
-
257
- export function getHooksVersion() {
258
- return HOOKS_VERSION;
259
- }
260
-
261
- export function getHookDefinitions() {
262
- return MORPH_HOOKS;
263
- }