@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,8 +2,13 @@ import chalk from 'chalk';
2
2
  import { execFileSync, spawnSync } from 'child_process';
3
3
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
4
4
  import { dirname, join } from 'path';
5
+ import { contractExists, NO_CONTRACT_MESSAGE } from '../../../framework/hooks/shared/contract.js';
6
+ import { featureFromBranch } from '../../../framework/hooks/shared/feature-slug.js';
5
7
  import { detectDefaultBranch } from '../../lib/git/default-branch.js';
6
8
  import { diffLines, fileClass } from '../../lib/diff/diff-lines.js';
9
+ import { worktreeEnv } from '../project/env.js';
10
+
11
+ const TEST_TIMEOUT_MS = 30 * 60 * 1000;
7
12
 
8
13
  const git = (cwd, args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
9
14
 
@@ -26,16 +31,61 @@ function baseContent(cwd, base, path) {
26
31
  }
27
32
 
28
33
  function runTest(cwd, command) {
29
- const r = spawnSync(command, { cwd, shell: true, stdio: 'pipe', encoding: 'utf8' });
34
+ const r = spawnSync(command, {
35
+ cwd, shell: true, stdio: 'pipe', encoding: 'utf8', timeout: TEST_TIMEOUT_MS, windowsHide: true,
36
+ env: { ...process.env, ...worktreeEnv(cwd) },
37
+ });
30
38
  return r.status === 0 ? 'pass' : 'fail';
31
39
  }
32
40
 
41
+ function writeTree(cwd, path, content) {
42
+ if (content === null) rmSync(join(cwd, path), { force: true });
43
+ else {
44
+ mkdirSync(dirname(join(cwd, path)), { recursive: true });
45
+ writeFileSync(join(cwd, path), content);
46
+ }
47
+ }
48
+
49
+ // Per worktree and outside the tree: a killed run leaves the reverted files with their only copy here.
50
+ function backupDir(cwd) {
51
+ return join(git(cwd, ['rev-parse', '--absolute-git-dir']).trim(), 'morph-prove-red');
52
+ }
53
+
54
+ function saveBackup(dir, cwd, targets) {
55
+ rmSync(dir, { recursive: true, force: true });
56
+ mkdirSync(dir, { recursive: true });
57
+ const files = targets.map((path, i) => {
58
+ const existed = existsSync(join(cwd, path));
59
+ if (existed) writeFileSync(join(dir, String(i)), readFileSync(join(cwd, path)));
60
+ return { path, existed };
61
+ });
62
+ writeFileSync(join(dir, 'manifest.json'), JSON.stringify({ files }));
63
+ }
64
+
65
+ function restoreBackup(dir, cwd) {
66
+ const { files } = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8'));
67
+ files.forEach(({ path, existed }, i) => writeTree(cwd, path, existed ? readFileSync(join(dir, String(i))) : null));
68
+ rmSync(dir, { recursive: true, force: true });
69
+ return files.map((f) => f.path);
70
+ }
71
+
72
+ /** Puts back what a `prove-red` killed mid-run left reverted; the paths restored, `[]` when there was nothing. */
73
+ export function restorePendingProveRed(cwd) {
74
+ try {
75
+ const dir = backupDir(cwd);
76
+ return existsSync(join(dir, 'manifest.json')) ? restoreBackup(dir, cwd) : [];
77
+ } catch {
78
+ return [];
79
+ }
80
+ }
81
+
33
82
  /**
34
83
  * The "see it fail without the change" proof, done by the CLI: run the scenario's test with the change,
35
84
  * put the feature's production code back to the merge-base, run it again, restore. Only `code` files
36
- * are reverted (never tests), and the restore runs in `finally` from an in-memory copy.
85
+ * are reverted (never tests), from a copy on disk that the next run restores if this one is killed.
37
86
  */
38
87
  export function proveRed(cwd, { test, files = null }) {
88
+ const recovered = restorePendingProveRed(cwd);
39
89
  const base = mergeBase(cwd);
40
90
  if (!base) return { code: 2, out: { error: 'no-base', hint: 'sem merge-base com a branch padrão: não há "sem a mudança" para comparar' } };
41
91
  const changed = diffLines(cwd, base).filter((f) => fileClass(f.path) === 'code').map((f) => f.path);
@@ -49,41 +99,30 @@ export function proveRed(cwd, { test, files = null }) {
49
99
  return { code: 2, out: { withChange, withoutChange: null, reverted: [], hint: 'o teste já está vermelho COM a mudança: conserte antes de provar' } };
50
100
  }
51
101
 
52
- const saved = new Map(targets.map((p) => [p, existsSync(join(cwd, p)) ? readFileSync(join(cwd, p)) : null]));
102
+ const dir = backupDir(cwd);
103
+ saveBackup(dir, cwd, targets);
53
104
  let withoutChange;
54
105
  try {
55
- for (const path of targets) {
56
- const old = baseContent(cwd, base, path);
57
- if (old === null) rmSync(join(cwd, path), { force: true });
58
- else {
59
- mkdirSync(dirname(join(cwd, path)), { recursive: true });
60
- writeFileSync(join(cwd, path), old);
61
- }
62
- }
106
+ for (const path of targets) writeTree(cwd, path, baseContent(cwd, base, path));
63
107
  withoutChange = runTest(cwd, test);
64
108
  } finally {
65
- for (const [path, content] of saved) {
66
- if (content === null) rmSync(join(cwd, path), { force: true });
67
- else {
68
- mkdirSync(dirname(join(cwd, path)), { recursive: true });
69
- writeFileSync(join(cwd, path), content);
70
- }
71
- }
109
+ restoreBackup(dir, cwd);
72
110
  }
73
111
 
74
- const out = { base, withChange, withoutChange, reverted: targets };
112
+ const out = { base, withChange, withoutChange, reverted: targets, ...(recovered.length ? { recovered } : {}) };
75
113
  if (withoutChange === 'pass') {
76
114
  return { code: 1, out: { ...out, hint: 'o teste passa SEM a mudança: ele não prova o cenário (filtro errado, ou asserção que já era verdade)' } };
77
115
  }
78
116
  return { code: 0, out };
79
117
  }
80
118
 
81
- export function proveRedCommand(feature, options = {}) {
119
+ export function proveRedCommand(featureArg, options = {}) {
82
120
  const cwd = process.cwd();
83
- if (!options.test) {
84
- console.error(chalk.red('\n❌ --test "<comando do teste do cenário>" é obrigatório\n'));
121
+ if (!contractExists(cwd)) {
122
+ console.error(chalk.red(NO_CONTRACT_MESSAGE));
85
123
  process.exit(2);
86
124
  }
125
+ const feature = featureArg || featureFromBranch(cwd) || 'feature';
87
126
  const files = options.files ? String(options.files).split(',').map((f) => f.trim().replace(/\\/g, '/')).filter(Boolean) : null;
88
127
  const { code, out } = proveRed(cwd, { test: options.test, files });
89
128
  const payload = { feature, ...out };
@@ -1,19 +1,17 @@
1
1
  import { join } from 'path';
2
2
 
3
3
  export const OUTPUT_SCHEMA = {
4
- plan: { filename: 'plan.md', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
5
- checks: { filename: 'checks.json', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
6
- planCritique: { filename: 'critica.md', phaseDir: '2-plan', phase: 'plan', protected: false },
4
+ plan: { filename: 'plan.md', phaseDir: '2-plan' },
5
+ checks: { filename: 'checks.json', phaseDir: '2-plan' },
7
6
 
8
- uiMockups: { filename: 'mockups.md', phaseDir: '1-design', phase: 'uiux', protected: true, approvalGate: 'uiux' },
7
+ uiMockups: { filename: 'mockups.md', phaseDir: '1-design' },
9
8
 
10
- implementReport: { filename: 'report.md', phaseDir: '3-implement', phase: 'implement', protected: false },
11
- evidencias: { dirname: 'evidencias', filenamePattern: '^C\\d+\\.md$', displayFilename: '{Cn}.md',
12
- phaseDir: '3-implement', phase: 'implement', protected: false, multi: true },
9
+ implementReport: { filename: 'report.md', phaseDir: '3-implement' },
10
+ evidencias: { dirname: 'evidencias', phaseDir: '3-implement', multi: true },
13
11
 
14
- verifierReport: { filename: 'verifier.md', phaseDir: '4-review', phase: 'review', protected: false },
15
- reviewerReport: { filename: 'reviewer.md', phaseDir: '4-review', phase: 'review', protected: false },
16
- securityReport: { filename: 'security.md', phaseDir: '4-review', phase: 'review', protected: false },
12
+ verifierReport: { filename: 'verifier.md', phaseDir: '4-review' },
13
+ reviewerReport: { filename: 'reviewer.md', phaseDir: '4-review' },
14
+ securityReport: { filename: 'security.md', phaseDir: '4-review' },
17
15
  };
18
16
 
19
17
  function leafSegment(entry) {
@@ -27,20 +25,3 @@ export function getAbsoluteOutputPath(projectRoot, featureName, outputType) {
27
25
  }
28
26
  return join(projectRoot, '.morph', 'features', featureName, entry.phaseDir, leafSegment(entry));
29
27
  }
30
-
31
- export const FILENAME_TO_OUTPUT = Object.fromEntries(
32
- Object.entries(OUTPUT_SCHEMA)
33
- .filter(([, entry]) => !entry.multi)
34
- .map(([key, entry]) => [entry.filename, key])
35
- );
36
-
37
- export const OUTPUT_PHASE_MAP = Object.fromEntries(
38
- Object.entries(OUTPUT_SCHEMA).map(([key, entry]) => [key, entry.phase])
39
- );
40
-
41
- export const PROTECTED_SPEC_FILES = Object.fromEntries(
42
- Object.entries(OUTPUT_SCHEMA)
43
- .filter(([, entry]) => entry.protected && entry.approvalGate && !entry.multi)
44
- .map(([, entry]) => [entry.filename, entry.approvalGate])
45
- );
46
-
@@ -1,53 +1,19 @@
1
1
  import { readFileSync, existsSync } from 'fs';
2
- import { join, dirname } from 'path';
3
- import { fileURLToPath } from 'url';
2
+ import { join } from 'path';
4
3
 
5
- const __filename = fileURLToPath(import.meta.url);
6
- const __dirname = dirname(__filename);
4
+ const FRAMEWORK_TEMPLATES_DIR = join(import.meta.dirname, '../../../framework/templates');
7
5
 
8
- // Keyed by REGISTRY.json path, so the framework and a project registry never shadow each other.
9
- const _registryCache = new Map();
6
+ let registry = null;
10
7
 
11
- export function loadTemplateRegistry(projectPath = null) {
12
- const registryPath = projectPath
13
- ? join(projectPath, 'framework/templates/REGISTRY.json')
14
- : join(__dirname, '../../../framework/templates/REGISTRY.json');
15
-
16
- const cached = _registryCache.get(registryPath);
17
- if (cached) {
18
- return cached;
19
- }
20
-
21
- if (!existsSync(registryPath)) {
22
- throw new Error(`Template registry not found: ${registryPath}`);
23
- }
24
-
25
- try {
26
- const content = readFileSync(registryPath, 'utf-8');
27
- const parsed = JSON.parse(content);
28
- _registryCache.set(registryPath, parsed);
29
- return parsed;
30
- } catch (error) {
31
- throw new Error(`Failed to parse template registry: ${error.message}`);
32
- }
8
+ function loadTemplateRegistry() {
9
+ registry ??= JSON.parse(readFileSync(join(FRAMEWORK_TEMPLATES_DIR, 'REGISTRY.json'), 'utf-8'));
10
+ return registry;
33
11
  }
34
12
 
35
- export function clearRegistryCache() {
36
- _registryCache.clear();
13
+ export function getTemplateById(templateId) {
14
+ return (loadTemplateRegistry().templates || []).find(t => t.id === templateId) || null;
37
15
  }
38
16
 
39
- function getAllTemplates(projectPath = null) {
40
- const registry = loadTemplateRegistry(projectPath);
41
- return registry.templates || [];
42
- }
43
-
44
- export function getTemplateById(templateId, projectPath = null) {
45
- const templates = getAllTemplates(projectPath);
46
- return templates.find(t => t.id === templateId) || null;
47
- }
48
-
49
- const FRAMEWORK_TEMPLATES_DIR = join(__dirname, '../../../framework/templates');
50
-
51
17
  /** Path inside this package's `framework/templates/`, not a project's `.morph/`; throws when missing. */
52
18
  export function resolveFrameworkTemplatePath(templateId) {
53
19
  const template = getTemplateById(templateId);
@@ -62,4 +28,3 @@ export function resolveFrameworkTemplatePath(templateId) {
62
28
  }
63
29
  return abs;
64
30
  }
65
-
@@ -49,26 +49,6 @@ function registerHelpers() {
49
49
  return a === b;
50
50
  });
51
51
 
52
- Handlebars.registerHelper('ne', function (a, b) {
53
- return a !== b;
54
- });
55
-
56
- Handlebars.registerHelper('lt', function (a, b) {
57
- return a < b;
58
- });
59
-
60
- Handlebars.registerHelper('gt', function (a, b) {
61
- return a > b;
62
- });
63
-
64
- Handlebars.registerHelper('lte', function (a, b) {
65
- return a <= b;
66
- });
67
-
68
- Handlebars.registerHelper('gte', function (a, b) {
69
- return a >= b;
70
- });
71
-
72
52
  Handlebars.registerHelper('and', function (...args) {
73
53
  // Handlebars passes its options object as the last argument.
74
54
  const values = args.slice(0, -1);
@@ -81,31 +61,10 @@ function registerHelpers() {
81
61
  return values.some(Boolean);
82
62
  });
83
63
 
84
- Handlebars.registerHelper('not', function (value) {
85
- return !value;
86
- });
87
-
88
- Handlebars.registerHelper('uppercase', function (str) {
89
- return typeof str === 'string' ? str.toUpperCase() : '';
90
- });
91
-
92
- Handlebars.registerHelper('lowercase', function (str) {
93
- return typeof str === 'string' ? str.toLowerCase() : '';
94
- });
95
-
96
- Handlebars.registerHelper('capitalize', function (str) {
97
- if (typeof str !== 'string') return '';
98
- return str.charAt(0).toUpperCase() + str.slice(1);
99
- });
100
-
101
64
  Handlebars.registerHelper('default', function (value, defaultValue) {
102
65
  return value != null && value !== '' ? value : defaultValue;
103
66
  });
104
67
 
105
- Handlebars.registerHelper('json', function (obj) {
106
- return JSON.stringify(obj, null, 2);
107
- });
108
-
109
68
  Handlebars.registerHelper('now', function (format) {
110
69
  const date = new Date();
111
70
  if (format === 'iso') {
@@ -118,39 +77,6 @@ function registerHelpers() {
118
77
  return date.toISOString().split('T')[0];
119
78
  });
120
79
 
121
- Handlebars.registerHelper('year', function () {
122
- return new Date().getFullYear();
123
- });
124
-
125
- Handlebars.registerHelper('formatDate', function (date, format) {
126
- if (!date) return '';
127
-
128
- const d = new Date(date);
129
- if (isNaN(d.getTime())) return date;
130
-
131
- switch (format) {
132
- case 'iso':
133
- return d.toISOString();
134
- case 'date':
135
- return d.toISOString().split('T')[0];
136
- case 'time':
137
- return d.toTimeString().split(' ')[0];
138
- case 'datetime':
139
- return d.toISOString().replace('T', ' ').split('.')[0];
140
- case 'short':
141
- return d.toLocaleDateString();
142
- case 'long':
143
- return d.toLocaleDateString('en-US', {
144
- weekday: 'long',
145
- year: 'numeric',
146
- month: 'long',
147
- day: 'numeric'
148
- });
149
- default:
150
- return d.toISOString().split('T')[0];
151
- }
152
- });
153
-
154
80
  Handlebars.registerHelper('pluralize', function (str) {
155
81
  if (typeof str !== 'string') return '';
156
82
 
@@ -184,129 +110,14 @@ function registerHelpers() {
184
110
  }
185
111
  });
186
112
 
187
- Handlebars.registerHelper('singularize', function (str) {
188
- if (typeof str !== 'string') return '';
189
-
190
- const irregulars = {
191
- 'people': 'person',
192
- 'children': 'child',
193
- 'feet': 'foot',
194
- 'teeth': 'tooth',
195
- 'mice': 'mouse',
196
- 'geese': 'goose'
197
- };
198
-
199
- const lower = str.toLowerCase();
200
- if (irregulars[lower]) {
201
- return str[0] === str[0].toUpperCase()
202
- ? irregulars[lower].charAt(0).toUpperCase() + irregulars[lower].slice(1)
203
- : irregulars[lower];
204
- }
205
-
206
- if (str.endsWith('ies')) {
207
- return str.slice(0, -3) + 'y';
208
- } else if (str.endsWith('ves')) {
209
- return str.slice(0, -3) + 'f';
210
- } else if (str.endsWith('es')) {
211
- return str.slice(0, -2);
212
- } else if (str.endsWith('s') && !str.endsWith('ss')) {
213
- return str.slice(0, -1);
214
- } else {
215
- return str;
216
- }
217
- });
218
-
219
- Handlebars.registerHelper('trim', function (str) {
220
- return typeof str === 'string' ? str.trim() : '';
221
- });
222
-
223
- Handlebars.registerHelper('replace', function (str, search, replacement) {
224
- if (typeof str !== 'string') return '';
225
- return str.replace(new RegExp(search, 'g'), replacement);
226
- });
227
-
228
- Handlebars.registerHelper('concat', function (...args) {
229
- // Handlebars passes its options object as the last argument.
230
- const strings = args.slice(0, -1);
231
- return strings.join('');
232
- });
233
-
234
- Handlebars.registerHelper('substr', function (str, start, length) {
235
- if (typeof str !== 'string') return '';
236
- return length !== undefined ? str.substring(start, start + length) : str.substring(start);
237
- });
238
-
239
- Handlebars.registerHelper('startsWith', function (str, prefix) {
240
- if (typeof str !== 'string') return false;
241
- return str.startsWith(prefix);
242
- });
243
-
244
- Handlebars.registerHelper('endsWith', function (str, suffix) {
245
- if (typeof str !== 'string') return false;
246
- return str.endsWith(suffix);
247
- });
248
-
249
- Handlebars.registerHelper('contains', function (str, substring) {
250
- if (typeof str !== 'string') return false;
251
- return str.includes(substring);
252
- });
253
-
254
- Handlebars.registerHelper('length', function (value) {
255
- if (Array.isArray(value) || typeof value === 'string') {
256
- return value.length;
257
- }
258
- return 0;
259
- });
260
-
261
113
  Handlebars.registerHelper('add', function (a, b) {
262
114
  return Number(a) + Number(b);
263
115
  });
264
-
265
- Handlebars.registerHelper('subtract', function (a, b) {
266
- return Number(a) - Number(b);
267
- });
268
-
269
- Handlebars.registerHelper('multiply', function (a, b) {
270
- return Number(a) * Number(b);
271
- });
272
-
273
- Handlebars.registerHelper('divide', function (a, b) {
274
- return Number(b) !== 0 ? Number(a) / Number(b) : 0;
275
- });
276
-
277
- Handlebars.registerHelper('mod', function (a, b) {
278
- return Number(a) % Number(b);
279
- });
280
-
281
- Handlebars.registerHelper('round', function (num, decimals = 0) {
282
- const multiplier = Math.pow(10, decimals);
283
- return Math.round(Number(num) * multiplier) / multiplier;
284
- });
285
-
286
- Handlebars.registerHelper('join', function (array, separator = ', ') {
287
- if (!Array.isArray(array)) return '';
288
- return array.join(separator);
289
- });
290
-
291
- Handlebars.registerHelper('first', function (array) {
292
- if (!Array.isArray(array) || array.length === 0) return undefined;
293
- return array[0];
294
- });
295
-
296
- Handlebars.registerHelper('last', function (array) {
297
- if (!Array.isArray(array) || array.length === 0) return undefined;
298
- return array[array.length - 1];
299
- });
300
-
301
- Handlebars.registerHelper('slice', function (array, start, end) {
302
- if (!Array.isArray(array)) return [];
303
- return array.slice(start, end);
304
- });
305
116
  }
306
117
 
307
118
  registerHelpers();
308
119
 
309
- export function renderTemplate(templatePath, variables, options = {}) {
120
+ export function renderTemplate(templatePath, variables) {
310
121
  if (!existsSync(templatePath)) {
311
122
  throw new Error(`Template file not found: ${templatePath}`);
312
123
  }
@@ -315,7 +126,7 @@ export function renderTemplate(templatePath, variables, options = {}) {
315
126
  const templateContent = readFileSync(templatePath, 'utf-8');
316
127
 
317
128
  const template = Handlebars.compile(templateContent, {
318
- noEscape: options.noEscape !== undefined ? options.noEscape : true,
129
+ noEscape: true,
319
130
  strict: false,
320
131
  preventIndent: true,
321
132
  });
@@ -337,16 +148,8 @@ export function getTemplatePlaceholdersFromString(templateString) {
337
148
 
338
149
  const skipHelpers = [
339
150
  'if', 'unless', 'each', 'with', 'lookup', 'log', 'else',
340
- 'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
341
- 'and', 'or', 'not',
151
+ 'eq', 'and', 'or', 'default', 'now', 'pluralize', 'add',
342
152
  'pascalCase', 'camelCase', 'titleCase', 'upperSnakeCase', 'snakeCase', 'kebabCase',
343
- 'uppercase', 'lowercase', 'capitalize', 'trim', 'replace', 'concat', 'substr',
344
- 'startsWith', 'endsWith', 'contains', 'length',
345
- 'formatDate', 'now', 'year',
346
- 'pluralize', 'singularize',
347
- 'add', 'subtract', 'multiply', 'divide', 'mod', 'round',
348
- 'join', 'first', 'last', 'slice',
349
- 'default', 'json'
350
153
  ];
351
154
 
352
155
  if (!skipHelpers.includes(placeholder)) {
@@ -9,7 +9,7 @@ import { auditRenamedApi, auditPromptSource, renamedApiGate } from './code-audit
9
9
  /** Os cinco ids, na ordem em que o relatório os imprime. */
10
10
  export const AI_CHECK_IDS = ['pin-drift', 'removed-api', 'pricing-missing', 'api-per-alias', 'prompt-source'];
11
11
 
12
- export const AI_CHECK_NAMES = {
12
+ const AI_CHECK_NAMES = {
13
13
  'pin-drift': 'pin × projeto (versões de pacote de IA)',
14
14
  'removed-api': 'API renomeada antes do 1.0 GA',
15
15
  'pricing-missing': 'tarifa por alias do registry de modelos',
@@ -4,6 +4,7 @@
4
4
  import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
7
+ import { stripBom } from '../json-file.js';
7
8
 
8
9
  export const SCAN_IGNORED_DIRS = new Set([
9
10
  'node_modules',
@@ -15,7 +16,7 @@ export const SCAN_IGNORED_DIRS = new Set([
15
16
 
16
17
  // Deliberadamente curto: decide se há assunto, não cataloga o ecossistema; um pacote de IA fora daqui
17
18
  // que esteja no pin ainda é pego por `pin-drift`.
18
- export const AI_PACKAGE_PREFIXES = [
19
+ const AI_PACKAGE_PREFIXES = [
19
20
  'Microsoft.Agents.AI',
20
21
  'Microsoft.Extensions.AI',
21
22
  'Microsoft.SemanticKernel',
@@ -33,10 +34,6 @@ export function isAiPackage(name) {
33
34
  );
34
35
  }
35
36
 
36
- function stripBom(text) {
37
- return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
38
- }
39
-
40
37
  /** Tags fecham na ordem e todo `<` tem `>`: um `.csproj` truncado vira `unreadable`, não "sem drift". */
41
38
  export function isWellFormedXml(xml) {
42
39
  const stack = [];
@@ -5,22 +5,17 @@
5
5
  import { readFileSync } from 'node:fs';
6
6
  import { relative } from 'node:path';
7
7
  import { collectProjectFiles } from './ai-project-scan.js';
8
+ import { lineOf } from '../text.js';
8
9
  import { stripComments } from '../../../framework/hooks/shared/comment-stripper.js';
9
10
 
10
11
  /** Símbolos renomeados antes do 1.0 GA, e o nome vivo de cada um. */
11
- export const RENAMED_SYMBOLS = {
12
+ const RENAMED_SYMBOLS = {
12
13
  AgentThread: 'AgentSession',
13
14
  GetNewThread: 'CreateSessionAsync()',
14
15
  ChatMessageStore: 'a conversa persistida do projeto (ver ai-agents/agent-session.md)',
15
16
  };
16
17
 
17
- function lineOf(text, index) {
18
- let line = 1;
19
- for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line += 1;
20
- return line;
21
- }
22
-
23
- export function collectCsharpFiles(root) {
18
+ function collectCsharpFiles(root) {
24
19
  return collectProjectFiles(root, (name) => name.toLowerCase().endsWith('.cs'));
25
20
  }
26
21
 
@@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { isAbsolute, join, basename } from 'node:path';
7
7
  import { collectProjectFiles } from './ai-project-scan.js';
8
+ import { stripBom } from '../json-file.js';
8
9
  import { jsoncToJson } from '../../../framework/hooks/shared/comment-stripper.js';
9
10
 
10
11
  const MAX_JSON_CHARS = 512 * 1024;
@@ -15,7 +16,7 @@ function readJsonSafe(file) {
15
16
  try {
16
17
  const raw = readFileSync(file, 'utf8');
17
18
  if (raw.length > MAX_JSON_CHARS) return null;
18
- const text = raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
19
+ const text = stripBom(raw);
19
20
  try {
20
21
  return JSON.parse(text);
21
22
  } catch {
@@ -6,7 +6,7 @@ import { detectDefaultBranch } from '../git/default-branch.js';
6
6
  import { parseReport } from '../../../framework/hooks/shared/report-progress.js';
7
7
  import { checksCoverage } from '../review-reports.js';
8
8
 
9
- export const RISK_CATEGORIES = ['dados', 'pessoas', 'acesso', 'infra'];
9
+ const RISK_CATEGORIES = ['dados', 'pessoas', 'acesso', 'infra'];
10
10
 
11
11
  // Money charged to a real person sits with "pessoas": the harm lands on someone outside the repo.
12
12
  const LINE_CATEGORY = [
@@ -18,7 +18,7 @@ const LINE_CATEGORY = [
18
18
  const STOP_RUNGS = new Set(['migrar', 'irreversível']);
19
19
  const MAX_READ = 512 * 1024;
20
20
 
21
- export function baseRefOf(cwd) {
21
+ function baseRefOf(cwd) {
22
22
  const branch = detectDefaultBranch(cwd);
23
23
  if (!branch) return null;
24
24
  for (const ref of [`origin/${branch}`, branch]) {
@@ -47,7 +47,7 @@ export function changedFiles(cwd, { committed = false } = {}) {
47
47
  /** Work outside `.morph/` that the PR would leave behind: modified tracked files and untracked, unignored ones. */
48
48
  export function uncommittedSignals(cwd) {
49
49
  let text;
50
- try { text = git(cwd, ['status', '--porcelain', '-uall']); } catch { return []; }
50
+ try { text = git(cwd, ['-c', 'core.quotepath=off', 'status', '--porcelain', '-uall']); } catch { return []; }
51
51
  const paths = text.split('\n').filter(Boolean).map((l) => l.slice(3).replace(/^"|"$/g, '')).filter((p) => !p.startsWith('.morph/'));
52
52
  return paths.length ? [{ kind: 'nao-commitado', onde: paths.slice(0, 5).join(', ') + (paths.length > 5 ? ` e mais ${paths.length - 5}` : '') }] : [];
53
53
  }
@@ -107,16 +107,34 @@ export function finalSignals(checks, reportText, runs) {
107
107
  return out;
108
108
  }
109
109
 
110
- /** Personas of the single review round: verifier and reviewer always, security when it wrote a report. */
111
- export function reviewSignals(reports, checkIds = []) {
110
+ // A review counts for the commit it read: code outside `.morph/` that changed after it was not reviewed.
111
+ function staleReason(cwd, sha) {
112
+ if (!cwd) return null;
113
+ if (!sha) return 'sem Reviewed-SHA';
114
+ try {
115
+ git(cwd, ['diff', '--quiet', sha, 'HEAD', '--', '.', ':(exclude).morph']);
116
+ return null;
117
+ } catch (error) {
118
+ return error.status === 1 ? `o código mudou depois do ${sha.slice(0, 7)} revisado` : `Reviewed-SHA ${sha.slice(0, 7)} não existe neste repo`;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Personas of the single review round: verifier and reviewer always, security when it wrote a report.
124
+ * With `cwd`, a report whose `Reviewed-SHA` is missing or older than the code counts as no review.
125
+ */
126
+ export function reviewSignals(reports, checkIds = [], cwd = null) {
112
127
  const required = ['verifier', 'reviewer', ...(reports.security.status === 'missing' ? [] : ['security'])];
113
128
  const out = [];
114
129
  const absent = required.filter((role) => reports[role].status !== 'ok');
115
130
  if (absent.length) out.push({ kind: 'sem-revisao', onde: absent.map((r) => `${r} (${reports[r].status})`).join(', ') });
116
- const fix = required.filter((role) => reports[role].status === 'ok' && (reports[role].verdict === 'FIX' || reports[role].blockers.length));
131
+ const open = (role) => [...reports[role].blockers, ...reports[role].untyped];
132
+ const fix = required.filter((role) => reports[role].status === 'ok' && (reports[role].verdict === 'FIX' || open(role).length));
117
133
  if (fix.length) {
118
- out.push({ kind: 'revisao-fix', onde: fix.map((r) => `${r}: ${reports[r].blockers.map((b) => `${b.id} ${b.type}`).join(', ') || 'FIX'}`).join('; ') });
134
+ out.push({ kind: 'revisao-fix', onde: fix.map((r) => `${r}: ${open(r).map((b) => `${b.id} ${b.type}`).join(', ') || 'FIX'}`).join('; ') });
119
135
  }
136
+ const stale = required.filter((role) => reports[role].status === 'ok').map((role) => [role, staleReason(cwd, reports[role].reviewedSha)]).filter(([, why]) => why);
137
+ if (stale.length) out.push({ kind: 'sem-revisao', onde: stale.map(([role, why]) => `${role} (${why})`).join(', ') });
120
138
  if (reports.verifier.status === 'ok' && checkIds.length) {
121
139
  const { missing, notProven } = checksCoverage(checkIds, reports.verifier.checks);
122
140
  const open = [...missing, ...notProven.map((n) => `${n.id} ${n.status}`)];
@@ -1,12 +1,13 @@
1
- import { existsSync, readFileSync } from 'fs';
1
+ import { existsSync } from 'fs';
2
2
  import { join } from 'path';
3
+ import { readJsonFile } from '../json-file.js';
3
4
  import { CONTRACT_FILE } from '../../../framework/hooks/shared/contract.js';
4
5
 
5
6
  export function readMorphConfig(projectPath) {
6
7
  const configPath = join(projectPath, CONTRACT_FILE);
7
8
  if (!existsSync(configPath)) return null;
8
9
  try {
9
- return JSON.parse(readFileSync(configPath, 'utf8').replace(/^/, ''));
10
+ return readJsonFile(configPath);
10
11
  } catch {
11
12
  return null;
12
13
  }