@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
@@ -9,24 +9,18 @@ import { isAbsolute, relative, resolve } from 'path';
9
9
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
10
10
  import { commentFindings, docCommentsForbidden, MAX_BLOCK_LINES } from '../../shared/comment-rules.js';
11
11
  import { isGenerated, isProjectSource } from '../../shared/source-files.js';
12
+ import { applyEdit } from '../../shared/payload-utils.js';
12
13
 
13
14
  const MAX_LISTED = 10;
14
15
 
15
16
  const RULE_LABEL = {
16
- process: 'história de processo (ADR, cenário, fatia, gate, plan.md)',
17
+ process: 'história de processo (ADR, cenário, plan.md, checks.json)',
17
18
  banner: 'banner ou #region',
18
19
  'commented-code': 'código comentado (o git guarda o antigo: apague)',
19
20
  'doc-comment': '///·JSDoc em código que não é pacote publicado',
20
21
  'long-block': `bloco com mais de ${MAX_BLOCK_LINES} linhas`,
21
22
  };
22
23
 
23
- function spliceEdit(original, oldString, newString, replaceAll) {
24
- if (replaceAll) return original.split(oldString).join(newString);
25
- const at = original.indexOf(oldString);
26
- if (at < 0) return null;
27
- return original.slice(0, at) + newString + original.slice(at + oldString.length);
28
- }
29
-
30
24
  function readOrNull(file) {
31
25
  try {
32
26
  return readFileSync(file, 'utf8');
@@ -45,7 +39,7 @@ function contentsOf(payload, absolute) {
45
39
  }
46
40
  if (typeof response.originalFile !== 'string') return null;
47
41
  const after = readOrNull(absolute)
48
- ?? spliceEdit(response.originalFile, input.old_string ?? '', input.new_string ?? '', input.replace_all === true);
42
+ ?? applyEdit(response.originalFile, input.old_string ?? '', input.new_string ?? '', input.replace_all === true);
49
43
  return after === null ? null : { before, after };
50
44
  }
51
45
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
3
- import { contractExists } from '../../shared/contract.js';
3
+ import { sessionContractRoot } from '../../shared/contract.js';
4
4
  import { gitInvocations } from '../../shared/command-tokens.js';
5
5
 
6
6
  export const CONVENTIONAL = /^(feat|fix|refactor|test|chore|docs|perf|ci|build|style|revert)(\([^)]+\))?!?: \S/;
