@polymorphism-tech/morph-spec 10.12.0 → 11.0.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.
- package/CLAUDE.md +27 -57
- package/README.md +51 -340
- package/bin/morph-spec.js +22 -373
- package/docs/CHEATSHEET.md +37 -166
- package/docs/QUICKSTART.md +14 -74
- package/framework/CLAUDE.md +15 -26
- package/framework/MORPH.md +34 -101
- package/framework/agents.json +8 -8
- package/framework/commands/morph-apply.md +5 -5
- package/framework/commands/morph-infra.md +1 -1
- package/framework/docs/CLI.md +74 -886
- package/framework/evals/review-checklist.md +14 -14
- package/framework/hooks/README.md +21 -189
- package/framework/hooks/claude-code/core/README.md +2 -5
- package/framework/hooks/claude-code/core/conventional-commit.js +2 -2
- package/framework/hooks/claude-code/core/denylist.json +3 -3
- package/framework/hooks/claude-code/core/graph-refresh-kick.js +2 -2
- package/framework/hooks/claude-code/core/masked-exit.js +6 -6
- package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
- package/framework/hooks/claude-code/core/protect-spec-files.js +17 -61
- package/framework/hooks/claude-code/core/stack-changed.js +35 -0
- package/framework/hooks/claude-code/core/validate-completion.js +31 -86
- package/framework/hooks/shared/{heavy-command.js → command-kind.js} +6 -79
- package/framework/hooks/shared/command-tokens.js +0 -139
- package/framework/hooks/shared/contract.js +14 -0
- package/framework/hooks/shared/feature-slug.js +21 -0
- package/framework/hooks/shared/frontend-locations.js +0 -1
- package/framework/hooks/shared/git-paths.js +0 -15
- package/framework/hooks/shared/graph-freshness.js +0 -19
- package/framework/hooks/shared/hook-response.js +0 -7
- package/framework/hooks/shared/morph-cli.js +2 -81
- package/framework/hooks/shared/owner-words.js +2 -120
- package/framework/hooks/shared/payload-utils.js +0 -39
- package/framework/hooks/shared/report-progress.js +7 -101
- package/framework/hooks/statusline.js +16 -60
- package/framework/mcp/registry.json +2 -2
- package/framework/rules/ai-agents-standards.md +1 -1
- package/framework/rules/asaas-standards.md +1 -1
- package/framework/rules/ef-standards.md +1 -1
- package/framework/rules/gsap-standards.md +1 -1
- package/framework/rules/hangfire-standards.md +1 -1
- package/framework/rules/implement-report.md +3 -3
- package/framework/rules/neon-auth-standards.md +1 -1
- package/framework/rules/nextjs-standards.md +1 -1
- package/framework/rules/plan-grammar.md +13 -11
- package/framework/rules/resend-standards.md +1 -1
- package/framework/rules/ui-design.md +4 -0
- package/framework/schemas/config.schema.json +95 -310
- package/framework/skills/README.md +12 -32
- package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
- package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
- package/framework/skills/core/morph-apply/SKILL.md +21 -46
- package/framework/skills/core/morph-plan/SKILL.md +28 -63
- package/framework/skills/core/morph-uiux/SKILL.md +23 -25
- package/framework/{templates/docs/ui-mockups.md → skills/core/morph-uiux/references/mockups.md} +4 -4
- package/framework/standards/STANDARDS.json +10 -11
- package/framework/standards/STANDARDS.meta.json +1 -1
- package/framework/standards/ai-agents/evals-with-cache.md +18 -32
- package/framework/standards/ai-agents/observability-patterns.md +2 -2
- package/framework/standards/architecture/code-comments.md +2 -5
- package/framework/standards/architecture/engineering-lens.md +1 -1
- package/framework/standards/backend/dotnet/testing.md +4 -4
- package/framework/standards/frontend/nextjs/lint.md +24 -10
- package/framework/standards/frontend/nextjs/testing.md +2 -2
- package/framework/standards/infrastructure/docker/local-compose-isolation.md +14 -30
- package/framework/templates/CLAUDE.md.core.guide.md +2 -2
- package/framework/templates/README.md +1 -1
- package/framework/templates/REGISTRY.json +3 -33
- package/framework/templates/docs/plan.md +3 -2
- package/framework/templates/dotnet/ai-kit/README.md +2 -4
- package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalCacheMissException.cs +1 -1
- package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Evals/EvalFixture.cs +1 -1
- package/package.json +1 -2
- package/src/commands/graph/explain.js +2 -1
- package/src/commands/graph/status.js +2 -1
- package/src/commands/mcp/mcp-setup.js +1 -2
- package/src/commands/project/doctor.js +5 -341
- package/src/commands/project/env.js +21 -52
- package/src/commands/project/init-contract.js +47 -0
- package/src/commands/project/init.js +36 -66
- package/src/commands/project/stack-scan.js +1 -1
- package/src/commands/project/update.js +15 -50
- package/src/commands/validation/check.js +128 -0
- package/src/commands/validation/plan-check.js +41 -64
- package/src/commands/validation/prove-red.js +1 -1
- package/src/core/paths/output-schema.js +0 -22
- package/src/core/templates/template-renderer.js +0 -14
- package/src/lib/ai/ai-project-scan.js +1 -6
- package/src/lib/check/attempts.js +38 -0
- package/src/lib/check/signals.js +145 -0
- package/src/lib/config/project-config.js +13 -0
- package/src/lib/contract/apply.js +62 -0
- package/src/lib/contract/defaults.js +96 -0
- package/src/lib/contract/merge.js +79 -0
- package/src/lib/contract/ports.js +43 -0
- package/src/lib/contract/scan.js +102 -0
- package/src/lib/detectors/claude-config-detector.js +7 -0
- package/src/lib/{procs → detectors}/mcp-config.js +1 -37
- package/src/lib/diff/diff-lines.js +64 -0
- package/src/lib/generators/architecture-scanner.js +1 -1
- package/src/lib/generators/scaffold-generator.js +0 -7
- package/src/lib/git/default-branch.js +0 -122
- package/src/lib/graph/diff-tree.js +2 -1
- package/src/lib/graph/god-nodes.js +2 -1
- package/src/lib/graph/graphify-runtime.js +0 -1
- package/src/lib/graph/graphifyignore.js +1 -1
- package/src/lib/graph/sanitize.js +2 -8
- package/src/lib/installers/memory-installer.js +15 -30
- package/src/lib/installers/stack-sync.js +16 -9
- package/src/lib/plan/checks.js +20 -64
- package/src/lib/plan/media.js +1 -1
- package/src/lib/plan/plan-parser.js +5 -5
- package/src/lib/review-reports.js +3 -77
- package/src/lib/scan/worktree-dirs.js +3 -0
- package/src/lib/specs/adr-index.js +2 -2
- package/src/lib/stack/dotnet-build-ignores.js +10 -2
- package/src/lib/stack/stack-scan.js +2 -2
- package/src/lib/stack-filter.js +3 -2
- package/src/lib/tests-audit/audit.js +1 -1
- package/src/scripts/setup-infra.js +6 -59
- package/src/utils/agents-installer.js +1 -34
- package/src/utils/atomic-json.js +27 -0
- package/src/utils/file-copier.js +4 -12
- package/src/utils/hooks-installer.js +9 -107
- package/claude-plugin.json +0 -14
- package/framework/commands/morph-archive.md +0 -46
- package/framework/commands/morph-hotfix.md +0 -17
- package/framework/commands/morph-preflight.md +0 -180
- package/framework/commands/morph-review.md +0 -15
- package/framework/commands/morph-status.md +0 -37
- package/framework/hooks/claude-code/core/block-destructive-worktree-removal.js +0 -80
- package/framework/hooks/claude-code/core/block-raw-worktree-add.js +0 -72
- package/framework/hooks/claude-code/core/enforce-phase-writes.js +0 -100
- package/framework/hooks/claude-code/core/gate-guard.js +0 -148
- package/framework/hooks/claude-code/core/heavy-gate.js +0 -78
- package/framework/hooks/claude-code/core/heavy-release.js +0 -23
- package/framework/hooks/claude-code/core/loop-detect.js +0 -79
- package/framework/hooks/claude-code/core/state-sync.js +0 -214
- package/framework/hooks/claude-code/core/telemetry-log.js +0 -259
- package/framework/hooks/claude-code/core/test-budget.js +0 -29
- package/framework/hooks/claude-code/core/worktree-context.js +0 -249
- package/framework/hooks/claude-code/core/worktree-create.js +0 -119
- package/framework/hooks/claude-code/core/worktree-env-inject.js +0 -68
- package/framework/hooks/claude-code/core/worktree-remove.js +0 -55
- package/framework/hooks/shared/build-check.js +0 -120
- package/framework/hooks/shared/claim-registry.js +0 -125
- package/framework/hooks/shared/e2e-check.js +0 -1022
- package/framework/hooks/shared/feature-locator.js +0 -82
- package/framework/hooks/shared/gate-event.js +0 -18
- package/framework/hooks/shared/gate-question.js +0 -20
- package/framework/hooks/shared/heavy-config.js +0 -113
- package/framework/hooks/shared/heavy-holders.js +0 -85
- package/framework/hooks/shared/heavy-slots.js +0 -280
- package/framework/hooks/shared/host-services.js +0 -440
- package/framework/hooks/shared/next-step.js +0 -181
- package/framework/hooks/shared/redact-secrets.js +0 -44
- package/framework/hooks/shared/reparse-scan.js +0 -40
- package/framework/hooks/shared/state-reader.js +0 -220
- package/framework/hooks/shared/state-writer.js +0 -112
- package/framework/hooks/shared/telemetry-logger.js +0 -101
- package/framework/hooks/shared/transcript-usage.js +0 -58
- package/framework/hooks/shared/worktree-root.js +0 -71
- package/framework/phases.json +0 -92
- package/framework/schemas/feature.schema.json +0 -242
- package/framework/skills/core/morph-apply/references/hotfix.md +0 -46
- package/framework/skills/core/morph-apply/references/machine.md +0 -30
- package/framework/skills/core/morph-apply/references/review.md +0 -77
- package/framework/skills/core/morph-plan/references/critique.md +0 -51
- package/framework/skills/core/morph-plan/references/interview.md +0 -37
- package/framework/templates/state.template.json +0 -17
- package/src/commands/dashboard/dashboard.js +0 -74
- package/src/commands/e2e/e2e.js +0 -400
- package/src/commands/observability/cost.js +0 -283
- package/src/commands/project/branch.js +0 -129
- package/src/commands/project/claim.js +0 -132
- package/src/commands/project/doctor-procs.js +0 -162
- package/src/commands/project/fleet.js +0 -66
- package/src/commands/project/heavy.js +0 -81
- package/src/commands/project/install-plugin-cmd.js +0 -27
- package/src/commands/project/status.js +0 -61
- package/src/commands/project/worktree.js +0 -1234
- package/src/commands/state/advance.js +0 -248
- package/src/commands/state/approve.js +0 -303
- package/src/commands/state/archive.js +0 -231
- package/src/commands/state/auto-approval.js +0 -67
- package/src/commands/state/create.js +0 -274
- package/src/commands/state/delete.js +0 -192
- package/src/commands/state/finish.js +0 -1247
- package/src/commands/state/gate-check.js +0 -244
- package/src/commands/state/gate-decision.js +0 -122
- package/src/commands/state/list.js +0 -244
- package/src/commands/state/next.js +0 -24
- package/src/commands/state/recap.js +0 -80
- package/src/commands/state/report-check.js +0 -244
- package/src/commands/state/retype.js +0 -110
- package/src/commands/validation/verify.js +0 -421
- package/src/core/state/feature-identity.js +0 -10
- package/src/core/state/gate-order.js +0 -23
- package/src/core/state/lifecycle-audit.js +0 -171
- package/src/core/state/state-manager.js +0 -523
- package/src/core/templates/template-seed.js +0 -21
- package/src/core/work-types.js +0 -44
- package/src/dashboard/app/App.jsx +0 -84
- package/src/dashboard/app/components/ActivityFeed.jsx +0 -166
- package/src/dashboard/app/components/CommandPalette.jsx +0 -144
- package/src/dashboard/app/components/DetailPanel.jsx +0 -43
- package/src/dashboard/app/components/EntityLink.jsx +0 -42
- package/src/dashboard/app/components/ErrorBoundary.jsx +0 -47
- package/src/dashboard/app/components/FlowGraph.jsx +0 -19
- package/src/dashboard/app/components/GatePauses.jsx +0 -116
- package/src/dashboard/app/components/KnowledgeMarkdown.jsx +0 -42
- package/src/dashboard/app/components/Markdown.jsx +0 -38
- package/src/dashboard/app/components/PhaseRail.jsx +0 -100
- package/src/dashboard/app/components/SearchFilter.jsx +0 -36
- package/src/dashboard/app/components/SessionMap.jsx +0 -77
- package/src/dashboard/app/components/Sidebar.jsx +0 -147
- package/src/dashboard/app/hooks/useMorphQuery.js +0 -44
- package/src/dashboard/app/hooks/usePref.js +0 -34
- package/src/dashboard/app/lib/format.js +0 -69
- package/src/dashboard/app/lib/phases.js +0 -75
- package/src/dashboard/app/lib/project.js +0 -38
- package/src/dashboard/app/main.jsx +0 -13
- package/src/dashboard/app/pages/Activity.jsx +0 -28
- package/src/dashboard/app/pages/AgentMap.jsx +0 -363
- package/src/dashboard/app/pages/FeatureDetail.jsx +0 -579
- package/src/dashboard/app/pages/Features.jsx +0 -393
- package/src/dashboard/app/pages/Guide.jsx +0 -145
- package/src/dashboard/app/pages/HookInspector.jsx +0 -444
- package/src/dashboard/app/pages/PhasePipeline.jsx +0 -273
- package/src/dashboard/app/pages/Portfolio.jsx +0 -190
- package/src/dashboard/app/pages/RulesMap.jsx +0 -285
- package/src/dashboard/app/pages/SkillsLibrary.jsx +0 -468
- package/src/dashboard/app/pages/Standards.jsx +0 -392
- package/src/dashboard/app/styles/index.css +0 -187
- package/src/dashboard/index.html +0 -14
- package/src/dashboard/package.json +0 -32
- package/src/dashboard/scanner/activity-scanner.js +0 -321
- package/src/dashboard/scanner/agents-scanner.js +0 -67
- package/src/dashboard/scanner/docs-scanner.js +0 -34
- package/src/dashboard/scanner/feature-status.js +0 -7
- package/src/dashboard/scanner/features-scanner.js +0 -397
- package/src/dashboard/scanner/hooks-scanner.js +0 -96
- package/src/dashboard/scanner/index.js +0 -21
- package/src/dashboard/scanner/phases-scanner.js +0 -14
- package/src/dashboard/scanner/portfolio.js +0 -129
- package/src/dashboard/scanner/project-api.js +0 -160
- package/src/dashboard/scanner/rules-scanner.js +0 -46
- package/src/dashboard/scanner/skills-scanner.js +0 -104
- package/src/dashboard/scanner/standards-scanner.js +0 -38
- package/src/dashboard/vite-plugin-morph-data.js +0 -120
- package/src/dashboard/vite.config.js +0 -26
- package/src/lib/ci/ci-verify.js +0 -30
- package/src/lib/ci/github-ci.js +0 -52
- package/src/lib/ci/pr-checks.js +0 -76
- package/src/lib/e2e/applicability.js +0 -39
- package/src/lib/e2e/compose-env.js +0 -80
- package/src/lib/e2e/stack-teardown.js +0 -96
- package/src/lib/git/branch-classifier.js +0 -104
- package/src/lib/git/evidence-staleness.js +0 -40
- package/src/lib/git/gh.js +0 -15
- package/src/lib/git/pending-prs.js +0 -58
- package/src/lib/git/pr-files.js +0 -31
- package/src/lib/git/pr-index.js +0 -39
- package/src/lib/git/tree-fingerprint.js +0 -58
- package/src/lib/git/tree-state.js +0 -125
- package/src/lib/heavy/cleanup.js +0 -72
- package/src/lib/heavy/gate.js +0 -168
- package/src/lib/heavy/live-stacks.js +0 -64
- package/src/lib/heavy/reclaim.js +0 -107
- package/src/lib/heavy/watchdog.js +0 -46
- package/src/lib/next-step.js +0 -12
- package/src/lib/plan/critique.js +0 -67
- package/src/lib/plan/plan-template.js +0 -18
- package/src/lib/procs/classify.js +0 -91
- package/src/lib/procs/list.js +0 -124
- package/src/lib/procs/prune.js +0 -47
- package/src/lib/procs/wslconfig.js +0 -70
- package/src/lib/projects/registry.js +0 -121
- package/src/lib/recap/piper.js +0 -36
- package/src/lib/recap/recap.js +0 -259
- package/src/lib/review-confirmation.js +0 -66
- package/src/lib/risk/diff-risk.js +0 -137
- package/src/lib/risk-detector.js +0 -638
- package/src/lib/specs/design-seed.js +0 -18
- package/src/lib/specs/screen-checklist.js +0 -315
- package/src/lib/stack/stack-profile.js +0 -69
- package/src/lib/tasks/eval-node.js +0 -293
- package/src/lib/tasks/linux-runner.js +0 -200
- package/src/lib/tasks/test-nodes.js +0 -414
- package/src/lib/tasks/test-runner.js +0 -569
- package/src/lib/telemetry/metrics.js +0 -384
- package/src/lib/telemetry/telemetry-reader.js +0 -276
- package/src/lib/telemetry/verify-event.js +0 -57
- package/src/lib/validators/code-budget/code-budget-validator.js +0 -170
- package/src/lib/validators/contracts/contract-compliance-validator.js +0 -219
- package/src/lib/validators/nextjs/next-component-validator.js +0 -142
- package/src/lib/validators/packages/package-validator.js +0 -310
- package/src/lib/validators/reuse/reuse-validator.js +0 -202
- package/src/lib/validators/reuse/symbol-scanner.js +0 -64
- package/src/lib/validators/validation-runner.js +0 -188
- package/src/lib/validators/verify-cache.js +0 -63
- package/src/lib/validators/verify-runner.js +0 -971
- package/src/lib/verify/affected.js +0 -143
- package/src/lib/verify/detached.js +0 -159
- package/src/lib/view/feature-html.js +0 -480
- package/src/lib/view/feature-page.client.js +0 -109
- package/src/lib/view/feature-page.css +0 -278
- package/src/lib/view/feature-view.js +0 -113
- package/src/lib/view/flow-layers.js +0 -79
- package/src/lib/view/flow-svg.js +0 -63
- package/src/lib/view/tokens.css +0 -18
- package/src/lib/work-type-detector.js +0 -81
- package/src/lib/worktree/dirs.js +0 -3
- package/src/lib/worktree/docker-audit.js +0 -175
- package/src/lib/worktree/env-allocator.js +0 -177
- package/src/lib/worktree/feature-truth.js +0 -145
- package/src/lib/worktree/finish-backup.js +0 -529
- package/src/lib/worktree/fleet-scanner.js +0 -223
- package/src/lib/worktree/ignored-triage.js +0 -136
- package/src/lib/worktree/vscode-settings.js +0 -112
- package/src/lib/worktree/worktree-audit.js +0 -323
- package/src/lib/worktree/worktree-include.js +0 -44
- package/src/scripts/install-plugin.js +0 -114
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { join } from 'path';
|
|
2
2
|
|
|
3
|
-
/** The one page of a feature, at its root: it belongs to no phase, and only the CLI writes it. */
|
|
4
|
-
export const FEATURE_VIEW_FILE = 'feature.html';
|
|
5
|
-
|
|
6
3
|
export const OUTPUT_SCHEMA = {
|
|
7
4
|
plan: { filename: 'plan.md', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
|
|
8
5
|
checks: { filename: 'checks.json', phaseDir: '2-plan', phase: 'plan', protected: true, approvalGate: 'plan' },
|
|
@@ -41,22 +38,6 @@ export function getAbsoluteOutputPath(projectRoot, featureName, outputType) {
|
|
|
41
38
|
return join(projectRoot, '.morph', 'features', featureName, entry.phaseDir, leafSegment(entry));
|
|
42
39
|
}
|
|
43
40
|
|
|
44
|
-
export function getFeatureDir(featureName) {
|
|
45
|
-
return join('.morph', 'features', featureName).replace(/\\/g, '/');
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** `multi` types contribute their directory, so `created` means "the folder exists". */
|
|
49
|
-
export function getAllOutputPaths(featureName) {
|
|
50
|
-
const outputs = {};
|
|
51
|
-
for (const [key] of Object.entries(OUTPUT_SCHEMA)) {
|
|
52
|
-
outputs[key] = {
|
|
53
|
-
created: false,
|
|
54
|
-
path: getOutputPath(featureName, key),
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
return outputs;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
41
|
export const FILENAME_TO_OUTPUT = Object.fromEntries(
|
|
61
42
|
Object.entries(OUTPUT_SCHEMA)
|
|
62
43
|
.filter(([, entry]) => !entry.multi)
|
|
@@ -73,6 +54,3 @@ export const PROTECTED_SPEC_FILES = Object.fromEntries(
|
|
|
73
54
|
.map(([, entry]) => [entry.filename, entry.approvalGate])
|
|
74
55
|
);
|
|
75
56
|
|
|
76
|
-
export function resolveContractsOutputType() {
|
|
77
|
-
return 'plan';
|
|
78
|
-
}
|
|
@@ -326,20 +326,6 @@ export function renderTemplate(templatePath, variables, options = {}) {
|
|
|
326
326
|
}
|
|
327
327
|
}
|
|
328
328
|
|
|
329
|
-
export function renderTemplateString(templateString, variables, options = {}) {
|
|
330
|
-
try {
|
|
331
|
-
const template = Handlebars.compile(templateString, {
|
|
332
|
-
noEscape: options.noEscape !== undefined ? options.noEscape : true,
|
|
333
|
-
strict: false,
|
|
334
|
-
preventIndent: true,
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
return template(variables);
|
|
338
|
-
} catch (error) {
|
|
339
|
-
throw new Error(`Failed to render template string: ${error.message}`);
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
|
|
343
329
|
export function getTemplatePlaceholdersFromString(templateString) {
|
|
344
330
|
const placeholders = new Set();
|
|
345
331
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
|
-
import { WORKTREE_DIR_NAMES } from '../worktree
|
|
6
|
+
import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
|
|
7
7
|
|
|
8
8
|
export const SCAN_IGNORED_DIRS = new Set([
|
|
9
9
|
'node_modules',
|
|
@@ -241,8 +241,3 @@ export function scanAiPackageRefs(root) {
|
|
|
241
241
|
return { projectFiles, cpmFiles, unreadable, packages };
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
-
/** `null` quando o projeto não declara o pacote de forma resolvível. */
|
|
245
|
-
export function findPackage(scan, name) {
|
|
246
|
-
if (!scan || !Array.isArray(scan.packages)) return null;
|
|
247
|
-
return scan.packages.find((p) => p.name === name) ?? null;
|
|
248
|
-
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
|
|
5
|
+
const FILE = join('.morph', 'memory', 'check-attempts.json');
|
|
6
|
+
|
|
7
|
+
// Numbers, paths and timings change between two runs of the same failure; the words do not.
|
|
8
|
+
const signatureOf = (failures) => createHash('sha256')
|
|
9
|
+
.update(failures.map((f) => `${f.id}:${f.tail.replace(/[\d.:\\/]+/g, '#')}`).join('\n'))
|
|
10
|
+
.digest('hex').slice(0, 12);
|
|
11
|
+
|
|
12
|
+
function read(root) {
|
|
13
|
+
try { return JSON.parse(readFileSync(join(root, FILE), 'utf8')); } catch { return {}; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** One red `check` is one attempt; the same failure again in a row is one more `same`. Green resets the branch. */
|
|
17
|
+
export function recordAttempt(root, branch, failures) {
|
|
18
|
+
const all = read(root);
|
|
19
|
+
const key = branch || 'HEAD';
|
|
20
|
+
if (!failures.length) {
|
|
21
|
+
delete all[key];
|
|
22
|
+
} else {
|
|
23
|
+
const sig = signatureOf(failures);
|
|
24
|
+
const prev = all[key] ?? { count: 0, same: 0, sig: null };
|
|
25
|
+
all[key] = { count: prev.count + 1, same: prev.sig === sig ? prev.same + 1 : 1, sig };
|
|
26
|
+
}
|
|
27
|
+
mkdirSync(dirname(join(root, FILE)), { recursive: true });
|
|
28
|
+
writeFileSync(join(root, FILE), JSON.stringify(all, null, 2));
|
|
29
|
+
return all[key] ?? { count: 0, same: 0, sig: null };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function stuckSignal(attempt, limits = {}) {
|
|
33
|
+
const maxIterations = limits.maxIterations ?? 8;
|
|
34
|
+
const sameErrorStop = limits.sameErrorStop ?? 3;
|
|
35
|
+
if (attempt.same >= sameErrorStop) return { kind: 'preso', motivo: `${attempt.same} tentativas seguidas presas no mesmo erro (limite ${sameErrorStop})` };
|
|
36
|
+
if (attempt.count >= maxIterations) return { kind: 'preso', motivo: `${attempt.count} tentativas vermelhas (limite ${maxIterations})` };
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { minimatch } from 'minimatch';
|
|
4
|
+
import { diffLines, git } from '../diff/diff-lines.js';
|
|
5
|
+
import { detectDefaultBranch } from '../git/default-branch.js';
|
|
6
|
+
import { parseReport } from '../../../framework/hooks/shared/report-progress.js';
|
|
7
|
+
import { checksCoverage } from '../review-reports.js';
|
|
8
|
+
|
|
9
|
+
export const RISK_CATEGORIES = ['dados', 'pessoas', 'acesso', 'infra'];
|
|
10
|
+
|
|
11
|
+
// Money charged to a real person sits with "pessoas": the harm lands on someone outside the repo.
|
|
12
|
+
const LINE_CATEGORY = [
|
|
13
|
+
['pessoas', /\b(whatsapp|sendmessage|sendtemplate|sms|smtp|sendemail|payment|pagamento|cobran\w*|invoice|fatura|checkout|refund|estorno|stripe|asaas)\b/i],
|
|
14
|
+
['acesso', /\b(permiss\w*|authoriz\w*|autoriza\w*|requirerole|isadmin|password|senha|secret|apikey|api_key)\b/i],
|
|
15
|
+
['dados', /\b(pii|lgpd|gdpr|cpf|cnpj|redact\w*|anonimi\w*|drop\s+table|truncate\s+table|delete\s+from)\b/i],
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
const STOP_RUNGS = new Set(['migrar', 'irreversível']);
|
|
19
|
+
const MAX_READ = 512 * 1024;
|
|
20
|
+
|
|
21
|
+
export function baseRefOf(cwd) {
|
|
22
|
+
const branch = detectDefaultBranch(cwd);
|
|
23
|
+
if (!branch) return null;
|
|
24
|
+
for (const ref of [`origin/${branch}`, branch]) {
|
|
25
|
+
try {
|
|
26
|
+
const base = git(cwd, ['merge-base', 'HEAD', ref]).trim();
|
|
27
|
+
if (base) return base;
|
|
28
|
+
} catch { /* next ref */ }
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The changed files against the merge-base; null when git cannot tell. Mid-work the working tree counts;
|
|
35
|
+
* `committed` reads only what the PR carries.
|
|
36
|
+
*/
|
|
37
|
+
export function changedFiles(cwd, { committed = false } = {}) {
|
|
38
|
+
const base = baseRefOf(cwd);
|
|
39
|
+
if (!base) return null;
|
|
40
|
+
try {
|
|
41
|
+
return diffLines(cwd, base, committed ? 'HEAD' : null).filter((f) => !f.path.startsWith('.morph/')).map((f) => (f.untracked ? withContent(cwd, f) : f));
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Work outside `.morph/` that the PR would leave behind: modified tracked files and untracked, unignored ones. */
|
|
48
|
+
export function uncommittedSignals(cwd) {
|
|
49
|
+
let text;
|
|
50
|
+
try { text = git(cwd, ['status', '--porcelain', '-uall']); } catch { return []; }
|
|
51
|
+
const paths = text.split('\n').filter(Boolean).map((l) => l.slice(3).replace(/^"|"$/g, '')).filter((p) => !p.startsWith('.morph/'));
|
|
52
|
+
return paths.length ? [{ kind: 'nao-commitado', onde: paths.slice(0, 5).join(', ') + (paths.length > 5 ? ` e mais ${paths.length - 5}` : '') }] : [];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// diffLines marks a new untracked file without its lines; the signals read what it adds.
|
|
56
|
+
function withContent(cwd, file) {
|
|
57
|
+
try {
|
|
58
|
+
const text = readFileSync(join(cwd, file.path), 'utf8');
|
|
59
|
+
return text.length > MAX_READ ? file : { ...file, added: text.split('\n') };
|
|
60
|
+
} catch {
|
|
61
|
+
return file;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function riskSignals(files, risk = {}) {
|
|
66
|
+
const out = [];
|
|
67
|
+
for (const cat of RISK_CATEGORIES) {
|
|
68
|
+
const globs = Array.isArray(risk[cat]) ? risk[cat] : [];
|
|
69
|
+
const byPath = files.find((f) => globs.some((g) => minimatch(f.path, g, { dot: true })));
|
|
70
|
+
if (byPath) { out.push({ kind: 'risco', categoria: cat, onde: byPath.path, por: 'caminho' }); continue; }
|
|
71
|
+
const re = LINE_CATEGORY.find(([c]) => c === cat)?.[1];
|
|
72
|
+
const byLine = re && files.find((f) => f.added.some((l) => re.test(l)));
|
|
73
|
+
if (byLine) out.push({ kind: 'risco', categoria: cat, onde: byLine.path, por: 'linha' });
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function sizeSignals(files, limits = {}) {
|
|
79
|
+
return limits.maxFiles && files.length > limits.maxFiles
|
|
80
|
+
? [{ kind: 'pr-grande', onde: `${files.length} arquivos`, limite: limits.maxFiles }]
|
|
81
|
+
: [];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function planSignals(checks, limits = {}) {
|
|
85
|
+
if (!checks) return [];
|
|
86
|
+
const out = [];
|
|
87
|
+
if (checks.summary?.source === 'proposta') out.push({ kind: 'cenarios-propostos', onde: 'plan.md' });
|
|
88
|
+
for (const c of checks.checks ?? []) {
|
|
89
|
+
if (STOP_RUNGS.has(c.rung)) out.push({ kind: 'degrau', onde: c.id, degrau: c.rung });
|
|
90
|
+
}
|
|
91
|
+
if (limits.maxScenarios && (checks.checks?.length ?? 0) > limits.maxScenarios) {
|
|
92
|
+
out.push({ kind: 'plano-grande', onde: `${checks.checks.length} cenários`, limite: limits.maxScenarios });
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function reportSignals(reportText) {
|
|
98
|
+
return [...parseReport(reportText)].filter(([, row]) => row.status === 'bloqueado').map(([id]) => ({ kind: 'bloqueado', onde: id }));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** At the end of the run: a scenario of the plan not `feito` in report.md, and a run that proved nothing. */
|
|
102
|
+
export function finalSignals(checks, reportText, runs) {
|
|
103
|
+
const rows = parseReport(reportText);
|
|
104
|
+
const open = (checks?.checks ?? []).map((c) => c.id).filter((id) => rows.get(id)?.status !== 'feito' && rows.get(id)?.status !== 'bloqueado');
|
|
105
|
+
const out = open.length ? [{ kind: 'pendente', onde: open.join(', ') }] : [];
|
|
106
|
+
if (!runs.length) out.push({ kind: 'sem-prova', onde: 'nenhum comando de teste do contrato rodou' });
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Personas of the single review round: verifier and reviewer always, security when it wrote a report. */
|
|
111
|
+
export function reviewSignals(reports, checkIds = []) {
|
|
112
|
+
const required = ['verifier', 'reviewer', ...(reports.security.status === 'missing' ? [] : ['security'])];
|
|
113
|
+
const out = [];
|
|
114
|
+
const absent = required.filter((role) => reports[role].status !== 'ok');
|
|
115
|
+
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));
|
|
117
|
+
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('; ') });
|
|
119
|
+
}
|
|
120
|
+
if (reports.verifier.status === 'ok' && checkIds.length) {
|
|
121
|
+
const { missing, notProven } = checksCoverage(checkIds, reports.verifier.checks);
|
|
122
|
+
const open = [...missing, ...notProven.map((n) => `${n.id} ${n.status}`)];
|
|
123
|
+
if (open.length) out.push({ kind: 'nao-provado', onde: open.join(', ') });
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const SAY = {
|
|
129
|
+
risco: (s) => `mexe em ${s.categoria} (${s.onde}, pelo ${s.por})`,
|
|
130
|
+
'pr-grande': (s) => `PR grande: ${s.onde}, limite ${s.limite}`,
|
|
131
|
+
'cenarios-propostos': () => 'os cenários foram propostos pelo agente (a issue veio incompleta): aprovar antes de implementar',
|
|
132
|
+
degrau: (s) => `${s.onde} tem degrau "${s.degrau}"`,
|
|
133
|
+
'plano-grande': (s) => `plano grande: ${s.onde}, limite ${s.limite}`,
|
|
134
|
+
preso: (s) => s.motivo,
|
|
135
|
+
vermelho: (s) => `testes vermelhos: ${s.onde}`,
|
|
136
|
+
bloqueado: (s) => `${s.onde} bloqueado: espera uma decisão (ver ## Notas)`,
|
|
137
|
+
pendente: (s) => `cenário não fechado no report.md: ${s.onde}`,
|
|
138
|
+
'sem-prova': (s) => s.onde,
|
|
139
|
+
'sem-revisao': (s) => `revisão em contexto novo sem relatório completo: ${s.onde}`,
|
|
140
|
+
'revisao-fix': (s) => `a revisão pediu correção: ${s.onde}`,
|
|
141
|
+
'nao-provado': (s) => `o verificador não provou: ${s.onde}`,
|
|
142
|
+
'nao-commitado': (s) => `fora do commit, o PR não leva: ${s.onde}`,
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
export const signalText = (s) => (SAY[s.kind] ?? (() => s.kind))(s);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { CONTRACT_FILE } from '../../../framework/hooks/shared/contract.js';
|
|
4
|
+
|
|
5
|
+
export function readMorphConfig(projectPath) {
|
|
6
|
+
const configPath = join(projectPath, CONTRACT_FILE);
|
|
7
|
+
if (!existsSync(configPath)) return null;
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(readFileSync(configPath, 'utf8').replace(/^/, ''));
|
|
10
|
+
} catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync } from 'fs';
|
|
2
|
+
import { dirname, join } from 'path';
|
|
3
|
+
import { atomicWriteJson } from '../../utils/atomic-json.js';
|
|
4
|
+
import { CONTRACT_FILE } from '../../../framework/hooks/shared/contract.js';
|
|
5
|
+
import { readMorphConfig } from '../config/project-config.js';
|
|
6
|
+
import { getProjectTags, parseStacks, shouldInstall } from '../stack-filter.js';
|
|
7
|
+
import { scanRepo } from './scan.js';
|
|
8
|
+
import { contractFromScan } from './defaults.js';
|
|
9
|
+
import { mergeContract } from './merge.js';
|
|
10
|
+
|
|
11
|
+
const FRAMEWORK_SRC = join(import.meta.dirname, '..', '..', '..', 'framework');
|
|
12
|
+
// Inside config.json, not beside it: `update` wipes .morph/config/ and restores only that file.
|
|
13
|
+
export const PRINTS_KEY = '_generated';
|
|
14
|
+
|
|
15
|
+
const readJson = (path) => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
|
|
16
|
+
|
|
17
|
+
/** What `init` would write, without writing: the dry run and the real run share it. */
|
|
18
|
+
export function planContract(root) {
|
|
19
|
+
const scan = scanRepo(root);
|
|
20
|
+
const contract = contractFromScan(root, scan);
|
|
21
|
+
const { [PRINTS_KEY]: prints = {}, ...current } = readMorphConfig(root) ?? {};
|
|
22
|
+
const merged = mergeContract(current, contract, prints);
|
|
23
|
+
return { scan, contract, ...merged, config: { ...merged.config, [PRINTS_KEY]: merged.prints }, tags: getProjectTags(merged.config) };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function applyContract(root) {
|
|
27
|
+
const plan = planContract(root);
|
|
28
|
+
const configPath = join(root, CONTRACT_FILE);
|
|
29
|
+
mkdirSync(dirname(configPath), { recursive: true });
|
|
30
|
+
atomicWriteJson(configPath, plan.config);
|
|
31
|
+
return plan;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function names(dir, pick) {
|
|
35
|
+
if (!existsSync(dir)) return [];
|
|
36
|
+
return readdirSync(dir, { withFileTypes: true }).map((e) => pick(e)).filter(Boolean);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The rules, skills, commands and agents the project tags select, read from the framework the CLI ships. */
|
|
40
|
+
export function installPreview(tags, frameworkSrc = FRAMEWORK_SRC) {
|
|
41
|
+
const pickMd = (dir) => (e) => {
|
|
42
|
+
if (!e.isFile() || !e.name.endsWith('.md')) return null;
|
|
43
|
+
return shouldInstall(parseStacks(readFileSync(join(dir, e.name), 'utf8')), tags) ? e.name.replace(/\.md$/, '') : null;
|
|
44
|
+
};
|
|
45
|
+
const rulesDir = join(frameworkSrc, 'rules');
|
|
46
|
+
const commandsDir = join(frameworkSrc, 'commands');
|
|
47
|
+
const skillsDir = join(frameworkSrc, 'skills', 'core');
|
|
48
|
+
const skills = names(skillsDir, (e) => {
|
|
49
|
+
const file = join(skillsDir, e.name, 'SKILL.md');
|
|
50
|
+
return e.isDirectory() && existsSync(file) && shouldInstall(parseStacks(readFileSync(file, 'utf8')), tags) ? e.name : null;
|
|
51
|
+
});
|
|
52
|
+
const agentsJson = readJson(join(frameworkSrc, 'agents.json'));
|
|
53
|
+
const agents = Object.entries(agentsJson?.agents ?? {})
|
|
54
|
+
.filter(([, a]) => shouldInstall(a.stack ?? [], tags))
|
|
55
|
+
.map(([id]) => id);
|
|
56
|
+
return {
|
|
57
|
+
rules: names(rulesDir, pickMd(rulesDir)),
|
|
58
|
+
skills,
|
|
59
|
+
commands: names(commandsDir, pickMd(commandsDir)),
|
|
60
|
+
agents,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
|
|
4
|
+
export const CONTRACT_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_LIMITS = Object.freeze({ maxScenarios: 6, maxFiles: 20, maxIterations: 8, sameErrorStop: 3 });
|
|
7
|
+
|
|
8
|
+
// Globs over repo-relative paths; the line regex of diff-lines catches what a path cannot name.
|
|
9
|
+
export const DEFAULT_RISK = Object.freeze({
|
|
10
|
+
dados: ['**/Migrations/**', '**/migrations/**', '**/*.sql', '**/prisma/schema.prisma', '**/alembic/versions/**', '**/drizzle/**'],
|
|
11
|
+
pessoas: ['**/*{WhatsApp,Whatsapp,whatsapp,Kapso,kapso}*{,/**}', '**/*{Email,email,Mailer,mailer}*{,/**}', '**/*{Sms,sms,Twilio,twilio}*{,/**}'],
|
|
12
|
+
acesso: ['**/{Auth,auth,Authorization,authorization,Identity,identity}/**', '**/middleware.{ts,js}', '**/*{Permission,permission,Policy,policy}*', '**/appsettings*.json', '**/.env*'],
|
|
13
|
+
infra: ['.github/workflows/**', '**/Dockerfile*', '**/{docker-,}compose*.{yml,yaml}', 'infra/**', '**/*.tf', '**/*.bicep', '**/nginx/**'],
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const NO_TEST_SCRIPT = /no test specified/i;
|
|
17
|
+
const FAST_SCRIPTS = ['lint', 'typecheck', 'type-check', 'test:unit', 'test'];
|
|
18
|
+
|
|
19
|
+
const slug = (dir) => (dir === '.' ? 'root' : dir.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase());
|
|
20
|
+
|
|
21
|
+
function runnerOf(root, dir) {
|
|
22
|
+
if (existsSync(join(root, dir, 'pnpm-lock.yaml')) || existsSync(join(root, 'pnpm-lock.yaml'))) return 'pnpm';
|
|
23
|
+
if (existsSync(join(root, dir, 'yarn.lock')) || existsSync(join(root, 'yarn.lock'))) return 'yarn';
|
|
24
|
+
return 'npm';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function nodeTests(root, pkg) {
|
|
28
|
+
const pm = runnerOf(root, pkg.dir);
|
|
29
|
+
const cwd = pkg.dir === '.' ? undefined : pkg.dir;
|
|
30
|
+
const has = (s) => pkg.scripts[s] && !NO_TEST_SCRIPT.test(pkg.scripts[s]);
|
|
31
|
+
const fast = FAST_SCRIPTS.filter(has).filter((s) => !(s === 'test' && has('test:unit')));
|
|
32
|
+
const entries = fast.map((s) => ({ id: `${slug(pkg.dir)}-${s.replace(':', '-')}`, tier: 'fast', cwd, command: `${pm} run ${s}` }));
|
|
33
|
+
if (has('build')) entries.push({ id: `${slug(pkg.dir)}-build`, tier: 'full', cwd, command: `${pm} run build` });
|
|
34
|
+
for (const e of entries) if (!e.cwd) delete e.cwd;
|
|
35
|
+
return entries;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function dotnetTests(scan) {
|
|
39
|
+
const target = scan.solutions.length === 1 ? scan.solutions[0] : null;
|
|
40
|
+
const testProjects = scan.dotnet.filter((p) => p.isTest).map((p) => p.path);
|
|
41
|
+
const dirSlug = (p) => slug(p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '.');
|
|
42
|
+
const out = target
|
|
43
|
+
? [{ id: 'dotnet-build', tier: 'fast', command: `dotnet build ${target} --nologo -v q` }]
|
|
44
|
+
: scan.dotnet.filter((p) => !p.isTest).map((p) => ({ id: `dotnet-build-${dirSlug(p.path)}`, tier: 'fast', command: `dotnet build ${p.path} --nologo -v q` }));
|
|
45
|
+
if (target && testProjects.length) out.push({ id: 'dotnet-test', tier: 'full', command: `dotnet test ${target} --nologo` });
|
|
46
|
+
else for (const p of testProjects) out.push({ id: `dotnet-test-${dirSlug(p)}`, tier: 'full', command: `dotnet test ${p} --nologo` });
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function pythonTests(scan) {
|
|
51
|
+
const out = [];
|
|
52
|
+
const roots = [...new Map(scan.python.map((p) => [p.dir, p])).values()];
|
|
53
|
+
for (const p of roots) {
|
|
54
|
+
const cwd = p.dir === '.' ? undefined : p.dir;
|
|
55
|
+
const base = (e) => (cwd ? { ...e, cwd } : e);
|
|
56
|
+
if (scan.python.some((q) => q.dir === p.dir && q.ruff)) out.push(base({ id: `${slug(p.dir)}-ruff`, tier: 'fast', command: 'ruff check .' }));
|
|
57
|
+
if (scan.python.some((q) => q.dir === p.dir && q.pytest)) out.push(base({ id: `${slug(p.dir)}-pytest`, tier: 'fast', command: 'python -m pytest -q' }));
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const SECRET_NAME = /SECRET|KEY|TOKEN|PASSWORD|PASS\b|_URL$|_DSN$|CONNECTION/;
|
|
63
|
+
|
|
64
|
+
function testSecretsOf(root) {
|
|
65
|
+
const names = new Set();
|
|
66
|
+
for (const f of ['.env.test.example', '.env.e2e.example', '.env.test.template', '.env.e2e.template']) {
|
|
67
|
+
let text = '';
|
|
68
|
+
try { text = readFileSync(join(root, f), 'utf8'); } catch { continue; }
|
|
69
|
+
for (const m of text.matchAll(/^\s*([A-Z][A-Z0-9_]*)\s*=/gm)) if (SECRET_NAME.test(m[1])) names.add(m[1]);
|
|
70
|
+
}
|
|
71
|
+
return [...names].sort();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const COMPOSE_PREFERENCE = [/^docker-compose\.dev\.ya?ml$/, /^compose\.dev\.ya?ml$/, /^docker-compose\.ya?ml$/, /^compose\.ya?ml$/];
|
|
75
|
+
|
|
76
|
+
/** The contract a scan implies; every field here is what `init` may regenerate. */
|
|
77
|
+
export function contractFromScan(root, scan) {
|
|
78
|
+
const tests = [
|
|
79
|
+
...(scan.dotnet.length ? dotnetTests(scan) : []),
|
|
80
|
+
...scan.node.flatMap((p) => nodeTests(root, p)),
|
|
81
|
+
...pythonTests(scan),
|
|
82
|
+
];
|
|
83
|
+
const rootCompose = scan.compose.filter((f) => !f.includes('/'));
|
|
84
|
+
const compose = COMPOSE_PREFERENCE.map((re) => rootCompose.find((f) => re.test(f))).find(Boolean)
|
|
85
|
+
?? scan.compose.find((f) => !/e2e|test/i.test(f)) ?? null;
|
|
86
|
+
return {
|
|
87
|
+
contractVersion: CONTRACT_VERSION,
|
|
88
|
+
stack: scan.stack,
|
|
89
|
+
tags: scan.tags,
|
|
90
|
+
deps: compose ? { compose } : {},
|
|
91
|
+
tests,
|
|
92
|
+
risk: DEFAULT_RISK,
|
|
93
|
+
testSecrets: testSecretsOf(root),
|
|
94
|
+
limits: DEFAULT_LIMITS,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
|
|
3
|
+
const fingerprint = (value) => createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex').slice(0, 16);
|
|
4
|
+
const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
5
|
+
const isEmpty = (v) => v === undefined || v === null || (Array.isArray(v) && !v.length)
|
|
6
|
+
|| (typeof v === 'object' && !Array.isArray(v) && !Object.keys(v).length);
|
|
7
|
+
|
|
8
|
+
// A value still equal to what init wrote last time follows the scan; a value someone changed stays theirs.
|
|
9
|
+
function mergeValue(key, current, next, prints, report) {
|
|
10
|
+
if (isEmpty(current)) {
|
|
11
|
+
if (isEmpty(next)) return current;
|
|
12
|
+
prints[key] = fingerprint(next);
|
|
13
|
+
report.push({ key, action: 'added' });
|
|
14
|
+
return next;
|
|
15
|
+
}
|
|
16
|
+
if (same(current, next)) {
|
|
17
|
+
prints[key] = fingerprint(next);
|
|
18
|
+
return current;
|
|
19
|
+
}
|
|
20
|
+
if (prints[key] === fingerprint(current)) {
|
|
21
|
+
prints[key] = fingerprint(next);
|
|
22
|
+
report.push({ key, action: 'updated' });
|
|
23
|
+
return next;
|
|
24
|
+
}
|
|
25
|
+
delete prints[key];
|
|
26
|
+
report.push({ key, action: 'kept' });
|
|
27
|
+
return current;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A test list someone wrote by hand is theirs: the scan only fills an empty one or refreshes its own entries.
|
|
31
|
+
function mergeTests(current, next, prints, report) {
|
|
32
|
+
if (!Array.isArray(current) && !next.length) return undefined;
|
|
33
|
+
const list = Array.isArray(current) ? current : [];
|
|
34
|
+
const ours = (t) => t?.id && prints[`project.tests#${t.id}`];
|
|
35
|
+
if (list.some((t) => !ours(t))) {
|
|
36
|
+
report.push({ key: 'project.tests', action: 'kept' });
|
|
37
|
+
return list;
|
|
38
|
+
}
|
|
39
|
+
const byId = new Map(list.map((t) => [t.id, t]));
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const t of next) {
|
|
42
|
+
const key = `project.tests#${t.id}`;
|
|
43
|
+
out.push(mergeValue(key, byId.get(t.id), t, prints, report));
|
|
44
|
+
byId.delete(t.id);
|
|
45
|
+
}
|
|
46
|
+
for (const [id, t] of byId) {
|
|
47
|
+
const key = `project.tests#${id}`;
|
|
48
|
+
if (prints[key] === fingerprint(t)) {
|
|
49
|
+
delete prints[key];
|
|
50
|
+
report.push({ key, action: 'removed' });
|
|
51
|
+
} else {
|
|
52
|
+
out.push(t);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Folds a freshly generated contract into the config, never over a hand edit. */
|
|
59
|
+
export function mergeContract(config, contract, previousPrints = {}) {
|
|
60
|
+
const prints = { ...previousPrints };
|
|
61
|
+
const report = [];
|
|
62
|
+
const out = structuredClone(config ?? {});
|
|
63
|
+
out.project ??= {};
|
|
64
|
+
const p = out.project;
|
|
65
|
+
|
|
66
|
+
out.contractVersion = contract.contractVersion;
|
|
67
|
+
p.stack = mergeValue('project.stack', p.stack, contract.stack, prints, report);
|
|
68
|
+
p.tags = mergeValue('project.tags', p.tags, contract.tags, prints, report);
|
|
69
|
+
p.deps = mergeValue('project.deps', p.deps, contract.deps, prints, report);
|
|
70
|
+
p.tests = mergeTests(p.tests, contract.tests, prints, report);
|
|
71
|
+
p.risk ??= {};
|
|
72
|
+
for (const [cat, globs] of Object.entries(contract.risk)) {
|
|
73
|
+
p.risk[cat] = mergeValue(`project.risk.${cat}`, p.risk[cat], globs, prints, report);
|
|
74
|
+
}
|
|
75
|
+
p.testSecrets = mergeValue('project.testSecrets', p.testSecrets, contract.testSecrets, prints, report);
|
|
76
|
+
p.limits = mergeValue('project.limits', p.limits, contract.limits, prints, report);
|
|
77
|
+
for (const k of ['tags', 'deps', 'tests', 'testSecrets']) if (p[k] === undefined) delete p[k];
|
|
78
|
+
return { config: out, prints, report };
|
|
79
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
|
|
3
|
+
const BASE_PORT = 4000;
|
|
4
|
+
const BLOCK = 10;
|
|
5
|
+
const SLOTS = 100;
|
|
6
|
+
const OFFSETS = { web: 0, api: 1, postgres: 2, redis: 3 };
|
|
7
|
+
// Chromium refuses these (ERR_UNSAFE_PORT): a block holding one is a stack the browser cannot open.
|
|
8
|
+
const BROWSER_UNSAFE = new Set([4045, 4190]);
|
|
9
|
+
|
|
10
|
+
const slotOf = (branch) => createHash('sha256').update(branch).digest().readUInt32BE(0) % SLOTS;
|
|
11
|
+
|
|
12
|
+
/** Compose project names are lowercase letters, digits, `-` and `_`, starting with a letter or digit. */
|
|
13
|
+
export function composeProjectOf(branch) {
|
|
14
|
+
return String(branch).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[^a-z0-9]+|-+$/g, '') || 'morph';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Same branch, same ports, on any machine: no registry, no allocation. */
|
|
18
|
+
export function portBlockOf(branch) {
|
|
19
|
+
let slot = slotOf(branch);
|
|
20
|
+
for (let tries = 0; tries < SLOTS; tries++, slot = (slot + 1) % SLOTS) {
|
|
21
|
+
const base = BASE_PORT + slot * BLOCK;
|
|
22
|
+
const ports = Array.from({ length: BLOCK }, (_, i) => base + i);
|
|
23
|
+
if (!ports.some((p) => BROWSER_UNSAFE.has(p))) return base;
|
|
24
|
+
}
|
|
25
|
+
return BASE_PORT;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The env a worktree's dev servers, compose and tests share. `aliases`: `e2e.portEnvNames` ({ postgres: 'PG_PORT' }). */
|
|
29
|
+
export function branchEnv(branch, { stack = '', aliases = {} } = {}) {
|
|
30
|
+
const base = portBlockOf(branch);
|
|
31
|
+
const env = {
|
|
32
|
+
COMPOSE_PROJECT_NAME: composeProjectOf(branch),
|
|
33
|
+
PORT: String(base + OFFSETS.web),
|
|
34
|
+
API_PORT: String(base + OFFSETS.api),
|
|
35
|
+
POSTGRES_PORT: String(base + OFFSETS.postgres),
|
|
36
|
+
REDIS_PORT: String(base + OFFSETS.redis),
|
|
37
|
+
};
|
|
38
|
+
if (/\bdotnet\b/.test(stack)) env.ASPNETCORE_URLS = `http://localhost:${env.API_PORT}`;
|
|
39
|
+
for (const [port, name] of Object.entries(aliases ?? {})) {
|
|
40
|
+
if (Object.hasOwn(OFFSETS, port) && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) env[name] = String(base + OFFSETS[port]);
|
|
41
|
+
}
|
|
42
|
+
return env;
|
|
43
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'fs';
|
|
2
|
+
import { join, relative } from 'path';
|
|
3
|
+
import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
|
|
4
|
+
|
|
5
|
+
const SKIP_DIRS = new Set([
|
|
6
|
+
'node_modules', '.git', 'bin', 'obj', 'dist', 'build', 'out', 'coverage', '.next', '.nuxt', '.morph', '.claude',
|
|
7
|
+
'.vs', '.vscode', '.idea', 'venv', '.venv', '__pycache__', '.pytest_cache', 'wwwroot', 'umbraco', 'App_Plugins',
|
|
8
|
+
...WORKTREE_DIR_NAMES,
|
|
9
|
+
]);
|
|
10
|
+
const MAX_DEPTH = 4;
|
|
11
|
+
|
|
12
|
+
const MANIFEST = /^(package\.json|pyproject\.toml|requirements(-[\w-]+)?\.txt|components\.json|playwright\.config\.[cm]?[jt]s|vitest\.config\.[cm]?[jt]s|(docker-)?compose(\.[\w-]+)?\.ya?ml|Dockerfile)$|\.(csproj|slnx?)$/i;
|
|
13
|
+
|
|
14
|
+
const fwd = (p) => p.replace(/\\/g, '/');
|
|
15
|
+
|
|
16
|
+
function walk(root) {
|
|
17
|
+
const found = [];
|
|
18
|
+
const stack = [[root, 0]];
|
|
19
|
+
while (stack.length) {
|
|
20
|
+
const [dir, depth] = stack.pop();
|
|
21
|
+
let entries;
|
|
22
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
|
|
23
|
+
for (const e of entries) {
|
|
24
|
+
if (e.isDirectory()) {
|
|
25
|
+
if (depth < MAX_DEPTH && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) stack.push([join(dir, e.name), depth + 1]);
|
|
26
|
+
} else if (MANIFEST.test(e.name)) {
|
|
27
|
+
found.push(fwd(relative(root, join(dir, e.name))));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return found.sort();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const readText = (root, rel) => { try { return readFileSync(join(root, rel), 'utf8').replace(/^/, ''); } catch { return ''; } };
|
|
35
|
+
const readJson = (root, rel) => { try { return JSON.parse(readText(root, rel)); } catch { return null; } };
|
|
36
|
+
const dirOf = (rel) => (rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '.');
|
|
37
|
+
|
|
38
|
+
const NODE_TAGS = [
|
|
39
|
+
['next', 'nextjs'], ['react', 'react'], ['vue', 'vue'], ['gsap', 'gsap'], ['resend', 'resend'], ['stripe', 'stripe'],
|
|
40
|
+
['@neondatabase/serverless', 'neon'], ['pg', 'neon'], ['postgres', 'neon'],
|
|
41
|
+
['@neondatabase/auth', 'neon-auth'], ['@neon/auth', 'neon-auth'], ['@playwright/test', 'playwright'], ['asaas', 'asaas'],
|
|
42
|
+
];
|
|
43
|
+
const DOTNET_TAGS = [
|
|
44
|
+
[/^Microsoft\.EntityFrameworkCore/, 'ef'], [/^Hangfire/, 'hangfire'], [/^Microsoft\.(Agents\.AI|Extensions\.AI)/, 'maf'],
|
|
45
|
+
[/^Resend$/, 'resend'], [/asaas/i, 'asaas'], [/^Npgsql/, 'neon'], [/^Umbraco\.Cms/, 'umbraco'],
|
|
46
|
+
];
|
|
47
|
+
const DOTNET_TEST_PACKAGE = /^(Microsoft\.NET\.Test\.Sdk|xunit|NUnit|MSTest)/;
|
|
48
|
+
|
|
49
|
+
function nodePackage(root, rel) {
|
|
50
|
+
const pkg = readJson(root, rel);
|
|
51
|
+
if (!pkg) return null;
|
|
52
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
53
|
+
const scripts = Object.fromEntries(Object.entries(pkg.scripts || {}).filter(([, v]) => typeof v === 'string'));
|
|
54
|
+
return { dir: dirOf(rel), name: pkg.name ?? null, deps: Object.keys(deps), scripts };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function dotnetProject(root, rel) {
|
|
58
|
+
const text = readText(root, rel);
|
|
59
|
+
const packages = [...text.matchAll(/<PackageReference\s+Include="([^"]+)"/g)].map((m) => m[1]);
|
|
60
|
+
const isTest = packages.some((p) => DOTNET_TEST_PACKAGE.test(p)) || /<IsTestProject>\s*true/i.test(text);
|
|
61
|
+
return { path: rel, packages, isTest };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function pythonProject(root, rel) {
|
|
65
|
+
const text = readText(root, rel).toLowerCase();
|
|
66
|
+
return { dir: dirOf(rel), path: rel, pytest: /\bpytest\b/.test(text), ruff: /\bruff\b/.test(text) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** What the repo is made of, read from its manifests; nothing is executed. */
|
|
70
|
+
export function scanRepo(root) {
|
|
71
|
+
const files = walk(root);
|
|
72
|
+
const tags = new Set();
|
|
73
|
+
const node = files.filter((f) => /(^|\/)package\.json$/.test(f)).map((f) => nodePackage(root, f)).filter(Boolean)
|
|
74
|
+
.filter((p) => p.deps.length || Object.keys(p.scripts).length);
|
|
75
|
+
const dotnet = files.filter((f) => /\.csproj$/i.test(f)).map((f) => dotnetProject(root, f));
|
|
76
|
+
const solutions = files.filter((f) => /\.slnx?$/i.test(f));
|
|
77
|
+
const python = files.filter((f) => /(^|\/)(pyproject\.toml|requirements(-[\w-]+)?\.txt)$/i.test(f)).map((f) => pythonProject(root, f));
|
|
78
|
+
const compose = files.filter((f) => /(^|\/)(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(f));
|
|
79
|
+
const playwright = files.filter((f) => /(^|\/)playwright\.config\./.test(f));
|
|
80
|
+
|
|
81
|
+
for (const p of node) for (const [dep, tag] of NODE_TAGS) if (p.deps.includes(dep)) tags.add(tag);
|
|
82
|
+
for (const p of dotnet) for (const pkg of p.packages) for (const [re, tag] of DOTNET_TAGS) if (re.test(pkg)) tags.add(tag);
|
|
83
|
+
if (files.some((f) => /(^|\/)components\.json$/.test(f))) tags.add('shadcn');
|
|
84
|
+
if (compose.length || files.some((f) => /(^|\/)Dockerfile$/.test(f))) tags.add('docker');
|
|
85
|
+
|
|
86
|
+
const stacks = [];
|
|
87
|
+
if (dotnet.length) stacks.push('dotnet');
|
|
88
|
+
if (tags.has('nextjs')) stacks.push('nextjs');
|
|
89
|
+
else if (tags.has('react')) stacks.push('react');
|
|
90
|
+
else if (tags.has('vue')) stacks.push('vue');
|
|
91
|
+
else if (node.length) stacks.push('node');
|
|
92
|
+
if (python.length) stacks.push('python');
|
|
93
|
+
const staticSite = !stacks.length && existsSync(join(root, 'index.html'));
|
|
94
|
+
if (staticSite) stacks.push('static');
|
|
95
|
+
for (const t of ['nextjs', 'react', 'vue']) tags.delete(t);
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
stack: stacks.length ? stacks.join('+') : null,
|
|
99
|
+
tags: [...tags].sort(),
|
|
100
|
+
node, dotnet, solutions, python, compose, playwright,
|
|
101
|
+
};
|
|
102
|
+
}
|