@@ -35,7 +35,7 @@ export function nonConventionalSubject(command) {
35
35
 
36
36
  export async function run(payload) {
37
37
  try {
38
- if (!contractExists()) return null;
38
+ if (!sessionContractRoot(payload)) return null;
39
39
 
40
40
  const command = payload?.tool_input?.command || '';
41
41
  if (!command.includes('commit')) return null;
@@ -47,7 +47,7 @@ export async function run(payload) {
47
47
  'Formato: `<tipo>(<escopo>): <assunto>` — tipo em feat, fix, refactor, test, chore ' +
48
48
  '(também docs, perf, ci, build, style, revert); `!` antes de `:` marca breaking change.\n' +
49
49
  'Exemplos: `feat(orders): aceita cupom no checkout`, `fix: trata pedido sem itens`, ' +
50
- '`chore(F2): wip handler de pagamento`.'
50
+ '`chore(deps): atualiza o SDK de pagamento`.'
51
51
  );
52
52
  } catch {
53
53
  return null;
@@ -3,12 +3,12 @@
3
3
  // Wide filter on purpose: the refresh only runs when the root's graph is behind HEAD, and a HEAD-moving command
4
4
  // left unrecognized is how the graph falls behind.
5
5
 
6
- import { contractExists } from '../../shared/contract.js';
6
+ import { sessionContractRoot } from '../../shared/contract.js';
7
7
  import { runStandalone } from '../../shared/hook-response.js';
8
+ import { SHELL_TOOLS } from '../../shared/payload-utils.js';
8
9
  import { tokenize } from '../../shared/command-tokens.js';
9
10
  import { kickGraphRefresh } from '../../shared/graph-refresh.js';
10
11
 
11
- const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
12
12
  const GIT_TOOL = /(^|[\\/])(git|gh|morph-spec)(\.exe|\.cmd)?$/i;
13
13
 
14
14
  export function touchesGit(command) {
@@ -17,13 +17,13 @@ export function touchesGit(command) {
17
17
  .some((t) => GIT_TOOL.test(t));
18
18
  }
19
19
 
20
- export async function run(payload) {
20
+ export async function run(payload, { kick = kickGraphRefresh } = {}) {
21
21
  try {
22
22
  if (!SHELL_TOOLS.has(payload?.tool_name)) return null;
23
23
  if (!touchesGit(payload?.tool_input?.command)) return null;
24
- const dir = payload?.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
25
- if (!contractExists(dir)) return null;
26
- kickGraphRefresh(dir);
24
+ const dir = sessionContractRoot(payload);
25
+ if (!dir) return null;
26
+ kick(dir);
27
27
  } catch {}
28
28
  return null;
29
29
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { contractExists } from '../../shared/contract.js';
3
+ import { sessionContractRoot } from '../../shared/contract.js';
4
4
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
5
5
  import { exitCodeMasked, hasUnquotedPipe, producerOf } from '../../shared/command-tokens.js';
6
6
  import { buildOrTestKind, morphCheckCall, testRunKind } from '../../shared/command-kind.js';
@@ -30,10 +30,11 @@ function maskForm(command) {
30
30
 
31
31
  export async function run(payload) {
32
32
  try {
33
+ // Bash only: the masking forms judged here are POSIX shell semantics.
33
34
  if (payload?.tool_name !== 'Bash') return null;
34
35
  const command = payload.tool_input?.command;
35
36
  if (typeof command !== 'string' || !command.trim()) return null;
36
- if (!contractExists(payload.cwd || undefined)) return null;
37
+ if (!sessionContractRoot(payload)) return null;
37
38
  if (!exitCodeMasked(command) || EXIT_SHOWN.test(command)) return null;
38
39
  const kind = runKind(producerOf(command));
39
40
  if (!kind) return null;
@@ -41,7 +42,7 @@ export async function run(payload) {
41
42
  `⚠️ O resultado de \`${kind}\` ficou escondido: o "passou/falhou" que apareceu é o do último comando, `
42
43
  + 'não o do teste ou da compilação.\n'
43
44
  + `${SESSION_MARK} o exit está mascarado por \`${maskForm(command)}\`; grave a saída em arquivo `
44
- + '(`… > .morph/logs/test-last.log 2>&1`) e leia o arquivo.',
45
+ + '(`mkdir -p .morph/logs && … > .morph/logs/test-last.log 2>&1`) e leia o arquivo.',
45
46
  'PostToolUse'
46
47
  );
47
48
  } catch {
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
3
3
  import { join, dirname } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
6
- import { contractExists } from '../../shared/contract.js';
6
+ import { sessionContractRoot } from '../../shared/contract.js';
7
7
  import { tokenize } from '../../shared/command-tokens.js';
8
8
 
9
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -40,7 +40,7 @@ export function matchesExecutableRule(command, rule) {
40
40
 
41
41
  export async function run(payload) {
42
42
  try {
43
- if (!contractExists()) return null;
43
+ if (!sessionContractRoot(payload)) return null;
44
44
 
45
45
  const command = payload?.tool_input?.command || '';
46
46
  if (!command) return null;
@@ -4,7 +4,7 @@ import { existsSync, readFileSync } from 'fs';
4
4
  import { contractExists } from '../../shared/contract.js';
5
5
  import { isFeaturePath, extractFeatureName, getBasename } from '../../shared/phase-utils.js';
6
6
  import { blockResult, runStandalone } from '../../shared/hook-response.js';
7
- import { getFilePath, getToolName, resolveMorphRoot, resolveTargetPath } from '../../shared/payload-utils.js';
7
+ import { applyEdit, getFilePath, getToolName, resolveMorphRoot, resolveTargetPath } from '../../shared/payload-utils.js';
8
8
  import { ERRATA_HEADING, errataViolation } from '../../shared/errata.js';
9
9
  import { SESSION_MARK } from '../../shared/owner-words.js';
10
10
 
@@ -15,9 +15,7 @@ function proposedText(payload, toolName, original) {
15
15
  const oldStr = payload?.tool_input?.old_string;
16
16
  const newStr = payload?.tool_input?.new_string;
17
17
  if (typeof oldStr !== 'string' || typeof newStr !== 'string') return null;
18
- return payload?.tool_input?.replace_all
19
- ? original.split(oldStr).join(newStr)
20
- : original.replace(oldStr, newStr);
18
+ return applyEdit(original, oldStr, newStr, payload?.tool_input?.replace_all === true) ?? original;
21
19
  }
22
20
  const content = payload?.tool_input?.content;
23
21
  return typeof content === 'string' ? content : null;
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { execFileSync } from 'child_process';
4
- import { contractExists } from '../../shared/contract.js';
4
+ import { sessionContractRoot } from '../../shared/contract.js';
5
5
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
6
6
  import { gitInvocations } from '../../shared/command-tokens.js';
7
+ import { SHELL_TOOLS } from '../../shared/payload-utils.js';
7
8
  import { SESSION_MARK } from '../../shared/owner-words.js';
8
9
 
9
10
  export const STACK_MANIFEST = /(^|\/)(package\.json|pyproject\.toml|requirements(-[\w-]+)?\.txt|[^/]+\.csproj|[^/]+\.slnx?|Directory\.Packages\.props|(docker-)?compose(\.[\w-]+)?\.ya?ml)$/i;
@@ -15,11 +16,11 @@ function committedFiles(cwd) {
15
16
 
16
17
  export async function run(payload, deps = {}) {
17
18
  try {
18
- if (payload?.tool_name !== 'Bash') return null;
19
+ if (!SHELL_TOOLS.has(payload?.tool_name)) return null;
19
20
  const command = payload.tool_input?.command;
20
21
  if (typeof command !== 'string' || !gitInvocations(command).some(({ sub }) => sub === 'commit')) return null;
21
- const cwd = payload.cwd || process.env.CLAUDE_PROJECT_DIR || process.cwd();
22
- if (!contractExists(cwd)) return null;
22
+ const cwd = sessionContractRoot(payload);
23
+ if (!cwd) return null;
23
24
  const touched = (deps.committedFiles ?? committedFiles)(cwd).filter((f) => STACK_MANIFEST.test(f));
24
25
  if (!touched.length) return null;
25
26
  return contextResult(
@@ -3,8 +3,9 @@
3
3
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { createHash } from 'crypto';
6
- import { contractExists } from '../../shared/contract.js';
6
+ import { contractRoot } from '../../shared/contract.js';
7
7
  import { featureFromBranch } from '../../shared/feature-slug.js';
8
+ import { morphStateDir } from '../../shared/git-paths.js';
8
9
  import { contextResult, runStandalone } from '../../shared/hook-response.js';
9
10
  import { implementProgress } from '../../shared/report-progress.js';
10
11
  import { scenarioLabel, SESSION_MARK } from '../../shared/owner-words.js';
@@ -16,28 +17,30 @@ export function unprovenScenarios(featurePath) {
16
17
  .map((c) => `${scenarioLabel(c)} está marcado feito sem prova (o teste, a linha de código ou o passo que mostra que funciona).`);
17
18
  }
18
19
 
19
- // Every Stop runs the audit; only a changed warning set is said again.
20
- function changed(memDir, slug, warnings) {
21
- const path = join(memDir, 'warned-hashes.json');
20
+ // Every Stop runs the audit; only a changed warning set is said again. The memory lives in the
21
+ // git common dir, never in the project tree: without one, the warning repeats.
22
+ function changed(stateDir, slug, warnings) {
23
+ const hash = warnings.length ? createHash('sha1').update(warnings.join('\n')).digest('hex') : null;
24
+ if (!stateDir) return Boolean(hash);
25
+ const path = join(stateDir, 'warned-hashes.json');
22
26
  let seen = {};
23
27
  try { if (existsSync(path)) seen = JSON.parse(readFileSync(path, 'utf-8')); } catch { /* start fresh */ }
24
- const hash = warnings.length ? createHash('sha1').update(warnings.join('\n')).digest('hex') : null;
25
- if (seen[slug] === hash) return false;
28
+ if ((seen[slug] ?? null) === hash) return false;
26
29
  if (hash) seen[slug] = hash; else delete seen[slug];
27
- try { mkdirSync(memDir, { recursive: true }); writeFileSync(path, JSON.stringify(seen, null, 2)); } catch { /* fail-open */ }
30
+ try { mkdirSync(stateDir, { recursive: true }); writeFileSync(path, JSON.stringify(seen, null, 2)); } catch { /* fail-open */ }
28
31
  return Boolean(hash);
29
32
  }
30
33
 
31
34
  export async function run() {
32
35
  try {
33
- const cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
34
- if (!contractExists(cwd)) return null;
35
- const slug = featureFromBranch(cwd);
36
+ const root = contractRoot(process.env.CLAUDE_PROJECT_DIR || process.cwd());
37
+ if (!root) return null;
38
+ const slug = featureFromBranch(root);
36
39
  if (!slug) return null;
37
- const featurePath = join(cwd, '.morph', 'features', slug);
40
+ const featurePath = join(root, '.morph', 'features', slug);
38
41
  if (!existsSync(featurePath)) return null;
39
42
  const warnings = unprovenScenarios(featurePath);
40
- if (!changed(join(cwd, '.morph', 'memory'), slug, warnings)) return null;
43
+ if (!changed(morphStateDir(root), slug, warnings)) return null;
41
44
  return contextResult([
42
45
  'MORPH-SPEC — relatório da construção:',
43
46
  ...warnings.map((w) => ` • ${w}`),
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { dirname, join, resolve } from 'node:path';
3
3
 
4
4
  export const CONTRACT_FILE = join('.morph', 'config', 'config.json');
5
5
 
@@ -12,3 +12,24 @@ export function contractExists(projectPath) {
12
12
  return false;
13
13
  }
14
14
  }
15
+
16
+ /** The closest directory at or above `start` that holds the contract, or `null`. */
17
+ export function contractRoot(start) {
18
+ try {
19
+ let dir = resolve(start || process.cwd());
20
+ for (;;) {
21
+ if (existsSync(join(dir, CONTRACT_FILE))) return dir;
22
+ const parent = dirname(dir);
23
+ if (parent === dir) return null;
24
+ dir = parent;
25
+ }
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ // A shell `cd` moves `payload.cwd` below the root, or out of the project: the session's project still counts.
32
+ export function sessionContractRoot(payload) {
33
+ return contractRoot(payload?.cwd)
34
+ ?? (process.env.CLAUDE_PROJECT_DIR ? contractRoot(process.env.CLAUDE_PROJECT_DIR) : null);
35
+ }
@@ -66,6 +66,12 @@ export function resolveGitCommonDir(startDir) {
66
66
  }
67
67
  }
68
68
 
69
+ /** Where morph-spec keeps machine state: inside the common git dir, shared by every worktree and never in the tree. */
70
+ export function morphStateDir(startDir) {
71
+ const common = startDir ? resolveGitCommonDir(startDir) : null;
72
+ return common ? join(common, 'morph-spec') : null;
73
+ }
74
+
69
75
  const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
70
76
 
71
77
  /** `null` for every shape it does not read (linked worktree, reftable, unborn branch): the caller asks git. */
@@ -9,7 +9,7 @@ import {
9
9
  renameSync, unlinkSync, writeFileSync,
10
10
  } from 'fs';
11
11
  import { basename, dirname, join, resolve } from 'path';
12
- import { resolveGitCommonDir } from './git-paths.js';
12
+ import { morphStateDir, resolveGitCommonDir } from './git-paths.js';
13
13
 
14
14
  export const GRAPH_DIR = 'graphify-out';
15
15
  export const GRAPHIFY_IGNORE = '.graphifyignore';
@@ -114,8 +114,8 @@ export function treeKey(tree) {
114
114
  }
115
115
 
116
116
  export function refreshStatePath(dir) {
117
- const common = dir ? resolveGitCommonDir(dir) : null;
118
- return common ? join(common, 'morph-spec', STATE_FILE) : null;
117
+ const state = morphStateDir(dir);
118
+ return state ? join(state, STATE_FILE) : null;
119
119
  }
120
120
 
121
121
  function readState(path) {
@@ -1,5 +1,5 @@
1
1
  // Só a raiz: o worker destacado nasce com `cwd` no git common dir, porque no win32
2
- // um diretório em uso não se apaga e o `finish` de uma worktree falhava no meio.
2
+ // um diretório em uso não se apaga e remover a worktree falharia no meio.
3
3
  // A worktree anda por `morph-spec graph refresh`, em primeiro plano.
4
4
 
5
5
  import { spawn, spawnSync } from 'child_process';
@@ -10,7 +10,7 @@ import {
10
10
  import { dirname, join, resolve } from 'path';
11
11
  import { homedir } from 'os';
12
12
  import { fileURLToPath } from 'url';
13
- import { readPrimaryHead, resolveGitCommonDir, workTreeTop } from './git-paths.js';
13
+ import { morphStateDir, readPrimaryHead, resolveGitCommonDir, workTreeTop } from './git-paths.js';
14
14
  import { findFirstOnPath, quoteForCmd } from './morph-cli.js';
15
15
  import { backgroundArgs } from './background-spawn.js';
16
16
  import { ensureCommonExclude } from './git-exclude.js';
@@ -43,18 +43,13 @@ export function isPrimaryTree(dir) {
43
43
  return Boolean(top && primary && treeKey(top) === treeKey(primary));
44
44
  }
45
45
 
46
- function stateDir(dir) {
47
- const common = resolveGitCommonDir(dir);
48
- return common ? join(common, 'morph-spec') : null;
49
- }
50
-
51
46
  export function refreshLockPath(dir) {
52
- const d = stateDir(dir);
47
+ const d = morphStateDir(dir);
53
48
  return d ? join(d, 'graph-refresh.lock') : null;
54
49
  }
55
50
 
56
51
  function refreshLogPath(dir) {
57
- const d = stateDir(dir);
52
+ const d = morphStateDir(dir);
58
53
  return d ? join(d, 'graph-refresh.log') : null;
59
54
  }
60
55
 
@@ -182,7 +177,7 @@ export function runGraphify(tree, args, { env = process.env, timeout = GRAPHIFY_
182
177
  }
183
178
 
184
179
  // O registro da semente copia só o que se SABE do grafo da raiz; `graphify-out/`
185
- // vai para o exclude do common dir, senão a worktree fica suja para o `finish`.
180
+ // vai para o exclude do common dir, senão a worktree fica suja para quem for removê-la.
186
181
  export function seedGraphFromRoot(tree, root) {
187
182
  if (!tree || !root || treeKey(tree) === treeKey(root)) return { seeded: false, reason: 'is-root' };
188
183
  if (existsSync(graphFile(tree))) return { seeded: false, reason: 'present' };
@@ -1,18 +1,6 @@
1
1
  // A top-level `additionalContext` is NOT honored for any event: it must be nested
2
2
  // under `hookSpecificOutput` (https://code.claude.com/docs/en/hooks.md).
3
3
 
4
- export function block(reason) {
5
- console.log(JSON.stringify({ decision: 'block', reason }));
6
- process.exit(0);
7
- }
8
-
9
- export function approve(context) {
10
- if (context) {
11
- console.log(JSON.stringify({ decision: 'approve', additionalContext: context }));
12
- }
13
- process.exit(0);
14
- }
15
-
16
4
  export function injectContext(text, eventName) {
17
5
  console.log(JSON.stringify({
18
6
  hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
@@ -20,12 +8,7 @@ export function injectContext(text, eventName) {
20
8
  process.exit(0);
21
9
  }
22
10
 
23
- export function pass() {
24
- process.exit(0);
25
- }
26
-
27
- // `run()` returns these instead of exiting: chain.js runs several hooks in one
28
- // process. Same JSON shapes as block()/approve()/injectContext() above.
11
+ // `run()` returns these instead of exiting: chain.js runs several hooks in one process.
29
12
  export function blockResult(reason) {
30
13
  return { decision: 'block', reason };
31
14
  }
@@ -29,10 +29,21 @@ export function resolveTargetPath(filePath, fallbackCwd) {
29
29
  }
30
30
 
31
31
  export function getFilePath(payload) {
32
- const raw = payload?.tool_input?.file_path || payload?.tool_input?.path || '';
32
+ const raw = payload?.tool_input?.file_path || '';
33
33
  return raw.replace(/\\/g, '/');
34
34
  }
35
35
 
36
+ /** The tools whose `tool_input.command` is a shell line; also the matcher of the shell hook groups. */
37
+ export const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
38
+
39
+ /** What the Edit tool writes, or `null` when `oldString` is absent. Splices: `String.replace` would expand `$&` in the new text. */
40
+ export function applyEdit(original, oldString, newString, replaceAll = false) {
41
+ if (replaceAll) return original.split(oldString).join(newString);
42
+ const at = original.indexOf(oldString);
43
+ if (at < 0) return null;
44
+ return original.slice(0, at) + newString + original.slice(at + oldString.length);
45
+ }
46
+
36
47
  export function getToolName(payload) {
37
48
  return payload?.tool_name || 'unknown';
38
49
  }
@@ -1,62 +1,14 @@
1
- // GENERATED by scripts/generate-refs.js — DO NOT EDIT manually
2
- // Source of truth: src/core/paths/output-schema.js
3
- // Regenerate with: node scripts/generate-refs.js
4
-
5
- export const PHASE_DIRS = {
6
- plan: '2-plan',
7
- uiux: '1-design',
8
- implement: '3-implement',
9
- review: '4-review',
10
- };
11
-
12
- export const OUTPUT_PHASE_MAP = {
13
- plan: 'plan',
14
- checks: 'plan',
15
- planCritique: 'plan',
16
- uiMockups: 'uiux',
17
- implementReport: 'implement',
18
- evidencias: 'implement',
19
- verifierReport: 'review',
20
- reviewerReport: 'review',
21
- securityReport: 'review',
22
- };
23
-
24
- export const FILENAME_TO_OUTPUT = {
25
- 'plan.md': 'plan',
26
- 'checks.json': 'checks',
27
- 'critica.md': 'planCritique',
28
- 'mockups.md': 'uiMockups',
29
- 'report.md': 'implementReport',
30
- 'verifier.md': 'verifierReport',
31
- 'reviewer.md': 'reviewerReport',
32
- 'security.md': 'securityReport',
33
- };
34
-
35
- export const PROTECTED_SPEC_FILES = {
36
- 'plan.md': 'plan',
37
- 'checks.json': 'plan',
38
- 'mockups.md': 'uiux',
39
- };
40
-
1
+ const posix = (filePath) => filePath.replace(/\\/g, '/');
41
2
 
42
3
  export function extractFeatureName(filePath) {
43
- const normalized = filePath.replace(/\\/g, '/');
44
- const match = normalized.match(/\.morph\/features\/([^/]+)\//);
45
- return match ? match[1] : null;
46
- }
47
-
48
- export function extractPhaseDir(filePath) {
49
- const normalized = filePath.replace(/\\/g, '/');
50
- const match = normalized.match(/\.morph\/features\/[^/]+\/(\d+-[^/]+)\//);
4
+ const match = posix(filePath).match(/\.morph\/features\/([^/]+)\//);
51
5
  return match ? match[1] : null;
52
6
  }
53
7
 
54
8
  export function isFeaturePath(filePath) {
55
- const normalized = filePath.replace(/\\/g, '/');
56
- return normalized.includes('.morph/features/');
9
+ return posix(filePath).includes('.morph/features/');
57
10
  }
58
11
 
59
12
  export function getBasename(filePath) {
60
- const normalized = filePath.replace(/\\/g, '/');
61
- return normalized.split('/').pop();
13
+ return posix(filePath).split('/').pop();
62
14
  }
@@ -7,7 +7,7 @@ export const PARTIAL_MARKER = /^[\s#>*_]*PARCIAL\b/;
7
7
 
8
8
  export const STATUSES = ['pendente', 'feito', 'bloqueado'];
9
9
 
10
- export function checksPath(featureDir) {
10
+ function checksPath(featureDir) {
11
11
  return join(featureDir, '2-plan', 'checks.json');
12
12
  }
13
13